diff --git a/vendor/github.com/chewxy/math32/.gitignore b/vendor/github.com/chewxy/math32/.gitignore new file mode 100644 index 0000000..daf913b --- /dev/null +++ b/vendor/github.com/chewxy/math32/.gitignore @@ -0,0 +1,24 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof diff --git a/vendor/github.com/chewxy/math32/LICENSE b/vendor/github.com/chewxy/math32/LICENSE new file mode 100644 index 0000000..60021b2 --- /dev/null +++ b/vendor/github.com/chewxy/math32/LICENSE @@ -0,0 +1,25 @@ +BSD 2-Clause License + +Copyright (c) 2021, Xuanyi Chew and the Go Authors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. 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. + +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 HOLDER 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. diff --git a/vendor/github.com/chewxy/math32/README.md b/vendor/github.com/chewxy/math32/README.md new file mode 100644 index 0000000..c88082c --- /dev/null +++ b/vendor/github.com/chewxy/math32/README.md @@ -0,0 +1,7 @@ +# math32 [![GoDoc](https://godoc.org/github.com/chewxy/math32?status.svg)](https://godoc.org/github.com/chewxy/math32) + +A `float32` version of Go's math package. The majority of code in this library is a thin `float32` wrapper over the results of the `math` package that comes in the standard lib. + + +The original code is lifted from the Go standard library which is governed by +a BSD-style licence which can be found here: https://golang.org/LICENSE. diff --git a/vendor/github.com/chewxy/math32/_exp_arm64.s b/vendor/github.com/chewxy/math32/_exp_arm64.s new file mode 100644 index 0000000..d91f266 --- /dev/null +++ b/vendor/github.com/chewxy/math32/_exp_arm64.s @@ -0,0 +1,183 @@ +//go:build !tinygo && !noasm +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#define Ln2Hi 6.9313812256e-01 +#define Ln2Lo 9.0580006145e-06 +#define Log2e 1.4426950216e+00 +#define Overflow 7.097827e+02 +#define Underflow -7.451332e+02 +#define Overflow2 1.024000e+03 +#define Underflow2 -1.0740e+03 +#define NearZero 0x317fffff // 2**-28 +#define PosInf 0x7f800000 +#define FracMask 0x07fffff +#define C1 0x34000000 // 2**-23 +#define P1 1.6666667163e-01 // 0x3FC55555; 0x55555555 +#define P2 -2.7777778450e-03 // 0xBF66C16C; 0x16BEBD93 +#define P3 6.6137559770e-05 // 0x3F11566A; 0xAF25DE2C +#define P4 -1.6533901999e-06 // 0xBEBBBD41; 0xC5D26BF1 +#define P5 4.1381369442e-08 // 0x3E663769; 0x72BEA4D0 + +// Exp returns e**x, the base-e exponential of x. +// This is an assembly implementation of the method used for function Exp in file exp.go. +// +// func archExp(x float32) float32 +TEXT ·archExp(SB),$0-12 + FMOVS x+0(FP), F0 // F0 = x + FCMPS F0, F0 + BNE isNaN // x = NaN, return NaN + FMOVS $Overflow, F1 + FCMPS F1, F0 + BGT overflow // x > Overflow, return PosInf + FMOVS $Underflow, F1 + FCMPS F1, F0 + BLT underflow // x < Underflow, return 0 + MOVW $NearZero, R0 + FMOVS R0, F2 + FABSS F0, F3 + FMOVS $1.0, F1 // F1 = 1.0 + FCMPS F2, F3 + BLT nearzero // fabs(x) < NearZero, return 1 + x + // argument reduction, x = k*ln2 + r, |r| <= 0.5*ln2 + // computed as r = hi - lo for extra precision. + FMOVS $Log2e, F2 + FMOVS $0.5, F3 + FNMSUBS F0, F3, F2, F4 // Log2e*x - 0.5 + FMADDS F0, F3, F2, F3 // Log2e*x + 0.5 + FCMPS $0.0, F0 + FCSELS LT, F4, F3, F3 // F3 = k + FCVTZSS F3, R1 // R1 = int(k) + SCVTFS R1, F3 // F3 = float32(int(k)) + FMOVS $Ln2Hi, F4 // F4 = Ln2Hi + FMOVS $Ln2Lo, F5 // F5 = Ln2Lo + FMSUBS F3, F0, F4, F4 // F4 = hi = x - float32(int(k))*Ln2Hi + FMULS F3, F5 // F5 = lo = float32(int(k)) * Ln2Lo + FSUBS F5, F4, F6 // F6 = r = hi - lo + FMULS F6, F6, F7 // F7 = t = r * r + // compute y + FMOVS $P5, F8 // F8 = P5 + FMOVS $P4, F9 // F9 = P4 + FMADDS F7, F9, F8, F13 // P4+t*P5 + FMOVS $P3, F10 // F10 = P3 + FMADDS F7, F10, F13, F13 // P3+t*(P4+t*P5) + FMOVS $P2, F11 // F11 = P2 + FMADDS F7, F11, F13, F13 // P2+t*(P3+t*(P4+t*P5)) + FMOVS $P1, F12 // F12 = P1 + FMADDS F7, F12, F13, F13 // P1+t*(P2+t*(P3+t*(P4+t*P5))) + FMSUBS F7, F6, F13, F13 // F13 = c = r - t*(P1+t*(P2+t*(P3+t*(P4+t*P5)))) + FMOVS $2.0, F14 + FSUBS F13, F14 + FMULS F6, F13, F15 + FDIVS F14, F15 // F15 = (r*c)/(2-c) + FSUBS F15, F5, F15 // lo-(r*c)/(2-c) + FSUBS F4, F15, F15 // (lo-(r*c)/(2-c))-hi + FSUBS F15, F1, F16 // F16 = y = 1-((lo-(r*c)/(2-c))-hi) + // inline Ldexp(y, k), benefit: + // 1, no parameter pass overhead. + // 2, skip unnecessary checks for Inf/NaN/Zero + FMOVS F16, R0 + ANDS $FracMask, R0, R2 // fraction + LSRW $23, R0, R5 // exponent + ADDS R1, R5 // R1 = int(k) + CMPW $1, R5 + BGE normal + ADDS $23, R5 // denormal + MOVW $C1, R8 + FMOVS R8, F1 // m = 2**-23 +normal: + ORRW R5<<23, R2, R0 + FMOVS R0, F0 + FMULS F1, F0 // return m * x + FMOVS F0, ret+8(FP) + RET +nearzero: + FADDS F1, F0 +isNaN: + FMOVS F0, ret+8(FP) + RET +underflow: + MOVW ZR, ret+8(FP) + RET +overflow: + MOVW $PosInf, R0 + MOVW R0, ret+8(FP) + RET + + +// Exp2 returns 2**x, the base-2 exponential of x. +// This is an assembly implementation of the method used for function Exp2 in file exp.go. +// +// func archExp2(x float32) float32 +TEXT ·archExp2(SB),$0-12 // Is this correct? + FMOVS x+0(FP), F0 // F0 = x + FCMPS F0, F0 + BNE isNaN // x = NaN, return NaN + FMOVS $Overflow2, F1 + FCMPS F1, F0 + BGT overflow // x > Overflow, return PosInf + FMOVS $Underflow2, F1 + FCMPS F1, F0 + BLT underflow // x < Underflow, return 0 + // argument reduction; x = r*lg(e) + k with |r| <= ln(2)/2 + // computed as r = hi - lo for extra precision. + FMOVS $0.5, F2 + FSUBS F2, F0, F3 // x + 0.5 + FADDS F2, F0, F4 // x - 0.5 + FCMPS $0.0, F0 + FCSELS LT, F3, F4, F3 // F3 = k + FCVTZSS F3, R1 // R1 = int(k) + SCVTFS R1, F3 // F3 = float32(int(k)) + FSUBS F3, F0, F3 // t = x - float32(int(k)) + FMOVS $Ln2Hi, F4 // F4 = Ln2Hi + FMOVS $Ln2Lo, F5 // F5 = Ln2Lo + FMULS F3, F4 // F4 = hi = t * Ln2Hi + FNMULS F3, F5 // F5 = lo = -t * Ln2Lo + FSUBS F5, F4, F6 // F6 = r = hi - lo + FMULS F6, F6, F7 // F7 = t = r * r + // compute y + FMOVS $P5, F8 // F8 = P5 + FMOVS $P4, F9 // F9 = P4 + FMADDS F7, F9, F8, F13 // P4+t*P5 + FMOVS $P3, F10 // F10 = P3 + FMADDS F7, F10, F13, F13 // P3+t*(P4+t*P5) + FMOVS $P2, F11 // F11 = P2 + FMADDS F7, F11, F13, F13 // P2+t*(P3+t*(P4+t*P5)) + FMOVS $P1, F12 // F12 = P1 + FMADDS F7, F12, F13, F13 // P1+t*(P2+t*(P3+t*(P4+t*P5))) + FMSUBS F7, F6, F13, F13 // F13 = c = r - t*(P1+t*(P2+t*(P3+t*(P4+t*P5)))) + FMOVS $2.0, F14 + FSUBS F13, F14 + FMULS F6, F13, F15 + FDIVS F14, F15 // F15 = (r*c)/(2-c) + FMOVS $1.0, F1 // F1 = 1.0 + FSUBS F15, F5, F15 // lo-(r*c)/(2-c) + FSUBS F4, F15, F15 // (lo-(r*c)/(2-c))-hi + FSUBS F15, F1, F16 // F16 = y = 1-((lo-(r*c)/(2-c))-hi) + // inline Ldexp(y, k), benefit: + // 1, no parameter pass overhead. + // 2, skip unnecessary checks for Inf/NaN/Zero + FMOVS F16, R0 + ANDS $FracMask, R0, R2 // fraction + LSRW $23, R0, R5 // exponent + ADDS R1, R5 // R1 = int(k) + CMPW $1, R5 + BGE normal + ADDS $23, R5 // denormal + MOVW $C1, R8 + FMOVS R8, F1 // m = 2**-52 +normal: + ORRW R5<<23, R2, R0 + FMOVS R0, F0 + FMULS F1, F0 // return m * x +isNaN: + FMOVS F0, ret+8(FP) + RET +underflow: + MOVW ZR, ret+8(FP) + RET +overflow: + MOVW $PosInf, R0 + MOVW R0, ret+8(FP) + RET diff --git a/vendor/github.com/chewxy/math32/_stubs_risc64.s b/vendor/github.com/chewxy/math32/_stubs_risc64.s new file mode 100644 index 0000000..fbee974 --- /dev/null +++ b/vendor/github.com/chewxy/math32/_stubs_risc64.s @@ -0,0 +1,22 @@ +//go:build !tinygo && !noasm +#include "textflag.h" + +// func archExp(x float32) float32 +TEXT ·archExp(SB),NOSPLIT,$0 + B ·exp(SB) + +// func archExp2(x float32) float32 +TEXT ·archExp2(SB),NOSPLIT,$0 + B ·exp2(SB) + +// func archLog(x float32) float32 +TEXT ·archLog(SB),NOSPLIT,$0 + B ·log(SB) + +// func archRemainder(x, y float32) float32 +TEXT ·archRemainder(SB),NOSPLIT,$0 + B ·remainder(SB) + +// func archSqrt(x float32) float32 +TEXT ·archSqrt(SB),NOSPLIT,$0 + B ·sqrt(SB) diff --git a/vendor/github.com/chewxy/math32/abs.go b/vendor/github.com/chewxy/math32/abs.go new file mode 100644 index 0000000..9f097f3 --- /dev/null +++ b/vendor/github.com/chewxy/math32/abs.go @@ -0,0 +1,10 @@ +package math32 + +// Abs returns the absolute value of x. +// +// Special cases are: +// Abs(±Inf) = +Inf +// Abs(NaN) = NaN +func Abs(x float32) float32 { + return Float32frombits(Float32bits(x) &^ (1 << 31)) +} diff --git a/vendor/github.com/chewxy/math32/acos.go b/vendor/github.com/chewxy/math32/acos.go new file mode 100644 index 0000000..84567ef --- /dev/null +++ b/vendor/github.com/chewxy/math32/acos.go @@ -0,0 +1,9 @@ +package math32 + +// Acos returns the arccosine, in radians, of x. +// +// Special case is: +// Acos(x) = NaN if x < -1 or x > 1 +func Acos(x float32) float32 { + return Pi/2 - Asin(x) +} diff --git a/vendor/github.com/chewxy/math32/acosh.go b/vendor/github.com/chewxy/math32/acosh.go new file mode 100644 index 0000000..4cd6d0f --- /dev/null +++ b/vendor/github.com/chewxy/math32/acosh.go @@ -0,0 +1,53 @@ +package math32 + +// The original C code, the long comment, and the constants +// below are from FreeBSD's /usr/src/lib/msun/src/e_acosh.c +// and came with this notice. The go code is a simplified +// version of the original C. +// +// ==================================================== +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// +// Developed at SunPro, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== +// +// +// __ieee754_acosh(x) +// Method : +// Based on +// acosh(x) = log [ x + sqrt(x*x-1) ] +// we have +// acosh(x) := log(x)+ln2, if x is large; else +// acosh(x) := log(2x-1/(sqrt(x*x-1)+x)) if x>2; else +// acosh(x) := log1p(t+sqrt(2.0*t+t*t)); where t=x-1. +// +// Special cases: +// acosh(x) is NaN with signal if x<1. +// acosh(NaN) is NaN without signal. +// + +// Acosh returns the inverse hyperbolic cosine of x. +// +// Special cases are: +// Acosh(+Inf) = +Inf +// Acosh(x) = NaN if x < 1 +// Acosh(NaN) = NaN +func Acosh(x float32) float32 { + const Large = 1 << 28 // 2**28 + // first case is special case + switch { + case x < 1 || IsNaN(x): + return NaN() + case x == 1: + return 0 + case x >= Large: + return Log(x) + Ln2 // x > 2**28 + case x > 2: + return Log(2*x - 1/(x+Sqrt(x*x-1))) // 2**28 > x > 2 + } + t := x - 1 + return Log1p(t + Sqrt(2*t+t*t)) // 2 >= x > 1 +} diff --git a/vendor/github.com/chewxy/math32/asin.go b/vendor/github.com/chewxy/math32/asin.go new file mode 100644 index 0000000..6e80818 --- /dev/null +++ b/vendor/github.com/chewxy/math32/asin.go @@ -0,0 +1,27 @@ +package math32 + +func Asin(x float32) float32 { + if x == 0 { + return x // special case + } + sign := false + if x < 0 { + x = -x + sign = true + } + if x > 1 { + return NaN() // special case + } + + temp := Sqrt(1 - x*x) + if x > 0.7 { + temp = Pi/2 - satan(temp/x) + } else { + temp = satan(x / temp) + } + + if sign { + temp = -temp + } + return temp +} diff --git a/vendor/github.com/chewxy/math32/asinh.go b/vendor/github.com/chewxy/math32/asinh.go new file mode 100644 index 0000000..731cff9 --- /dev/null +++ b/vendor/github.com/chewxy/math32/asinh.go @@ -0,0 +1,65 @@ +package math32 + +// The original C code, the long comment, and the constants +// below are from FreeBSD's /usr/src/lib/msun/src/s_asinh.c +// and came with this notice. The go code is a simplified +// version of the original C. +// +// ==================================================== +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// +// Developed at SunPro, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== +// +// +// asinh(x) +// Method : +// Based on +// asinh(x) = sign(x) * log [ |x| + sqrt(x*x+1) ] +// we have +// asinh(x) := x if 1+x*x=1, +// := sign(x)*(log(x)+ln2)) for large |x|, else +// := sign(x)*log(2|x|+1/(|x|+sqrt(x*x+1))) if|x|>2, else +// := sign(x)*log1p(|x| + x**2/(1 + sqrt(1+x**2))) +// + +// Asinh returns the inverse hyperbolic sine of x. +// +// Special cases are: +// Asinh(±0) = ±0 +// Asinh(±Inf) = ±Inf +// Asinh(NaN) = NaN +func Asinh(x float32) float32 { + const ( + Ln2 = 6.93147180559945286227e-01 // 0x3FE62E42FEFA39EF + NearZero = 1.0 / (1 << 28) // 2**-28 + Large = 1 << 28 // 2**28 + ) + // special cases + if IsNaN(x) || IsInf(x, 0) { + return x + } + sign := false + if x < 0 { + x = -x + sign = true + } + var temp float32 + switch { + case x > Large: + temp = Log(x) + Ln2 // |x| > 2**28 + case x > 2: + temp = Log(2*x + 1/(Sqrt(x*x+1)+x)) // 2**28 > |x| > 2.0 + case x < NearZero: + temp = x // |x| < 2**-28 + default: + temp = Log1p(x + x*x/(1+Sqrt(1+x*x))) // 2.0 > |x| > 2**-28 + } + if sign { + temp = -temp + } + return temp +} diff --git a/vendor/github.com/chewxy/math32/atan.go b/vendor/github.com/chewxy/math32/atan.go new file mode 100644 index 0000000..5eb311f --- /dev/null +++ b/vendor/github.com/chewxy/math32/atan.go @@ -0,0 +1,90 @@ +package math32 + +func Atan(x float32) float32 { + if x == 0 { + return x + } + if x > 0 { + return satan(x) + } + return -satan(-x) +} + +// The original C code, the long comment, and the constants below were +// from http://netlib.sandia.gov/cephes/cmath/atan.c, available from +// http://www.netlib.org/cephes/cmath.tgz. +// The go code is a version of the original C. +// +// atan.c +// Inverse circular tangent (arctangent) +// +// SYNOPSIS: +// double x, y, atan(); +// y = atan( x ); +// +// DESCRIPTION: +// Returns radian angle between -pi/2 and +pi/2 whose tangent is x. +// +// Range reduction is from three intervals into the interval from zero to 0.66. +// The approximant uses a rational function of degree 4/5 of the form +// x + x**3 P(x)/Q(x). +// +// ACCURACY: +// Relative error: +// arithmetic domain # trials peak rms +// DEC -10, 10 50000 2.4e-17 8.3e-18 +// IEEE -10, 10 10^6 1.8e-16 5.0e-17 +// +// Cephes Math Library Release 2.8: June, 2000 +// Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier +// +// The readme file at http://netlib.sandia.gov/cephes/ says: +// Some software in this archive may be from the book _Methods and +// Programs for Mathematical Functions_ (Prentice-Hall or Simon & Schuster +// International, 1989) or from the Cephes Mathematical Library, a +// commercial product. In either event, it is copyrighted by the author. +// What you see here may be used freely but it comes with no support or +// guarantee. +// +// The two known misprints in the book are repaired here in the +// source listings for the gamma function and the incomplete beta +// integral. +// +// Stephen L. Moshier +// moshier@na-net.ornl.gov + +// xatan evaluates a series valid in the range [0, 0.66]. +func xatan(x float32) float32 { + const ( + P0 = -8.750608600031904122785e-01 + P1 = -1.615753718733365076637e+01 + P2 = -7.500855792314704667340e+01 + P3 = -1.228866684490136173410e+02 + P4 = -6.485021904942025371773e+01 + Q0 = +2.485846490142306297962e+01 + Q1 = +1.650270098316988542046e+02 + Q2 = +4.328810604912902668951e+02 + Q3 = +4.853903996359136964868e+02 + Q4 = +1.945506571482613964425e+02 + ) + z := x * x + z = z * ((((P0*z+P1)*z+P2)*z+P3)*z + P4) / (((((z+Q0)*z+Q1)*z+Q2)*z+Q3)*z + Q4) + z = x*z + x + return z +} + +// satan reduces its argument (known to be positive) +// to the range [0, 0.66] and calls xatan. +func satan(x float32) float32 { + const ( + Morebits float32 = 6.123233995736765886130e-17 // pi/2 = PIO2 + Morebits + Tan3pio8 float32 = 2.41421356237309504880 // tan(3*pi/8) + ) + if x <= 0.66 { + return xatan(x) + } + if x > Tan3pio8 { + return Pi/2 - xatan(1/x) + Morebits + } + return Pi/4 + xatan((x-1)/(x+1)) + 0.5*Morebits +} diff --git a/vendor/github.com/chewxy/math32/atan2.go b/vendor/github.com/chewxy/math32/atan2.go new file mode 100644 index 0000000..1bcea99 --- /dev/null +++ b/vendor/github.com/chewxy/math32/atan2.go @@ -0,0 +1,62 @@ +package math32 + +// Atan2 returns the arc tangent of y/x, using the signs of the two to determine the quadrant of the return value. +// Special cases are (in order): +// Atan2(y, NaN) = NaN +// Atan2(NaN, x) = NaN +// Atan2(+0, x>=0) = +0 +// Atan2(-0, x>=0) = -0 +// Atan2(+0, x<=-0) = +Pi +// Atan2(-0, x<=-0) = -Pi +// Atan2(y>0, 0) = +Pi/2 +// Atan2(y<0, 0) = -Pi/2 +// Atan2(+Inf, +Inf) = +Pi/4 +// Atan2(-Inf, +Inf) = -Pi/4 +// Atan2(+Inf, -Inf) = 3Pi/4 +// Atan2(-Inf, -Inf) = -3Pi/4 +// Atan2(y, +Inf) = 0 +// Atan2(y>0, -Inf) = +Pi +// Atan2(y<0, -Inf) = -Pi +// Atan2(+Inf, x) = +Pi/2 +// Atan2(-Inf, x) = -Pi/2 +func Atan2(y, x float32) float32 { + // special cases + switch { + case IsNaN(y) || IsNaN(x): + return NaN() + case y == 0: + if x >= 0 && !Signbit(x) { + return Copysign(0, y) + } + return Copysign(Pi, y) + case x == 0: + return Copysign(Pi/2, y) + case IsInf(x, 0): + if IsInf(x, 1) { + switch { + case IsInf(y, 0): + return Copysign(Pi/4, y) + default: + return Copysign(0, y) + } + } + switch { + case IsInf(y, 0): + return Copysign(3*Pi/4, y) + default: + return Copysign(Pi, y) + } + case IsInf(y, 0): + return Copysign(Pi/2, y) + } + + // Call atan and determine the quadrant. + q := Atan(y / x) + if x < 0 { + if q <= 0 { + return q + Pi + } + return q - Pi + } + return q +} diff --git a/vendor/github.com/chewxy/math32/atanh.go b/vendor/github.com/chewxy/math32/atanh.go new file mode 100644 index 0000000..324ae44 --- /dev/null +++ b/vendor/github.com/chewxy/math32/atanh.go @@ -0,0 +1,73 @@ +package math32 + +// The original C code, the long comment, and the constants +// below are from FreeBSD's /usr/src/lib/msun/src/e_atanh.c +// and came with this notice. The go code is a simplified +// version of the original C. +// +// ==================================================== +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// +// Developed at SunPro, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== +// +// +// __ieee754_atanh(x) +// Method : +// 1. Reduce x to positive by atanh(-x) = -atanh(x) +// 2. For x>=0.5 +// 1 2x x +// atanh(x) = --- * log(1 + -------) = 0.5 * log1p(2 * --------) +// 2 1 - x 1 - x +// +// For x<0.5 +// atanh(x) = 0.5*log1p(2x+2x*x/(1-x)) +// +// Special cases: +// atanh(x) is NaN if |x| > 1 with signal; +// atanh(NaN) is that NaN with no signal; +// atanh(+-1) is +-INF with signal. +// + +// Atanh returns the inverse hyperbolic tangent of x. +// +// Special cases are: +// Atanh(1) = +Inf +// Atanh(±0) = ±0 +// Atanh(-1) = -Inf +// Atanh(x) = NaN if x < -1 or x > 1 +// Atanh(NaN) = NaN +func Atanh(x float32) float32 { + const NearZero = 1.0 / (1 << 28) // 2**-28 + // special cases + switch { + case x < -1 || x > 1 || IsNaN(x): + return NaN() + case x == 1: + return Inf(1) + case x == -1: + return Inf(-1) + } + sign := false + if x < 0 { + x = -x + sign = true + } + var temp float32 + switch { + case x < NearZero: + temp = x + case x < 0.5: + temp = x + x + temp = 0.5 * Log1p(temp+temp*x/(1-x)) + default: + temp = 0.5 * Log1p((x+x)/(1-x)) + } + if sign { + temp = -temp + } + return temp +} diff --git a/vendor/github.com/chewxy/math32/bits.go b/vendor/github.com/chewxy/math32/bits.go new file mode 100644 index 0000000..075444f --- /dev/null +++ b/vendor/github.com/chewxy/math32/bits.go @@ -0,0 +1,58 @@ +package math32 + +const ( + uvnan = 0x7FE00000 + uvinf = 0x7F800000 + uvone = 0x3f800000 + uvneginf = 0xFF800000 + mask = 0xFF + shift = 32 - 8 - 1 + bias = 127 + signMask = 1 << 31 + fracMask = 1<= 0, negative infinity if sign < 0. +func Inf(sign int) float32 { + var v uint32 + if sign >= 0 { + v = uvinf + } else { + v = uvneginf + } + return Float32frombits(v) +} + +// NaN returns an IEEE 754 ``not-a-number'' value. +func NaN() float32 { return Float32frombits(uvnan) } + +// IsNaN reports whether f is an IEEE 754 ``not-a-number'' value. +func IsNaN(f float32) (is bool) { + // IEEE 754 says that only NaNs satisfy f != f. + // To avoid the floating-point hardware, could use: + // x := Float32bits(f) + // return uint32(x>>shift)&mask == mask && x != uvinf && x != uvneginf + return f != f +} + +// IsInf reports whether f is an infinity, according to sign. +// If sign > 0, IsInf reports whether f is positive infinity. +// If sign < 0, IsInf reports whether f is negative infinity. +// If sign == 0, IsInf reports whether f is either infinity. +func IsInf(f float32, sign int) bool { + // Test for infinity by comparing against maximum float. + // To avoid the floating-point hardware, could use: + // x := Float32bits(f) + // return sign >= 0 && x == uvinf || sign <= 0 && x == uvneginf + return sign >= 0 && f > MaxFloat32 || sign <= 0 && f < -MaxFloat32 +} + +// normalize returns a normal number y and exponent exp +// satisfying x == y × 2**exp. It assumes x is finite and non-zero. +func normalize(x float32) (y float32, exp int) { + const SmallestNormal = 1.1754943508222875079687365e-38 // 2**-(127 - 1) + if Abs(x) < SmallestNormal { + return x * (1 << shift), -shift + } + return x, 0 +} diff --git a/vendor/github.com/chewxy/math32/cbrt.go b/vendor/github.com/chewxy/math32/cbrt.go new file mode 100644 index 0000000..804565a --- /dev/null +++ b/vendor/github.com/chewxy/math32/cbrt.go @@ -0,0 +1,7 @@ +package math32 + +import "math" + +func Cbrt(x float32) float32 { + return float32(math.Cbrt(float64(x))) +} diff --git a/vendor/github.com/chewxy/math32/const.go b/vendor/github.com/chewxy/math32/const.go new file mode 100644 index 0000000..1af7cae --- /dev/null +++ b/vendor/github.com/chewxy/math32/const.go @@ -0,0 +1,42 @@ +package math32 + +// Mathematical constants. +const ( + E = float32(2.71828182845904523536028747135266249775724709369995957496696763) // http://oeis.org/A001113 + Pi = float32(3.14159265358979323846264338327950288419716939937510582097494459) // http://oeis.org/A000796 + Phi = float32(1.61803398874989484820458683436563811772030917980576286213544862) // http://oeis.org/A001622 + + Sqrt2 = float32(1.41421356237309504880168872420969807856967187537694807317667974) // http://oeis.org/A002193 + SqrtE = float32(1.64872127070012814684865078781416357165377610071014801157507931) // http://oeis.org/A019774 + SqrtPi = float32(1.77245385090551602729816748334114518279754945612238712821380779) // http://oeis.org/A002161 + SqrtPhi = float32(1.27201964951406896425242246173749149171560804184009624861664038) // http://oeis.org/A139339 + + Ln2 = float32(0.693147180559945309417232121458176568075500134360255254120680009) // http://oeis.org/A002162 + Log2E = float32(1 / Ln2) + Ln10 = float32(2.30258509299404568401799145468436420760110148862877297603332790) // http://oeis.org/A002392 + Log10E = float32(1 / Ln10) +) + +// Floating-point limit values. +// Max is the largest finite value representable by the type. +// SmallestNonzero is the smallest positive, non-zero value representable by the type. +const ( + MaxFloat32 = 3.40282346638528859811704183484516925440e+38 // 2**127 * (2**24 - 1) / 2**23 + SmallestNonzeroFloat32 = 1.401298464324817070923729583289916131280e-45 // 1 / 2**(127 - 1 + 23) +) + +// Integer limit values. +const ( + MaxInt8 = 1<<7 - 1 + MinInt8 = -1 << 7 + MaxInt16 = 1<<15 - 1 + MinInt16 = -1 << 15 + MaxInt32 = 1<<31 - 1 + MinInt32 = -1 << 31 + MaxInt64 = 1<<63 - 1 + MinInt64 = -1 << 63 + MaxUint8 = 1<<8 - 1 + MaxUint16 = 1<<16 - 1 + MaxUint32 = 1<<32 - 1 + MaxUint64 = 1<<64 - 1 +) diff --git a/vendor/github.com/chewxy/math32/copysign.go b/vendor/github.com/chewxy/math32/copysign.go new file mode 100644 index 0000000..dbdabe2 --- /dev/null +++ b/vendor/github.com/chewxy/math32/copysign.go @@ -0,0 +1,8 @@ +package math32 + +import "math" + +func Copysign(x, y float32) float32 { + const sign = 1 << 31 + return math.Float32frombits(math.Float32bits(x)&^sign | math.Float32bits(y)&sign) +} diff --git a/vendor/github.com/chewxy/math32/cosh.go b/vendor/github.com/chewxy/math32/cosh.go new file mode 100644 index 0000000..81bf5ac --- /dev/null +++ b/vendor/github.com/chewxy/math32/cosh.go @@ -0,0 +1,10 @@ +package math32 + +func Cosh(x float32) float32 { + x = Abs(x) + if x > 21 { + return Exp(x) * 0.5 + } + ex := Exp(x) + return (ex + 1/ex) * 0.5 +} diff --git a/vendor/github.com/chewxy/math32/dim.go b/vendor/github.com/chewxy/math32/dim.go new file mode 100644 index 0000000..240862e --- /dev/null +++ b/vendor/github.com/chewxy/math32/dim.go @@ -0,0 +1,77 @@ +package math32 + +// Dim returns the maximum of x-y or 0. +// +// Special cases are: +// +// Dim(+Inf, +Inf) = NaN +// Dim(-Inf, -Inf) = NaN +// Dim(x, NaN) = Dim(NaN, x) = NaN +func Dim(x, y float32) float32 { + return dim(x, y) +} + +func dim(x, y float32) float32 { + return max(x-y, 0) +} + +// Max returns the larger of x or y. +// +// Special cases are: +// +// Max(x, +Inf) = Max(+Inf, x) = +Inf +// Max(x, NaN) = Max(NaN, x) = NaN +// Max(+0, ±0) = Max(±0, +0) = +0 +// Max(-0, -0) = -0 +func Max(x, y float32) float32 { + return max(x, y) +} + +func max(x, y float32) float32 { + // special cases + switch { + case IsInf(x, 1) || IsInf(y, 1): + return Inf(1) + case IsNaN(x) || IsNaN(y): + return NaN() + case x == 0 && x == y: + if Signbit(x) { + return y + } + return x + } + if x > y { + return x + } + return y +} + +// Min returns the smaller of x or y. +// +// Special cases are: +// +// Min(x, -Inf) = Min(-Inf, x) = -Inf +// Min(x, NaN) = Min(NaN, x) = NaN +// Min(-0, ±0) = Min(±0, -0) = -0 +func Min(x, y float32) float32 { + return min(x, y) +} + +func min(x, y float32) float32 { + // special cases + switch { + case IsInf(x, -1) || IsInf(y, -1): + return Inf(-1) + case IsNaN(x) || IsNaN(y): + return NaN() + case x == 0 && x == y: + if Signbit(x) { + return x + } + return y + } + if x < y { + return x + } + return y +} diff --git a/vendor/github.com/chewxy/math32/doc.go b/vendor/github.com/chewxy/math32/doc.go new file mode 100644 index 0000000..2857f6f --- /dev/null +++ b/vendor/github.com/chewxy/math32/doc.go @@ -0,0 +1,34 @@ +/* +Package math32 provides basic constants and mathematical functions for float32 types. + +At its core, it's mostly just a wrapper in form of float32(math.XXX). This applies to the following functions: + Acos + Acosh + Asin + Asinh + Atan + Atan2 + Atanh + Cbrt + Cos + Cosh + Erfc + Gamma + J0 + J1 + Jn + Log10 + Log1p + Log2 + Logb + Pow10 + Sin + Sinh + Tan + Y0 + Y1 + +Everything else is a float32 implementation. Implementation schedule is sporadic an uncertain. But eventually all functions will be replaced + +*/ +package math32 diff --git a/vendor/github.com/chewxy/math32/erf.go b/vendor/github.com/chewxy/math32/erf.go new file mode 100644 index 0000000..465db34 --- /dev/null +++ b/vendor/github.com/chewxy/math32/erf.go @@ -0,0 +1,7 @@ +package math32 + +import "math" + +func Erf(x float32) float32 { + return float32(math.Erf(float64(x))) +} diff --git a/vendor/github.com/chewxy/math32/erfc.go b/vendor/github.com/chewxy/math32/erfc.go new file mode 100644 index 0000000..0568d97 --- /dev/null +++ b/vendor/github.com/chewxy/math32/erfc.go @@ -0,0 +1,7 @@ +package math32 + +import "math" + +func Erfc(x float32) float32 { + return float32(math.Erfc(float64(x))) +} diff --git a/vendor/github.com/chewxy/math32/exp.go b/vendor/github.com/chewxy/math32/exp.go new file mode 100644 index 0000000..0a23e43 --- /dev/null +++ b/vendor/github.com/chewxy/math32/exp.go @@ -0,0 +1,122 @@ +package math32 + +func Exp(x float32) float32 { + if haveArchExp { + return archExp(x) + } + return exp(x) +} + +func exp(x float32) float32 { + const ( + Ln2Hi = float32(6.9313812256e-01) + Ln2Lo = float32(9.0580006145e-06) + Log2e = float32(1.4426950216e+00) + + Overflow = 7.09782712893383973096e+02 + Underflow = -7.45133219101941108420e+02 + NearZero = 1.0 / (1 << 28) // 2**-28 + + LogMax = 0x42b2d4fc // The bitmask of log(FLT_MAX), rounded down. This value is the largest input that can be passed to exp() without producing overflow. + LogMin = 0x42aeac50 // The bitmask of |log(REAL_FLT_MIN)|, rounding down + + ) + // hx := Float32bits(x) & uint32(0x7fffffff) + + // special cases + switch { + case IsNaN(x) || IsInf(x, 1): + return x + case IsInf(x, -1): + return 0 + case x > Overflow: + return Inf(1) + case x < Underflow: + // case hx > LogMax: + // return Inf(1) + // case x < 0 && hx > LogMin: + return 0 + case -NearZero < x && x < NearZero: + return 1 + x + } + + // reduce; computed as r = hi - lo for extra precision. + var k int + switch { + case x < 0: + k = int(Log2e*x - 0.5) + case x > 0: + k = int(Log2e*x + 0.5) + } + hi := x - float32(k)*Ln2Hi + lo := float32(k) * Ln2Lo + + // compute + return expmulti(hi, lo, k) +} + +// Exp2 returns 2**x, the base-2 exponential of x. +// +// Special cases are the same as Exp. +func Exp2(x float32) float32 { + if haveArchExp2 { + return archExp2(x) + } + return exp2(x) +} + +func exp2(x float32) float32 { + const ( + Ln2Hi = 6.9313812256e-01 + Ln2Lo = 9.0580006145e-06 + + Overflow = 1.0239999999999999e+03 + Underflow = -1.0740e+03 + ) + + // special cases + switch { + case IsNaN(x) || IsInf(x, 1): + return x + case IsInf(x, -1): + return 0 + case x > Overflow: + return Inf(1) + case x < Underflow: + return 0 + } + + // argument reduction; x = r×lg(e) + k with |r| ≤ ln(2)/2. + // computed as r = hi - lo for extra precision. + var k int + switch { + case x > 0: + k = int(x + 0.5) + case x < 0: + k = int(x - 0.5) + } + t := x - float32(k) + hi := t * Ln2Hi + lo := -t * Ln2Lo + + // compute + return expmulti(hi, lo, k) +} + +// exp1 returns e**r × 2**k where r = hi - lo and |r| ≤ ln(2)/2. +func expmulti(hi, lo float32, k int) float32 { + const ( + P1 = float32(1.6666667163e-01) /* 0x3e2aaaab */ + P2 = float32(-2.7777778450e-03) /* 0xbb360b61 */ + P3 = float32(6.6137559770e-05) /* 0x388ab355 */ + P4 = float32(-1.6533901999e-06) /* 0xb5ddea0e */ + P5 = float32(4.1381369442e-08) /* 0x3331bb4c */ + ) + + r := hi - lo + t := r * r + c := r - t*(P1+t*(P2+t*(P3+t*(P4+t*P5)))) + y := 1 - ((lo - (r*c)/(2-c)) - hi) + // TODO(rsc): make sure Ldexp can handle boundary k + return Ldexp(y, k) +} diff --git a/vendor/github.com/chewxy/math32/exp2_asm.go b/vendor/github.com/chewxy/math32/exp2_asm.go new file mode 100644 index 0000000..3d2e1d6 --- /dev/null +++ b/vendor/github.com/chewxy/math32/exp2_asm.go @@ -0,0 +1,14 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !noasm && !tinygo && (amd64 || 386 || arm || ppc64le || wasm) +// +build !noasm +// +build !tinygo +// +build amd64 386 arm ppc64le wasm + +package math32 + +const haveArchExp2 = true + +func archExp2(x float32) float32 diff --git a/vendor/github.com/chewxy/math32/exp2_noasm.go b/vendor/github.com/chewxy/math32/exp2_noasm.go new file mode 100644 index 0000000..13ca9c4 --- /dev/null +++ b/vendor/github.com/chewxy/math32/exp2_noasm.go @@ -0,0 +1,14 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build noasm || tinygo || !(amd64 || 386 || arm || ppc64le || wasm) +// +build noasm tinygo !amd64,!386,!arm,!ppc64le,!wasm + +package math32 + +const haveArchExp2 = false + +func archExp2(x float32) float32 { + panic("not implemented") +} diff --git a/vendor/github.com/chewxy/math32/exp_amd64.s b/vendor/github.com/chewxy/math32/exp_amd64.s new file mode 100644 index 0000000..a0a30b4 --- /dev/null +++ b/vendor/github.com/chewxy/math32/exp_amd64.s @@ -0,0 +1,114 @@ +//go:build !tinygo && !noasm +// Copyright 2014 Xuanyi Chew. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +// +// The original code is lifted from the Go standard library which is governed by +// a BSD-style licence which can be found here: https://golang.org/LICENSE + +#include "textflag.h" + +// The method is based on a paper by Naoki Shibata: "Efficient evaluation +// methods of elementary functions suitable for SIMD computation", Proc. +// of International Supercomputing Conference 2010 (ISC'10), pp. 25 -- 32 +// (May 2010). The paper is available at +// http://www.springerlink.com/content/340228x165742104/ +// +// The original code and the constants below are from the author's +// implementation available at http://freshmeat.net/projects/sleef. +// The README file says, "The software is in public domain. +// You can use the software without any obligation." +// +// This code is a simplified version of the original. +// The magic numbers for the float32 are lifted from the same project + + +#define LN2 0.693147182464599609375 // log_e(2) +#define LOG2E 1.44269502162933349609375 // 1/LN2 +#define LN2U 0.693145751953125 // upper half LN2 +#define LN2L 1.428606765330187045e-06 // lower half LN2 +#define T0 1.0 +#define T1 0.5 +#define T2 0.166665524244308471679688 +#define T3 0.0416710823774337768554688 +#define T4 0.00836596917361021041870117 +#define PosInf 0x7F800000 +#define NegInf 0xFF800000 + +// func archExp(x float32) float32 +TEXT ·archExp(SB),NOSPLIT,$0 +// test bits for not-finite + MOVL x+0(FP), BX + MOVQ $~(1<<31), AX // sign bit mask + MOVL BX, DX + ANDL AX, DX + MOVL $PosInf, AX + CMPL AX, DX + JLE notFinite + MOVL BX, X0 + MOVSS $LOG2E, X1 + MULSS X0, X1 + CVTSS2SL X1, BX // BX = exponent + CVTSL2SS BX, X1 + MOVSS $LN2U, X2 + MULSS X1, X2 + SUBSS X2, X0 + MOVSS $LN2L, X2 + MULSS X1, X2 + SUBSS X2, X0 + // reduce argument + MULSS $0.0625, X0 + // Taylor series evaluation + ADDSS $T4, X1 + MULSS X0, X1 + ADDSS $T3, X1 + MULSS X0, X1 + ADDSS $T2, X1 + MULSS X0, X1 + ADDSS $T1, X1 + MULSS X0, X1 + ADDSS $T0, X1 + MULSS X1, X0 + MOVSS $2.0, X1 + ADDSS X0, X1 + MULSS X1, X0 + MOVSS $2.0, X1 + ADDSS X0, X1 + MULSS X1, X0 + MOVSS $2.0, X1 + ADDSS X0, X1 + MULSS X1, X0 + MOVSS $2.0, X1 + ADDSS X0, X1 + MULSS X1, X0 + ADDSS $1.0, X0 + // return fr * 2**exponent + MOVL $0x7F, AX // bias + ADDL AX, BX + JLE underflow + CMPL BX, $0xFF + JGE overflow + MOVL $23, CX + SHLQ CX, BX + MOVL BX, X1 + MULSS X1, X0 + MOVSS X0, ret+8(FP) + RET +notFinite: + // test bits for -Inf + MOVL $NegInf, AX + CMPQ AX, BX + JNE notNegInf + // -Inf, return 0 +underflow: // return 0 + MOVL $0, AX + MOVL AX, ret+8(FP) + RET +overflow: // return +Inf + MOVL $PosInf, BX +notNegInf: // NaN or +Inf, return x + MOVL BX, ret+8(FP) + RET + +TEXT ·archExp2(SB),NOSPLIT,$0 + JMP ·exp2(SB) diff --git a/vendor/github.com/chewxy/math32/exp_asm.go b/vendor/github.com/chewxy/math32/exp_asm.go new file mode 100644 index 0000000..5b6f7d2 --- /dev/null +++ b/vendor/github.com/chewxy/math32/exp_asm.go @@ -0,0 +1,14 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !noasm && !tinygo && (amd64 || 386 || arm || ppc64le || wasm || s390x) +// +build !noasm +// +build !tinygo +// +build amd64 386 arm ppc64le wasm s390x + +package math32 + +const haveArchExp = true + +func archExp(x float32) float32 diff --git a/vendor/github.com/chewxy/math32/exp_noasm.go b/vendor/github.com/chewxy/math32/exp_noasm.go new file mode 100644 index 0000000..838022b --- /dev/null +++ b/vendor/github.com/chewxy/math32/exp_noasm.go @@ -0,0 +1,14 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build noasm || tinygo || !(amd64 || 386 || arm || ppc64le || wasm || s390x) +// +build noasm tinygo !amd64,!386,!arm,!ppc64le,!wasm,!s390x + +package math32 + +const haveArchExp = false + +func archExp(x float32) float32 { + panic("not implemented") +} diff --git a/vendor/github.com/chewxy/math32/expm1f.go b/vendor/github.com/chewxy/math32/expm1f.go new file mode 100644 index 0000000..fd94deb --- /dev/null +++ b/vendor/github.com/chewxy/math32/expm1f.go @@ -0,0 +1,240 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math32 + +// The original C code, the long comment, and the constants +// below are from FreeBSD's /usr/src/lib/msun/src/s_expm1.c +// and came with this notice. The go code is a simplified +// version of the original C. +// +// ==================================================== +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// +// Developed at SunPro, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== +// +// expm1(x) +// Returns exp(x)-1, the exponential of x minus 1. +// +// Method +// 1. Argument reduction: +// Given x, find r and integer k such that +// +// x = k*ln2 + r, |r| <= 0.5*ln2 ~ 0.34658 +// +// Here a correction term c will be computed to compensate +// the error in r when rounded to a floating-point number. +// +// 2. Approximating expm1(r) by a special rational function on +// the interval [0,0.34658]: +// Since +// r*(exp(r)+1)/(exp(r)-1) = 2+ r**2/6 - r**4/360 + ... +// we define R1(r*r) by +// r*(exp(r)+1)/(exp(r)-1) = 2+ r**2/6 * R1(r*r) +// That is, +// R1(r**2) = 6/r *((exp(r)+1)/(exp(r)-1) - 2/r) +// = 6/r * ( 1 + 2.0*(1/(exp(r)-1) - 1/r)) +// = 1 - r**2/60 + r**4/2520 - r**6/100800 + ... +// We use a special Reme algorithm on [0,0.347] to generate +// a polynomial of degree 5 in r*r to approximate R1. The +// maximum error of this polynomial approximation is bounded +// by 2**-61. In other words, +// R1(z) ~ 1.0 + Q1*z + Q2*z**2 + Q3*z**3 + Q4*z**4 + Q5*z**5 +// where Q1 = -1.6666666666666567384E-2, +// Q2 = 3.9682539681370365873E-4, +// Q3 = -9.9206344733435987357E-6, +// Q4 = 2.5051361420808517002E-7, +// Q5 = -6.2843505682382617102E-9; +// (where z=r*r, and the values of Q1 to Q5 are listed below) +// with error bounded by +// | 5 | -61 +// | 1.0+Q1*z+...+Q5*z - R1(z) | <= 2 +// | | +// +// expm1(r) = exp(r)-1 is then computed by the following +// specific way which minimize the accumulation rounding error: +// 2 3 +// r r [ 3 - (R1 + R1*r/2) ] +// expm1(r) = r + --- + --- * [--------------------] +// 2 2 [ 6 - r*(3 - R1*r/2) ] +// +// To compensate the error in the argument reduction, we use +// expm1(r+c) = expm1(r) + c + expm1(r)*c +// ~ expm1(r) + c + r*c +// Thus c+r*c will be added in as the correction terms for +// expm1(r+c). Now rearrange the term to avoid optimization +// screw up: +// ( 2 2 ) +// ({ ( r [ R1 - (3 - R1*r/2) ] ) } r ) +// expm1(r+c)~r - ({r*(--- * [--------------------]-c)-c} - --- ) +// ({ ( 2 [ 6 - r*(3 - R1*r/2) ] ) } 2 ) +// ( ) +// +// = r - E +// 3. Scale back to obtain expm1(x): +// From step 1, we have +// expm1(x) = either 2**k*[expm1(r)+1] - 1 +// = or 2**k*[expm1(r) + (1-2**-k)] +// 4. Implementation notes: +// (A). To save one multiplication, we scale the coefficient Qi +// to Qi*2**i, and replace z by (x**2)/2. +// (B). To achieve maximum accuracy, we compute expm1(x) by +// (i) if x < -56*ln2, return -1.0, (raise inexact if x!=inf) +// (ii) if k=0, return r-E +// (iii) if k=-1, return 0.5*(r-E)-0.5 +// (iv) if k=1 if r < -0.25, return 2*((r+0.5)- E) +// else return 1.0+2.0*(r-E); +// (v) if (k<-2||k>56) return 2**k(1-(E-r)) - 1 (or exp(x)-1) +// (vi) if k <= 20, return 2**k((1-2**-k)-(E-r)), else +// (vii) return 2**k(1-((E+2**-k)-r)) +// +// Special cases: +// expm1(INF) is INF, expm1(NaN) is NaN; +// expm1(-INF) is -1, and +// for finite argument, only expm1(0)=0 is exact. +// +// Accuracy: +// according to an error analysis, the error is always less than +// 1 ulp (unit in the last place). +// +// Misc. info. +// For IEEE double +// if x > 7.09782712893383973096e+02 then expm1(x) overflow +// +// Constants: +// The hexadecimal values are the intended ones for the following +// constants. The decimal values may be used, provided that the +// compiler will convert from decimal to binary accurately enough +// to produce the hexadecimal values shown. +// + +// Expm1 returns e**x - 1, the base-e exponential of x minus 1. +// It is more accurate than Exp(x) - 1 when x is near zero. +// +// Special cases are: +// Expm1(+Inf) = +Inf +// Expm1(-Inf) = -1 +// Expm1(NaN) = NaN +// Very large values overflow to -1 or +Inf. +func Expm1(x float32) float32 { + return expm1(x) +} + +func expm1(x float32) float32 { + const ( + Othreshold = 89.415985 // 0x42b2d4fc + Ln2X27 = 1.871497344970703125e+01 // 0x4195b844 + Ln2HalfX3 = 1.0397207736968994140625 // 0x3F851592 + Ln2Half = 3.465735912322998046875e-01 // 0x3eb17218 + Ln2Hi = 6.9313812256e-01 // 0x3f317180 + Ln2Lo = 9.0580006145e-06 // 0x3717f7d1 + InvLn2 = 1.4426950216e+00 // 0x3fb8aa3b + Tiny = 1.0 / (1 << 54) // 2**-54 = 0x3c90000000000000 + + /* scaled coefficients related to expm1 */ + Q1 = -3.3333335072e-02 /* 0xbd088889 */ + Q2 = 1.5873016091e-03 /* 0x3ad00d01 */ + Q3 = -7.9365076090e-05 /* 0xb8a670cd */ + Q4 = 4.0082177293e-06 /* 0x36867e54 */ + Q5 = -2.0109921195e-07 /* 0xb457edbb */ + ) + + // special cases + switch { + case IsInf(x, 1) || IsNaN(x): + return x + case IsInf(x, -1): + return -1 + } + + absx := x + sign := false + if x < 0 { + absx = -absx + sign = true + } + + // filter out huge argument + if absx >= Ln2X27 { // if |x| >= 27 * ln2 + if sign { + return -1 // x < -56*ln2, return -1 + } + if absx >= Othreshold { // if |x| >= 89.415985... + return Inf(1) + } + } + + // argument reduction + var c float32 + var k int + if absx > Ln2Half { // if |x| > 0.5 * ln2 + var hi, lo float32 + if absx < Ln2HalfX3 { // and |x| < 1.5 * ln2 + if !sign { + hi = x - Ln2Hi + lo = Ln2Lo + k = 1 + } else { + hi = x + Ln2Hi + lo = -Ln2Lo + k = -1 + } + } else { + if !sign { + k = int(InvLn2*x + 0.5) + } else { + k = int(InvLn2*x - 0.5) + } + t := float32(k) + hi = x - t*Ln2Hi // t * Ln2Hi is exact here + lo = t * Ln2Lo + } + x = hi - lo + c = (hi - x) - lo + } else if absx < Tiny { // when |x| < 2**-54, return x + return x + } else { + k = 0 + } + + // x is now in primary range + hfx := 0.5 * x + hxs := x * hfx + r1 := 1 + hxs*(Q1+hxs*(Q2+hxs*(Q3+hxs*(Q4+hxs*Q5)))) + t := 3 - r1*hfx + e := hxs * ((r1 - t) / (6.0 - x*t)) + if k != 0 { + e = (x*(e-c) - c) + e -= hxs + switch { + case k == -1: + return 0.5*(x-e) - 0.5 + case k == 1: + if x < -0.25 { + return -2 * (e - (x + 0.5)) + } + return 1 + 2*(x-e) + case k <= -2 || k > 56: // suffice to return exp(x)-1 + y := 1 - (e - x) + y = Float32frombits(Float32bits(y) + uint32(k)<<23) // add k to y's exponent + return y - 1 + } + if k < 20 { + t := Float32frombits(0x3f800000 - (0x1000000 >> uint(k))) // t=1-2**-k + y := t - (e - x) + y = Float32frombits(Float32bits(y) + uint32(k)<<23) // add k to y's exponent + return y + } + t := Float32frombits(uint32(0x7f-k) << 23) // 2**-k + y := x - (e + t) + y += 1 + y = Float32frombits(Float32bits(y) + uint32(k)<<23) // add k to y's exponent + return y + } + return x - (x*e - hxs) // c is 0 +} diff --git a/vendor/github.com/chewxy/math32/floor.go b/vendor/github.com/chewxy/math32/floor.go new file mode 100644 index 0000000..2f14d70 --- /dev/null +++ b/vendor/github.com/chewxy/math32/floor.go @@ -0,0 +1,58 @@ +package math32 + +// Floor returns the greatest integer value less than or equal to x. +// +// Special cases are: +// Floor(±0) = ±0 +// Floor(±Inf) = ±Inf +// Floor(NaN) = NaN +func Floor(x float32) float32 { + return floor(x) +} + +func floor(x float32) float32 { + if x == 0 || IsNaN(x) || IsInf(x, 0) { + return x + } + if x < 0 { + d, fract := Modf(-x) + if fract != 0.0 { + d = d + 1 + } + return -d + } + d, _ := Modf(x) + return d +} + +// Ceil returns the least integer value greater than or equal to x. +// +// Special cases are: +// Ceil(±0) = ±0 +// Ceil(±Inf) = ±Inf +// Ceil(NaN) = NaN +func Ceil(x float32) float32 { + return ceil(x) +} + +func ceil(x float32) float32 { + return -Floor(-x) +} + +// Trunc returns the integer value of x. +// +// Special cases are: +// Trunc(±0) = ±0 +// Trunc(±Inf) = ±Inf +// Trunc(NaN) = NaN +func Trunc(x float32) float32 { + return trunc(x) +} + +func trunc(x float32) float32 { + if x == 0 || IsNaN(x) || IsInf(x, 0) { + return x + } + d, _ := Modf(x) + return d +} diff --git a/vendor/github.com/chewxy/math32/frexp.go b/vendor/github.com/chewxy/math32/frexp.go new file mode 100644 index 0000000..ebf66b7 --- /dev/null +++ b/vendor/github.com/chewxy/math32/frexp.go @@ -0,0 +1,31 @@ +package math32 + +// Frexp breaks f into a normalized fraction +// and an integral power of two. +// It returns frac and exp satisfying f == frac × 2**exp, +// with the absolute value of frac in the interval [½, 1). +// +// Special cases are: +// Frexp(±0) = ±0, 0 +// Frexp(±Inf) = ±Inf, 0 +// Frexp(NaN) = NaN, 0 +func Frexp(f float32) (frac float32, exp int) { + return frexp(f) +} + +func frexp(f float32) (frac float32, exp int) { + // special cases + switch { + case f == 0: + return f, 0 // correctly return -0 + case IsInf(f, 0) || IsNaN(f): + return f, 0 + } + f, exp = normalize(f) + x := Float32bits(f) + exp += int((x>>shift)&mask) - bias + 1 + x &^= mask << shift + x |= (-1 + bias) << shift + frac = Float32frombits(x) + return +} diff --git a/vendor/github.com/chewxy/math32/gamma.go b/vendor/github.com/chewxy/math32/gamma.go new file mode 100644 index 0000000..07c19b2 --- /dev/null +++ b/vendor/github.com/chewxy/math32/gamma.go @@ -0,0 +1,7 @@ +package math32 + +import "math" + +func Gamma(x float32) float32 { + return float32(math.Gamma(float64(x))) +} diff --git a/vendor/github.com/chewxy/math32/hypot.go b/vendor/github.com/chewxy/math32/hypot.go new file mode 100644 index 0000000..8836e0c --- /dev/null +++ b/vendor/github.com/chewxy/math32/hypot.go @@ -0,0 +1,41 @@ +package math32 + +/* + Hypot -- sqrt(p*p + q*q), but overflows only if the result does. +*/ + +// Hypot returns Sqrt(p*p + q*q), taking care to avoid +// unnecessary overflow and underflow. +// +// Special cases are: +// Hypot(±Inf, q) = +Inf +// Hypot(p, ±Inf) = +Inf +// Hypot(NaN, q) = NaN +// Hypot(p, NaN) = NaN +func Hypot(p, q float32) float32 { + return hypot(p, q) +} + +func hypot(p, q float32) float32 { + // special cases + switch { + case IsInf(p, 0) || IsInf(q, 0): + return Inf(1) + case IsNaN(p) || IsNaN(q): + return NaN() + } + if p < 0 { + p = -p + } + if q < 0 { + q = -q + } + if p < q { + p, q = q, p + } + if p == 0 { + return 0 + } + q = q / p + return p * Sqrt(1+q*q) +} diff --git a/vendor/github.com/chewxy/math32/j0.go b/vendor/github.com/chewxy/math32/j0.go new file mode 100644 index 0000000..0f5023c --- /dev/null +++ b/vendor/github.com/chewxy/math32/j0.go @@ -0,0 +1,7 @@ +package math32 + +import "math" + +func J0(x float32) float32 { + return float32(math.J0(float64(x))) +} diff --git a/vendor/github.com/chewxy/math32/j1.go b/vendor/github.com/chewxy/math32/j1.go new file mode 100644 index 0000000..e86e72e --- /dev/null +++ b/vendor/github.com/chewxy/math32/j1.go @@ -0,0 +1,7 @@ +package math32 + +import "math" + +func J1(x float32) float32 { + return float32(math.J1(float64(x))) +} diff --git a/vendor/github.com/chewxy/math32/jn.go b/vendor/github.com/chewxy/math32/jn.go new file mode 100644 index 0000000..e5b474a --- /dev/null +++ b/vendor/github.com/chewxy/math32/jn.go @@ -0,0 +1,11 @@ +package math32 + +import "math" + +func Jn(n int, x float32) float32 { + return float32(math.Jn(n, float64(x))) +} + +func Yn(n int, x float32) float32 { + return float32(math.Yn(n, float64(x))) +} diff --git a/vendor/github.com/chewxy/math32/ldexp.go b/vendor/github.com/chewxy/math32/ldexp.go new file mode 100644 index 0000000..637bbd2 --- /dev/null +++ b/vendor/github.com/chewxy/math32/ldexp.go @@ -0,0 +1,43 @@ +package math32 + +// Ldexp is the inverse of Frexp. +// It returns frac × 2**exp. +// +// Special cases are: +// Ldexp(±0, exp) = ±0 +// Ldexp(±Inf, exp) = ±Inf +// Ldexp(NaN, exp) = NaN +func Ldexp(frac float32, exp int) float32 { + return ldexp(frac, exp) +} + +func ldexp(frac float32, exp int) float32 { + // special cases + switch { + case frac == 0: + return frac // correctly return -0 + case IsInf(frac, 0) || IsNaN(frac): + return frac + } + frac, e := normalize(frac) + exp += e + x := Float32bits(frac) + exp += int(x>>shift)&mask - bias + if exp < -149 { + return Copysign(0, frac) // underflow + } + if exp > 127 { // overflow + if frac < 0 { + return Inf(-1) + } + return Inf(1) + } + var m float32 = 1 + if exp < -(127 - 1) { // denormal + exp += shift + m = 1.0 / (1 << 23) // 1/(2**-23) + } + x &^= mask << shift + x |= uint32(exp+bias) << shift + return m * Float32frombits(x) +} diff --git a/vendor/github.com/chewxy/math32/lgamma.go b/vendor/github.com/chewxy/math32/lgamma.go new file mode 100644 index 0000000..ed4b7d2 --- /dev/null +++ b/vendor/github.com/chewxy/math32/lgamma.go @@ -0,0 +1,8 @@ +package math32 + +import "math" + +func Lgamma(x float32) (lgamma float32, sign int) { + lg, sign := math.Lgamma(float64(x)) + return float32(lg), sign +} diff --git a/vendor/github.com/chewxy/math32/log.go b/vendor/github.com/chewxy/math32/log.go new file mode 100644 index 0000000..f92b1da --- /dev/null +++ b/vendor/github.com/chewxy/math32/log.go @@ -0,0 +1,124 @@ +package math32 + +/* + Floating-point logarithm. +*/ + +// The original C code, the long comment, and the constants +// below are from FreeBSD's /usr/src/lib/msun/src/e_log.c +// and came with this notice. The go code is a simpler +// version of the original C. +// +// ==================================================== +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// +// Developed at SunPro, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== +// +// __ieee754_log(x) +// Return the logarithm of x +// +// Method : +// 1. Argument Reduction: find k and f such that +// x = 2**k * (1+f), +// where sqrt(2)/2 < 1+f < sqrt(2) . +// +// 2. Approximation of log(1+f). +// Let s = f/(2+f) ; based on log(1+f) = log(1+s) - log(1-s) +// = 2s + 2/3 s**3 + 2/5 s**5 + ....., +// = 2s + s*R +// We use a special Reme algorithm on [0,0.1716] to generate +// a polynomial of degree 14 to approximate R. The maximum error +// of this polynomial approximation is bounded by 2**-58.45. In +// other words, +// 2 4 6 8 10 12 14 +// R(z) ~ L1*s +L2*s +L3*s +L4*s +L5*s +L6*s +L7*s +// (the values of L1 to L7 are listed in the program) and +// | 2 14 | -58.45 +// | L1*s +...+L7*s - R(z) | <= 2 +// | | +// Note that 2s = f - s*f = f - hfsq + s*hfsq, where hfsq = f*f/2. +// In order to guarantee error in log below 1ulp, we compute log by +// log(1+f) = f - s*(f - R) (if f is not too large) +// log(1+f) = f - (hfsq - s*(hfsq+R)). (better accuracy) +// +// 3. Finally, log(x) = k*Ln2 + log(1+f). +// = k*Ln2_hi+(f-(hfsq-(s*(hfsq+R)+k*Ln2_lo))) +// Here Ln2 is split into two floating point number: +// Ln2_hi + Ln2_lo, +// where n*Ln2_hi is always exact for |n| < 2000. +// +// Special cases: +// log(x) is NaN with signal if x < 0 (including -INF) ; +// log(+INF) is +INF; log(0) is -INF with signal; +// log(NaN) is that NaN with no signal. +// +// Accuracy: +// according to an error analysis, the error is always less than +// 1 ulp (unit in the last place). +// +// Constants: +// The hexadecimal values are the intended ones for the following +// constants. The decimal values may be used, provided that the +// compiler will convert from decimal to binary accurately enough +// to produce the hexadecimal values shown. + +// Log returns the natural logarithm of x. +// +// Special cases are: +// Log(+Inf) = +Inf +// Log(0) = -Inf +// Log(x < 0) = NaN +// Log(NaN) = NaN +func Log(x float32) float32 { + if haveArchLog { + return archLog(x) + } + return log(x) +} + +func log(x float32) float32 { + const ( + Ln2Hi = 6.9313812256e-01 /* 0x3f317180 */ + Ln2Lo = 9.0580006145e-06 /* 0x3717f7d1 */ + L1 = 6.6666668653e-01 /* 0x3f2aaaab */ + L2 = 4.0000000596e-01 /* 0x3ecccccd */ + L3 = 2.8571429849e-01 /* 0x3e924925 */ + L4 = 2.2222198546e-01 /* 0x3e638e29 */ + L5 = 1.8183572590e-01 /* 0x3e3a3325 */ + L6 = 1.5313838422e-01 /* 0x3e1cd04f */ + L7 = 1.4798198640e-01 /* 0x3e178897 */ + ) + + // special cases + switch { + case IsNaN(x) || IsInf(x, 1): + return x + case x < 0: + return NaN() + case x == 0: + return Inf(-1) + } + + // reduce + f1, ki := Frexp(x) + if f1 < Sqrt2/2 { + f1 *= 2 + ki-- + } + f := f1 - 1 + k := float32(ki) + + // compute + s := f / (2 + f) + s2 := s * s + s4 := s2 * s2 + t1 := s2 * (L1 + s4*(L3+s4*(L5+s4*L7))) + t2 := s4 * (L2 + s4*(L4+s4*L6)) + R := t1 + t2 + hfsq := 0.5 * f * f + return k*Ln2Hi - ((hfsq - (s*(hfsq+R) + k*Ln2Lo)) - f) +} diff --git a/vendor/github.com/chewxy/math32/log10.go b/vendor/github.com/chewxy/math32/log10.go new file mode 100644 index 0000000..c1fee28 --- /dev/null +++ b/vendor/github.com/chewxy/math32/log10.go @@ -0,0 +1,7 @@ +package math32 + +import "math" + +func Log10(x float32) float32 { + return float32(math.Log10(float64(x))) +} diff --git a/vendor/github.com/chewxy/math32/log1p.go b/vendor/github.com/chewxy/math32/log1p.go new file mode 100644 index 0000000..490b9da --- /dev/null +++ b/vendor/github.com/chewxy/math32/log1p.go @@ -0,0 +1,7 @@ +package math32 + +import "math" + +func Log1p(x float32) float32 { + return float32(math.Log1p(float64(x))) +} diff --git a/vendor/github.com/chewxy/math32/log2.go b/vendor/github.com/chewxy/math32/log2.go new file mode 100644 index 0000000..0063a2a --- /dev/null +++ b/vendor/github.com/chewxy/math32/log2.go @@ -0,0 +1,7 @@ +package math32 + +import "math" + +func Log2(x float32) float32 { + return float32(math.Log2(float64(x))) +} diff --git a/vendor/github.com/chewxy/math32/log_amd64.s b/vendor/github.com/chewxy/math32/log_amd64.s new file mode 100644 index 0000000..1027217 --- /dev/null +++ b/vendor/github.com/chewxy/math32/log_amd64.s @@ -0,0 +1,112 @@ +//go:build !tinygo && !noasm +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSS-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +#define HSqrt2 7.07106781186547524401e-01 // sqrt(2)/2 +#define Ln2Hi 6.9313812256e-01 // 0x3f317180 +#define Ln2Lo 9.0580006145e-06 // 0x3717f7d1 +#define L1 6.6666668653e-01 // 0x3f2aaaab +#define L2 4.0000000596e-01 // 0x3ecccccd +#define L3 2.8571429849e-01 // 0x3e924925 +#define L4 2.2222198546e-01 // 0x3e638e29 +#define L5 1.8183572590e-01 // 0x3e3a3325 +#define L6 1.5313838422e-01 // 0x3e1cd04f +#define L7 1.4798198640e-01 // 0x3e178897 +#define NaN 0x7FE00000 +#define PosInf 0x7F800000 +#define NegInf 0xFF800000 + +// func archLog(x float64) float64 +TEXT ·archLog(SB),NOSPLIT,$0 + // test bits for special cases + MOVL x+0(FP), BX + MOVQ $~(1<<31), AX // sign bit mask + ANDQ BX, AX + JEQ isZero + MOVL $0, AX + CMPL AX, BX + JGT isNegative + MOVL $PosInf, AX + CMPQ AX, BX + JLE isInfOrNaN + // f1, ki := math.Frexp(x); k := float64(ki) + MOVL BX, X0 + MOVL $0x007FFFFF, AX + MOVL AX, X2 + ANDPS X0, X2 + MOVSS $0.5, X0 // 0x3FE0000000000000 + ORPS X0, X2 // X2= f1 + SHRQ $23, BX + ANDL $0xFF, BX + SUBL $0x7E, BX + CVTSL2SS BX, X1 // x1= k, x2= f1 + // if f1 < math.Sqrt2/2 { k -= 1; f1 *= 2 } + MOVSS $HSqrt2, X0 // x0= 0.7071, x1= k, x2= f1 + CMPSS X2, X0, 5 // cmpnlt; x0= 0 or ^0, x1= k, x2 = f1 + MOVSS $1.0, X3 // x0= 0 or ^0, x1= k, x2 = f1, x3= 1 + ANDPS X0, X3 // x0= 0 or ^0, x1= k, x2 = f1, x3= 0 or 1 + SUBSS X3, X1 // x0= 0 or ^0, x1= k, x2 = f1, x3= 0 or 1 + MOVSS $1.0, X0 // x0= 1, x1= k, x2= f1, x3= 0 or 1 + ADDSS X0, X3 // x0= 1, x1= k, x2= f1, x3= 1 or 2 + MULSS X3, X2 // x0= 1, x1= k, x2= f1 + // f := f1 - 1 + SUBSS X0, X2 // x1= k, x2= f + // s := f / (2 + f) + MOVSS $2.0, X0 + ADDSS X2, X0 + MOVUPS X2, X3 + DIVSS X0, X3 // x1=k, x2= f, x3= s + // s2 := s * s + MOVUPS X3, X4 // x1= k, x2= f, x3= s + MULSS X4, X4 // x1= k, x2= f, x3= s, x4= s2 + // s4 := s2 * s2 + MOVUPS X4, X5 // x1= k, x2= f, x3= s, x4= s2 + MULSS X5, X5 // x1= k, x2= f, x3= s, x4= s2, x5= s4 + // t1 := s2 * (L1 + s4*(L3+s4*(L5+s4*L7))) + MOVSS $L7, X6 + MULSS X5, X6 + ADDSS $L5, X6 + MULSS X5, X6 + ADDSS $L3, X6 + MULSS X5, X6 + ADDSS $L1, X6 + MULSS X6, X4 // x1= k, x2= f, x3= s, x4= t1, x5= s4 + // t2 := s4 * (L2 + s4*(L4+s4*L6)) + MOVSS $L6, X6 + MULSS X5, X6 + ADDSS $L4, X6 + MULSS X5, X6 + ADDSS $L2, X6 + MULSS X6, X5 // x1= k, x2= f, x3= s, x4= t1, x5= t2 + // R := t1 + t2 + ADDSS X5, X4 // x1= k, x2= f, x3= s, x4= R + // hfsq := 0.5 * f * f + MOVSS $0.5, X0 + MULSS X2, X0 + MULSS X2, X0 // x0= hfsq, x1= k, x2= f, x3= s, x4= R + // return k*Ln2Hi - ((hfsq - (s*(hfsq+R) + k*Ln2Lo)) - f) + ADDSS X0, X4 // x0= hfsq, x1= k, x2= f, x3= s, x4= hfsq+R + MULSS X4, X3 // x0= hfsq, x1= k, x2= f, x3= s*(hfsq+R) + MOVSS $Ln2Lo, X4 + MULSS X1, X4 // x4= k*Ln2Lo + ADDSS X4, X3 // x0= hfsq, x1= k, x2= f, x3= s*(hfsq+R)+k*Ln2Lo + SUBSS X3, X0 // x0= hfsq-(s*(hfsq+R)+k*Ln2Lo), x1= k, x2= f + SUBSS X2, X0 // x0= (hfsq-(s*(hfsq+R)+k*Ln2Lo))-f, x1= k + MULSS $Ln2Hi, X1 // x0= (hfsq-(s*(hfsq+R)+k*Ln2Lo))-f, x1= k*Ln2Hi + SUBSS X0, X1 // x1= k*Ln2Hi-((hfsq-(s*(hfsq+R)+k*Ln2Lo))-f) + MOVSS X1, ret+8(FP) + RET +isInfOrNaN: + MOVL BX, ret+8(FP) // +Inf or NaN, return x + RET +isNegative: + MOVL $NaN, AX + MOVL AX, ret+8(FP) // return NaN + RET +isZero: + MOVL $NegInf, AX + MOVL AX, ret+8(FP) // return -Inf + RET diff --git a/vendor/github.com/chewxy/math32/log_asm.go b/vendor/github.com/chewxy/math32/log_asm.go new file mode 100644 index 0000000..9491e1a --- /dev/null +++ b/vendor/github.com/chewxy/math32/log_asm.go @@ -0,0 +1,14 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !noasm && !tinygo && (amd64 || arm || s390x || 386 || arm64 || ppc64le || wasm) +// +build !noasm +// +build !tinygo +// +build amd64 arm s390x 386 arm64 ppc64le wasm + +package math32 + +const haveArchLog = true + +func archLog(x float32) float32 diff --git a/vendor/github.com/chewxy/math32/log_noasm.go b/vendor/github.com/chewxy/math32/log_noasm.go new file mode 100644 index 0000000..e7eb6f1 --- /dev/null +++ b/vendor/github.com/chewxy/math32/log_noasm.go @@ -0,0 +1,14 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build noasm || tinygo || (!amd64 && !arm && !s390x && !386 && !arm64 && !ppc64le && !wasm) +// +build noasm tinygo !amd64,!arm,!s390x,!386,!arm64,!ppc64le,!wasm + +package math32 + +const haveArchLog = false + +func archLog(x float32) float32 { + panic("not implemented") +} diff --git a/vendor/github.com/chewxy/math32/logb.go b/vendor/github.com/chewxy/math32/logb.go new file mode 100644 index 0000000..8e5f353 --- /dev/null +++ b/vendor/github.com/chewxy/math32/logb.go @@ -0,0 +1,11 @@ +package math32 + +import "math" + +func Logb(x float32) float32 { + return float32(math.Logb(float64(x))) +} + +func Ilogb(x float32) int { + return math.Ilogb(float64(x)) +} diff --git a/vendor/github.com/chewxy/math32/mod.go b/vendor/github.com/chewxy/math32/mod.go new file mode 100644 index 0000000..5a2f886 --- /dev/null +++ b/vendor/github.com/chewxy/math32/mod.go @@ -0,0 +1,44 @@ +package math32 + +// Mod returns the floating-point remainder of x/y. +// The magnitude of the result is less than y and its +// sign agrees with that of x. +// +// Special cases are: +// Mod(±Inf, y) = NaN +// Mod(NaN, y) = NaN +// Mod(x, 0) = NaN +// Mod(x, ±Inf) = x +// Mod(x, NaN) = NaN +func Mod(x, y float32) float32 { + return mod(x, y) +} + +func mod(x, y float32) float32 { + if y == 0 || IsInf(x, 0) || IsNaN(x) || IsNaN(y) { + return NaN() + } + if y < 0 { + y = -y + } + + yfr, yexp := Frexp(y) + sign := false + r := x + if x < 0 { + r = -x + sign = true + } + + for r >= y { + rfr, rexp := Frexp(r) + if rfr < yfr { + rexp = rexp - 1 + } + r = r - Ldexp(y, rexp-yexp) + } + if sign { + r = -r + } + return r +} diff --git a/vendor/github.com/chewxy/math32/modf.go b/vendor/github.com/chewxy/math32/modf.go new file mode 100644 index 0000000..15f50f5 --- /dev/null +++ b/vendor/github.com/chewxy/math32/modf.go @@ -0,0 +1,35 @@ +package math32 + +// Modf returns integer and fractional floating-point numbers +// that sum to f. Both values have the same sign as f. +// +// Special cases are: +// Modf(±Inf) = ±Inf, NaN +// Modf(NaN) = NaN, NaN +func Modf(f float32) (int float32, frac float32) { + return modf(f) +} + +func modf(f float32) (int float32, frac float32) { + if f < 1 { + switch { + case f < 0: + int, frac = Modf(-f) + return -int, -frac + case f == 0: + return f, f // Return -0, -0 when f == -0 + } + return 0, f + } + + x := Float32bits(f) + e := uint(x>>shift)&mask - bias + + // Keep the top 9+e bits, the integer part; clear the rest. + if e < 32-9 { + x &^= 1<<(32-9-e) - 1 + } + int = Float32frombits(x) + frac = f - int + return +} diff --git a/vendor/github.com/chewxy/math32/nextafter.go b/vendor/github.com/chewxy/math32/nextafter.go new file mode 100644 index 0000000..f656c63 --- /dev/null +++ b/vendor/github.com/chewxy/math32/nextafter.go @@ -0,0 +1,28 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math32 + +// Nextafter returns the next representable float32 value after x towards y. +// +// Special cases are: +// +// Nextafter32(x, x) = x +// Nextafter32(NaN, y) = NaN +// Nextafter32(x, NaN) = NaN +func Nextafter(x, y float32) (r float32) { + switch { + case IsNaN(x) || IsNaN(y): // special case + r = float32(NaN()) + case x == y: + r = x + case x == 0: + r = float32(Copysign(Float32frombits(1), y)) + case (y > x) == (x > 0): + r = Float32frombits(Float32bits(x) + 1) + default: + r = Float32frombits(Float32bits(x) - 1) + } + return +} diff --git a/vendor/github.com/chewxy/math32/pow.go b/vendor/github.com/chewxy/math32/pow.go new file mode 100644 index 0000000..f5338f9 --- /dev/null +++ b/vendor/github.com/chewxy/math32/pow.go @@ -0,0 +1,139 @@ +package math32 + +import "math" + +func isOddInt(x float32) bool { + xi, xf := Modf(x) + return xf == 0 && int32(xi)&1 == 1 +} + +// Special cases taken from FreeBSD's /usr/src/lib/msun/src/e_pow.c +// updated by IEEE Std. 754-2008 "Section 9.2.1 Special values". + +// Pow returns x**y, the base-x exponential of y. +// +// Special cases are (in order): +// Pow(x, ±0) = 1 for any x +// Pow(1, y) = 1 for any y +// Pow(x, 1) = x for any x +// Pow(NaN, y) = NaN +// Pow(x, NaN) = NaN +// Pow(±0, y) = ±Inf for y an odd integer < 0 +// Pow(±0, -Inf) = +Inf +// Pow(±0, +Inf) = +0 +// Pow(±0, y) = +Inf for finite y < 0 and not an odd integer +// Pow(±0, y) = ±0 for y an odd integer > 0 +// Pow(±0, y) = +0 for finite y > 0 and not an odd integer +// Pow(-1, ±Inf) = 1 +// Pow(x, +Inf) = +Inf for |x| > 1 +// Pow(x, -Inf) = +0 for |x| > 1 +// Pow(x, +Inf) = +0 for |x| < 1 +// Pow(x, -Inf) = +Inf for |x| < 1 +// Pow(+Inf, y) = +Inf for y > 0 +// Pow(+Inf, y) = +0 for y < 0 +// Pow(-Inf, y) = Pow(-0, -y) +// Pow(x, y) = NaN for finite x < 0 and finite non-integer y +func Pow(x, y float32) float32 { + switch { + case y == 0 || x == 1: + return 1 + case y == 1: + return x + case y == 0.5: + return Sqrt(x) + case y == -0.5: + return 1 / Sqrt(x) + case IsNaN(x) || IsNaN(y): + return NaN() + case x == 0: + switch { + case y < 0: + if isOddInt(y) { + return Copysign(Inf(1), x) + } + return Inf(1) + case y > 0: + if isOddInt(y) { + return x + } + return 0 + } + case IsInf(y, 0): + switch { + case x == -1: + return 1 + case (Abs(x) < 1) == IsInf(y, 1): + return 0 + default: + return Inf(1) + } + case IsInf(x, 0): + if IsInf(x, -1) { + return Pow(1/x, -y) // Pow(-0, -y) + } + switch { + case y < 0: + return 0 + case y > 0: + return Inf(1) + } + } + + absy := y + flip := false + if absy < 0 { + absy = -absy + flip = true + } + yi, yf := Modf(absy) + if yf != 0 && x < 0 { + return NaN() + } + if yi >= 1<<31 { + return Exp(y * Log(x)) + } + + // ans = a1 * 2**ae (= 1 for now). + a1 := float32(1.0) + ae := 0 + + // ans *= x**yf + if yf != 0 { + if yf > 0.5 { + yf-- + yi++ + } + a1 = Exp(yf * Log(x)) + } + + // ans *= x**yi + // by multiplying in successive squarings + // of x according to bits of yi. + // accumulate powers of two into exp. + x1, xe := Frexp(x) + for i := int32(yi); i != 0; i >>= 1 { + if i&1 == 1 { + a1 *= x1 + ae += xe + } + x1 *= x1 + xe <<= 1 + if x1 < .5 { + x1 += x1 + xe-- + } + } + + // ans = a1*2**ae + // if flip { ans = 1 / ans } + // but in the opposite order + if flip { + a1 = 1 / a1 + ae = -ae + } + return Ldexp(a1, ae) +} + +func Pow10(e int) float32 { + return float32(math.Pow10(e)) +} diff --git a/vendor/github.com/chewxy/math32/remainder.go b/vendor/github.com/chewxy/math32/remainder.go new file mode 100644 index 0000000..7cdc50b --- /dev/null +++ b/vendor/github.com/chewxy/math32/remainder.go @@ -0,0 +1,95 @@ +package math32 + +// The original C code and the comment below are from +// FreeBSD's /usr/src/lib/msun/src/e_remainder.c and came +// with this notice. The go code is a simplified version of +// the original C. +// +// ==================================================== +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// +// Developed at SunPro, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== +// +// __ieee754_remainder(x,y) +// Return : +// returns x REM y = x - [x/y]*y as if in infinite +// precision arithmetic, where [x/y] is the (infinite bit) +// integer nearest x/y (in half way cases, choose the even one). +// Method : +// Based on Mod() returning x - [x/y]chopped * y exactly. + +// Remainder returns the IEEE 754 floating-point remainder of x/y. +// +// Special cases are: +// Remainder(±Inf, y) = NaN +// Remainder(NaN, y) = NaN +// Remainder(x, 0) = NaN +// Remainder(x, ±Inf) = x +// Remainder(x, NaN) = NaN +func Remainder(x, y float32) float32 { + if haveArchRemainder { + return archRemainder(x, y) + } + return remainder(x, y) +} + +func remainder(x, y float32) float32 { + + // special cases + switch { + case IsNaN(x) || IsNaN(y) || IsInf(x, 0) || y == 0: + return NaN() + case IsInf(y, 0): + return x + } + + hx := Float32bits(x) + hy := Float32bits(y) + + hy &= 0x7fffffff + hx &= 0x7fffffff + + if hy <= 0x7effffff { + x = Mod(x, y+y) // now x < 2y + } + + if hx-hy == 0 { + return 0 + } + + sign := false + if x < 0 { + x = -x + sign = true + } + + if y < 0 { + y = -y + } + + if hy < 0x01000000 { + if x+x > y { + x -= y + if x+x >= y { + x -= y + } + } + } else { + yHalf := 0.5 * y + if x > yHalf { + x -= y + if x >= yHalf { + x -= y + } + } + } + + if sign { + x = -x + } + return x +} diff --git a/vendor/github.com/chewxy/math32/remainder_amd64.s b/vendor/github.com/chewxy/math32/remainder_amd64.s new file mode 100644 index 0000000..0d489ba --- /dev/null +++ b/vendor/github.com/chewxy/math32/remainder_amd64.s @@ -0,0 +1,9 @@ +//go:build !tinygo && !noasm +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +TEXT ·archRemainder(SB),NOSPLIT,$0 + JMP ·remainder(SB) diff --git a/vendor/github.com/chewxy/math32/remainder_asm.go b/vendor/github.com/chewxy/math32/remainder_asm.go new file mode 100644 index 0000000..d4e41c1 --- /dev/null +++ b/vendor/github.com/chewxy/math32/remainder_asm.go @@ -0,0 +1,10 @@ +//go:build !noasm && !tinygo && (amd64 || s390x || arm || ppc64le || 386 || wasm) +// +build !noasm +// +build !tinygo +// +build amd64 s390x arm ppc64le 386 wasm + +package math32 + +const haveArchRemainder = true + +func archRemainder(x, y float32) float32 diff --git a/vendor/github.com/chewxy/math32/remainder_noasm.go b/vendor/github.com/chewxy/math32/remainder_noasm.go new file mode 100644 index 0000000..f240675 --- /dev/null +++ b/vendor/github.com/chewxy/math32/remainder_noasm.go @@ -0,0 +1,10 @@ +//go:build noasm || tinygo || (!amd64 && !s390x && !arm && !ppc64le && !386 && !wasm) +// +build noasm tinygo !amd64,!s390x,!arm,!ppc64le,!386,!wasm + +package math32 + +const haveArchRemainder = false + +func archRemainder(x, y float32) float32 { + panic("not implemented") +} diff --git a/vendor/github.com/chewxy/math32/round.go b/vendor/github.com/chewxy/math32/round.go new file mode 100644 index 0000000..100fc45 --- /dev/null +++ b/vendor/github.com/chewxy/math32/round.go @@ -0,0 +1,76 @@ +package math32 + +// Round returns the nearest integer, rounding half away from zero. +// +// Special cases are: +// Round(±0) = ±0 +// Round(±Inf) = ±Inf +// Round(NaN) = NaN +func Round(x float32) float32 { + // Round is a faster implementation of: + // + // func Round(x float64) float64 { + // t := Trunc(x) + // if Abs(x-t) >= 0.5 { + // return t + Copysign(1, x) + // } + // return t + // } + bits := Float32bits(x) + e := uint(bits>>shift) & mask + if e < bias { + // Round abs(x) < 1 including denormals. + bits &= signMask // +-0 + if e == bias-1 { + bits |= uvone // +-1 + } + } else if e < bias+shift { + // Round any abs(x) >= 1 containing a fractional component [0,1). + // + // Numbers with larger exponents are returned unchanged since they + // must be either an integer, infinity, or NaN. + const half = 1 << (shift - 1) + e -= bias + bits += half >> e + bits &^= fracMask >> e + } + return Float32frombits(bits) +} + +// RoundToEven returns the nearest integer, rounding ties to even. +// +// Special cases are: +// RoundToEven(±0) = ±0 +// RoundToEven(±Inf) = ±Inf +// RoundToEven(NaN) = NaN +func RoundToEven(x float32) float32 { + // RoundToEven is a faster implementation of: + // + // func RoundToEven(x float64) float64 { + // t := math.Trunc(x) + // odd := math.Remainder(t, 2) != 0 + // if d := math.Abs(x - t); d > 0.5 || (d == 0.5 && odd) { + // return t + math.Copysign(1, x) + // } + // return t + // } + bits := Float32bits(x) + e := uint(bits>>shift) & mask + if e >= bias { + // Round abs(x) >= 1. + // - Large numbers without fractional components, infinity, and NaN are unchanged. + // - Add 0.499.. or 0.5 before truncating depending on whether the truncated + // number is even or odd (respectively). + const halfMinusULP = (1 << (shift - 1)) - 1 + e -= bias + bits += (halfMinusULP + (bits>>(shift-e))&1) >> e + bits &^= fracMask >> e + } else if e == bias-1 && bits&fracMask != 0 { + // Round 0.5 < abs(x) < 1. + bits = bits&signMask | uvone // +-1 + } else { + // Round abs(x) <= 0.5 including denormals. + bits &= signMask // +-0 + } + return Float32frombits(bits) +} diff --git a/vendor/github.com/chewxy/math32/signbit.go b/vendor/github.com/chewxy/math32/signbit.go new file mode 100644 index 0000000..0c9587b --- /dev/null +++ b/vendor/github.com/chewxy/math32/signbit.go @@ -0,0 +1,6 @@ +package math32 + +// Signbit returns true if x is negative or negative zero. +func Signbit(x float32) bool { + return Float32bits(x)&(1<<31) != 0 +} diff --git a/vendor/github.com/chewxy/math32/sincos.go b/vendor/github.com/chewxy/math32/sincos.go new file mode 100644 index 0000000..4b9dda1 --- /dev/null +++ b/vendor/github.com/chewxy/math32/sincos.go @@ -0,0 +1,387 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math32 + +import "math/bits" + +/* + Floating-point sine and cosine. +*/ + +// The original C code, the long comment, and the constants +// below were from http://netlib.sandia.gov/cephes/cmath/sin.c, +// available from http://www.netlib.org/cephes/cmath.tgz. +// The go code is a simplified version of the original C. +// +// sin.c +// +// Circular sine +// +// SYNOPSIS: +// +// double x, y, sin(); +// y = sin( x ); +// +// DESCRIPTION: +// +// Range reduction is into intervals of pi/4. The reduction error is nearly +// eliminated by contriving an extended precision modular arithmetic. +// +// Two polynomial approximating functions are employed. +// Between 0 and pi/4 the sine is approximated by +// x + x**3 P(x**2). +// Between pi/4 and pi/2 the cosine is represented as +// 1 - x**2 Q(x**2). +// +// ACCURACY: +// +// Relative error: +// arithmetic domain # trials peak rms +// DEC 0, 10 150000 3.0e-17 7.8e-18 +// IEEE -1.07e9,+1.07e9 130000 2.1e-16 5.4e-17 +// +// Partial loss of accuracy begins to occur at x = 2**30 = 1.074e9. The loss +// is not gradual, but jumps suddenly to about 1 part in 10e7. Results may +// be meaningless for x > 2**49 = 5.6e14. +// +// cos.c +// +// Circular cosine +// +// SYNOPSIS: +// +// double x, y, cos(); +// y = cos( x ); +// +// DESCRIPTION: +// +// Range reduction is into intervals of pi/4. The reduction error is nearly +// eliminated by contriving an extended precision modular arithmetic. +// +// Two polynomial approximating functions are employed. +// Between 0 and pi/4 the cosine is approximated by +// 1 - x**2 Q(x**2). +// Between pi/4 and pi/2 the sine is represented as +// x + x**3 P(x**2). +// +// ACCURACY: +// +// Relative error: +// arithmetic domain # trials peak rms +// IEEE -1.07e9,+1.07e9 130000 2.1e-16 5.4e-17 +// DEC 0,+1.07e9 17000 3.0e-17 7.2e-18 +// +// Cephes Math Library Release 2.8: June, 2000 +// Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier +// +// The readme file at http://netlib.sandia.gov/cephes/ says: +// Some software in this archive may be from the book _Methods and +// Programs for Mathematical Functions_ (Prentice-Hall or Simon & Schuster +// International, 1989) or from the Cephes Mathematical Library, a +// commercial product. In either event, it is copyrighted by the author. +// What you see here may be used freely but it comes with no support or +// guarantee. +// +// The two known misprints in the book are repaired here in the +// source listings for the gamma function and the incomplete beta +// integral. +// +// Stephen L. Moshier +// moshier@na-net.ornl.gov + +// sin coefficients +var _sin = [...]float32{ + 1.58962301576546568060e-10, // 0x3de5d8fd1fd19ccd + -2.50507477628578072866e-8, // 0xbe5ae5e5a9291f5d + 2.75573136213857245213e-6, // 0x3ec71de3567d48a1 + -1.98412698295895385996e-4, // 0xbf2a01a019bfdf03 + 8.33333333332211858878e-3, // 0x3f8111111110f7d0 + -1.66666666666666307295e-1, // 0xbfc5555555555548 +} + +// cos coefficients +var _cos = [...]float32{ + -1.13585365213876817300e-11, // 0xbda8fa49a0861a9b + 2.08757008419747316778e-9, // 0x3e21ee9d7b4e3f05 + -2.75573141792967388112e-7, // 0xbe927e4f7eac4bc6 + 2.48015872888517045348e-5, // 0x3efa01a019c844f5 + -1.38888888888730564116e-3, // 0xbf56c16c16c14f91 + 4.16666666666665929218e-2, // 0x3fa555555555554b +} + +// Sincos returns Sin(x), Cos(x). +// +// Special cases are: +// Sincos(±0) = ±0, 1 +// Sincos(±Inf) = NaN, NaN +// Sincos(NaN) = NaN, NaN +func Sincos(x float32) (sin, cos float32) { + const ( + PI4A = 7.85398125648498535156e-1 // 0x3fe921fb40000000, Pi/4 split into three parts + PI4B = 3.77489470793079817668e-8 // 0x3e64442d00000000, + PI4C = 2.69515142907905952645e-15 // 0x3ce8469898cc5170, + ) + // special cases + switch { + case x == 0: + return x, 1 // return ±0.0, 1.0 + case IsNaN(x) || IsInf(x, 0): + return NaN(), NaN() + } + + // make argument positive + sinSign, cosSign := false, false + if x < 0 { + x = -x + sinSign = true + } + + var j uint64 + var y, z float32 + if x >= reduceThreshold { + j, z = trigReduce(x) + } else { + j = uint64(x * (4 / Pi)) // integer part of x/(Pi/4), as integer for tests on the phase angle + y = float32(j) // integer part of x/(Pi/4), as float + + if j&1 == 1 { // map zeros to origin + j++ + y++ + } + j &= 7 // octant modulo 2Pi radians (360 degrees) + z = ((x - y*PI4A) - y*PI4B) - y*PI4C // Extended precision modular arithmetic + } + if j > 3 { // reflect in x axis + j -= 4 + sinSign, cosSign = !sinSign, !cosSign + } + if j > 1 { + cosSign = !cosSign + } + + zz := z * z + cos = 1.0 - 0.5*zz + zz*zz*((((((_cos[0]*zz)+_cos[1])*zz+_cos[2])*zz+_cos[3])*zz+_cos[4])*zz+_cos[5]) + sin = z + z*zz*((((((_sin[0]*zz)+_sin[1])*zz+_sin[2])*zz+_sin[3])*zz+_sin[4])*zz+_sin[5]) + if j == 1 || j == 2 { + sin, cos = cos, sin + } + if cosSign { + cos = -cos + } + if sinSign { + sin = -sin + } + return +} + +// Sin returns the sine of the radian argument x. +// +// Special cases are: +// Sin(±0) = ±0 +// Sin(±Inf) = NaN +// Sin(NaN) = NaN +func Sin(x float32) float32 { + const ( + PI4A = 7.85398125648498535156e-1 // 0x3fe921fb40000000, Pi/4 split into three parts + PI4B = 3.77489470793079817668e-8 // 0x3e64442d00000000, + PI4C = 2.69515142907905952645e-15 // 0x3ce8469898cc5170, + ) + // special cases + switch { + case x == 0 || IsNaN(x): + return x // return ±0 || NaN() + case IsInf(x, 0): + return NaN() + } + + // make argument positive but save the sign + sign := false + if x < 0 { + x = -x + sign = true + } + + var j uint64 + var y, z float32 + if x >= reduceThreshold { + j, z = trigReduce(x) + } else { + j = uint64(x * (4 / Pi)) // integer part of x/(Pi/4), as integer for tests on the phase angle + y = float32(j) // integer part of x/(Pi/4), as float + + // map zeros to origin + if j&1 == 1 { + j++ + y++ + } + j &= 7 // octant modulo 2Pi radians (360 degrees) + z = ((x - y*PI4A) - y*PI4B) - y*PI4C // Extended precision modular arithmetic + } + // reflect in x axis + if j > 3 { + sign = !sign + j -= 4 + } + zz := z * z + if j == 1 || j == 2 { + y = 1.0 - 0.5*zz + zz*zz*((((((_cos[0]*zz)+_cos[1])*zz+_cos[2])*zz+_cos[3])*zz+_cos[4])*zz+_cos[5]) + } else { + y = z + z*zz*((((((_sin[0]*zz)+_sin[1])*zz+_sin[2])*zz+_sin[3])*zz+_sin[4])*zz+_sin[5]) + } + if sign { + y = -y + } + return y +} + +// Cos returns the cosine of the radian argument x. +// +// Special cases are: +// Cos(±Inf) = NaN +// Cos(NaN) = NaN +func Cos(x float32) float32 { + const ( + PI4A = 7.85398125648498535156e-1 // 0x3fe921fb40000000, Pi/4 split into three parts + PI4B = 3.77489470793079817668e-8 // 0x3e64442d00000000, + PI4C = 2.69515142907905952645e-15 // 0x3ce8469898cc5170, + ) + // special cases + switch { + case IsNaN(x) || IsInf(x, 0): + return NaN() + } + + // make argument positive + sign := false + x = Abs(x) + + var j uint64 + var y, z float32 + if x >= reduceThreshold { + j, z = trigReduce(x) + } else { + j = uint64(x * (4 / Pi)) // integer part of x/(Pi/4), as integer for tests on the phase angle + y = float32(j) // integer part of x/(Pi/4), as float + + // map zeros to origin + if j&1 == 1 { + j++ + y++ + } + j &= 7 // octant modulo 2Pi radians (360 degrees) + z = ((x - y*PI4A) - y*PI4B) - y*PI4C // Extended precision modular arithmetic + } + + if j > 3 { + j -= 4 + sign = !sign + } + if j > 1 { + sign = !sign + } + + zz := z * z + if j == 1 || j == 2 { + y = z + z*zz*((((((_sin[0]*zz)+_sin[1])*zz+_sin[2])*zz+_sin[3])*zz+_sin[4])*zz+_sin[5]) + } else { + y = 1.0 - 0.5*zz + zz*zz*((((((_cos[0]*zz)+_cos[1])*zz+_cos[2])*zz+_cos[3])*zz+_cos[4])*zz+_cos[5]) + } + if sign { + y = -y + } + return y +} + +// reduceThreshold is the maximum value of x where the reduction using Pi/4 +// in 3 float64 parts still gives accurate results. This threshold +// is set by y*C being representable as a float64 without error +// where y is given by y = floor(x * (4 / Pi)) and C is the leading partial +// terms of 4/Pi. Since the leading terms (PI4A and PI4B in sin.go) have 30 +// and 32 trailing zero bits, y should have less than 30 significant bits. +// y < 1<<30 -> floor(x*4/Pi) < 1<<30 -> x < (1<<30 - 1) * Pi/4 +// So, conservatively we can take x < 1<<29. +// Above this threshold Payne-Hanek range reduction must be used. +const reduceThreshold = 1 << 29 + +// trigReduce implements Payne-Hanek range reduction by Pi/4 +// for x > 0. It returns the integer part mod 8 (j) and +// the fractional part (z) of x / (Pi/4). +// The implementation is based on: +// "ARGUMENT REDUCTION FOR HUGE ARGUMENTS: Good to the Last Bit" +// K. C. Ng et al, March 24, 1992 +// The simulated multi-precision calculation of x*B uses 64-bit integer arithmetic. +func trigReduce(x float32) (j uint64, z float32) { + const PI4 = Pi / 4 + if x < PI4 { + return 0, x + } + // Extract out the integer and exponent such that, + // x = ix * 2 ** exp. + ix := Float32bits(x) + exp := int(ix>>shift&mask) - bias - shift + ix &^= mask << shift + ix |= 1 << shift + // Use the exponent to extract the 3 appropriate uint64 digits from mPi4, + // B ~ (z0, z1, z2), such that the product leading digit has the exponent -61. + // Note, exp >= -53 since x >= PI4 and exp < 971 for maximum float64. + const floatingbits = 32 - 3 + digit, bitshift := uint(exp+floatingbits)/32, uint(exp+floatingbits)%32 + z0 := (mPi4[digit] << bitshift) | (mPi4[digit+1] >> (32 - bitshift)) + z1 := (mPi4[digit+1] << bitshift) | (mPi4[digit+2] >> (32 - bitshift)) + z2 := (mPi4[digit+2] << bitshift) | (mPi4[digit+3] >> (32 - bitshift)) + // Multiply mantissa by the digits and extract the upper two digits (hi, lo). + z2hi, _ := bits.Mul64(z2, uint64(ix)) + z1hi, z1lo := bits.Mul64(z1, uint64(ix)) + z0lo := z0 * uint64(ix) + lo, c := bits.Add64(z1lo, z2hi, 0) + hi, _ := bits.Add64(z0lo, z1hi, c) + // The top 3 bits are j. + j = hi >> floatingbits + // Extract the fraction and find its magnitude. + hi = hi<<3 | lo>>floatingbits + lz := uint(bits.LeadingZeros64(hi)) + e := uint64(bias - (lz + 1)) + // Clear implicit mantissa bit and shift into place. + hi = (hi << (lz + 1)) | (lo >> (32 - (lz + 1))) + hi >>= 43 - shift + // Include the exponent and convert to a float. + hi |= e << shift + z = Float32frombits(uint32(hi)) + // Map zeros to origin. + if j&1 == 1 { + j++ + j &= 7 + z-- + } + // Multiply the fractional part by pi/4. + return j, z * PI4 +} + +// mPi4 is the binary digits of 4/pi as a uint64 array, +// that is, 4/pi = Sum mPi4[i]*2^(-64*i) +// 19 64-bit digits and the leading one bit give 1217 bits +// of precision to handle the largest possible float64 exponent. +var mPi4 = [...]uint64{ + 0x0000000000000001, + 0x45f306dc9c882a53, + 0xf84eafa3ea69bb81, + 0xb6c52b3278872083, + 0xfca2c757bd778ac3, + 0x6e48dc74849ba5c0, + 0x0c925dd413a32439, + 0xfc3bd63962534e7d, + 0xd1046bea5d768909, + 0xd338e04d68befc82, + 0x7323ac7306a673e9, + 0x3908bf177bf25076, + 0x3ff12fffbc0b301f, + 0xde5e2316b414da3e, + 0xda6cfd9e4f96136e, + 0x9e8c7ecd3cbfd45a, + 0xea4f758fd7cbe2f6, + 0x7a0e73ef14a525d4, + 0xd7f6bf623f1aba10, + 0xac06608df8f6d757, +} diff --git a/vendor/github.com/chewxy/math32/sinhf.go b/vendor/github.com/chewxy/math32/sinhf.go new file mode 100644 index 0000000..ff91243 --- /dev/null +++ b/vendor/github.com/chewxy/math32/sinhf.go @@ -0,0 +1,40 @@ +package math32 + +func Sinh(x float32) float32 { + // The coefficients are #2029 from Hart & Cheney. (20.36D) + const ( + P0 = -0.6307673640497716991184787251e+6 + P1 = -0.8991272022039509355398013511e+5 + P2 = -0.2894211355989563807284660366e+4 + P3 = -0.2630563213397497062819489e+2 + Q0 = -0.6307673640497716991212077277e+6 + Q1 = 0.1521517378790019070696485176e+5 + Q2 = -0.173678953558233699533450911e+3 + ) + + sign := false + if x < 0 { + x = -x + sign = true + } + + var temp float32 + switch { + case x > 21: + temp = Exp(x) * 0.5 + + case x > 0.5: + ex := Exp(x) + temp = (ex - 1/ex) * 0.5 + + default: + sq := x * x + temp = (((P3*sq+P2)*sq+P1)*sq + P0) * x + temp = temp / (((sq+Q2)*sq+Q1)*sq + Q0) + } + + if sign { + temp = -temp + } + return temp +} diff --git a/vendor/github.com/chewxy/math32/sqrt.go b/vendor/github.com/chewxy/math32/sqrt.go new file mode 100644 index 0000000..fccf6b2 --- /dev/null +++ b/vendor/github.com/chewxy/math32/sqrt.go @@ -0,0 +1,65 @@ +package math32 + +// Sqrt returns the square root of x. + +// Special cases are: +// Sqrt(+Inf) = +Inf +// Sqrt(±0) = ±0 +// Sqrt(x < 0) = NaN +// Sqrt(NaN) = NaN +func Sqrt(x float32) float32 { + if haveArchSqrt { + return archSqrt(x) + } + return sqrt(x) +} + +// TODO: add assembly for !build noasm +func sqrt(x float32) float32 { + // special cases + switch { + case x == 0 || IsNaN(x) || IsInf(x, 1): + return x + case x < 0: + return NaN() + } + ix := Float32bits(x) + + // normalize x + exp := int((ix >> shift) & mask) + if exp == 0 { // subnormal x + for ix&(1<>= 1 // exp = exp/2, exponent of square root + // generate sqrt(x) bit by bit + ix <<= 1 + var q, s uint32 // q = sqrt(x) + r := uint32(1 << (shift + 1)) // r = moving bit from MSB to LSB + for r != 0 { + t := s + r + if t <= ix { + s = t + r + ix -= t + q += r + } + ix <<= 1 + r >>= 1 + } + // final rounding + if ix != 0 { // remainder, result not exact + q += q & 1 // round according to extra bit + } + ix = q>>1 + uint32(exp-1+bias)< 2**49 = 5.6e14. +// [Accuracy loss statement from sin.go comments.] +// +// Cephes Math Library Release 2.8: June, 2000 +// Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier +// +// The readme file at http://netlib.sandia.gov/cephes/ says: +// Some software in this archive may be from the book _Methods and +// Programs for Mathematical Functions_ (Prentice-Hall or Simon & Schuster +// International, 1989) or from the Cephes Mathematical Library, a +// commercial product. In either event, it is copyrighted by the author. +// What you see here may be used freely but it comes with no support or +// guarantee. +// +// The two known misprints in the book are repaired here in the +// source listings for the gamma function and the incomplete beta +// integral. +// +// Stephen L. Moshier +// moshier@na-net.ornl.gov + +// tan coefficients +var _tanP = [...]float32{ + -1.30936939181383777646e4, // 0xc0c992d8d24f3f38 + 1.15351664838587416140e6, // 0x413199eca5fc9ddd + -1.79565251976484877988e7, // 0xc1711fead3299176 +} +var _tanQ = [...]float32{ + 1.00000000000000000000e0, + 1.36812963470692954678e4, //0x40cab8a5eeb36572 + -1.32089234440210967447e6, //0xc13427bc582abc96 + 2.50083801823357915839e7, //0x4177d98fc2ead8ef + -5.38695755929454629881e7, //0xc189afe03cbe5a31 +} + +func Tan(x float32) float32 { + return tan(x) +} + +func tan(x float32) float32 { + const ( + PI4A = 7.85398125648498535156e-1 // 0x3fe921fb40000000, Pi/4 split into three parts + PI4B = 3.77489470793079817668e-8 // 0x3e64442d00000000, + PI4C = 2.69515142907905952645e-15 // 0x3ce8469898cc5170, + ) + // special cases + switch { + case x == 0 || IsNaN(x): + return x // return ±0 || NaN() + case IsInf(x, 0): + return NaN() + } + + // make argument positive but save the sign + sign := false + if x < 0 { + x = -x + sign = true + } + var j uint64 + var y, z float32 + if x >= reduceThreshold { + j, z = trigReduce(x) + } else { + j = uint64(x * (4 / Pi)) // integer part of x/(Pi/4), as integer for tests on the phase angle + y = float32(j) // integer part of x/(Pi/4), as float + + /* map zeros and singularities to origin */ + if j&1 == 1 { + j++ + y++ + } + + z = ((x - y*PI4A) - y*PI4B) - y*PI4C + } + zz := z * z + + if zz > 1e-14 { + y = z + z*(zz*(((_tanP[0]*zz)+_tanP[1])*zz+_tanP[2])/((((zz+_tanQ[1])*zz+_tanQ[2])*zz+_tanQ[3])*zz+_tanQ[4])) + } else { + y = z + } + if j&2 == 2 { + y = -1 / y + } + if sign { + y = -y + } + return y +} diff --git a/vendor/github.com/chewxy/math32/tanh.go b/vendor/github.com/chewxy/math32/tanh.go new file mode 100644 index 0000000..f73e2ef --- /dev/null +++ b/vendor/github.com/chewxy/math32/tanh.go @@ -0,0 +1,77 @@ +package math32 + +// The original C code, the long comment, and the constants +// below were from http://netlib.sandia.gov/cephes/cmath/tanh.c, +// available from http://www.netlib.org/cephes/single.tgz. +// The go code is a simplified version of the original C. +// tanhf.c +// +// Hyperbolic tangent +// +// +// +// SYNOPSIS: +// +// float x, y, tanhf(); +// +// y = tanhf( x ); +// +// +// +// DESCRIPTION: +// +// Returns hyperbolic tangent of argument in the range MINLOG to +// MAXLOG. +// +// A polynomial approximation is used for |x| < 0.625. +// Otherwise, +// +// tanh(x) = sinh(x)/cosh(x) = 1 - 2/(exp(2x) + 1). +// +// +// +// ACCURACY: +// +// Relative error: +// arithmetic domain # trials peak rms +// IEEE -2,2 100000 1.3e-7 2.6e-8 +// +// + +/* +Cephes Math Library Release 2.2: June, 1992 +Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier +Direct inquiries to 30 Frost Street, Cambridge, MA 02140 +*/ + +/* Single precision hyperbolic tangent + * test interval: [-0.625, +0.625] + * trials: 10000 + * peak relative error: 7.2e-8 + * rms relative error: 2.6e-8 + */ + +func Tanh(x float32) float32 { + const MAXLOG = 88.02969187150841 + z := Abs(x) + switch { + case z > 0.5*MAXLOG: + if x < 0 { + return -1 + } + return 1 + case z >= 0.625: + s := Exp(z + z) + z = 1 - 2/(s+1) + if x < 0 { + z = -z + } + default: + if x == 0 { + return x + } + s := x * x + z = ((((-5.70498872745E-3*s+2.06390887954E-2)*s-5.37397155531E-2)*s+1.33314422036E-1)*s-3.33332819422E-1)*s*x + x + } + return z +} diff --git a/vendor/github.com/chewxy/math32/unsafe.go b/vendor/github.com/chewxy/math32/unsafe.go new file mode 100644 index 0000000..2497e41 --- /dev/null +++ b/vendor/github.com/chewxy/math32/unsafe.go @@ -0,0 +1,21 @@ +package math32 + +import "unsafe" + +// Float32bits returns the IEEE 754 binary representation of f. +func Float32bits(f float32) uint32 { return *(*uint32)(unsafe.Pointer(&f)) } + +// Float32frombits returns the floating point number corresponding +// to the IEEE 754 binary representation b. +func Float32frombits(b uint32) float32 { return *(*float32)(unsafe.Pointer(&b)) } + +// Float64bits returns the IEEE 754 binary representation of f. +func Float64bits(f float64) uint64 { return *(*uint64)(unsafe.Pointer(&f)) } + +// Float64frombits returns the floating point number corresponding +// the IEEE 754 binary representation b. +func Float64frombits(b uint64) float64 { return *(*float64)(unsafe.Pointer(&b)) } + +func float32ibits(f float32) int32 { return *(*int32)(unsafe.Pointer(&f)) } + +func float32fromibits(b int32) float32 { return *(*float32)(unsafe.Pointer(&b)) } diff --git a/vendor/github.com/chewxy/math32/y0.go b/vendor/github.com/chewxy/math32/y0.go new file mode 100644 index 0000000..cf275eb --- /dev/null +++ b/vendor/github.com/chewxy/math32/y0.go @@ -0,0 +1,7 @@ +package math32 + +import "math" + +func Y0(x float32) float32 { + return float32(math.Y0(float64(x))) +} diff --git a/vendor/github.com/chewxy/math32/y1.go b/vendor/github.com/chewxy/math32/y1.go new file mode 100644 index 0000000..bd09d29 --- /dev/null +++ b/vendor/github.com/chewxy/math32/y1.go @@ -0,0 +1,7 @@ +package math32 + +import "math" + +func Y1(x float32) float32 { + return float32(math.Y1(float64(x))) +} diff --git a/vendor/github.com/ebitengine/gomobile/LICENSE b/vendor/github.com/ebitengine/gomobile/LICENSE new file mode 100644 index 0000000..2a7cf70 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/LICENSE @@ -0,0 +1,27 @@ +Copyright 2009 The Go Authors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google LLC nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/ebitengine/gomobile/PATENTS b/vendor/github.com/ebitengine/gomobile/PATENTS new file mode 100644 index 0000000..7330990 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/PATENTS @@ -0,0 +1,22 @@ +Additional IP Rights Grant (Patents) + +"This implementation" means the copyrightable works distributed by +Google as part of the Go project. + +Google hereby grants to You a perpetual, worldwide, non-exclusive, +no-charge, royalty-free, irrevocable (except as stated in this section) +patent license to make, have made, use, offer to sell, sell, import, +transfer and otherwise run, modify and propagate the contents of this +implementation of Go, where such license applies only to those patent +claims, both currently owned or controlled by Google and acquired in +the future, licensable by Google that are necessarily infringed by this +implementation of Go. This grant does not include claims that would be +infringed only as a consequence of further modification of this +implementation. If you or your agent or exclusive licensee institute or +order or agree to the institution of patent litigation against any +entity (including a cross-claim or counterclaim in a lawsuit) alleging +that this implementation of Go or any code incorporated within this +implementation of Go constitutes direct or contributory patent +infringement, or inducement of patent infringement, then any patent +rights granted to you under this License for this implementation of Go +shall terminate as of the date such litigation is filed. diff --git a/vendor/github.com/ebitengine/gomobile/app/GoNativeActivity.java b/vendor/github.com/ebitengine/gomobile/app/GoNativeActivity.java new file mode 100644 index 0000000..e829c8c --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/app/GoNativeActivity.java @@ -0,0 +1,67 @@ +package org.golang.app; + +import android.app.Activity; +import android.app.NativeActivity; +import android.content.Context; +import android.content.pm.ActivityInfo; +import android.content.pm.PackageManager; +import android.os.Bundle; +import android.util.Log; +import android.view.KeyCharacterMap; + +public class GoNativeActivity extends NativeActivity { + private static GoNativeActivity goNativeActivity; + + public GoNativeActivity() { + super(); + goNativeActivity = this; + } + + String getTmpdir() { + return getCacheDir().getAbsolutePath(); + } + + static int getRune(int deviceId, int keyCode, int metaState) { + try { + int rune = KeyCharacterMap.load(deviceId).get(keyCode, metaState); + if (rune == 0) { + return -1; + } + return rune; + } catch (KeyCharacterMap.UnavailableException e) { + return -1; + } catch (Exception e) { + Log.e("Go", "exception reading KeyCharacterMap", e); + return -1; + } + } + + private void load() { + // Interestingly, NativeActivity uses a different method + // to find native code to execute, avoiding + // System.loadLibrary. The result is Java methods + // implemented in C with JNIEXPORT (and JNI_OnLoad) are not + // available unless an explicit call to System.loadLibrary + // is done. So we do it here, borrowing the name of the + // library from the same AndroidManifest.xml metadata used + // by NativeActivity. + try { + ActivityInfo ai = getPackageManager().getActivityInfo( + getIntent().getComponent(), PackageManager.GET_META_DATA); + if (ai.metaData == null) { + Log.e("Go", "loadLibrary: no manifest metadata found"); + return; + } + String libName = ai.metaData.getString("android.app.lib_name"); + System.loadLibrary(libName); + } catch (Exception e) { + Log.e("Go", "loadLibrary failed", e); + } + } + + @Override + public void onCreate(Bundle savedInstanceState) { + load(); + super.onCreate(savedInstanceState); + } +} diff --git a/vendor/github.com/ebitengine/gomobile/app/android.c b/vendor/github.com/ebitengine/gomobile/app/android.c new file mode 100644 index 0000000..305d586 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/app/android.c @@ -0,0 +1,201 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build android +// +build android + +#include +#include +#include +#include +#include +#include +#include "_cgo_export.h" + +#define LOG_INFO(...) __android_log_print(ANDROID_LOG_INFO, "Go", __VA_ARGS__) +#define LOG_FATAL(...) __android_log_print(ANDROID_LOG_FATAL, "Go", __VA_ARGS__) + +static jclass current_class; + +static jclass find_class(JNIEnv *env, const char *class_name) { + jclass clazz = (*env)->FindClass(env, class_name); + if (clazz == NULL) { + (*env)->ExceptionClear(env); + LOG_FATAL("cannot find %s", class_name); + return NULL; + } + return clazz; +} + +static jmethodID find_method(JNIEnv *env, jclass clazz, const char *name, const char *sig) { + jmethodID m = (*env)->GetMethodID(env, clazz, name, sig); + if (m == 0) { + (*env)->ExceptionClear(env); + LOG_FATAL("cannot find method %s %s", name, sig); + return 0; + } + return m; +} + +static jmethodID find_static_method(JNIEnv *env, jclass clazz, const char *name, const char *sig) { + jmethodID m = (*env)->GetStaticMethodID(env, clazz, name, sig); + if (m == 0) { + (*env)->ExceptionClear(env); + LOG_FATAL("cannot find method %s %s", name, sig); + return 0; + } + return m; +} + +static jmethodID key_rune_method; + +jint JNI_OnLoad(JavaVM* vm, void* reserved) { + JNIEnv* env; + if ((*vm)->GetEnv(vm, (void**)&env, JNI_VERSION_1_6) != JNI_OK) { + return -1; + } + + return JNI_VERSION_1_6; +} + +static int main_running = 0; + +// Entry point from our subclassed NativeActivity. +// +// By here, the Go runtime has been initialized (as we are running in +// -buildmode=c-shared) but the first time it is called, Go's main.main +// hasn't been called yet. +// +// The Activity may be created and destroyed multiple times throughout +// the life of a single process. Each time, onCreate is called. +void ANativeActivity_onCreate(ANativeActivity *activity, void* savedState, size_t savedStateSize) { + if (!main_running) { + JNIEnv* env = activity->env; + + // Note that activity->clazz is mis-named. + current_class = (*env)->GetObjectClass(env, activity->clazz); + current_class = (*env)->NewGlobalRef(env, current_class); + key_rune_method = find_static_method(env, current_class, "getRune", "(III)I"); + + setCurrentContext(activity->vm, (*env)->NewGlobalRef(env, activity->clazz)); + + // Set TMPDIR. + jmethodID gettmpdir = find_method(env, current_class, "getTmpdir", "()Ljava/lang/String;"); + jstring jpath = (jstring)(*env)->CallObjectMethod(env, activity->clazz, gettmpdir, NULL); + const char* tmpdir = (*env)->GetStringUTFChars(env, jpath, NULL); + if (setenv("TMPDIR", tmpdir, 1) != 0) { + LOG_INFO("setenv(\"TMPDIR\", \"%s\", 1) failed: %d", tmpdir, errno); + } + (*env)->ReleaseStringUTFChars(env, jpath, tmpdir); + + // Call the Go main.main. + uintptr_t mainPC = (uintptr_t)dlsym(RTLD_DEFAULT, "main.main"); + if (!mainPC) { + LOG_FATAL("missing main.main"); + } + callMain(mainPC); + main_running = 1; + } + + // These functions match the methods on Activity, described at + // http://developer.android.com/reference/android/app/Activity.html + // + // Note that onNativeWindowResized is not called on resize. Avoid it. + // https://code.google.com/p/android/issues/detail?id=180645 + activity->callbacks->onStart = onStart; + activity->callbacks->onResume = onResume; + activity->callbacks->onSaveInstanceState = onSaveInstanceState; + activity->callbacks->onPause = onPause; + activity->callbacks->onStop = onStop; + activity->callbacks->onDestroy = onDestroy; + activity->callbacks->onWindowFocusChanged = onWindowFocusChanged; + activity->callbacks->onNativeWindowCreated = onNativeWindowCreated; + activity->callbacks->onNativeWindowRedrawNeeded = onNativeWindowRedrawNeeded; + activity->callbacks->onNativeWindowDestroyed = onNativeWindowDestroyed; + activity->callbacks->onInputQueueCreated = onInputQueueCreated; + activity->callbacks->onInputQueueDestroyed = onInputQueueDestroyed; + activity->callbacks->onConfigurationChanged = onConfigurationChanged; + activity->callbacks->onLowMemory = onLowMemory; + + onCreate(activity); +} + +// TODO(crawshaw): Test configuration on more devices. +static const EGLint RGB_888[] = { + EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, + EGL_SURFACE_TYPE, EGL_WINDOW_BIT, + EGL_BLUE_SIZE, 8, + EGL_GREEN_SIZE, 8, + EGL_RED_SIZE, 8, + EGL_DEPTH_SIZE, 16, + EGL_CONFIG_CAVEAT, EGL_NONE, + EGL_NONE +}; + +EGLDisplay display = NULL; +EGLSurface surface = NULL; + +static char* initEGLDisplay() { + display = eglGetDisplay(EGL_DEFAULT_DISPLAY); + if (!eglInitialize(display, 0, 0)) { + return "EGL initialize failed"; + } + return NULL; +} + +char* createEGLSurface(ANativeWindow* window) { + char* err; + EGLint numConfigs, format; + EGLConfig config; + EGLContext context; + + if (display == 0) { + if ((err = initEGLDisplay()) != NULL) { + return err; + } + } + + if (!eglChooseConfig(display, RGB_888, &config, 1, &numConfigs)) { + return "EGL choose RGB_888 config failed"; + } + if (numConfigs <= 0) { + return "EGL no config found"; + } + + eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format); + if (ANativeWindow_setBuffersGeometry(window, 0, 0, format) != 0) { + return "EGL set buffers geometry failed"; + } + + surface = eglCreateWindowSurface(display, config, window, NULL); + if (surface == EGL_NO_SURFACE) { + return "EGL create surface failed"; + } + + const EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; + context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttribs); + + if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) { + return "eglMakeCurrent failed"; + } + return NULL; +} + +char* destroyEGLSurface() { + if (!eglDestroySurface(display, surface)) { + return "EGL destroy surface failed"; + } + return NULL; +} + +int32_t getKeyRune(JNIEnv* env, AInputEvent* e) { + return (int32_t)(*env)->CallStaticIntMethod( + env, + current_class, + key_rune_method, + AInputEvent_getDeviceId(e), + AKeyEvent_getKeyCode(e), + AKeyEvent_getMetaState(e) + ); +} diff --git a/vendor/github.com/ebitengine/gomobile/app/android.go b/vendor/github.com/ebitengine/gomobile/app/android.go new file mode 100644 index 0000000..fe9a219 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/app/android.go @@ -0,0 +1,824 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build android + +/* +Android Apps are built with -buildmode=c-shared. They are loaded by a +running Java process. + +Before any entry point is reached, a global constructor initializes the +Go runtime, calling all Go init functions. All cgo calls will block +until this is complete. Next JNI_OnLoad is called. When that is +complete, one of two entry points is called. + +All-Go apps built using NativeActivity enter at ANativeActivity_onCreate. + +Go libraries (for example, those built with gomobile bind) do not use +the app package initialization. +*/ + +package app + +/* +#cgo LDFLAGS: -landroid -llog -lEGL -lGLESv2 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern EGLDisplay display; +extern EGLSurface surface; + + +char* createEGLSurface(ANativeWindow* window); +char* destroyEGLSurface(); +int32_t getKeyRune(JNIEnv* env, AInputEvent* e); +*/ +import "C" +import ( + "fmt" + "log" + "os" + "time" + "unsafe" + + "github.com/ebitengine/gomobile/app/internal/callfn" + "github.com/ebitengine/gomobile/event/key" + "github.com/ebitengine/gomobile/event/lifecycle" + "github.com/ebitengine/gomobile/event/paint" + "github.com/ebitengine/gomobile/event/size" + "github.com/ebitengine/gomobile/event/touch" + "github.com/ebitengine/gomobile/geom" + "github.com/ebitengine/gomobile/internal/mobileinit" +) + +// RunOnJVM runs fn on a new goroutine locked to an OS thread with a JNIEnv. +// +// RunOnJVM blocks until the call to fn is complete. Any Java +// exception or failure to attach to the JVM is returned as an error. +// +// The function fn takes vm, the current JavaVM*, +// env, the current JNIEnv*, and +// ctx, a jobject representing the global android.context.Context. +func RunOnJVM(fn func(vm, jniEnv, ctx uintptr) error) error { + return mobileinit.RunOnJVM(fn) +} + +//export setCurrentContext +func setCurrentContext(vm *C.JavaVM, ctx C.jobject) { + mobileinit.SetCurrentContext(unsafe.Pointer(vm), uintptr(ctx)) +} + +//export callMain +func callMain(mainPC uintptr) { + for _, name := range []string{"TMPDIR", "PATH", "LD_LIBRARY_PATH"} { + n := C.CString(name) + os.Setenv(name, C.GoString(C.getenv(n))) + C.free(unsafe.Pointer(n)) + } + + // Set timezone. + // + // Note that Android zoneinfo is stored in /system/usr/share/zoneinfo, + // but it is in some kind of packed TZiff file that we do not support + // yet. As a stopgap, we build a fixed zone using the tm_zone name. + var curtime C.time_t + var curtm C.struct_tm + C.time(&curtime) + C.localtime_r(&curtime, &curtm) + tzOffset := int(curtm.tm_gmtoff) + tz := C.GoString(curtm.tm_zone) + time.Local = time.FixedZone(tz, tzOffset) + + go callfn.CallFn(mainPC) +} + +//export onStart +func onStart(activity *C.ANativeActivity) { +} + +//export onResume +func onResume(activity *C.ANativeActivity) { +} + +//export onSaveInstanceState +func onSaveInstanceState(activity *C.ANativeActivity, outSize *C.size_t) unsafe.Pointer { + return nil +} + +//export onPause +func onPause(activity *C.ANativeActivity) { +} + +//export onStop +func onStop(activity *C.ANativeActivity) { +} + +//export onCreate +func onCreate(activity *C.ANativeActivity) { + // Set the initial configuration. + // + // Note we use unbuffered channels to talk to the activity loop, and + // NativeActivity calls these callbacks sequentially, so configuration + // will be set before <-windowRedrawNeeded is processed. + windowConfigChange <- windowConfigRead(activity) +} + +//export onDestroy +func onDestroy(activity *C.ANativeActivity) { +} + +//export onWindowFocusChanged +func onWindowFocusChanged(activity *C.ANativeActivity, hasFocus C.int) { +} + +//export onNativeWindowCreated +func onNativeWindowCreated(activity *C.ANativeActivity, window *C.ANativeWindow) { +} + +//export onNativeWindowRedrawNeeded +func onNativeWindowRedrawNeeded(activity *C.ANativeActivity, window *C.ANativeWindow) { + // Called on orientation change and window resize. + // Send a request for redraw, and block this function + // until a complete draw and buffer swap is completed. + // This is required by the redraw documentation to + // avoid bad draws. + windowRedrawNeeded <- window + <-windowRedrawDone +} + +//export onNativeWindowDestroyed +func onNativeWindowDestroyed(activity *C.ANativeActivity, window *C.ANativeWindow) { + windowDestroyed <- window +} + +//export onInputQueueCreated +func onInputQueueCreated(activity *C.ANativeActivity, q *C.AInputQueue) { + inputQueue <- q + <-inputQueueDone +} + +//export onInputQueueDestroyed +func onInputQueueDestroyed(activity *C.ANativeActivity, q *C.AInputQueue) { + inputQueue <- nil + <-inputQueueDone +} + +//export onContentRectChanged +func onContentRectChanged(activity *C.ANativeActivity, rect *C.ARect) { +} + +type windowConfig struct { + orientation size.Orientation + pixelsPerPt float32 +} + +func windowConfigRead(activity *C.ANativeActivity) windowConfig { + aconfig := C.AConfiguration_new() + C.AConfiguration_fromAssetManager(aconfig, activity.assetManager) + orient := C.AConfiguration_getOrientation(aconfig) + density := C.AConfiguration_getDensity(aconfig) + C.AConfiguration_delete(aconfig) + + // Calculate the screen resolution. This value is approximate. For example, + // a physical resolution of 200 DPI may be quantized to one of the + // ACONFIGURATION_DENSITY_XXX values such as 160 or 240. + // + // A more accurate DPI could possibly be calculated from + // https://developer.android.com/reference/android/util/DisplayMetrics.html#xdpi + // but this does not appear to be accessible via the NDK. In any case, the + // hardware might not even provide a more accurate number, as the system + // does not apparently use the reported value. See golang.org/issue/13366 + // for a discussion. + var dpi int + switch density { + case C.ACONFIGURATION_DENSITY_DEFAULT: + dpi = 160 + case C.ACONFIGURATION_DENSITY_LOW, + C.ACONFIGURATION_DENSITY_MEDIUM, + 213, // C.ACONFIGURATION_DENSITY_TV + C.ACONFIGURATION_DENSITY_HIGH, + 320, // ACONFIGURATION_DENSITY_XHIGH + 480, // ACONFIGURATION_DENSITY_XXHIGH + 640: // ACONFIGURATION_DENSITY_XXXHIGH + dpi = int(density) + case C.ACONFIGURATION_DENSITY_NONE: + log.Print("android device reports no screen density") + dpi = 72 + default: + log.Printf("android device reports unknown density: %d", density) + // All we can do is guess. + if density > 0 { + dpi = int(density) + } else { + dpi = 72 + } + } + + o := size.OrientationUnknown + switch orient { + case C.ACONFIGURATION_ORIENTATION_PORT: + o = size.OrientationPortrait + case C.ACONFIGURATION_ORIENTATION_LAND: + o = size.OrientationLandscape + } + + return windowConfig{ + orientation: o, + pixelsPerPt: float32(dpi) / 72, + } +} + +//export onConfigurationChanged +func onConfigurationChanged(activity *C.ANativeActivity) { + // A rotation event first triggers onConfigurationChanged, then + // calls onNativeWindowRedrawNeeded. We extract the orientation + // here and save it for the redraw event. + windowConfigChange <- windowConfigRead(activity) +} + +//export onLowMemory +func onLowMemory(activity *C.ANativeActivity) { +} + +var ( + inputQueue = make(chan *C.AInputQueue) + inputQueueDone = make(chan struct{}) + windowDestroyed = make(chan *C.ANativeWindow) + windowRedrawNeeded = make(chan *C.ANativeWindow) + windowRedrawDone = make(chan struct{}) + windowConfigChange = make(chan windowConfig) +) + +func init() { + theApp.registerGLViewportFilter() +} + +func main(f func(App)) { + mainUserFn = f + // TODO: merge the runInputQueue and mainUI functions? + go func() { + if err := mobileinit.RunOnJVM(runInputQueue); err != nil { + log.Fatalf("app: %v", err) + } + }() + // Preserve this OS thread for: + // 1. the attached JNI thread + // 2. the GL context + if err := mobileinit.RunOnJVM(mainUI); err != nil { + log.Fatalf("app: %v", err) + } +} + +var mainUserFn func(App) + +func mainUI(vm, jniEnv, ctx uintptr) error { + workAvailable := theApp.worker.WorkAvailable() + + donec := make(chan struct{}) + go func() { + // close the donec channel in a defer statement + // so that we could still be able to return even + // if mainUserFn panics. + defer close(donec) + + mainUserFn(theApp) + }() + + var pixelsPerPt float32 + var orientation size.Orientation + + for { + select { + case <-donec: + return nil + case cfg := <-windowConfigChange: + pixelsPerPt = cfg.pixelsPerPt + orientation = cfg.orientation + case w := <-windowRedrawNeeded: + if C.surface == nil { + if errStr := C.createEGLSurface(w); errStr != nil { + return fmt.Errorf("%s (%s)", C.GoString(errStr), eglGetError()) + } + } + theApp.sendLifecycle(lifecycle.StageFocused) + widthPx := int(C.ANativeWindow_getWidth(w)) + heightPx := int(C.ANativeWindow_getHeight(w)) + theApp.eventsIn <- size.Event{ + WidthPx: widthPx, + HeightPx: heightPx, + WidthPt: geom.Pt(float32(widthPx) / pixelsPerPt), + HeightPt: geom.Pt(float32(heightPx) / pixelsPerPt), + PixelsPerPt: pixelsPerPt, + Orientation: orientation, + } + theApp.eventsIn <- paint.Event{External: true} + case <-windowDestroyed: + if C.surface != nil { + if errStr := C.destroyEGLSurface(); errStr != nil { + return fmt.Errorf("%s (%s)", C.GoString(errStr), eglGetError()) + } + } + C.surface = nil + theApp.sendLifecycle(lifecycle.StageAlive) + case <-workAvailable: + theApp.worker.DoWork() + case <-theApp.publish: + // TODO: compare a generation number to redrawGen for stale paints? + if C.surface != nil { + // eglSwapBuffers blocks until vsync. + if C.eglSwapBuffers(C.display, C.surface) == C.EGL_FALSE { + log.Printf("app: failed to swap buffers (%s)", eglGetError()) + } + } + select { + case windowRedrawDone <- struct{}{}: + default: + } + theApp.publishResult <- PublishResult{} + } + } +} + +func runInputQueue(vm, jniEnv, ctx uintptr) error { + env := (*C.JNIEnv)(unsafe.Pointer(jniEnv)) // not a Go heap pointer + + // Android loopers select on OS file descriptors, not Go channels, so we + // translate the inputQueue channel to an ALooper_wake call. + l := C.ALooper_prepare(C.ALOOPER_PREPARE_ALLOW_NON_CALLBACKS) + pending := make(chan *C.AInputQueue, 1) + go func() { + for q := range inputQueue { + pending <- q + C.ALooper_wake(l) + } + }() + + var q *C.AInputQueue + for { + if C.ALooper_pollOnce(-1, nil, nil, nil) == C.ALOOPER_POLL_WAKE { + select { + default: + case p := <-pending: + if q != nil { + processEvents(env, q) + C.AInputQueue_detachLooper(q) + } + q = p + if q != nil { + C.AInputQueue_attachLooper(q, l, 0, nil, nil) + } + inputQueueDone <- struct{}{} + } + } + if q != nil { + processEvents(env, q) + } + } +} + +func processEvents(env *C.JNIEnv, q *C.AInputQueue) { + var e *C.AInputEvent + for C.AInputQueue_getEvent(q, &e) >= 0 { + if C.AInputQueue_preDispatchEvent(q, e) != 0 { + continue + } + processEvent(env, e) + C.AInputQueue_finishEvent(q, e, 0) + } +} + +func processEvent(env *C.JNIEnv, e *C.AInputEvent) { + switch C.AInputEvent_getType(e) { + case C.AINPUT_EVENT_TYPE_KEY: + processKey(env, e) + case C.AINPUT_EVENT_TYPE_MOTION: + // At most one of the events in this batch is an up or down event; get its index and change. + upDownIndex := C.size_t(C.AMotionEvent_getAction(e)&C.AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> C.AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT + upDownType := touch.TypeMove + switch C.AMotionEvent_getAction(e) & C.AMOTION_EVENT_ACTION_MASK { + case C.AMOTION_EVENT_ACTION_DOWN, C.AMOTION_EVENT_ACTION_POINTER_DOWN: + upDownType = touch.TypeBegin + case C.AMOTION_EVENT_ACTION_UP, C.AMOTION_EVENT_ACTION_POINTER_UP: + upDownType = touch.TypeEnd + } + + for i, n := C.size_t(0), C.AMotionEvent_getPointerCount(e); i < n; i++ { + t := touch.TypeMove + if i == upDownIndex { + t = upDownType + } + theApp.eventsIn <- touch.Event{ + X: float32(C.AMotionEvent_getX(e, i)), + Y: float32(C.AMotionEvent_getY(e, i)), + Sequence: touch.Sequence(C.AMotionEvent_getPointerId(e, i)), + Type: t, + } + } + default: + log.Printf("unknown input event, type=%d", C.AInputEvent_getType(e)) + } +} + +func processKey(env *C.JNIEnv, e *C.AInputEvent) { + deviceID := C.AInputEvent_getDeviceId(e) + if deviceID == 0 { + // Software keyboard input, leaving for scribe/IME. + return + } + + k := key.Event{ + Rune: rune(C.getKeyRune(env, e)), + Code: convAndroidKeyCode(int32(C.AKeyEvent_getKeyCode(e))), + } + switch C.AKeyEvent_getAction(e) { + case C.AKEY_EVENT_ACTION_DOWN: + k.Direction = key.DirPress + case C.AKEY_EVENT_ACTION_UP: + k.Direction = key.DirRelease + default: + k.Direction = key.DirNone + } + // TODO(crawshaw): set Modifiers. + theApp.eventsIn <- k +} + +func eglGetError() string { + switch errNum := C.eglGetError(); errNum { + case C.EGL_SUCCESS: + return "EGL_SUCCESS" + case C.EGL_NOT_INITIALIZED: + return "EGL_NOT_INITIALIZED" + case C.EGL_BAD_ACCESS: + return "EGL_BAD_ACCESS" + case C.EGL_BAD_ALLOC: + return "EGL_BAD_ALLOC" + case C.EGL_BAD_ATTRIBUTE: + return "EGL_BAD_ATTRIBUTE" + case C.EGL_BAD_CONTEXT: + return "EGL_BAD_CONTEXT" + case C.EGL_BAD_CONFIG: + return "EGL_BAD_CONFIG" + case C.EGL_BAD_CURRENT_SURFACE: + return "EGL_BAD_CURRENT_SURFACE" + case C.EGL_BAD_DISPLAY: + return "EGL_BAD_DISPLAY" + case C.EGL_BAD_SURFACE: + return "EGL_BAD_SURFACE" + case C.EGL_BAD_MATCH: + return "EGL_BAD_MATCH" + case C.EGL_BAD_PARAMETER: + return "EGL_BAD_PARAMETER" + case C.EGL_BAD_NATIVE_PIXMAP: + return "EGL_BAD_NATIVE_PIXMAP" + case C.EGL_BAD_NATIVE_WINDOW: + return "EGL_BAD_NATIVE_WINDOW" + case C.EGL_CONTEXT_LOST: + return "EGL_CONTEXT_LOST" + default: + return fmt.Sprintf("Unknown EGL err: %d", errNum) + } +} + +func convAndroidKeyCode(aKeyCode int32) key.Code { + // Many Android key codes do not map into USB HID codes. + // For those, key.CodeUnknown is returned. This switch has all + // cases, even the unknown ones, to serve as a documentation + // and search aid. + switch aKeyCode { + case C.AKEYCODE_UNKNOWN: + case C.AKEYCODE_SOFT_LEFT: + case C.AKEYCODE_SOFT_RIGHT: + case C.AKEYCODE_HOME: + return key.CodeHome + case C.AKEYCODE_BACK: + case C.AKEYCODE_CALL: + case C.AKEYCODE_ENDCALL: + case C.AKEYCODE_0: + return key.Code0 + case C.AKEYCODE_1: + return key.Code1 + case C.AKEYCODE_2: + return key.Code2 + case C.AKEYCODE_3: + return key.Code3 + case C.AKEYCODE_4: + return key.Code4 + case C.AKEYCODE_5: + return key.Code5 + case C.AKEYCODE_6: + return key.Code6 + case C.AKEYCODE_7: + return key.Code7 + case C.AKEYCODE_8: + return key.Code8 + case C.AKEYCODE_9: + return key.Code9 + case C.AKEYCODE_STAR: + case C.AKEYCODE_POUND: + case C.AKEYCODE_DPAD_UP: + case C.AKEYCODE_DPAD_DOWN: + case C.AKEYCODE_DPAD_LEFT: + case C.AKEYCODE_DPAD_RIGHT: + case C.AKEYCODE_DPAD_CENTER: + case C.AKEYCODE_VOLUME_UP: + return key.CodeVolumeUp + case C.AKEYCODE_VOLUME_DOWN: + return key.CodeVolumeDown + case C.AKEYCODE_POWER: + case C.AKEYCODE_CAMERA: + case C.AKEYCODE_CLEAR: + case C.AKEYCODE_A: + return key.CodeA + case C.AKEYCODE_B: + return key.CodeB + case C.AKEYCODE_C: + return key.CodeC + case C.AKEYCODE_D: + return key.CodeD + case C.AKEYCODE_E: + return key.CodeE + case C.AKEYCODE_F: + return key.CodeF + case C.AKEYCODE_G: + return key.CodeG + case C.AKEYCODE_H: + return key.CodeH + case C.AKEYCODE_I: + return key.CodeI + case C.AKEYCODE_J: + return key.CodeJ + case C.AKEYCODE_K: + return key.CodeK + case C.AKEYCODE_L: + return key.CodeL + case C.AKEYCODE_M: + return key.CodeM + case C.AKEYCODE_N: + return key.CodeN + case C.AKEYCODE_O: + return key.CodeO + case C.AKEYCODE_P: + return key.CodeP + case C.AKEYCODE_Q: + return key.CodeQ + case C.AKEYCODE_R: + return key.CodeR + case C.AKEYCODE_S: + return key.CodeS + case C.AKEYCODE_T: + return key.CodeT + case C.AKEYCODE_U: + return key.CodeU + case C.AKEYCODE_V: + return key.CodeV + case C.AKEYCODE_W: + return key.CodeW + case C.AKEYCODE_X: + return key.CodeX + case C.AKEYCODE_Y: + return key.CodeY + case C.AKEYCODE_Z: + return key.CodeZ + case C.AKEYCODE_COMMA: + return key.CodeComma + case C.AKEYCODE_PERIOD: + return key.CodeFullStop + case C.AKEYCODE_ALT_LEFT: + return key.CodeLeftAlt + case C.AKEYCODE_ALT_RIGHT: + return key.CodeRightAlt + case C.AKEYCODE_SHIFT_LEFT: + return key.CodeLeftShift + case C.AKEYCODE_SHIFT_RIGHT: + return key.CodeRightShift + case C.AKEYCODE_TAB: + return key.CodeTab + case C.AKEYCODE_SPACE: + return key.CodeSpacebar + case C.AKEYCODE_SYM: + case C.AKEYCODE_EXPLORER: + case C.AKEYCODE_ENVELOPE: + case C.AKEYCODE_ENTER: + return key.CodeReturnEnter + case C.AKEYCODE_DEL: + return key.CodeDeleteBackspace + case C.AKEYCODE_GRAVE: + return key.CodeGraveAccent + case C.AKEYCODE_MINUS: + return key.CodeHyphenMinus + case C.AKEYCODE_EQUALS: + return key.CodeEqualSign + case C.AKEYCODE_LEFT_BRACKET: + return key.CodeLeftSquareBracket + case C.AKEYCODE_RIGHT_BRACKET: + return key.CodeRightSquareBracket + case C.AKEYCODE_BACKSLASH: + return key.CodeBackslash + case C.AKEYCODE_SEMICOLON: + return key.CodeSemicolon + case C.AKEYCODE_APOSTROPHE: + return key.CodeApostrophe + case C.AKEYCODE_SLASH: + return key.CodeSlash + case C.AKEYCODE_AT: + case C.AKEYCODE_NUM: + case C.AKEYCODE_HEADSETHOOK: + case C.AKEYCODE_FOCUS: + case C.AKEYCODE_PLUS: + case C.AKEYCODE_MENU: + case C.AKEYCODE_NOTIFICATION: + case C.AKEYCODE_SEARCH: + case C.AKEYCODE_MEDIA_PLAY_PAUSE: + case C.AKEYCODE_MEDIA_STOP: + case C.AKEYCODE_MEDIA_NEXT: + case C.AKEYCODE_MEDIA_PREVIOUS: + case C.AKEYCODE_MEDIA_REWIND: + case C.AKEYCODE_MEDIA_FAST_FORWARD: + case C.AKEYCODE_MUTE: + case C.AKEYCODE_PAGE_UP: + return key.CodePageUp + case C.AKEYCODE_PAGE_DOWN: + return key.CodePageDown + case C.AKEYCODE_PICTSYMBOLS: + case C.AKEYCODE_SWITCH_CHARSET: + case C.AKEYCODE_BUTTON_A: + case C.AKEYCODE_BUTTON_B: + case C.AKEYCODE_BUTTON_C: + case C.AKEYCODE_BUTTON_X: + case C.AKEYCODE_BUTTON_Y: + case C.AKEYCODE_BUTTON_Z: + case C.AKEYCODE_BUTTON_L1: + case C.AKEYCODE_BUTTON_R1: + case C.AKEYCODE_BUTTON_L2: + case C.AKEYCODE_BUTTON_R2: + case C.AKEYCODE_BUTTON_THUMBL: + case C.AKEYCODE_BUTTON_THUMBR: + case C.AKEYCODE_BUTTON_START: + case C.AKEYCODE_BUTTON_SELECT: + case C.AKEYCODE_BUTTON_MODE: + case C.AKEYCODE_ESCAPE: + return key.CodeEscape + case C.AKEYCODE_FORWARD_DEL: + return key.CodeDeleteForward + case C.AKEYCODE_CTRL_LEFT: + return key.CodeLeftControl + case C.AKEYCODE_CTRL_RIGHT: + return key.CodeRightControl + case C.AKEYCODE_CAPS_LOCK: + return key.CodeCapsLock + case C.AKEYCODE_SCROLL_LOCK: + case C.AKEYCODE_META_LEFT: + return key.CodeLeftGUI + case C.AKEYCODE_META_RIGHT: + return key.CodeRightGUI + case C.AKEYCODE_FUNCTION: + case C.AKEYCODE_SYSRQ: + case C.AKEYCODE_BREAK: + case C.AKEYCODE_MOVE_HOME: + case C.AKEYCODE_MOVE_END: + case C.AKEYCODE_INSERT: + return key.CodeInsert + case C.AKEYCODE_FORWARD: + case C.AKEYCODE_MEDIA_PLAY: + case C.AKEYCODE_MEDIA_PAUSE: + case C.AKEYCODE_MEDIA_CLOSE: + case C.AKEYCODE_MEDIA_EJECT: + case C.AKEYCODE_MEDIA_RECORD: + case C.AKEYCODE_F1: + return key.CodeF1 + case C.AKEYCODE_F2: + return key.CodeF2 + case C.AKEYCODE_F3: + return key.CodeF3 + case C.AKEYCODE_F4: + return key.CodeF4 + case C.AKEYCODE_F5: + return key.CodeF5 + case C.AKEYCODE_F6: + return key.CodeF6 + case C.AKEYCODE_F7: + return key.CodeF7 + case C.AKEYCODE_F8: + return key.CodeF8 + case C.AKEYCODE_F9: + return key.CodeF9 + case C.AKEYCODE_F10: + return key.CodeF10 + case C.AKEYCODE_F11: + return key.CodeF11 + case C.AKEYCODE_F12: + return key.CodeF12 + case C.AKEYCODE_NUM_LOCK: + return key.CodeKeypadNumLock + case C.AKEYCODE_NUMPAD_0: + return key.CodeKeypad0 + case C.AKEYCODE_NUMPAD_1: + return key.CodeKeypad1 + case C.AKEYCODE_NUMPAD_2: + return key.CodeKeypad2 + case C.AKEYCODE_NUMPAD_3: + return key.CodeKeypad3 + case C.AKEYCODE_NUMPAD_4: + return key.CodeKeypad4 + case C.AKEYCODE_NUMPAD_5: + return key.CodeKeypad5 + case C.AKEYCODE_NUMPAD_6: + return key.CodeKeypad6 + case C.AKEYCODE_NUMPAD_7: + return key.CodeKeypad7 + case C.AKEYCODE_NUMPAD_8: + return key.CodeKeypad8 + case C.AKEYCODE_NUMPAD_9: + return key.CodeKeypad9 + case C.AKEYCODE_NUMPAD_DIVIDE: + return key.CodeKeypadSlash + case C.AKEYCODE_NUMPAD_MULTIPLY: + return key.CodeKeypadAsterisk + case C.AKEYCODE_NUMPAD_SUBTRACT: + return key.CodeKeypadHyphenMinus + case C.AKEYCODE_NUMPAD_ADD: + return key.CodeKeypadPlusSign + case C.AKEYCODE_NUMPAD_DOT: + return key.CodeKeypadFullStop + case C.AKEYCODE_NUMPAD_COMMA: + case C.AKEYCODE_NUMPAD_ENTER: + return key.CodeKeypadEnter + case C.AKEYCODE_NUMPAD_EQUALS: + return key.CodeKeypadEqualSign + case C.AKEYCODE_NUMPAD_LEFT_PAREN: + case C.AKEYCODE_NUMPAD_RIGHT_PAREN: + case C.AKEYCODE_VOLUME_MUTE: + return key.CodeMute + case C.AKEYCODE_INFO: + case C.AKEYCODE_CHANNEL_UP: + case C.AKEYCODE_CHANNEL_DOWN: + case C.AKEYCODE_ZOOM_IN: + case C.AKEYCODE_ZOOM_OUT: + case C.AKEYCODE_TV: + case C.AKEYCODE_WINDOW: + case C.AKEYCODE_GUIDE: + case C.AKEYCODE_DVR: + case C.AKEYCODE_BOOKMARK: + case C.AKEYCODE_CAPTIONS: + case C.AKEYCODE_SETTINGS: + case C.AKEYCODE_TV_POWER: + case C.AKEYCODE_TV_INPUT: + case C.AKEYCODE_STB_POWER: + case C.AKEYCODE_STB_INPUT: + case C.AKEYCODE_AVR_POWER: + case C.AKEYCODE_AVR_INPUT: + case C.AKEYCODE_PROG_RED: + case C.AKEYCODE_PROG_GREEN: + case C.AKEYCODE_PROG_YELLOW: + case C.AKEYCODE_PROG_BLUE: + case C.AKEYCODE_APP_SWITCH: + case C.AKEYCODE_BUTTON_1: + case C.AKEYCODE_BUTTON_2: + case C.AKEYCODE_BUTTON_3: + case C.AKEYCODE_BUTTON_4: + case C.AKEYCODE_BUTTON_5: + case C.AKEYCODE_BUTTON_6: + case C.AKEYCODE_BUTTON_7: + case C.AKEYCODE_BUTTON_8: + case C.AKEYCODE_BUTTON_9: + case C.AKEYCODE_BUTTON_10: + case C.AKEYCODE_BUTTON_11: + case C.AKEYCODE_BUTTON_12: + case C.AKEYCODE_BUTTON_13: + case C.AKEYCODE_BUTTON_14: + case C.AKEYCODE_BUTTON_15: + case C.AKEYCODE_BUTTON_16: + case C.AKEYCODE_LANGUAGE_SWITCH: + case C.AKEYCODE_MANNER_MODE: + case C.AKEYCODE_3D_MODE: + case C.AKEYCODE_CONTACTS: + case C.AKEYCODE_CALENDAR: + case C.AKEYCODE_MUSIC: + case C.AKEYCODE_CALCULATOR: + } + /* Defined in an NDK API version beyond what we use today: + C.AKEYCODE_ASSIST + C.AKEYCODE_BRIGHTNESS_DOWN + C.AKEYCODE_BRIGHTNESS_UP + C.AKEYCODE_EISU + C.AKEYCODE_HENKAN + C.AKEYCODE_KANA + C.AKEYCODE_KATAKANA_HIRAGANA + C.AKEYCODE_MEDIA_AUDIO_TRACK + C.AKEYCODE_MUHENKAN + C.AKEYCODE_RO + C.AKEYCODE_YEN + C.AKEYCODE_ZENKAKU_HANKAKU + */ + return key.CodeUnknown +} diff --git a/vendor/github.com/ebitengine/gomobile/app/app.go b/vendor/github.com/ebitengine/gomobile/app/app.go new file mode 100644 index 0000000..639f6e1 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/app/app.go @@ -0,0 +1,213 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build linux || darwin || windows + +package app + +import ( + "github.com/ebitengine/gomobile/event/lifecycle" + "github.com/ebitengine/gomobile/event/size" + "github.com/ebitengine/gomobile/gl" + _ "github.com/ebitengine/gomobile/internal/mobileinit" +) + +// Main is called by the main.main function to run the mobile application. +// +// It calls f on the App, in a separate goroutine, as some OS-specific +// libraries require being on 'the main thread'. +func Main(f func(App)) { + main(f) +} + +// App is how a GUI mobile application interacts with the OS. +type App interface { + // Events returns the events channel. It carries events from the system to + // the app. The type of such events include: + // - lifecycle.Event + // - mouse.Event + // - paint.Event + // - size.Event + // - touch.Event + // from the github.com/ebitengine/gomobile/event/etc packages. Other packages may + // define other event types that are carried on this channel. + Events() <-chan interface{} + + // Send sends an event on the events channel. It does not block. + Send(event interface{}) + + // Publish flushes any pending drawing commands, such as OpenGL calls, and + // swaps the back buffer to the screen. + Publish() PublishResult + + // TODO: replace filters (and the Events channel) with a NextEvent method? + + // Filter calls each registered event filter function in sequence. + Filter(event interface{}) interface{} + + // RegisterFilter registers a event filter function to be called by Filter. The + // function can return a different event, or return nil to consume the event, + // but the function can also return its argument unchanged, where its purpose + // is to trigger a side effect rather than modify the event. + RegisterFilter(f func(interface{}) interface{}) +} + +// PublishResult is the result of an App.Publish call. +type PublishResult struct { + // BackBufferPreserved is whether the contents of the back buffer was + // preserved. If false, the contents are undefined. + BackBufferPreserved bool +} + +var theApp = &app{ + eventsOut: make(chan interface{}), + lifecycleStage: lifecycle.StageDead, + publish: make(chan struct{}), + publishResult: make(chan PublishResult), +} + +func init() { + theApp.eventsIn = pump(theApp.eventsOut) + theApp.glctx, theApp.worker = gl.NewContext() +} + +func (a *app) sendLifecycle(to lifecycle.Stage) { + if a.lifecycleStage == to { + return + } + a.eventsIn <- lifecycle.Event{ + From: a.lifecycleStage, + To: to, + DrawContext: a.glctx, + } + a.lifecycleStage = to +} + +type app struct { + filters []func(interface{}) interface{} + + eventsOut chan interface{} + eventsIn chan interface{} + lifecycleStage lifecycle.Stage + publish chan struct{} + publishResult chan PublishResult + + glctx gl.Context + worker gl.Worker +} + +func (a *app) Events() <-chan interface{} { + return a.eventsOut +} + +func (a *app) Send(event interface{}) { + a.eventsIn <- event +} + +func (a *app) Publish() PublishResult { + // gl.Flush is a lightweight (on modern GL drivers) blocking call + // that ensures all GL functions pending in the gl package have + // been passed onto the GL driver before the app package attempts + // to swap the screen buffer. + // + // This enforces that the final receive (for this paint cycle) on + // gl.WorkAvailable happens before the send on endPaint. + a.glctx.Flush() + a.publish <- struct{}{} + return <-a.publishResult +} + +func (a *app) Filter(event interface{}) interface{} { + for _, f := range a.filters { + event = f(event) + } + return event +} + +func (a *app) RegisterFilter(f func(interface{}) interface{}) { + a.filters = append(a.filters, f) +} + +type stopPumping struct{} + +// pump returns a channel src such that sending on src will eventually send on +// dst, in order, but that src will always be ready to send/receive soon, even +// if dst currently isn't. It is effectively an infinitely buffered channel. +// +// In particular, goroutine A sending on src will not deadlock even if goroutine +// B that's responsible for receiving on dst is currently blocked trying to +// send to A on a separate channel. +// +// Send a stopPumping on the src channel to close the dst channel after all queued +// events are sent on dst. After that, other goroutines can still send to src, +// so that such sends won't block forever, but such events will be ignored. +func pump(dst chan interface{}) (src chan interface{}) { + src = make(chan interface{}) + go func() { + // initialSize is the initial size of the circular buffer. It must be a + // power of 2. + const initialSize = 16 + i, j, buf, mask := 0, 0, make([]interface{}, initialSize), initialSize-1 + + srcActive := true + for { + maybeDst := dst + if i == j { + maybeDst = nil + } + if maybeDst == nil && !srcActive { + // Pump is stopped and empty. + break + } + + select { + case maybeDst <- buf[i&mask]: + buf[i&mask] = nil + i++ + + case e := <-src: + if _, ok := e.(stopPumping); ok { + srcActive = false + continue + } + + if !srcActive { + continue + } + + // Allocate a bigger buffer if necessary. + if i+len(buf) == j { + b := make([]interface{}, 2*len(buf)) + n := copy(b, buf[j&mask:]) + copy(b[n:], buf[:j&mask]) + i, j = 0, len(buf) + buf, mask = b, len(b)-1 + } + + buf[j&mask] = e + j++ + } + } + + close(dst) + // Block forever. + for range src { + } + }() + return src +} + +// TODO: do this for all build targets, not just linux (x11 and Android)? If +// so, should package gl instead of this package call RegisterFilter?? +// +// TODO: does Android need this?? It seems to work without it (Nexus 7, +// KitKat). If only x11 needs this, should we move this to x11.go?? +func (a *app) registerGLViewportFilter() { + a.RegisterFilter(func(e interface{}) interface{} { + if e, ok := e.(size.Event); ok { + a.glctx.Viewport(0, 0, e.WidthPx, e.HeightPx) + } + return e + }) +} diff --git a/vendor/github.com/ebitengine/gomobile/app/app_windows.go b/vendor/github.com/ebitengine/gomobile/app/app_windows.go new file mode 100644 index 0000000..c94e644 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/app/app_windows.go @@ -0,0 +1,13 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package app + +import ( + "log" +) + +func main(f func(a App)) { + log.Fatal("main is not implemented on Windows") +} diff --git a/vendor/github.com/ebitengine/gomobile/app/darwin_desktop.go b/vendor/github.com/ebitengine/gomobile/app/darwin_desktop.go new file mode 100644 index 0000000..897352c --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/app/darwin_desktop.go @@ -0,0 +1,495 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build darwin && !ios + +package app + +// Simple on-screen app debugging for OS X. Not an officially supported +// development target for apps, as screens with mice are very different +// than screens with touch panels. + +/* +#cgo CFLAGS: -x objective-c -DGL_SILENCE_DEPRECATION +#cgo LDFLAGS: -framework Cocoa -framework OpenGL +#import // for HIToolbox/Events.h +#import +#include + +void runApp(void); +void stopApp(void); +void makeCurrentContext(GLintptr); +uint64 threadID(); +*/ +import "C" +import ( + "log" + "runtime" + "sync" + + "github.com/ebitengine/gomobile/event/key" + "github.com/ebitengine/gomobile/event/lifecycle" + "github.com/ebitengine/gomobile/event/paint" + "github.com/ebitengine/gomobile/event/size" + "github.com/ebitengine/gomobile/event/touch" + "github.com/ebitengine/gomobile/geom" +) + +var initThreadID uint64 + +func init() { + // Lock the goroutine responsible for initialization to an OS thread. + // This means the goroutine running main (and calling runApp below) + // is locked to the OS thread that started the program. This is + // necessary for the correct delivery of Cocoa events to the process. + // + // A discussion on this topic: + // https://groups.google.com/forum/#!msg/golang-nuts/IiWZ2hUuLDA/SNKYYZBelsYJ + runtime.LockOSThread() + initThreadID = uint64(C.threadID()) +} + +func main(f func(App)) { + if tid := uint64(C.threadID()); tid != initThreadID { + log.Fatalf("app.Main called on thread %d, but app.init ran on %d", tid, initThreadID) + } + + go func() { + f(theApp) + C.stopApp() + }() + + C.runApp() +} + +// loop is the primary drawing loop. +// +// After Cocoa has captured the initial OS thread for processing Cocoa +// events in runApp, it starts loop on another goroutine. It is locked +// to an OS thread for its OpenGL context. +// +// The loop processes GL calls until a publish event appears. +// Then it runs any remaining GL calls and flushes the screen. +// +// As NSOpenGLCPSwapInterval is set to 1, the call to CGLFlushDrawable +// blocks until the screen refresh. +func (a *app) loop(ctx C.GLintptr) { + runtime.LockOSThread() + C.makeCurrentContext(ctx) + + workAvailable := a.worker.WorkAvailable() + + for { + select { + case <-workAvailable: + a.worker.DoWork() + case <-theApp.publish: + loop1: + for { + select { + case <-workAvailable: + a.worker.DoWork() + default: + break loop1 + } + } + C.CGLFlushDrawable(C.CGLGetCurrentContext()) + theApp.publishResult <- PublishResult{} + select { + case drawDone <- struct{}{}: + default: + } + } + } +} + +var drawDone = make(chan struct{}) + +// drawgl is used by Cocoa to occasionally request screen updates. +// +//export drawgl +func drawgl() { + switch theApp.lifecycleStage { + case lifecycle.StageFocused, lifecycle.StageVisible: + theApp.Send(paint.Event{ + External: true, + }) + <-drawDone + } +} + +//export startloop +func startloop(ctx C.GLintptr) { + go theApp.loop(ctx) +} + +var windowHeightPx float32 + +//export setGeom +func setGeom(pixelsPerPt float32, widthPx, heightPx int) { + windowHeightPx = float32(heightPx) + theApp.eventsIn <- size.Event{ + WidthPx: widthPx, + HeightPx: heightPx, + WidthPt: geom.Pt(float32(widthPx) / pixelsPerPt), + HeightPt: geom.Pt(float32(heightPx) / pixelsPerPt), + PixelsPerPt: pixelsPerPt, + } +} + +var touchEvents struct { + sync.Mutex + pending []touch.Event +} + +func sendTouch(t touch.Type, x, y float32) { + theApp.eventsIn <- touch.Event{ + X: x, + Y: windowHeightPx - y, + Sequence: 0, + Type: t, + } +} + +//export eventMouseDown +func eventMouseDown(x, y float32) { sendTouch(touch.TypeBegin, x, y) } + +//export eventMouseDragged +func eventMouseDragged(x, y float32) { sendTouch(touch.TypeMove, x, y) } + +//export eventMouseEnd +func eventMouseEnd(x, y float32) { sendTouch(touch.TypeEnd, x, y) } + +//export lifecycleDead +func lifecycleDead() { theApp.sendLifecycle(lifecycle.StageDead) } + +//export eventKey +func eventKey(runeVal int32, direction uint8, code uint16, flags uint32) { + var modifiers key.Modifiers + for _, mod := range mods { + if flags&mod.flags == mod.flags { + modifiers |= mod.mod + } + } + + theApp.eventsIn <- key.Event{ + Rune: convRune(rune(runeVal)), + Code: convVirtualKeyCode(code), + Modifiers: modifiers, + Direction: key.Direction(direction), + } +} + +//export eventFlags +func eventFlags(flags uint32) { + for _, mod := range mods { + if flags&mod.flags == mod.flags && lastFlags&mod.flags != mod.flags { + eventKey(-1, uint8(key.DirPress), mod.code, flags) + } + if lastFlags&mod.flags == mod.flags && flags&mod.flags != mod.flags { + eventKey(-1, uint8(key.DirRelease), mod.code, flags) + } + } + lastFlags = flags +} + +var lastFlags uint32 + +var mods = [...]struct { + flags uint32 + code uint16 + mod key.Modifiers +}{ + // Left and right variants of modifier keys have their own masks, + // but they are not documented. These were determined empirically. + {1<<17 | 0x102, C.kVK_Shift, key.ModShift}, + {1<<17 | 0x104, C.kVK_RightShift, key.ModShift}, + {1<<18 | 0x101, C.kVK_Control, key.ModControl}, + // TODO key.ControlRight + {1<<19 | 0x120, C.kVK_Option, key.ModAlt}, + {1<<19 | 0x140, C.kVK_RightOption, key.ModAlt}, + {1<<20 | 0x108, C.kVK_Command, key.ModMeta}, + {1<<20 | 0x110, C.kVK_Command, key.ModMeta}, // TODO: missing kVK_RightCommand +} + +//export lifecycleAlive +func lifecycleAlive() { theApp.sendLifecycle(lifecycle.StageAlive) } + +//export lifecycleVisible +func lifecycleVisible() { + theApp.sendLifecycle(lifecycle.StageVisible) +} + +//export lifecycleFocused +func lifecycleFocused() { theApp.sendLifecycle(lifecycle.StageFocused) } + +// convRune marks the Carbon/Cocoa private-range unicode rune representing +// a non-unicode key event to -1, used for Rune in the key package. +// +// http://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/CORPCHAR.TXT +func convRune(r rune) rune { + if '\uE000' <= r && r <= '\uF8FF' { + return -1 + } + return r +} + +// convVirtualKeyCode converts a Carbon/Cocoa virtual key code number +// into the standard keycodes used by the key package. +// +// To get a sense of the key map, see the diagram on +// +// http://boredzo.org/blog/archives/2007-05-22/virtual-key-codes +func convVirtualKeyCode(vkcode uint16) key.Code { + switch vkcode { + case C.kVK_ANSI_A: + return key.CodeA + case C.kVK_ANSI_B: + return key.CodeB + case C.kVK_ANSI_C: + return key.CodeC + case C.kVK_ANSI_D: + return key.CodeD + case C.kVK_ANSI_E: + return key.CodeE + case C.kVK_ANSI_F: + return key.CodeF + case C.kVK_ANSI_G: + return key.CodeG + case C.kVK_ANSI_H: + return key.CodeH + case C.kVK_ANSI_I: + return key.CodeI + case C.kVK_ANSI_J: + return key.CodeJ + case C.kVK_ANSI_K: + return key.CodeK + case C.kVK_ANSI_L: + return key.CodeL + case C.kVK_ANSI_M: + return key.CodeM + case C.kVK_ANSI_N: + return key.CodeN + case C.kVK_ANSI_O: + return key.CodeO + case C.kVK_ANSI_P: + return key.CodeP + case C.kVK_ANSI_Q: + return key.CodeQ + case C.kVK_ANSI_R: + return key.CodeR + case C.kVK_ANSI_S: + return key.CodeS + case C.kVK_ANSI_T: + return key.CodeT + case C.kVK_ANSI_U: + return key.CodeU + case C.kVK_ANSI_V: + return key.CodeV + case C.kVK_ANSI_W: + return key.CodeW + case C.kVK_ANSI_X: + return key.CodeX + case C.kVK_ANSI_Y: + return key.CodeY + case C.kVK_ANSI_Z: + return key.CodeZ + case C.kVK_ANSI_1: + return key.Code1 + case C.kVK_ANSI_2: + return key.Code2 + case C.kVK_ANSI_3: + return key.Code3 + case C.kVK_ANSI_4: + return key.Code4 + case C.kVK_ANSI_5: + return key.Code5 + case C.kVK_ANSI_6: + return key.Code6 + case C.kVK_ANSI_7: + return key.Code7 + case C.kVK_ANSI_8: + return key.Code8 + case C.kVK_ANSI_9: + return key.Code9 + case C.kVK_ANSI_0: + return key.Code0 + // TODO: move the rest of these codes to constants in key.go + // if we are happy with them. + case C.kVK_Return: + return key.CodeReturnEnter + case C.kVK_Escape: + return key.CodeEscape + case C.kVK_Delete: + return key.CodeDeleteBackspace + case C.kVK_Tab: + return key.CodeTab + case C.kVK_Space: + return key.CodeSpacebar + case C.kVK_ANSI_Minus: + return key.CodeHyphenMinus + case C.kVK_ANSI_Equal: + return key.CodeEqualSign + case C.kVK_ANSI_LeftBracket: + return key.CodeLeftSquareBracket + case C.kVK_ANSI_RightBracket: + return key.CodeRightSquareBracket + case C.kVK_ANSI_Backslash: + return key.CodeBackslash + // 50: Keyboard Non-US "#" and ~ + case C.kVK_ANSI_Semicolon: + return key.CodeSemicolon + case C.kVK_ANSI_Quote: + return key.CodeApostrophe + case C.kVK_ANSI_Grave: + return key.CodeGraveAccent + case C.kVK_ANSI_Comma: + return key.CodeComma + case C.kVK_ANSI_Period: + return key.CodeFullStop + case C.kVK_ANSI_Slash: + return key.CodeSlash + case C.kVK_CapsLock: + return key.CodeCapsLock + case C.kVK_F1: + return key.CodeF1 + case C.kVK_F2: + return key.CodeF2 + case C.kVK_F3: + return key.CodeF3 + case C.kVK_F4: + return key.CodeF4 + case C.kVK_F5: + return key.CodeF5 + case C.kVK_F6: + return key.CodeF6 + case C.kVK_F7: + return key.CodeF7 + case C.kVK_F8: + return key.CodeF8 + case C.kVK_F9: + return key.CodeF9 + case C.kVK_F10: + return key.CodeF10 + case C.kVK_F11: + return key.CodeF11 + case C.kVK_F12: + return key.CodeF12 + // 70: PrintScreen + // 71: Scroll Lock + // 72: Pause + // 73: Insert + case C.kVK_Home: + return key.CodeHome + case C.kVK_PageUp: + return key.CodePageUp + case C.kVK_ForwardDelete: + return key.CodeDeleteForward + case C.kVK_End: + return key.CodeEnd + case C.kVK_PageDown: + return key.CodePageDown + case C.kVK_RightArrow: + return key.CodeRightArrow + case C.kVK_LeftArrow: + return key.CodeLeftArrow + case C.kVK_DownArrow: + return key.CodeDownArrow + case C.kVK_UpArrow: + return key.CodeUpArrow + case C.kVK_ANSI_KeypadClear: + return key.CodeKeypadNumLock + case C.kVK_ANSI_KeypadDivide: + return key.CodeKeypadSlash + case C.kVK_ANSI_KeypadMultiply: + return key.CodeKeypadAsterisk + case C.kVK_ANSI_KeypadMinus: + return key.CodeKeypadHyphenMinus + case C.kVK_ANSI_KeypadPlus: + return key.CodeKeypadPlusSign + case C.kVK_ANSI_KeypadEnter: + return key.CodeKeypadEnter + case C.kVK_ANSI_Keypad1: + return key.CodeKeypad1 + case C.kVK_ANSI_Keypad2: + return key.CodeKeypad2 + case C.kVK_ANSI_Keypad3: + return key.CodeKeypad3 + case C.kVK_ANSI_Keypad4: + return key.CodeKeypad4 + case C.kVK_ANSI_Keypad5: + return key.CodeKeypad5 + case C.kVK_ANSI_Keypad6: + return key.CodeKeypad6 + case C.kVK_ANSI_Keypad7: + return key.CodeKeypad7 + case C.kVK_ANSI_Keypad8: + return key.CodeKeypad8 + case C.kVK_ANSI_Keypad9: + return key.CodeKeypad9 + case C.kVK_ANSI_Keypad0: + return key.CodeKeypad0 + case C.kVK_ANSI_KeypadDecimal: + return key.CodeKeypadFullStop + case C.kVK_ANSI_KeypadEquals: + return key.CodeKeypadEqualSign + case C.kVK_F13: + return key.CodeF13 + case C.kVK_F14: + return key.CodeF14 + case C.kVK_F15: + return key.CodeF15 + case C.kVK_F16: + return key.CodeF16 + case C.kVK_F17: + return key.CodeF17 + case C.kVK_F18: + return key.CodeF18 + case C.kVK_F19: + return key.CodeF19 + case C.kVK_F20: + return key.CodeF20 + // 116: Keyboard Execute + case C.kVK_Help: + return key.CodeHelp + // 118: Keyboard Menu + // 119: Keyboard Select + // 120: Keyboard Stop + // 121: Keyboard Again + // 122: Keyboard Undo + // 123: Keyboard Cut + // 124: Keyboard Copy + // 125: Keyboard Paste + // 126: Keyboard Find + case C.kVK_Mute: + return key.CodeMute + case C.kVK_VolumeUp: + return key.CodeVolumeUp + case C.kVK_VolumeDown: + return key.CodeVolumeDown + // 130: Keyboard Locking Caps Lock + // 131: Keyboard Locking Num Lock + // 132: Keyboard Locking Scroll Lock + // 133: Keyboard Comma + // 134: Keyboard Equal Sign + // ...: Bunch of stuff + case C.kVK_Control: + return key.CodeLeftControl + case C.kVK_Shift: + return key.CodeLeftShift + case C.kVK_Option: + return key.CodeLeftAlt + case C.kVK_Command: + return key.CodeLeftGUI + case C.kVK_RightControl: + return key.CodeRightControl + case C.kVK_RightShift: + return key.CodeRightShift + case C.kVK_RightOption: + return key.CodeRightAlt + // TODO key.CodeRightGUI + default: + return key.CodeUnknown + } +} diff --git a/vendor/github.com/ebitengine/gomobile/app/darwin_desktop.m b/vendor/github.com/ebitengine/gomobile/app/darwin_desktop.m new file mode 100644 index 0000000..071124f --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/app/darwin_desktop.m @@ -0,0 +1,251 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build darwin && !ios +// +build darwin +// +build !ios + +#include "_cgo_export.h" +#include +#include + +#import +#import +#import + +void makeCurrentContext(GLintptr context) { + NSOpenGLContext* ctx = (NSOpenGLContext*)context; + [ctx makeCurrentContext]; +} + +uint64 threadID() { + uint64 id; + if (pthread_threadid_np(pthread_self(), &id)) { + abort(); + } + return id; +} + +@interface MobileGLView : NSOpenGLView +{ +} +@end + +@implementation MobileGLView +- (void)prepareOpenGL { + [super prepareOpenGL]; + [self setWantsBestResolutionOpenGLSurface:YES]; + GLint swapInt = 1; + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + [[self openGLContext] setValues:&swapInt forParameter:NSOpenGLCPSwapInterval]; +#pragma clang diagnostic pop + + // Using attribute arrays in OpenGL 3.3 requires the use of a VBA. + // But VBAs don't exist in ES 2. So we bind a default one. + GLuint vba; + glGenVertexArrays(1, &vba); + glBindVertexArray(vba); + + startloop((GLintptr)[self openGLContext]); +} + +- (void)reshape { + [super reshape]; + + // Calculate screen PPI. + // + // Note that the backingScaleFactor converts from logical + // pixels to actual pixels, but both of these units vary + // independently from real world size. E.g. + // + // 13" Retina Macbook Pro, 2560x1600, 227ppi, backingScaleFactor=2, scale=3.15 + // 15" Retina Macbook Pro, 2880x1800, 220ppi, backingScaleFactor=2, scale=3.06 + // 27" iMac, 2560x1440, 109ppi, backingScaleFactor=1, scale=1.51 + // 27" Retina iMac, 5120x2880, 218ppi, backingScaleFactor=2, scale=3.03 + NSScreen *screen = [NSScreen mainScreen]; + double screenPixW = [screen frame].size.width * [screen backingScaleFactor]; + + CGDirectDisplayID display = (CGDirectDisplayID)[[[screen deviceDescription] valueForKey:@"NSScreenNumber"] intValue]; + CGSize screenSizeMM = CGDisplayScreenSize(display); // in millimeters + float ppi = 25.4 * screenPixW / screenSizeMM.width; + float pixelsPerPt = ppi/72.0; + + // The width and height reported to the geom package are the + // bounds of the OpenGL view. Several steps are necessary. + // First, [self bounds] gives us the number of logical pixels + // in the view. Multiplying this by the backingScaleFactor + // gives us the number of actual pixels. + NSRect r = [self bounds]; + int w = r.size.width * [screen backingScaleFactor]; + int h = r.size.height * [screen backingScaleFactor]; + + setGeom(pixelsPerPt, w, h); +} + +- (void)drawRect:(NSRect)theRect { + // Called during resize. This gets rid of flicker when resizing. + drawgl(); +} + +- (void)mouseDown:(NSEvent *)theEvent { + double scale = [[NSScreen mainScreen] backingScaleFactor]; + NSPoint p = [theEvent locationInWindow]; + eventMouseDown(p.x * scale, p.y * scale); +} + +- (void)mouseUp:(NSEvent *)theEvent { + double scale = [[NSScreen mainScreen] backingScaleFactor]; + NSPoint p = [theEvent locationInWindow]; + eventMouseEnd(p.x * scale, p.y * scale); +} + +- (void)mouseDragged:(NSEvent *)theEvent { + double scale = [[NSScreen mainScreen] backingScaleFactor]; + NSPoint p = [theEvent locationInWindow]; + eventMouseDragged(p.x * scale, p.y * scale); +} + +- (void)windowDidBecomeKey:(NSNotification *)notification { + lifecycleFocused(); +} + +- (void)windowDidResignKey:(NSNotification *)notification { + if (![NSApp isHidden]) { + lifecycleVisible(); + } +} + +- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { + lifecycleAlive(); + [[NSRunningApplication currentApplication] activateWithOptions:(NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps)]; + [self.window makeKeyAndOrderFront:self]; + lifecycleVisible(); +} + +- (void)applicationWillTerminate:(NSNotification *)aNotification { + lifecycleDead(); +} + +- (void)applicationDidHide:(NSNotification *)aNotification { + lifecycleAlive(); +} + +- (void)applicationWillUnhide:(NSNotification *)notification { + lifecycleVisible(); +} + +- (void)windowWillClose:(NSNotification *)notification { + lifecycleAlive(); +} +@end + +@interface MobileResponder : NSResponder +{ +} +@end + +@implementation MobileResponder +- (void)keyDown:(NSEvent *)theEvent { + [self key:theEvent]; +} +- (void)keyUp:(NSEvent *)theEvent { + [self key:theEvent]; +} +- (void)key:(NSEvent *)theEvent { + NSRange range = [theEvent.characters rangeOfComposedCharacterSequenceAtIndex:0]; + + uint8_t buf[4] = {0, 0, 0, 0}; + if (![theEvent.characters getBytes:buf + maxLength:4 + usedLength:nil + encoding:NSUTF32LittleEndianStringEncoding + options:NSStringEncodingConversionAllowLossy + range:range + remainingRange:nil]) { + NSLog(@"failed to read key event %@", theEvent); + return; + } + + uint32_t rune = (uint32_t)buf[0]<<0 | (uint32_t)buf[1]<<8 | (uint32_t)buf[2]<<16 | (uint32_t)buf[3]<<24; + + uint8_t direction; + if ([theEvent isARepeat]) { + direction = 0; + } else if (theEvent.type == NSEventTypeKeyDown) { + direction = 1; + } else { + direction = 2; + } + eventKey((int32_t)rune, direction, theEvent.keyCode, theEvent.modifierFlags); +} + +- (void)flagsChanged:(NSEvent *)theEvent { + eventFlags(theEvent.modifierFlags); +} +@end + +void +runApp(void) { + [NSAutoreleasePool new]; + [NSApplication sharedApplication]; + [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; + + id menuBar = [[NSMenu new] autorelease]; + id menuItem = [[NSMenuItem new] autorelease]; + [menuBar addItem:menuItem]; + [NSApp setMainMenu:menuBar]; + + id menu = [[NSMenu new] autorelease]; + id name = [[NSProcessInfo processInfo] processName]; + + id hideMenuItem = [[[NSMenuItem alloc] initWithTitle:@"Hide" + action:@selector(hide:) keyEquivalent:@"h"] + autorelease]; + [menu addItem:hideMenuItem]; + + id quitMenuItem = [[[NSMenuItem alloc] initWithTitle:@"Quit" + action:@selector(terminate:) keyEquivalent:@"q"] + autorelease]; + [menu addItem:quitMenuItem]; + [menuItem setSubmenu:menu]; + + NSRect rect = NSMakeRect(0, 0, 600, 800); + + NSWindow* window = [[[NSWindow alloc] initWithContentRect:rect + styleMask:NSWindowStyleMaskTitled + backing:NSBackingStoreBuffered + defer:NO] + autorelease]; + window.styleMask |= NSWindowStyleMaskResizable; + window.styleMask |= NSWindowStyleMaskMiniaturizable; + window.styleMask |= NSWindowStyleMaskClosable; + window.title = name; + [window cascadeTopLeftFromPoint:NSMakePoint(20,20)]; + + NSOpenGLPixelFormatAttribute attr[] = { + NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersion3_2Core, + NSOpenGLPFAColorSize, 24, + NSOpenGLPFAAlphaSize, 8, + NSOpenGLPFADepthSize, 16, + NSOpenGLPFAAccelerated, + NSOpenGLPFADoubleBuffer, + NSOpenGLPFAAllowOfflineRenderers, + 0 + }; + id pixFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attr]; + MobileGLView* view = [[MobileGLView alloc] initWithFrame:rect pixelFormat:pixFormat]; + [window setContentView:view]; + [window setDelegate:view]; + [NSApp setDelegate:view]; + + window.nextResponder = [[[MobileResponder alloc] init] autorelease]; + + [NSApp run]; +} + +void stopApp(void) { + [NSApp terminate:nil]; +} diff --git a/vendor/github.com/ebitengine/gomobile/app/darwin_ios.go b/vendor/github.com/ebitengine/gomobile/app/darwin_ios.go new file mode 100644 index 0000000..b9fda42 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/app/darwin_ios.go @@ -0,0 +1,215 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build darwin && ios + +package app + +/* +#cgo CFLAGS: -x objective-c -DGL_SILENCE_DEPRECATION -DGLES_SILENCE_DEPRECATION +#cgo LDFLAGS: -framework Foundation -framework UIKit -framework GLKit -framework OpenGLES -framework QuartzCore +#include +#include +#include +#include +#import + +extern struct utsname sysInfo; + +void runApp(void); +void makeCurrentContext(GLintptr ctx); +void swapBuffers(GLintptr ctx); +uint64_t threadID(); +*/ +import "C" +import ( + "log" + "runtime" + "strings" + "sync" + + "github.com/ebitengine/gomobile/event/lifecycle" + "github.com/ebitengine/gomobile/event/paint" + "github.com/ebitengine/gomobile/event/size" + "github.com/ebitengine/gomobile/event/touch" + "github.com/ebitengine/gomobile/geom" +) + +var initThreadID uint64 + +func init() { + // Lock the goroutine responsible for initialization to an OS thread. + // This means the goroutine running main (and calling the run function + // below) is locked to the OS thread that started the program. This is + // necessary for the correct delivery of UIKit events to the process. + // + // A discussion on this topic: + // https://groups.google.com/forum/#!msg/golang-nuts/IiWZ2hUuLDA/SNKYYZBelsYJ + runtime.LockOSThread() + initThreadID = uint64(C.threadID()) +} + +func main(f func(App)) { + if tid := uint64(C.threadID()); tid != initThreadID { + log.Fatalf("app.Run called on thread %d, but app.init ran on %d", tid, initThreadID) + } + + go func() { + f(theApp) + // TODO(crawshaw): trigger runApp to return + }() + C.runApp() + panic("unexpected return from app.runApp") +} + +var pixelsPerPt float32 +var screenScale int // [UIScreen mainScreen].scale, either 1, 2, or 3. + +//export setScreen +func setScreen(scale int) { + C.uname(&C.sysInfo) + name := C.GoString(&C.sysInfo.machine[0]) + + var v float32 + + switch { + case strings.HasPrefix(name, "iPhone"): + v = 163 + case strings.HasPrefix(name, "iPad"): + // TODO: is there a better way to distinguish the iPad Mini? + switch name { + case "iPad2,5", "iPad2,6", "iPad2,7", "iPad4,4", "iPad4,5", "iPad4,6", "iPad4,7": + v = 163 // iPad Mini + default: + v = 132 + } + default: + v = 163 // names like i386 and x86_64 are the simulator + } + + if v == 0 { + log.Printf("unknown machine: %s", name) + v = 163 // emergency fallback + } + + pixelsPerPt = v * float32(scale) / 72 + screenScale = scale +} + +//export updateConfig +func updateConfig(width, height, orientation int32) { + o := size.OrientationUnknown + switch orientation { + case C.UIDeviceOrientationPortrait, C.UIDeviceOrientationPortraitUpsideDown: + o = size.OrientationPortrait + case C.UIDeviceOrientationLandscapeLeft, C.UIDeviceOrientationLandscapeRight: + o = size.OrientationLandscape + } + widthPx := screenScale * int(width) + heightPx := screenScale * int(height) + theApp.eventsIn <- size.Event{ + WidthPx: widthPx, + HeightPx: heightPx, + WidthPt: geom.Pt(float32(widthPx) / pixelsPerPt), + HeightPt: geom.Pt(float32(heightPx) / pixelsPerPt), + PixelsPerPt: pixelsPerPt, + Orientation: o, + } + theApp.eventsIn <- paint.Event{External: true} +} + +// touchIDs is the current active touches. The position in the array +// is the ID, the value is the UITouch* pointer value. +// +// It is widely reported that the iPhone can handle up to 5 simultaneous +// touch events, while the iPad can handle 11. +var touchIDs [11]uintptr + +var touchEvents struct { + sync.Mutex + pending []touch.Event +} + +//export sendTouch +func sendTouch(cTouch, cTouchType uintptr, x, y float32) { + id := -1 + for i, val := range touchIDs { + if val == cTouch { + id = i + break + } + } + if id == -1 { + for i, val := range touchIDs { + if val == 0 { + touchIDs[i] = cTouch + id = i + break + } + } + if id == -1 { + panic("out of touchIDs") + } + } + + t := touch.Type(cTouchType) + if t == touch.TypeEnd { + touchIDs[id] = 0 + } + + theApp.eventsIn <- touch.Event{ + X: x, + Y: y, + Sequence: touch.Sequence(id), + Type: t, + } +} + +//export lifecycleDead +func lifecycleDead() { theApp.sendLifecycle(lifecycle.StageDead) } + +//export lifecycleAlive +func lifecycleAlive() { theApp.sendLifecycle(lifecycle.StageAlive) } + +//export lifecycleVisible +func lifecycleVisible() { theApp.sendLifecycle(lifecycle.StageVisible) } + +//export lifecycleFocused +func lifecycleFocused() { theApp.sendLifecycle(lifecycle.StageFocused) } + +//export startloop +func startloop(ctx C.GLintptr) { + go theApp.loop(ctx) +} + +// loop is the primary drawing loop. +// +// After UIKit has captured the initial OS thread for processing UIKit +// events in runApp, it starts loop on another goroutine. It is locked +// to an OS thread for its OpenGL context. +func (a *app) loop(ctx C.GLintptr) { + runtime.LockOSThread() + C.makeCurrentContext(ctx) + + workAvailable := a.worker.WorkAvailable() + + for { + select { + case <-workAvailable: + a.worker.DoWork() + case <-theApp.publish: + loop1: + for { + select { + case <-workAvailable: + a.worker.DoWork() + default: + break loop1 + } + } + C.swapBuffers(ctx) + theApp.publishResult <- PublishResult{} + } + } +} diff --git a/vendor/github.com/ebitengine/gomobile/app/darwin_ios.m b/vendor/github.com/ebitengine/gomobile/app/darwin_ios.m new file mode 100644 index 0000000..21d73a5 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/app/darwin_ios.m @@ -0,0 +1,167 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build darwin && ios +// +build darwin +// +build ios + +#include "_cgo_export.h" +#include +#include +#include + +#import +#import + +struct utsname sysInfo; + +@interface GoAppAppController : GLKViewController +@end + +@interface GoAppAppDelegate : UIResponder +@property (strong, nonatomic) UIWindow *window; +@property (strong, nonatomic) GoAppAppController *controller; +@end + +@implementation GoAppAppDelegate +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { + lifecycleAlive(); + self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; + self.controller = [[GoAppAppController alloc] initWithNibName:nil bundle:nil]; + self.window.rootViewController = self.controller; + [self.window makeKeyAndVisible]; + return YES; +} + +- (void)applicationDidBecomeActive:(UIApplication * )application { + lifecycleFocused(); +} + +- (void)applicationWillResignActive:(UIApplication *)application { + lifecycleVisible(); +} + +- (void)applicationDidEnterBackground:(UIApplication *)application { + lifecycleAlive(); +} + +- (void)applicationWillTerminate:(UIApplication *)application { + lifecycleDead(); +} +@end + +@interface GoAppAppController () +@property (strong, nonatomic) EAGLContext *context; +@property (strong, nonatomic) GLKView *glview; +@end + +@implementation GoAppAppController +- (void)viewWillAppear:(BOOL)animated +{ + // TODO: replace by swapping out GLKViewController for a UIVIewController. + [super viewWillAppear:animated]; + self.paused = YES; +} + +- (void)viewDidLoad { + [super viewDidLoad]; + self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2]; + self.glview = (GLKView*)self.view; + self.glview.drawableDepthFormat = GLKViewDrawableDepthFormat24; + self.glview.multipleTouchEnabled = true; // TODO expose setting to user. + self.glview.context = self.context; + self.glview.userInteractionEnabled = YES; + self.glview.enableSetNeedsDisplay = YES; // only invoked once + + // Do not use the GLKViewController draw loop. + self.paused = YES; + self.resumeOnDidBecomeActive = NO; + self.preferredFramesPerSecond = 0; + + int scale = 1; + if ([[UIScreen mainScreen] respondsToSelector:@selector(displayLinkWithTarget:selector:)]) { + scale = (int)[UIScreen mainScreen].scale; // either 1.0, 2.0, or 3.0. + } + setScreen(scale); + + CGSize size = [UIScreen mainScreen].bounds.size; + UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; + updateConfig((int)size.width, (int)size.height, orientation); +} + +- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id)coordinator { + [coordinator animateAlongsideTransition:^(id context) { + // TODO(crawshaw): come up with a plan to handle animations. + } completion:^(id context) { + UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; + updateConfig((int)size.width, (int)size.height, orientation); + }]; +} + +- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect { + // Now that we have been asked to do the first draw, disable any + // future draw and hand control over to the Go paint.Event cycle. + self.glview.enableSetNeedsDisplay = NO; + startloop((GLintptr)self.context); +} + +#define TOUCH_TYPE_BEGIN 0 // touch.TypeBegin +#define TOUCH_TYPE_MOVE 1 // touch.TypeMove +#define TOUCH_TYPE_END 2 // touch.TypeEnd + +static void sendTouches(int change, NSSet* touches) { + CGFloat scale = [UIScreen mainScreen].scale; + for (UITouch* touch in touches) { + CGPoint p = [touch locationInView:touch.view]; + sendTouch((GoUintptr)touch, (GoUintptr)change, p.x*scale, p.y*scale); + } +} + +- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { + sendTouches(TOUCH_TYPE_BEGIN, touches); +} + +- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event { + sendTouches(TOUCH_TYPE_MOVE, touches); +} + +- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event { + sendTouches(TOUCH_TYPE_END, touches); +} + +- (void)touchesCanceled:(NSSet*)touches withEvent:(UIEvent*)event { + sendTouches(TOUCH_TYPE_END, touches); +} +@end + +void runApp(void) { + char* argv[] = {}; + @autoreleasepool { + UIApplicationMain(0, argv, nil, NSStringFromClass([GoAppAppDelegate class])); + } +} + +void makeCurrentContext(GLintptr context) { + EAGLContext* ctx = (EAGLContext*)context; + if (![EAGLContext setCurrentContext:ctx]) { + // TODO(crawshaw): determine how terrible this is. Exit? + NSLog(@"failed to set current context"); + } +} + +void swapBuffers(GLintptr context) { + __block EAGLContext* ctx = (EAGLContext*)context; + dispatch_sync(dispatch_get_main_queue(), ^{ + [EAGLContext setCurrentContext:ctx]; + [ctx presentRenderbuffer:GL_RENDERBUFFER]; + }); +} + +uint64_t threadID() { + uint64_t id; + if (pthread_threadid_np(pthread_self(), &id)) { + abort(); + } + return id; +} diff --git a/vendor/github.com/ebitengine/gomobile/app/doc.go b/vendor/github.com/ebitengine/gomobile/app/doc.go new file mode 100644 index 0000000..7e97843 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/app/doc.go @@ -0,0 +1,88 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* +Package app lets you write portable all-Go apps for Android and iOS. + +There are typically two ways to use Go on Android and iOS. The first +is to write a Go library and use `gomobile bind` to generate language +bindings for Java and Objective-C. Building a library does not +require the app package. The `gomobile bind` command produces output +that you can include in an Android Studio or Xcode project. For more +on language bindings, see https://github.com/ebitengine/gomobile/cmd/gobind. + +The second way is to write an app entirely in Go. The APIs are limited +to those that are portable between both Android and iOS, in particular +OpenGL, audio, and other Android NDK-like APIs. An all-Go app should +use this app package to initialize the app, manage its lifecycle, and +receive events. + +# Building apps + +Apps written entirely in Go have a main function, and can be built +with `gomobile build`, which directly produces runnable output for +Android and iOS. + +The gomobile tool can get installed with go get. For reference, see +https://github.com/ebitengine/gomobile/cmd/gomobile. + +For detailed instructions and documentation, see +https://golang.org/wiki/Mobile. + +# Event processing in Native Apps + +The Go runtime is initialized on Android when NativeActivity onCreate is +called, and on iOS when the process starts. In both cases, Go init functions +run before the app lifecycle has started. + +An app is expected to call the Main function in main.main. When the function +exits, the app exits. Inside the func passed to Main, call Filter on every +event received, and then switch on its type. Registered filters run when the +event is received, not when it is sent, so that filters run in the same +goroutine as other code that calls OpenGL. + + package main + + import ( + "log" + + "github.com/ebitengine/gomobile/app" + "github.com/ebitengine/gomobile/event/lifecycle" + "github.com/ebitengine/gomobile/event/paint" + ) + + func main() { + app.Main(func(a app.App) { + for e := range a.Events() { + switch e := a.Filter(e).(type) { + case lifecycle.Event: + // ... + case paint.Event: + log.Print("Call OpenGL here.") + a.Publish() + } + } + }) + } + +An event is represented by the empty interface type interface{}. Any value can +be an event. Commonly used types include Event types defined by the following +packages: + - github.com/ebitengine/gomobile/event/lifecycle + - github.com/ebitengine/gomobile/event/mouse + - github.com/ebitengine/gomobile/event/paint + - github.com/ebitengine/gomobile/event/size + - github.com/ebitengine/gomobile/event/touch + +For example, touch.Event is the type that represents touch events. Other +packages may define their own events, and send them on an app's event channel. + +Other packages can also register event filters, e.g. to manage resources in +response to lifecycle events. Such packages should call: + + app.RegisterFilter(etc) + +in an init function inside that package. +*/ +package app // import "github.com/ebitengine/gomobile/app" diff --git a/vendor/github.com/ebitengine/gomobile/app/internal/callfn/callfn.go b/vendor/github.com/ebitengine/gomobile/app/internal/callfn/callfn.go new file mode 100644 index 0000000..ecc3d45 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/app/internal/callfn/callfn.go @@ -0,0 +1,16 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build android && (arm || 386 || amd64 || arm64) + +// Package callfn provides an android entry point. +// +// It is a separate package from app because it contains Go assembly, +// which does not compile in a package using cgo. +package callfn + +// CallFn calls a zero-argument function by its program counter. +// It is only intended for calling main.main. Using it for +// anything else will not end well. +func CallFn(fn uintptr) diff --git a/vendor/github.com/ebitengine/gomobile/app/internal/callfn/callfn_386.s b/vendor/github.com/ebitengine/gomobile/app/internal/callfn/callfn_386.s new file mode 100644 index 0000000..d2bb54f --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/app/internal/callfn/callfn_386.s @@ -0,0 +1,11 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" +#include "funcdata.h" + +TEXT ·CallFn(SB),$0-4 + MOVL fn+0(FP), AX + CALL AX + RET diff --git a/vendor/github.com/ebitengine/gomobile/app/internal/callfn/callfn_amd64.s b/vendor/github.com/ebitengine/gomobile/app/internal/callfn/callfn_amd64.s new file mode 100644 index 0000000..8769604 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/app/internal/callfn/callfn_amd64.s @@ -0,0 +1,11 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" +#include "funcdata.h" + +TEXT ·CallFn(SB),$0-8 + MOVQ fn+0(FP), AX + CALL AX + RET diff --git a/vendor/github.com/ebitengine/gomobile/app/internal/callfn/callfn_arm.s b/vendor/github.com/ebitengine/gomobile/app/internal/callfn/callfn_arm.s new file mode 100644 index 0000000..d71f748 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/app/internal/callfn/callfn_arm.s @@ -0,0 +1,11 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" +#include "funcdata.h" + +TEXT ·CallFn(SB),$0-4 + MOVW fn+0(FP), R0 + BL (R0) + RET diff --git a/vendor/github.com/ebitengine/gomobile/app/internal/callfn/callfn_arm64.s b/vendor/github.com/ebitengine/gomobile/app/internal/callfn/callfn_arm64.s new file mode 100644 index 0000000..545ad50 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/app/internal/callfn/callfn_arm64.s @@ -0,0 +1,11 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" +#include "funcdata.h" + +TEXT ·CallFn(SB),$0-8 + MOVD fn+0(FP), R0 + BL (R0) + RET diff --git a/vendor/github.com/ebitengine/gomobile/app/x11.c b/vendor/github.com/ebitengine/gomobile/app/x11.c new file mode 100644 index 0000000..755bb24 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/app/x11.c @@ -0,0 +1,175 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build linux && !android +// +build linux,!android + +#include "_cgo_export.h" +#include +#include +#include +#include +#include +#include + +static Atom wm_delete_window; + +static Window +new_window(Display *x_dpy, EGLDisplay e_dpy, int w, int h, EGLContext *ctx, EGLSurface *surf) { + static const EGLint attribs[] = { + EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, + EGL_SURFACE_TYPE, EGL_WINDOW_BIT, + EGL_BLUE_SIZE, 8, + EGL_GREEN_SIZE, 8, + EGL_RED_SIZE, 8, + EGL_DEPTH_SIZE, 16, + EGL_CONFIG_CAVEAT, EGL_NONE, + EGL_NONE + }; + EGLConfig config; + EGLint num_configs; + if (!eglChooseConfig(e_dpy, attribs, &config, 1, &num_configs)) { + fprintf(stderr, "eglChooseConfig failed\n"); + exit(1); + } + EGLint vid; + if (!eglGetConfigAttrib(e_dpy, config, EGL_NATIVE_VISUAL_ID, &vid)) { + fprintf(stderr, "eglGetConfigAttrib failed\n"); + exit(1); + } + + XVisualInfo visTemplate; + visTemplate.visualid = vid; + int num_visuals; + XVisualInfo *visInfo = XGetVisualInfo(x_dpy, VisualIDMask, &visTemplate, &num_visuals); + if (!visInfo) { + fprintf(stderr, "XGetVisualInfo failed\n"); + exit(1); + } + + Window root = RootWindow(x_dpy, DefaultScreen(x_dpy)); + XSetWindowAttributes attr; + + attr.colormap = XCreateColormap(x_dpy, root, visInfo->visual, AllocNone); + if (!attr.colormap) { + fprintf(stderr, "XCreateColormap failed\n"); + exit(1); + } + + attr.event_mask = StructureNotifyMask | ExposureMask | + ButtonPressMask | ButtonReleaseMask | ButtonMotionMask; + Window win = XCreateWindow( + x_dpy, root, 0, 0, w, h, 0, visInfo->depth, InputOutput, + visInfo->visual, CWColormap | CWEventMask, &attr); + XFree(visInfo); + + XSizeHints sizehints; + sizehints.width = w; + sizehints.height = h; + sizehints.flags = USSize; + XSetNormalHints(x_dpy, win, &sizehints); + XSetStandardProperties(x_dpy, win, "App", "App", None, (char **)NULL, 0, &sizehints); + + static const EGLint ctx_attribs[] = { + EGL_CONTEXT_CLIENT_VERSION, 2, + EGL_NONE + }; + *ctx = eglCreateContext(e_dpy, config, EGL_NO_CONTEXT, ctx_attribs); + if (!*ctx) { + fprintf(stderr, "eglCreateContext failed\n"); + exit(1); + } + *surf = eglCreateWindowSurface(e_dpy, config, win, NULL); + if (!*surf) { + fprintf(stderr, "eglCreateWindowSurface failed\n"); + exit(1); + } + return win; +} + +Display *x_dpy; +EGLDisplay e_dpy; +EGLContext e_ctx; +EGLSurface e_surf; +Window win; + +void +createWindow(void) { + x_dpy = XOpenDisplay(NULL); + if (!x_dpy) { + fprintf(stderr, "XOpenDisplay failed\n"); + exit(1); + } + e_dpy = eglGetDisplay(x_dpy); + if (!e_dpy) { + fprintf(stderr, "eglGetDisplay failed\n"); + exit(1); + } + EGLint e_major, e_minor; + if (!eglInitialize(e_dpy, &e_major, &e_minor)) { + fprintf(stderr, "eglInitialize failed\n"); + exit(1); + } + eglBindAPI(EGL_OPENGL_ES_API); + win = new_window(x_dpy, e_dpy, 600, 800, &e_ctx, &e_surf); + + wm_delete_window = XInternAtom(x_dpy, "WM_DELETE_WINDOW", True); + if (wm_delete_window != None) { + XSetWMProtocols(x_dpy, win, &wm_delete_window, 1); + } + + XMapWindow(x_dpy, win); + if (!eglMakeCurrent(e_dpy, e_surf, e_surf, e_ctx)) { + fprintf(stderr, "eglMakeCurrent failed\n"); + exit(1); + } + + // Window size and DPI should be initialized before starting app. + XEvent ev; + while (1) { + if (XCheckMaskEvent(x_dpy, StructureNotifyMask, &ev) == False) { + continue; + } + if (ev.type == ConfigureNotify) { + onResize(ev.xconfigure.width, ev.xconfigure.height); + break; + } + } +} + +void +processEvents(void) { + while (XPending(x_dpy)) { + XEvent ev; + XNextEvent(x_dpy, &ev); + switch (ev.type) { + case ButtonPress: + onTouchBegin((float)ev.xbutton.x, (float)ev.xbutton.y); + break; + case ButtonRelease: + onTouchEnd((float)ev.xbutton.x, (float)ev.xbutton.y); + break; + case MotionNotify: + onTouchMove((float)ev.xmotion.x, (float)ev.xmotion.y); + break; + case ConfigureNotify: + onResize(ev.xconfigure.width, ev.xconfigure.height); + break; + case ClientMessage: + if (wm_delete_window != None && (Atom)ev.xclient.data.l[0] == wm_delete_window) { + onStop(); + return; + } + break; + } + } +} + +void +swapBuffers(void) { + if (eglSwapBuffers(e_dpy, e_surf) == EGL_FALSE) { + fprintf(stderr, "eglSwapBuffer failed\n"); + exit(1); + } +} diff --git a/vendor/github.com/ebitengine/gomobile/app/x11.go b/vendor/github.com/ebitengine/gomobile/app/x11.go new file mode 100644 index 0000000..9dab92b --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/app/x11.go @@ -0,0 +1,126 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build linux && !android + +package app + +/* +Simple on-screen app debugging for X11. Not an officially supported +development target for apps, as screens with mice are very different +than screens with touch panels. +*/ + +/* +#cgo LDFLAGS: -lEGL -lGLESv2 -lX11 + +void createWindow(void); +void processEvents(void); +void swapBuffers(void); +*/ +import "C" +import ( + "runtime" + "time" + + "github.com/ebitengine/gomobile/event/lifecycle" + "github.com/ebitengine/gomobile/event/paint" + "github.com/ebitengine/gomobile/event/size" + "github.com/ebitengine/gomobile/event/touch" + "github.com/ebitengine/gomobile/geom" +) + +func init() { + theApp.registerGLViewportFilter() +} + +func main(f func(App)) { + runtime.LockOSThread() + + workAvailable := theApp.worker.WorkAvailable() + + C.createWindow() + + // TODO: send lifecycle events when e.g. the X11 window is iconified or moved off-screen. + theApp.sendLifecycle(lifecycle.StageFocused) + + // TODO: translate X11 expose events to shiny paint events, instead of + // sending this synthetic paint event as a hack. + theApp.eventsIn <- paint.Event{} + + donec := make(chan struct{}) + go func() { + // close the donec channel in a defer statement + // so that we could still be able to return even + // if f panics. + defer close(donec) + + f(theApp) + }() + + // TODO: can we get the actual vsync signal? + ticker := time.NewTicker(time.Second / 60) + defer ticker.Stop() + var tc <-chan time.Time + + for { + select { + case <-donec: + return + case <-workAvailable: + theApp.worker.DoWork() + case <-theApp.publish: + C.swapBuffers() + tc = ticker.C + case <-tc: + tc = nil + theApp.publishResult <- PublishResult{} + } + C.processEvents() + } +} + +//export onResize +func onResize(w, h int) { + // TODO(nigeltao): don't assume 72 DPI. DisplayWidth and DisplayWidthMM + // is probably the best place to start looking. + pixelsPerPt := float32(1) + theApp.eventsIn <- size.Event{ + WidthPx: w, + HeightPx: h, + WidthPt: geom.Pt(w), + HeightPt: geom.Pt(h), + PixelsPerPt: pixelsPerPt, + } +} + +func sendTouch(t touch.Type, x, y float32) { + theApp.eventsIn <- touch.Event{ + X: x, + Y: y, + Sequence: 0, // TODO: button?? + Type: t, + } +} + +//export onTouchBegin +func onTouchBegin(x, y float32) { sendTouch(touch.TypeBegin, x, y) } + +//export onTouchMove +func onTouchMove(x, y float32) { sendTouch(touch.TypeMove, x, y) } + +//export onTouchEnd +func onTouchEnd(x, y float32) { sendTouch(touch.TypeEnd, x, y) } + +var stopped bool + +//export onStop +func onStop() { + if stopped { + return + } + stopped = true + theApp.sendLifecycle(lifecycle.StageDead) + theApp.eventsIn <- stopPumping{} +} diff --git a/vendor/github.com/ebitengine/gomobile/event/key/code_string.go b/vendor/github.com/ebitengine/gomobile/event/key/code_string.go new file mode 100644 index 0000000..6af78b3 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/event/key/code_string.go @@ -0,0 +1,60 @@ +// Code generated by "stringer -type=Code"; DO NOT EDIT + +package key + +import "fmt" + +const ( + _Code_name_0 = "CodeUnknown" + _Code_name_1 = "CodeACodeBCodeCCodeDCodeECodeFCodeGCodeHCodeICodeJCodeKCodeLCodeMCodeNCodeOCodePCodeQCodeRCodeSCodeTCodeUCodeVCodeWCodeXCodeYCodeZCode1Code2Code3Code4Code5Code6Code7Code8Code9Code0CodeReturnEnterCodeEscapeCodeDeleteBackspaceCodeTabCodeSpacebarCodeHyphenMinusCodeEqualSignCodeLeftSquareBracketCodeRightSquareBracketCodeBackslash" + _Code_name_2 = "CodeSemicolonCodeApostropheCodeGraveAccentCodeCommaCodeFullStopCodeSlashCodeCapsLockCodeF1CodeF2CodeF3CodeF4CodeF5CodeF6CodeF7CodeF8CodeF9CodeF10CodeF11CodeF12" + _Code_name_3 = "CodePauseCodeInsertCodeHomeCodePageUpCodeDeleteForwardCodeEndCodePageDownCodeRightArrowCodeLeftArrowCodeDownArrowCodeUpArrowCodeKeypadNumLockCodeKeypadSlashCodeKeypadAsteriskCodeKeypadHyphenMinusCodeKeypadPlusSignCodeKeypadEnterCodeKeypad1CodeKeypad2CodeKeypad3CodeKeypad4CodeKeypad5CodeKeypad6CodeKeypad7CodeKeypad8CodeKeypad9CodeKeypad0CodeKeypadFullStop" + _Code_name_4 = "CodeKeypadEqualSignCodeF13CodeF14CodeF15CodeF16CodeF17CodeF18CodeF19CodeF20CodeF21CodeF22CodeF23CodeF24" + _Code_name_5 = "CodeHelp" + _Code_name_6 = "CodeMuteCodeVolumeUpCodeVolumeDown" + _Code_name_7 = "CodeLeftControlCodeLeftShiftCodeLeftAltCodeLeftGUICodeRightControlCodeRightShiftCodeRightAltCodeRightGUI" + _Code_name_8 = "CodeCompose" +) + +var ( + _Code_index_0 = [...]uint8{0, 11} + _Code_index_1 = [...]uint16{0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 105, 110, 115, 120, 125, 130, 135, 140, 145, 150, 155, 160, 165, 170, 175, 180, 195, 205, 224, 231, 243, 258, 271, 292, 314, 327} + _Code_index_2 = [...]uint8{0, 13, 27, 42, 51, 63, 72, 84, 90, 96, 102, 108, 114, 120, 126, 132, 138, 145, 152, 159} + _Code_index_3 = [...]uint16{0, 9, 19, 27, 37, 54, 61, 73, 87, 100, 113, 124, 141, 156, 174, 195, 213, 228, 239, 250, 261, 272, 283, 294, 305, 316, 327, 338, 356} + _Code_index_4 = [...]uint8{0, 19, 26, 33, 40, 47, 54, 61, 68, 75, 82, 89, 96, 103} + _Code_index_5 = [...]uint8{0, 8} + _Code_index_6 = [...]uint8{0, 8, 20, 34} + _Code_index_7 = [...]uint8{0, 15, 28, 39, 50, 66, 80, 92, 104} + _Code_index_8 = [...]uint8{0, 11} +) + +func (i Code) String() string { + switch { + case i == 0: + return _Code_name_0 + case 4 <= i && i <= 49: + i -= 4 + return _Code_name_1[_Code_index_1[i]:_Code_index_1[i+1]] + case 51 <= i && i <= 69: + i -= 51 + return _Code_name_2[_Code_index_2[i]:_Code_index_2[i+1]] + case 72 <= i && i <= 99: + i -= 72 + return _Code_name_3[_Code_index_3[i]:_Code_index_3[i+1]] + case 103 <= i && i <= 115: + i -= 103 + return _Code_name_4[_Code_index_4[i]:_Code_index_4[i+1]] + case i == 117: + return _Code_name_5 + case 127 <= i && i <= 129: + i -= 127 + return _Code_name_6[_Code_index_6[i]:_Code_index_6[i+1]] + case 224 <= i && i <= 231: + i -= 224 + return _Code_name_7[_Code_index_7[i]:_Code_index_7[i+1]] + case i == 65536: + return _Code_name_8 + default: + return fmt.Sprintf("Code(%d)", i) + } +} diff --git a/vendor/github.com/ebitengine/gomobile/event/key/key.go b/vendor/github.com/ebitengine/gomobile/event/key/key.go new file mode 100644 index 0000000..ddbea6d --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/event/key/key.go @@ -0,0 +1,270 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:generate stringer -type=Code + +// Package key defines an event for physical keyboard keys. +// +// On-screen software keyboards do not send key events. +// +// See the github.com/ebitengine/gomobile/app package for details on the event model. +package key + +import ( + "fmt" + "strings" +) + +// Event is a key event. +type Event struct { + // Rune is the meaning of the key event as determined by the + // operating system. The mapping is determined by system-dependent + // current layout, modifiers, lock-states, etc. + // + // If non-negative, it is a Unicode codepoint: pressing the 'a' key + // generates different Runes 'a' or 'A' (but the same Code) depending on + // the state of the shift key. + // + // If -1, the key does not generate a Unicode codepoint. To distinguish + // them, look at Code. + Rune rune + + // Code is the identity of the physical key relative to a notional + // "standard" keyboard, independent of current layout, modifiers, + // lock-states, etc + // + // For standard key codes, its value matches USB HID key codes. + // Compare its value to uint32-typed constants in this package, such + // as CodeLeftShift and CodeEscape. + // + // Pressing the regular '2' key and number-pad '2' key (with Num-Lock) + // generate different Codes (but the same Rune). + Code Code + + // Modifiers is a bitmask representing a set of modifier keys: ModShift, + // ModAlt, etc. + Modifiers Modifiers + + // Direction is the direction of the key event: DirPress, DirRelease, + // or DirNone (for key repeats). + Direction Direction + + // TODO: add a Device ID, for multiple input devices? + // TODO: add a time.Time? +} + +func (e Event) String() string { + if e.Rune >= 0 { + return fmt.Sprintf("key.Event{%q (%v), %v, %v}", e.Rune, e.Code, e.Modifiers, e.Direction) + } + return fmt.Sprintf("key.Event{(%v), %v, %v}", e.Code, e.Modifiers, e.Direction) +} + +// Direction is the direction of the key event. +type Direction uint8 + +const ( + DirNone Direction = 0 + DirPress Direction = 1 + DirRelease Direction = 2 +) + +// Modifiers is a bitmask representing a set of modifier keys. +type Modifiers uint32 + +const ( + ModShift Modifiers = 1 << 0 + ModControl Modifiers = 1 << 1 + ModAlt Modifiers = 1 << 2 + ModMeta Modifiers = 1 << 3 // called "Command" on OS X +) + +// Code is the identity of a key relative to a notional "standard" keyboard. +type Code uint32 + +// Physical key codes. +// +// For standard key codes, its value matches USB HID key codes. +// TODO: add missing codes. +const ( + CodeUnknown Code = 0 + + CodeA Code = 4 + CodeB Code = 5 + CodeC Code = 6 + CodeD Code = 7 + CodeE Code = 8 + CodeF Code = 9 + CodeG Code = 10 + CodeH Code = 11 + CodeI Code = 12 + CodeJ Code = 13 + CodeK Code = 14 + CodeL Code = 15 + CodeM Code = 16 + CodeN Code = 17 + CodeO Code = 18 + CodeP Code = 19 + CodeQ Code = 20 + CodeR Code = 21 + CodeS Code = 22 + CodeT Code = 23 + CodeU Code = 24 + CodeV Code = 25 + CodeW Code = 26 + CodeX Code = 27 + CodeY Code = 28 + CodeZ Code = 29 + + Code1 Code = 30 + Code2 Code = 31 + Code3 Code = 32 + Code4 Code = 33 + Code5 Code = 34 + Code6 Code = 35 + Code7 Code = 36 + Code8 Code = 37 + Code9 Code = 38 + Code0 Code = 39 + + CodeReturnEnter Code = 40 + CodeEscape Code = 41 + CodeDeleteBackspace Code = 42 + CodeTab Code = 43 + CodeSpacebar Code = 44 + CodeHyphenMinus Code = 45 // - + CodeEqualSign Code = 46 // = + CodeLeftSquareBracket Code = 47 // [ + CodeRightSquareBracket Code = 48 // ] + CodeBackslash Code = 49 // \ + CodeSemicolon Code = 51 // ; + CodeApostrophe Code = 52 // ' + CodeGraveAccent Code = 53 // ` + CodeComma Code = 54 // , + CodeFullStop Code = 55 // . + CodeSlash Code = 56 // / + CodeCapsLock Code = 57 + + CodeF1 Code = 58 + CodeF2 Code = 59 + CodeF3 Code = 60 + CodeF4 Code = 61 + CodeF5 Code = 62 + CodeF6 Code = 63 + CodeF7 Code = 64 + CodeF8 Code = 65 + CodeF9 Code = 66 + CodeF10 Code = 67 + CodeF11 Code = 68 + CodeF12 Code = 69 + + CodePause Code = 72 + CodeInsert Code = 73 + CodeHome Code = 74 + CodePageUp Code = 75 + CodeDeleteForward Code = 76 + CodeEnd Code = 77 + CodePageDown Code = 78 + + CodeRightArrow Code = 79 + CodeLeftArrow Code = 80 + CodeDownArrow Code = 81 + CodeUpArrow Code = 82 + + CodeKeypadNumLock Code = 83 + CodeKeypadSlash Code = 84 // / + CodeKeypadAsterisk Code = 85 // * + CodeKeypadHyphenMinus Code = 86 // - + CodeKeypadPlusSign Code = 87 // + + CodeKeypadEnter Code = 88 + CodeKeypad1 Code = 89 + CodeKeypad2 Code = 90 + CodeKeypad3 Code = 91 + CodeKeypad4 Code = 92 + CodeKeypad5 Code = 93 + CodeKeypad6 Code = 94 + CodeKeypad7 Code = 95 + CodeKeypad8 Code = 96 + CodeKeypad9 Code = 97 + CodeKeypad0 Code = 98 + CodeKeypadFullStop Code = 99 // . + CodeKeypadEqualSign Code = 103 // = + + CodeF13 Code = 104 + CodeF14 Code = 105 + CodeF15 Code = 106 + CodeF16 Code = 107 + CodeF17 Code = 108 + CodeF18 Code = 109 + CodeF19 Code = 110 + CodeF20 Code = 111 + CodeF21 Code = 112 + CodeF22 Code = 113 + CodeF23 Code = 114 + CodeF24 Code = 115 + + CodeHelp Code = 117 + + CodeMute Code = 127 + CodeVolumeUp Code = 128 + CodeVolumeDown Code = 129 + + CodeLeftControl Code = 224 + CodeLeftShift Code = 225 + CodeLeftAlt Code = 226 + CodeLeftGUI Code = 227 + CodeRightControl Code = 228 + CodeRightShift Code = 229 + CodeRightAlt Code = 230 + CodeRightGUI Code = 231 + + // The following codes are not part of the standard USB HID Usage IDs for + // keyboards. See http://www.usb.org/developers/hidpage/Hut1_12v2.pdf + // + // Usage IDs are uint16s, so these non-standard values start at 0x10000. + + // CodeCompose is the Code for a compose key, sometimes called a multi key, + // used to input non-ASCII characters such as ñ being composed of n and ~. + // + // See https://en.wikipedia.org/wiki/Compose_key + CodeCompose Code = 0x10000 +) + +// TODO: Given we use runes outside the unicode space, should we provide a +// printing function? Related: it's a little unfortunate that printing a +// key.Event with %v gives not very readable output like: +// {100 7 key.Modifiers() Press} + +var mods = [...]struct { + m Modifiers + s string +}{ + {ModShift, "Shift"}, + {ModControl, "Control"}, + {ModAlt, "Alt"}, + {ModMeta, "Meta"}, +} + +func (m Modifiers) String() string { + var match []string + for _, mod := range mods { + if mod.m&m != 0 { + match = append(match, mod.s) + } + } + return "key.Modifiers(" + strings.Join(match, "|") + ")" +} + +func (d Direction) String() string { + switch d { + case DirNone: + return "None" + case DirPress: + return "Press" + case DirRelease: + return "Release" + default: + return fmt.Sprintf("key.Direction(%d)", d) + } +} diff --git a/vendor/github.com/ebitengine/gomobile/event/lifecycle/lifecycle.go b/vendor/github.com/ebitengine/gomobile/event/lifecycle/lifecycle.go new file mode 100644 index 0000000..44ec148 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/event/lifecycle/lifecycle.go @@ -0,0 +1,136 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package lifecycle defines an event for an app's lifecycle. +// +// The app lifecycle consists of moving back and forth between an ordered +// sequence of stages. For example, being at a stage greater than or equal to +// StageVisible means that the app is visible on the screen. +// +// A lifecycle event is a change from one stage to another, which crosses every +// intermediate stage. For example, changing from StageAlive to StageFocused +// implicitly crosses StageVisible. +// +// Crosses can be in a positive or negative direction. A positive crossing of +// StageFocused means that the app has gained the focus. A negative crossing +// means it has lost the focus. +// +// See the github.com/ebitengine/gomobile/app package for details on the event model. +package lifecycle // import "github.com/ebitengine/gomobile/event/lifecycle" + +import ( + "fmt" +) + +// Cross is whether a lifecycle stage was crossed. +type Cross uint32 + +func (c Cross) String() string { + switch c { + case CrossOn: + return "on" + case CrossOff: + return "off" + } + return "none" +} + +const ( + CrossNone Cross = 0 + CrossOn Cross = 1 + CrossOff Cross = 2 +) + +// Event is a lifecycle change from an old stage to a new stage. +type Event struct { + From, To Stage + + // DrawContext is the state used for painting, if any is valid. + // + // For OpenGL apps, a non-nil DrawContext is a gl.Context. + // + // TODO: make this an App method if we move away from an event channel? + DrawContext interface{} +} + +func (e Event) String() string { + return fmt.Sprintf("lifecycle.Event{From:%v, To:%v, DrawContext:%v}", e.From, e.To, e.DrawContext) +} + +// Crosses reports whether the transition from From to To crosses the stage s: +// - It returns CrossOn if it does, and the lifecycle change is positive. +// - It returns CrossOff if it does, and the lifecycle change is negative. +// - Otherwise, it returns CrossNone. +// +// See the documentation for Stage for more discussion of positive and negative +// crosses. +func (e Event) Crosses(s Stage) Cross { + switch { + case e.From < s && e.To >= s: + return CrossOn + case e.From >= s && e.To < s: + return CrossOff + } + return CrossNone +} + +// Stage is a stage in the app's lifecycle. The values are ordered, so that a +// lifecycle change from stage From to stage To implicitly crosses every stage +// in the range (min, max], exclusive on the low end and inclusive on the high +// end, where min is the minimum of From and To, and max is the maximum. +// +// The documentation for individual stages talk about positive and negative +// crosses. A positive lifecycle change is one where its From stage is less +// than its To stage. Similarly, a negative lifecycle change is one where From +// is greater than To. Thus, a positive lifecycle change crosses every stage in +// the range (From, To] in increasing order, and a negative lifecycle change +// crosses every stage in the range (To, From] in decreasing order. +type Stage uint32 + +// TODO: how does iOS map to these stages? What do cross-platform mobile +// abstractions do? + +const ( + // StageDead is the zero stage. No lifecycle change crosses this stage, + // but: + // - A positive change from this stage is the very first lifecycle change. + // - A negative change to this stage is the very last lifecycle change. + StageDead Stage = iota + + // StageAlive means that the app is alive. + // - A positive cross means that the app has been created. + // - A negative cross means that the app is being destroyed. + // Each cross, either from or to StageDead, will occur only once. + // On Android, these correspond to onCreate and onDestroy. + StageAlive + + // StageVisible means that the app window is visible. + // - A positive cross means that the app window has become visible. + // - A negative cross means that the app window has become invisible. + // On Android, these correspond to onStart and onStop. + // On Desktop, an app window can become invisible if e.g. it is minimized, + // unmapped, or not on a visible workspace. + StageVisible + + // StageFocused means that the app window has the focus. + // - A positive cross means that the app window has gained the focus. + // - A negative cross means that the app window has lost the focus. + // On Android, these correspond to onResume and onFreeze. + StageFocused +) + +func (s Stage) String() string { + switch s { + case StageDead: + return "StageDead" + case StageAlive: + return "StageAlive" + case StageVisible: + return "StageVisible" + case StageFocused: + return "StageFocused" + default: + return fmt.Sprintf("lifecycle.Stage(%d)", s) + } +} diff --git a/vendor/github.com/ebitengine/gomobile/event/paint/paint.go b/vendor/github.com/ebitengine/gomobile/event/paint/paint.go new file mode 100644 index 0000000..ae70197 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/event/paint/paint.go @@ -0,0 +1,24 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package paint defines an event for the app being ready to paint. +// +// See the github.com/ebitengine/gomobile/app package for details on the event model. +package paint // import "github.com/ebitengine/gomobile/event/paint" + +// Event indicates that the app is ready to paint the next frame of the GUI. +// +// A frame is completed by calling the App's Publish method. +type Event struct { + // External is true for paint events sent by the screen driver. + // + // An external event may be sent at any time in response to an + // operating system event, for example the window opened, was + // resized, or the screen memory was lost. + // + // Programs actively drawing to the screen as fast as vsync allows + // should ignore external paint events to avoid a backlog of paint + // events building up. + External bool +} diff --git a/vendor/github.com/ebitengine/gomobile/event/size/size.go b/vendor/github.com/ebitengine/gomobile/event/size/size.go new file mode 100644 index 0000000..30da5c0 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/event/size/size.go @@ -0,0 +1,92 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package size defines an event for the dimensions, physical resolution and +// orientation of the app's window. +// +// See the github.com/ebitengine/gomobile/app package for details on the event model. +package size // import "github.com/ebitengine/gomobile/event/size" + +import ( + "image" + + "github.com/ebitengine/gomobile/geom" +) + +// Event holds the dimensions, physical resolution and orientation of the app's +// window. +type Event struct { + // WidthPx and HeightPx are the window's dimensions in pixels. + WidthPx, HeightPx int + + // WidthPt and HeightPt are the window's physical dimensions in points + // (1/72 of an inch). + // + // The values are based on PixelsPerPt and are therefore approximate, as + // per the comment on PixelsPerPt. + WidthPt, HeightPt geom.Pt + + // PixelsPerPt is the window's physical resolution. It is the number of + // pixels in a single geom.Pt, from the github.com/ebitengine/gomobile/geom package. + // + // There are a wide variety of pixel densities in existing phones and + // tablets, so apps should be written to expect various non-integer + // PixelsPerPt values. In general, work in geom.Pt. + // + // The value is approximate, in that the OS, drivers or hardware may report + // approximate or quantized values. An N x N pixel square should be roughly + // 1 square inch for N = int(PixelsPerPt * 72), although different square + // lengths (in pixels) might be closer to 1 inch in practice. Nonetheless, + // this PixelsPerPt value should be consistent with e.g. the ratio of + // WidthPx to WidthPt. + PixelsPerPt float32 + + // Orientation is the orientation of the device screen. + Orientation Orientation +} + +// Size returns the window's size in pixels, at the time this size event was +// sent. +func (e Event) Size() image.Point { + return image.Point{e.WidthPx, e.HeightPx} +} + +// Bounds returns the window's bounds in pixels, at the time this size event +// was sent. +// +// The top-left pixel is always (0, 0). The bottom-right pixel is given by the +// width and height. +func (e Event) Bounds() image.Rectangle { + return image.Rectangle{Max: image.Point{e.WidthPx, e.HeightPx}} +} + +// Orientation is the orientation of the device screen. +type Orientation int + +const ( + // OrientationUnknown means device orientation cannot be determined. + // + // Equivalent on Android to Configuration.ORIENTATION_UNKNOWN + // and on iOS to: + // UIDeviceOrientationUnknown + // UIDeviceOrientationFaceUp + // UIDeviceOrientationFaceDown + OrientationUnknown Orientation = iota + + // OrientationPortrait is a device oriented so it is tall and thin. + // + // Equivalent on Android to Configuration.ORIENTATION_PORTRAIT + // and on iOS to: + // UIDeviceOrientationPortrait + // UIDeviceOrientationPortraitUpsideDown + OrientationPortrait + + // OrientationLandscape is a device oriented so it is short and wide. + // + // Equivalent on Android to Configuration.ORIENTATION_LANDSCAPE + // and on iOS to: + // UIDeviceOrientationLandscapeLeft + // UIDeviceOrientationLandscapeRight + OrientationLandscape +) diff --git a/vendor/github.com/ebitengine/gomobile/event/touch/touch.go b/vendor/github.com/ebitengine/gomobile/event/touch/touch.go new file mode 100644 index 0000000..093687b --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/event/touch/touch.go @@ -0,0 +1,72 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package touch defines an event for touch input. +// +// See the github.com/ebitengine/gomobile/app package for details on the event model. +package touch // import "github.com/ebitengine/gomobile/event/touch" + +// The best source on android input events is the NDK: include/android/input.h +// +// iOS event handling guide: +// https://developer.apple.com/library/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS + +import ( + "fmt" +) + +// Event is a touch event. +type Event struct { + // X and Y are the touch location, in pixels. + X, Y float32 + + // Sequence is the sequence number. The same number is shared by all events + // in a sequence. A sequence begins with a single TypeBegin, is followed by + // zero or more TypeMoves, and ends with a single TypeEnd. A Sequence + // distinguishes concurrent sequences but its value is subsequently reused. + Sequence Sequence + + // Type is the touch type. + Type Type +} + +// Sequence identifies a sequence of touch events. +type Sequence int64 + +// Type describes the type of a touch event. +type Type byte + +const ( + // TypeBegin is a user first touching the device. + // + // On Android, this is a AMOTION_EVENT_ACTION_DOWN. + // On iOS, this is a call to touchesBegan. + TypeBegin Type = iota + + // TypeMove is a user dragging across the device. + // + // A TypeMove is delivered between a TypeBegin and TypeEnd. + // + // On Android, this is a AMOTION_EVENT_ACTION_MOVE. + // On iOS, this is a call to touchesMoved. + TypeMove + + // TypeEnd is a user no longer touching the device. + // + // On Android, this is a AMOTION_EVENT_ACTION_UP. + // On iOS, this is a call to touchesEnded. + TypeEnd +) + +func (t Type) String() string { + switch t { + case TypeBegin: + return "begin" + case TypeMove: + return "move" + case TypeEnd: + return "end" + } + return fmt.Sprintf("touch.Type(%d)", t) +} diff --git a/vendor/github.com/ebitengine/gomobile/geom/geom.go b/vendor/github.com/ebitengine/gomobile/geom/geom.go new file mode 100644 index 0000000..03f184a --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/geom/geom.go @@ -0,0 +1,102 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* +Package geom defines a two-dimensional coordinate system. + +The coordinate system is based on an left-handed Cartesian plane. +That is, X increases to the right and Y increases down. For (x,y), + + (0,0) → (1,0) + ↓ ↘ + (0,1) (1,1) + +The display window places the origin (0, 0) in the upper-left corner of +the screen. Positions on the plane are measured in typographic points, +1/72 of an inch, which is represented by the Pt type. + +Any interface that draws to the screen using types from the geom package +scales the number of pixels to maintain a Pt as 1/72 of an inch. +*/ +package geom // import "github.com/ebitengine/gomobile/geom" + +/* +Notes on the various underlying coordinate systems. + +Both Android and iOS (UIKit) use upper-left-origin coordinate systems +with for events, however they have different units. + +UIKit measures distance in points. A point is a single-pixel on a +pre-Retina display. UIKit maintains a scale factor that to turn points +into pixels. On current retina devices, the scale factor is 2.0. + +A UIKit point does not correspond to a fixed physical distance, as the +iPhone has a 163 DPI/PPI (326 PPI retina) display, and the iPad has a +132 PPI (264 retina) display. Points are 32-bit floats. + +Even though point is the official UIKit term, they are commonly called +pixels. Indeed, the units were equivalent until the retina display was +introduced. + +N.b. as a UIKit point is unrelated to a typographic point, it is not +related to this packages's Pt and Point types. + +More details about iOS drawing: + +https://developer.apple.com/library/ios/documentation/2ddrawing/conceptual/drawingprintingios/GraphicsDrawingOverview/GraphicsDrawingOverview.html + +Android uses pixels. Sub-pixel precision is possible, so pixels are +represented as 32-bit floats. The ACONFIGURATION_DENSITY enum provides +the screen DPI/PPI, which varies frequently between devices. + +It would be tempting to adopt the pixel, given the clear pixel/DPI split +in the core android events API. However, the plot thickens: + +http://developer.android.com/training/multiscreen/screendensities.html + +Android promotes the notion of a density-independent pixel in many of +their interfaces, often prefixed by "dp". 1dp is a real physical length, +as "independent" means it is assumed to be 1/160th of an inch and is +adjusted for the current screen. + +In addition, android has a scale-indepdendent pixel used for expressing +a user's preferred text size. The user text size preference is a useful +notion not yet expressed in the geom package. + +For the sake of clarity when working across platforms, the geom package +tries to put distance between it and the word pixel. +*/ + +import "fmt" + +// Pt is a length. +// +// The unit Pt is a typographical point, 1/72 of an inch (0.3527 mm). +// +// It can be converted to a length in current device pixels by +// multiplying with PixelsPerPt after app initialization is complete. +type Pt float32 + +// Px converts the length to current device pixels. +func (p Pt) Px(pixelsPerPt float32) float32 { return float32(p) * pixelsPerPt } + +// String returns a string representation of p like "3.2pt". +func (p Pt) String() string { return fmt.Sprintf("%.2fpt", p) } + +// Point is a point in a two-dimensional plane. +type Point struct { + X, Y Pt +} + +// String returns a string representation of p like "(1.2,3.4)". +func (p Point) String() string { return fmt.Sprintf("(%.2f,%.2f)", p.X, p.Y) } + +// A Rectangle is region of points. +// The top-left point is Min, and the bottom-right point is Max. +type Rectangle struct { + Min, Max Point +} + +// String returns a string representation of r like "(3,4)-(6,5)". +func (r Rectangle) String() string { return r.Min.String() + "-" + r.Max.String() } diff --git a/vendor/github.com/ebitengine/gomobile/gl/consts.go b/vendor/github.com/ebitengine/gomobile/gl/consts.go new file mode 100644 index 0000000..370d0b8 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/gl/consts.go @@ -0,0 +1,657 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gl + +/* +Partially generated from the Khronos OpenGL API specification in XML +format, which is covered by the license: + + Copyright (c) 2013-2014 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. + +*/ + +const ( + POINTS = 0x0000 + LINES = 0x0001 + LINE_LOOP = 0x0002 + LINE_STRIP = 0x0003 + TRIANGLES = 0x0004 + TRIANGLE_STRIP = 0x0005 + TRIANGLE_FAN = 0x0006 + SRC_COLOR = 0x0300 + ONE_MINUS_SRC_COLOR = 0x0301 + SRC_ALPHA = 0x0302 + ONE_MINUS_SRC_ALPHA = 0x0303 + DST_ALPHA = 0x0304 + ONE_MINUS_DST_ALPHA = 0x0305 + DST_COLOR = 0x0306 + ONE_MINUS_DST_COLOR = 0x0307 + SRC_ALPHA_SATURATE = 0x0308 + FUNC_ADD = 0x8006 + BLEND_EQUATION = 0x8009 + BLEND_EQUATION_RGB = 0x8009 + BLEND_EQUATION_ALPHA = 0x883D + FUNC_SUBTRACT = 0x800A + FUNC_REVERSE_SUBTRACT = 0x800B + BLEND_DST_RGB = 0x80C8 + BLEND_SRC_RGB = 0x80C9 + BLEND_DST_ALPHA = 0x80CA + BLEND_SRC_ALPHA = 0x80CB + CONSTANT_COLOR = 0x8001 + ONE_MINUS_CONSTANT_COLOR = 0x8002 + CONSTANT_ALPHA = 0x8003 + ONE_MINUS_CONSTANT_ALPHA = 0x8004 + BLEND_COLOR = 0x8005 + ARRAY_BUFFER = 0x8892 + ELEMENT_ARRAY_BUFFER = 0x8893 + ARRAY_BUFFER_BINDING = 0x8894 + ELEMENT_ARRAY_BUFFER_BINDING = 0x8895 + STREAM_DRAW = 0x88E0 + STATIC_DRAW = 0x88E4 + DYNAMIC_DRAW = 0x88E8 + BUFFER_SIZE = 0x8764 + BUFFER_USAGE = 0x8765 + CURRENT_VERTEX_ATTRIB = 0x8626 + FRONT = 0x0404 + BACK = 0x0405 + FRONT_AND_BACK = 0x0408 + TEXTURE_2D = 0x0DE1 + CULL_FACE = 0x0B44 + BLEND = 0x0BE2 + DITHER = 0x0BD0 + STENCIL_TEST = 0x0B90 + DEPTH_TEST = 0x0B71 + SCISSOR_TEST = 0x0C11 + POLYGON_OFFSET_FILL = 0x8037 + SAMPLE_ALPHA_TO_COVERAGE = 0x809E + SAMPLE_COVERAGE = 0x80A0 + INVALID_ENUM = 0x0500 + INVALID_VALUE = 0x0501 + INVALID_OPERATION = 0x0502 + OUT_OF_MEMORY = 0x0505 + CW = 0x0900 + CCW = 0x0901 + LINE_WIDTH = 0x0B21 + ALIASED_POINT_SIZE_RANGE = 0x846D + ALIASED_LINE_WIDTH_RANGE = 0x846E + CULL_FACE_MODE = 0x0B45 + FRONT_FACE = 0x0B46 + DEPTH_RANGE = 0x0B70 + DEPTH_WRITEMASK = 0x0B72 + DEPTH_CLEAR_VALUE = 0x0B73 + DEPTH_FUNC = 0x0B74 + STENCIL_CLEAR_VALUE = 0x0B91 + STENCIL_FUNC = 0x0B92 + STENCIL_FAIL = 0x0B94 + STENCIL_PASS_DEPTH_FAIL = 0x0B95 + STENCIL_PASS_DEPTH_PASS = 0x0B96 + STENCIL_REF = 0x0B97 + STENCIL_VALUE_MASK = 0x0B93 + STENCIL_WRITEMASK = 0x0B98 + STENCIL_BACK_FUNC = 0x8800 + STENCIL_BACK_FAIL = 0x8801 + STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802 + STENCIL_BACK_PASS_DEPTH_PASS = 0x8803 + STENCIL_BACK_REF = 0x8CA3 + STENCIL_BACK_VALUE_MASK = 0x8CA4 + STENCIL_BACK_WRITEMASK = 0x8CA5 + VIEWPORT = 0x0BA2 + SCISSOR_BOX = 0x0C10 + COLOR_CLEAR_VALUE = 0x0C22 + COLOR_WRITEMASK = 0x0C23 + UNPACK_ALIGNMENT = 0x0CF5 + PACK_ALIGNMENT = 0x0D05 + MAX_TEXTURE_SIZE = 0x0D33 + MAX_VIEWPORT_DIMS = 0x0D3A + SUBPIXEL_BITS = 0x0D50 + RED_BITS = 0x0D52 + GREEN_BITS = 0x0D53 + BLUE_BITS = 0x0D54 + ALPHA_BITS = 0x0D55 + DEPTH_BITS = 0x0D56 + STENCIL_BITS = 0x0D57 + POLYGON_OFFSET_UNITS = 0x2A00 + POLYGON_OFFSET_FACTOR = 0x8038 + TEXTURE_BINDING_2D = 0x8069 + SAMPLE_BUFFERS = 0x80A8 + SAMPLES = 0x80A9 + SAMPLE_COVERAGE_VALUE = 0x80AA + SAMPLE_COVERAGE_INVERT = 0x80AB + NUM_COMPRESSED_TEXTURE_FORMATS = 0x86A2 + COMPRESSED_TEXTURE_FORMATS = 0x86A3 + DONT_CARE = 0x1100 + FASTEST = 0x1101 + NICEST = 0x1102 + GENERATE_MIPMAP_HINT = 0x8192 + BYTE = 0x1400 + UNSIGNED_BYTE = 0x1401 + SHORT = 0x1402 + UNSIGNED_SHORT = 0x1403 + INT = 0x1404 + UNSIGNED_INT = 0x1405 + FLOAT = 0x1406 + FIXED = 0x140C + DEPTH_COMPONENT = 0x1902 + ALPHA = 0x1906 + RGB = 0x1907 + RGBA = 0x1908 + LUMINANCE = 0x1909 + LUMINANCE_ALPHA = 0x190A + UNSIGNED_SHORT_4_4_4_4 = 0x8033 + UNSIGNED_SHORT_5_5_5_1 = 0x8034 + UNSIGNED_SHORT_5_6_5 = 0x8363 + MAX_VERTEX_ATTRIBS = 0x8869 + MAX_VERTEX_UNIFORM_VECTORS = 0x8DFB + MAX_VARYING_VECTORS = 0x8DFC + MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8B4D + MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8B4C + MAX_TEXTURE_IMAGE_UNITS = 0x8872 + MAX_FRAGMENT_UNIFORM_VECTORS = 0x8DFD + SHADER_TYPE = 0x8B4F + DELETE_STATUS = 0x8B80 + LINK_STATUS = 0x8B82 + VALIDATE_STATUS = 0x8B83 + ATTACHED_SHADERS = 0x8B85 + ACTIVE_UNIFORMS = 0x8B86 + ACTIVE_UNIFORM_MAX_LENGTH = 0x8B87 + ACTIVE_ATTRIBUTES = 0x8B89 + ACTIVE_ATTRIBUTE_MAX_LENGTH = 0x8B8A + SHADING_LANGUAGE_VERSION = 0x8B8C + CURRENT_PROGRAM = 0x8B8D + NEVER = 0x0200 + LESS = 0x0201 + EQUAL = 0x0202 + LEQUAL = 0x0203 + GREATER = 0x0204 + NOTEQUAL = 0x0205 + GEQUAL = 0x0206 + ALWAYS = 0x0207 + KEEP = 0x1E00 + REPLACE = 0x1E01 + INCR = 0x1E02 + DECR = 0x1E03 + INVERT = 0x150A + INCR_WRAP = 0x8507 + DECR_WRAP = 0x8508 + VENDOR = 0x1F00 + RENDERER = 0x1F01 + VERSION = 0x1F02 + EXTENSIONS = 0x1F03 + NEAREST = 0x2600 + LINEAR = 0x2601 + NEAREST_MIPMAP_NEAREST = 0x2700 + LINEAR_MIPMAP_NEAREST = 0x2701 + NEAREST_MIPMAP_LINEAR = 0x2702 + LINEAR_MIPMAP_LINEAR = 0x2703 + TEXTURE_MAG_FILTER = 0x2800 + TEXTURE_MIN_FILTER = 0x2801 + TEXTURE_WRAP_S = 0x2802 + TEXTURE_WRAP_T = 0x2803 + TEXTURE = 0x1702 + TEXTURE_CUBE_MAP = 0x8513 + TEXTURE_BINDING_CUBE_MAP = 0x8514 + TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515 + TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516 + TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517 + TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518 + TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519 + TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851A + MAX_CUBE_MAP_TEXTURE_SIZE = 0x851C + TEXTURE0 = 0x84C0 + TEXTURE1 = 0x84C1 + TEXTURE2 = 0x84C2 + TEXTURE3 = 0x84C3 + TEXTURE4 = 0x84C4 + TEXTURE5 = 0x84C5 + TEXTURE6 = 0x84C6 + TEXTURE7 = 0x84C7 + TEXTURE8 = 0x84C8 + TEXTURE9 = 0x84C9 + TEXTURE10 = 0x84CA + TEXTURE11 = 0x84CB + TEXTURE12 = 0x84CC + TEXTURE13 = 0x84CD + TEXTURE14 = 0x84CE + TEXTURE15 = 0x84CF + TEXTURE16 = 0x84D0 + TEXTURE17 = 0x84D1 + TEXTURE18 = 0x84D2 + TEXTURE19 = 0x84D3 + TEXTURE20 = 0x84D4 + TEXTURE21 = 0x84D5 + TEXTURE22 = 0x84D6 + TEXTURE23 = 0x84D7 + TEXTURE24 = 0x84D8 + TEXTURE25 = 0x84D9 + TEXTURE26 = 0x84DA + TEXTURE27 = 0x84DB + TEXTURE28 = 0x84DC + TEXTURE29 = 0x84DD + TEXTURE30 = 0x84DE + TEXTURE31 = 0x84DF + ACTIVE_TEXTURE = 0x84E0 + REPEAT = 0x2901 + CLAMP_TO_EDGE = 0x812F + MIRRORED_REPEAT = 0x8370 + VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622 + VERTEX_ATTRIB_ARRAY_SIZE = 0x8623 + VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624 + VERTEX_ATTRIB_ARRAY_TYPE = 0x8625 + VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886A + VERTEX_ATTRIB_ARRAY_POINTER = 0x8645 + VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889F + IMPLEMENTATION_COLOR_READ_TYPE = 0x8B9A + IMPLEMENTATION_COLOR_READ_FORMAT = 0x8B9B + COMPILE_STATUS = 0x8B81 + INFO_LOG_LENGTH = 0x8B84 + SHADER_SOURCE_LENGTH = 0x8B88 + SHADER_COMPILER = 0x8DFA + SHADER_BINARY_FORMATS = 0x8DF8 + NUM_SHADER_BINARY_FORMATS = 0x8DF9 + LOW_FLOAT = 0x8DF0 + MEDIUM_FLOAT = 0x8DF1 + HIGH_FLOAT = 0x8DF2 + LOW_INT = 0x8DF3 + MEDIUM_INT = 0x8DF4 + HIGH_INT = 0x8DF5 + FRAMEBUFFER = 0x8D40 + RENDERBUFFER = 0x8D41 + RGBA4 = 0x8056 + RGB5_A1 = 0x8057 + RGB565 = 0x8D62 + DEPTH_COMPONENT16 = 0x81A5 + STENCIL_INDEX8 = 0x8D48 + RENDERBUFFER_WIDTH = 0x8D42 + RENDERBUFFER_HEIGHT = 0x8D43 + RENDERBUFFER_INTERNAL_FORMAT = 0x8D44 + RENDERBUFFER_RED_SIZE = 0x8D50 + RENDERBUFFER_GREEN_SIZE = 0x8D51 + RENDERBUFFER_BLUE_SIZE = 0x8D52 + RENDERBUFFER_ALPHA_SIZE = 0x8D53 + RENDERBUFFER_DEPTH_SIZE = 0x8D54 + RENDERBUFFER_STENCIL_SIZE = 0x8D55 + FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8CD0 + FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8CD1 + FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8CD2 + FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8CD3 + COLOR_ATTACHMENT0 = 0x8CE0 + DEPTH_ATTACHMENT = 0x8D00 + STENCIL_ATTACHMENT = 0x8D20 + FRAMEBUFFER_COMPLETE = 0x8CD5 + FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8CD6 + FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8CD7 + FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8CD9 + FRAMEBUFFER_UNSUPPORTED = 0x8CDD + FRAMEBUFFER_BINDING = 0x8CA6 + RENDERBUFFER_BINDING = 0x8CA7 + MAX_RENDERBUFFER_SIZE = 0x84E8 + INVALID_FRAMEBUFFER_OPERATION = 0x0506 +) + +const ( + DEPTH_BUFFER_BIT = 0x00000100 + STENCIL_BUFFER_BIT = 0x00000400 + COLOR_BUFFER_BIT = 0x00004000 +) + +const ( + FLOAT_VEC2 = 0x8B50 + FLOAT_VEC3 = 0x8B51 + FLOAT_VEC4 = 0x8B52 + INT_VEC2 = 0x8B53 + INT_VEC3 = 0x8B54 + INT_VEC4 = 0x8B55 + BOOL = 0x8B56 + BOOL_VEC2 = 0x8B57 + BOOL_VEC3 = 0x8B58 + BOOL_VEC4 = 0x8B59 + FLOAT_MAT2 = 0x8B5A + FLOAT_MAT3 = 0x8B5B + FLOAT_MAT4 = 0x8B5C + SAMPLER_2D = 0x8B5E + SAMPLER_CUBE = 0x8B60 +) + +const ( + FRAGMENT_SHADER = 0x8B30 + VERTEX_SHADER = 0x8B31 +) + +const ( + FALSE = 0 + TRUE = 1 + ZERO = 0 + ONE = 1 + NO_ERROR = 0 + NONE = 0 +) + +// GL ES 3.0 constants. +const ( + ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH = 0x8A35 + ACTIVE_UNIFORM_BLOCKS = 0x8A36 + ALREADY_SIGNALED = 0x911A + ANY_SAMPLES_PASSED = 0x8C2F + ANY_SAMPLES_PASSED_CONSERVATIVE = 0x8D6A + BLUE = 0x1905 + BUFFER_ACCESS_FLAGS = 0x911F + BUFFER_MAP_LENGTH = 0x9120 + BUFFER_MAP_OFFSET = 0x9121 + BUFFER_MAPPED = 0x88BC + BUFFER_MAP_POINTER = 0x88BD + COLOR = 0x1800 + COLOR_ATTACHMENT10 = 0x8CEA + COLOR_ATTACHMENT1 = 0x8CE1 + COLOR_ATTACHMENT11 = 0x8CEB + COLOR_ATTACHMENT12 = 0x8CEC + COLOR_ATTACHMENT13 = 0x8CED + COLOR_ATTACHMENT14 = 0x8CEE + COLOR_ATTACHMENT15 = 0x8CEF + COLOR_ATTACHMENT2 = 0x8CE2 + COLOR_ATTACHMENT3 = 0x8CE3 + COLOR_ATTACHMENT4 = 0x8CE4 + COLOR_ATTACHMENT5 = 0x8CE5 + COLOR_ATTACHMENT6 = 0x8CE6 + COLOR_ATTACHMENT7 = 0x8CE7 + COLOR_ATTACHMENT8 = 0x8CE8 + COLOR_ATTACHMENT9 = 0x8CE9 + COMPARE_REF_TO_TEXTURE = 0x884E + COMPRESSED_R11_EAC = 0x9270 + COMPRESSED_RG11_EAC = 0x9272 + COMPRESSED_RGB8_ETC2 = 0x9274 + COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9276 + COMPRESSED_RGBA8_ETC2_EAC = 0x9278 + COMPRESSED_SIGNED_R11_EAC = 0x9271 + COMPRESSED_SIGNED_RG11_EAC = 0x9273 + COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 0x9279 + COMPRESSED_SRGB8_ETC2 = 0x9275 + COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9277 + CONDITION_SATISFIED = 0x911C + COPY_READ_BUFFER = 0x8F36 + COPY_READ_BUFFER_BINDING = 0x8F36 + COPY_WRITE_BUFFER = 0x8F37 + COPY_WRITE_BUFFER_BINDING = 0x8F37 + CURRENT_QUERY = 0x8865 + DEPTH = 0x1801 + DEPTH24_STENCIL8 = 0x88F0 + DEPTH32F_STENCIL8 = 0x8CAD + DEPTH_COMPONENT24 = 0x81A6 + DEPTH_COMPONENT32F = 0x8CAC + DEPTH_STENCIL = 0x84F9 + DEPTH_STENCIL_ATTACHMENT = 0x821A + DRAW_BUFFER0 = 0x8825 + DRAW_BUFFER10 = 0x882F + DRAW_BUFFER1 = 0x8826 + DRAW_BUFFER11 = 0x8830 + DRAW_BUFFER12 = 0x8831 + DRAW_BUFFER13 = 0x8832 + DRAW_BUFFER14 = 0x8833 + DRAW_BUFFER15 = 0x8834 + DRAW_BUFFER2 = 0x8827 + DRAW_BUFFER3 = 0x8828 + DRAW_BUFFER4 = 0x8829 + DRAW_BUFFER5 = 0x882A + DRAW_BUFFER6 = 0x882B + DRAW_BUFFER7 = 0x882C + DRAW_BUFFER8 = 0x882D + DRAW_BUFFER9 = 0x882E + DRAW_FRAMEBUFFER = 0x8CA9 + DRAW_FRAMEBUFFER_BINDING = 0x8CA6 + DYNAMIC_COPY = 0x88EA + DYNAMIC_READ = 0x88E9 + FLOAT_32_UNSIGNED_INT_24_8_REV = 0x8DAD + FLOAT_MAT2x3 = 0x8B65 + FLOAT_MAT2x4 = 0x8B66 + FLOAT_MAT3x2 = 0x8B67 + FLOAT_MAT3x4 = 0x8B68 + FLOAT_MAT4x2 = 0x8B69 + FLOAT_MAT4x3 = 0x8B6A + FRAGMENT_SHADER_DERIVATIVE_HINT = 0x8B8B + FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE = 0x8215 + FRAMEBUFFER_ATTACHMENT_BLUE_SIZE = 0x8214 + FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING = 0x8210 + FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE = 0x8211 + FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE = 0x8216 + FRAMEBUFFER_ATTACHMENT_GREEN_SIZE = 0x8213 + FRAMEBUFFER_ATTACHMENT_RED_SIZE = 0x8212 + FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE = 0x8217 + FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER = 0x8CD4 + FRAMEBUFFER_DEFAULT = 0x8218 + FRAMEBUFFER_INCOMPLETE_MULTISAMPLE = 0x8D56 + FRAMEBUFFER_UNDEFINED = 0x8219 + GREEN = 0x1904 + HALF_FLOAT = 0x140B + INT_2_10_10_10_REV = 0x8D9F + INTERLEAVED_ATTRIBS = 0x8C8C + INT_SAMPLER_2D = 0x8DCA + INT_SAMPLER_2D_ARRAY = 0x8DCF + INT_SAMPLER_3D = 0x8DCB + INT_SAMPLER_CUBE = 0x8DCC + INVALID_INDEX = 0xFFFFFFFF + MAJOR_VERSION = 0x821B + MAP_FLUSH_EXPLICIT_BIT = 0x0010 + MAP_INVALIDATE_BUFFER_BIT = 0x0008 + MAP_INVALIDATE_RANGE_BIT = 0x0004 + MAP_READ_BIT = 0x0001 + MAP_UNSYNCHRONIZED_BIT = 0x0020 + MAP_WRITE_BIT = 0x0002 + MAX = 0x8008 + MAX_3D_TEXTURE_SIZE = 0x8073 + MAX_ARRAY_TEXTURE_LAYERS = 0x88FF + MAX_COLOR_ATTACHMENTS = 0x8CDF + MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS = 0x8A33 + MAX_COMBINED_UNIFORM_BLOCKS = 0x8A2E + MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS = 0x8A31 + MAX_DRAW_BUFFERS = 0x8824 + MAX_ELEMENT_INDEX = 0x8D6B + MAX_ELEMENTS_INDICES = 0x80E9 + MAX_ELEMENTS_VERTICES = 0x80E8 + MAX_FRAGMENT_INPUT_COMPONENTS = 0x9125 + MAX_FRAGMENT_UNIFORM_BLOCKS = 0x8A2D + MAX_FRAGMENT_UNIFORM_COMPONENTS = 0x8B49 + MAX_PROGRAM_TEXEL_OFFSET = 0x8905 + MAX_SAMPLES = 0x8D57 + MAX_SERVER_WAIT_TIMEOUT = 0x9111 + MAX_TEXTURE_LOD_BIAS = 0x84FD + MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS = 0x8C8A + MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS = 0x8C8B + MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS = 0x8C80 + MAX_UNIFORM_BLOCK_SIZE = 0x8A30 + MAX_UNIFORM_BUFFER_BINDINGS = 0x8A2F + MAX_VARYING_COMPONENTS = 0x8B4B + MAX_VERTEX_OUTPUT_COMPONENTS = 0x9122 + MAX_VERTEX_UNIFORM_BLOCKS = 0x8A2B + MAX_VERTEX_UNIFORM_COMPONENTS = 0x8B4A + MIN = 0x8007 + MINOR_VERSION = 0x821C + MIN_PROGRAM_TEXEL_OFFSET = 0x8904 + NUM_EXTENSIONS = 0x821D + NUM_PROGRAM_BINARY_FORMATS = 0x87FE + NUM_SAMPLE_COUNTS = 0x9380 + OBJECT_TYPE = 0x9112 + PACK_ROW_LENGTH = 0x0D02 + PACK_SKIP_PIXELS = 0x0D04 + PACK_SKIP_ROWS = 0x0D03 + PIXEL_PACK_BUFFER = 0x88EB + PIXEL_PACK_BUFFER_BINDING = 0x88ED + PIXEL_UNPACK_BUFFER = 0x88EC + PIXEL_UNPACK_BUFFER_BINDING = 0x88EF + PRIMITIVE_RESTART_FIXED_INDEX = 0x8D69 + PROGRAM_BINARY_FORMATS = 0x87FF + PROGRAM_BINARY_LENGTH = 0x8741 + PROGRAM_BINARY_RETRIEVABLE_HINT = 0x8257 + QUERY_RESULT = 0x8866 + QUERY_RESULT_AVAILABLE = 0x8867 + R11F_G11F_B10F = 0x8C3A + R16F = 0x822D + R16I = 0x8233 + R16UI = 0x8234 + R32F = 0x822E + R32I = 0x8235 + R32UI = 0x8236 + R8 = 0x8229 + R8I = 0x8231 + R8_SNORM = 0x8F94 + R8UI = 0x8232 + RASTERIZER_DISCARD = 0x8C89 + READ_BUFFER = 0x0C02 + READ_FRAMEBUFFER = 0x8CA8 + READ_FRAMEBUFFER_BINDING = 0x8CAA + RED = 0x1903 + RED_INTEGER = 0x8D94 + RENDERBUFFER_SAMPLES = 0x8CAB + RG = 0x8227 + RG16F = 0x822F + RG16I = 0x8239 + RG16UI = 0x823A + RG32F = 0x8230 + RG32I = 0x823B + RG32UI = 0x823C + RG8 = 0x822B + RG8I = 0x8237 + RG8_SNORM = 0x8F95 + RG8UI = 0x8238 + RGB10_A2 = 0x8059 + RGB10_A2UI = 0x906F + RGB16F = 0x881B + RGB16I = 0x8D89 + RGB16UI = 0x8D77 + RGB32F = 0x8815 + RGB32I = 0x8D83 + RGB32UI = 0x8D71 + RGB8 = 0x8051 + RGB8I = 0x8D8F + RGB8_SNORM = 0x8F96 + RGB8UI = 0x8D7D + RGB9_E5 = 0x8C3D + RGBA16F = 0x881A + RGBA16I = 0x8D88 + RGBA16UI = 0x8D76 + RGBA32F = 0x8814 + RGBA32I = 0x8D82 + RGBA32UI = 0x8D70 + RGBA8 = 0x8058 + RGBA8I = 0x8D8E + RGBA8_SNORM = 0x8F97 + RGBA8UI = 0x8D7C + RGBA_INTEGER = 0x8D99 + RGB_INTEGER = 0x8D98 + RG_INTEGER = 0x8228 + SAMPLER_2D_ARRAY = 0x8DC1 + SAMPLER_2D_ARRAY_SHADOW = 0x8DC4 + SAMPLER_2D_SHADOW = 0x8B62 + SAMPLER_3D = 0x8B5F + SAMPLER_BINDING = 0x8919 + SAMPLER_CUBE_SHADOW = 0x8DC5 + SEPARATE_ATTRIBS = 0x8C8D + SIGNALED = 0x9119 + SIGNED_NORMALIZED = 0x8F9C + SRGB = 0x8C40 + SRGB8 = 0x8C41 + SRGB8_ALPHA8 = 0x8C43 + STATIC_COPY = 0x88E6 + STATIC_READ = 0x88E5 + STENCIL = 0x1802 + STREAM_COPY = 0x88E2 + STREAM_READ = 0x88E1 + SYNC_CONDITION = 0x9113 + SYNC_FENCE = 0x9116 + SYNC_FLAGS = 0x9115 + SYNC_FLUSH_COMMANDS_BIT = 0x00000001 + SYNC_GPU_COMMANDS_COMPLETE = 0x9117 + SYNC_STATUS = 0x9114 + TEXTURE_2D_ARRAY = 0x8C1A + TEXTURE_3D = 0x806F + TEXTURE_BASE_LEVEL = 0x813C + TEXTURE_BINDING_2D_ARRAY = 0x8C1D + TEXTURE_BINDING_3D = 0x806A + TEXTURE_COMPARE_FUNC = 0x884D + TEXTURE_COMPARE_MODE = 0x884C + TEXTURE_IMMUTABLE_FORMAT = 0x912F + TEXTURE_IMMUTABLE_LEVELS = 0x82DF + TEXTURE_MAX_LEVEL = 0x813D + TEXTURE_MAX_LOD = 0x813B + TEXTURE_MIN_LOD = 0x813A + TEXTURE_SWIZZLE_A = 0x8E45 + TEXTURE_SWIZZLE_B = 0x8E44 + TEXTURE_SWIZZLE_G = 0x8E43 + TEXTURE_SWIZZLE_R = 0x8E42 + TEXTURE_WRAP_R = 0x8072 + TIMEOUT_EXPIRED = 0x911B + TIMEOUT_IGNORED = 0xFFFFFFFFFFFFFFFF + TRANSFORM_FEEDBACK = 0x8E22 + TRANSFORM_FEEDBACK_ACTIVE = 0x8E24 + TRANSFORM_FEEDBACK_BINDING = 0x8E25 + TRANSFORM_FEEDBACK_BUFFER = 0x8C8E + TRANSFORM_FEEDBACK_BUFFER_BINDING = 0x8C8F + TRANSFORM_FEEDBACK_BUFFER_MODE = 0x8C7F + TRANSFORM_FEEDBACK_BUFFER_SIZE = 0x8C85 + TRANSFORM_FEEDBACK_BUFFER_START = 0x8C84 + TRANSFORM_FEEDBACK_PAUSED = 0x8E23 + TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN = 0x8C88 + TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH = 0x8C76 + TRANSFORM_FEEDBACK_VARYINGS = 0x8C83 + UNIFORM_ARRAY_STRIDE = 0x8A3C + UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES = 0x8A43 + UNIFORM_BLOCK_ACTIVE_UNIFORMS = 0x8A42 + UNIFORM_BLOCK_BINDING = 0x8A3F + UNIFORM_BLOCK_DATA_SIZE = 0x8A40 + UNIFORM_BLOCK_INDEX = 0x8A3A + UNIFORM_BLOCK_NAME_LENGTH = 0x8A41 + UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER = 0x8A46 + UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER = 0x8A44 + UNIFORM_BUFFER = 0x8A11 + UNIFORM_BUFFER_BINDING = 0x8A28 + UNIFORM_BUFFER_OFFSET_ALIGNMENT = 0x8A34 + UNIFORM_BUFFER_SIZE = 0x8A2A + UNIFORM_BUFFER_START = 0x8A29 + UNIFORM_IS_ROW_MAJOR = 0x8A3E + UNIFORM_MATRIX_STRIDE = 0x8A3D + UNIFORM_NAME_LENGTH = 0x8A39 + UNIFORM_OFFSET = 0x8A3B + UNIFORM_SIZE = 0x8A38 + UNIFORM_TYPE = 0x8A37 + UNPACK_IMAGE_HEIGHT = 0x806E + UNPACK_ROW_LENGTH = 0x0CF2 + UNPACK_SKIP_IMAGES = 0x806D + UNPACK_SKIP_PIXELS = 0x0CF4 + UNPACK_SKIP_ROWS = 0x0CF3 + UNSIGNALED = 0x9118 + UNSIGNED_INT_10F_11F_11F_REV = 0x8C3B + UNSIGNED_INT_2_10_10_10_REV = 0x8368 + UNSIGNED_INT_24_8 = 0x84FA + UNSIGNED_INT_5_9_9_9_REV = 0x8C3E + UNSIGNED_INT_SAMPLER_2D = 0x8DD2 + UNSIGNED_INT_SAMPLER_2D_ARRAY = 0x8DD7 + UNSIGNED_INT_SAMPLER_3D = 0x8DD3 + UNSIGNED_INT_SAMPLER_CUBE = 0x8DD4 + UNSIGNED_INT_VEC2 = 0x8DC6 + UNSIGNED_INT_VEC3 = 0x8DC7 + UNSIGNED_INT_VEC4 = 0x8DC8 + UNSIGNED_NORMALIZED = 0x8C17 + VERTEX_ARRAY_BINDING = 0x85B5 + VERTEX_ATTRIB_ARRAY_DIVISOR = 0x88FE + VERTEX_ATTRIB_ARRAY_INTEGER = 0x88FD + WAIT_FAILED = 0x911D +) diff --git a/vendor/github.com/ebitengine/gomobile/gl/dll_windows.go b/vendor/github.com/ebitengine/gomobile/gl/dll_windows.go new file mode 100644 index 0000000..1afc5f8 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/gl/dll_windows.go @@ -0,0 +1,243 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gl + +import ( + "archive/tar" + "compress/gzip" + "debug/pe" + "fmt" + "io" + "io/ioutil" + "log" + "net/http" + "os" + "path/filepath" + "runtime" +) + +var debug = log.New(ioutil.Discard, "gl: ", log.LstdFlags) + +func downloadDLLs() (path string, err error) { + url := "https://dl.google.com/go/mobile/angle-bd3f8780b-" + runtime.GOARCH + ".tgz" + debug.Printf("downloading %s", url) + resp, err := http.Get(url) + if err != nil { + return "", fmt.Errorf("gl: %v", err) + } + defer func() { + err2 := resp.Body.Close() + if err == nil && err2 != nil { + err = fmt.Errorf("gl: error reading body from %v: %v", url, err2) + } + }() + if resp.StatusCode != http.StatusOK { + err := fmt.Errorf("gl: error fetching %v, status: %v", url, resp.Status) + return "", err + } + + r, err := gzip.NewReader(resp.Body) + if err != nil { + return "", fmt.Errorf("gl: error reading gzip from %v: %v", url, err) + } + tr := tar.NewReader(r) + var bytesGLESv2, bytesEGL, bytesD3DCompiler []byte + for { + header, err := tr.Next() + if err == io.EOF { + break + } + if err != nil { + return "", fmt.Errorf("gl: error reading tar from %v: %v", url, err) + } + switch header.Name { + case "angle-" + runtime.GOARCH + "/libglesv2.dll": + bytesGLESv2, err = ioutil.ReadAll(tr) + case "angle-" + runtime.GOARCH + "/libegl.dll": + bytesEGL, err = ioutil.ReadAll(tr) + case "angle-" + runtime.GOARCH + "/d3dcompiler_47.dll": + bytesD3DCompiler, err = ioutil.ReadAll(tr) + default: // skip + } + if err != nil { + return "", fmt.Errorf("gl: error reading %v from %v: %v", header.Name, url, err) + } + } + if len(bytesGLESv2) == 0 || len(bytesEGL) == 0 || len(bytesD3DCompiler) == 0 { + return "", fmt.Errorf("gl: did not find all DLLs in %v", url) + } + + writeDLLs := func(path string) error { + if err := ioutil.WriteFile(filepath.Join(path, "libglesv2.dll"), bytesGLESv2, 0755); err != nil { + return fmt.Errorf("gl: cannot install ANGLE: %v", err) + } + if err := ioutil.WriteFile(filepath.Join(path, "libegl.dll"), bytesEGL, 0755); err != nil { + return fmt.Errorf("gl: cannot install ANGLE: %v", err) + } + if err := ioutil.WriteFile(filepath.Join(path, "d3dcompiler_47.dll"), bytesD3DCompiler, 0755); err != nil { + return fmt.Errorf("gl: cannot install ANGLE: %v", err) + } + return nil + } + + // First, we attempt to install these DLLs in LOCALAPPDATA/Shiny. + // + // Traditionally we would use the system32 directory, but it is + // no longer writable by normal programs. + os.MkdirAll(appdataPath(), 0775) + if err := writeDLLs(appdataPath()); err == nil { + return appdataPath(), nil + } + debug.Printf("DLLs could not be written to %s", appdataPath()) + + // Second, install in GOPATH/pkg if it exists. + gopath := os.Getenv("GOPATH") + gopathpkg := filepath.Join(gopath, "pkg") + if _, err := os.Stat(gopathpkg); err == nil && gopath != "" { + if err := writeDLLs(gopathpkg); err == nil { + return gopathpkg, nil + } + } + debug.Printf("DLLs could not be written to GOPATH") + + // Third, pick a temporary directory. + tmp := os.TempDir() + if err := writeDLLs(tmp); err != nil { + return "", fmt.Errorf("gl: unable to install ANGLE DLLs: %v", err) + } + return tmp, nil +} + +func appdataPath() string { + return filepath.Join(os.Getenv("LOCALAPPDATA"), "GoGL", runtime.GOARCH) +} + +func containsDLLs(dir string) bool { + compatible := func(name string) bool { + file, err := pe.Open(filepath.Join(dir, name)) + if err != nil { + return false + } + defer file.Close() + + switch file.Machine { + case pe.IMAGE_FILE_MACHINE_AMD64: + return "amd64" == runtime.GOARCH + case pe.IMAGE_FILE_MACHINE_ARM: + return "arm" == runtime.GOARCH + case pe.IMAGE_FILE_MACHINE_I386: + return "386" == runtime.GOARCH + } + return false + } + + return compatible("libglesv2.dll") && compatible("libegl.dll") && compatible("d3dcompiler_47.dll") +} + +func chromePath() string { + // dlls are stored in: + // //libglesv2.dll + + var installdirs = []string{ + // Chrome User + filepath.Join(os.Getenv("LOCALAPPDATA"), "Google", "Chrome", "Application"), + // Chrome System + filepath.Join(os.Getenv("ProgramFiles(x86)"), "Google", "Chrome", "Application"), + // Chromium + filepath.Join(os.Getenv("LOCALAPPDATA"), "Chromium", "Application"), + // Chrome Canary + filepath.Join(os.Getenv("LOCALAPPDATA"), "Google", "Chrome SxS", "Application"), + } + + for _, installdir := range installdirs { + versiondirs, err := ioutil.ReadDir(installdir) + if err != nil { + continue + } + + for _, versiondir := range versiondirs { + if !versiondir.IsDir() { + continue + } + + versionpath := filepath.Join(installdir, versiondir.Name()) + if containsDLLs(versionpath) { + return versionpath + } + } + } + + return "" +} + +func findDLLs() (err error) { + load := func(path string) (bool, error) { + if path != "" { + // don't try to start when one of the files is missing + if !containsDLLs(path) { + return false, nil + } + + LibD3DCompiler.Name = filepath.Join(path, filepath.Base(LibD3DCompiler.Name)) + LibGLESv2.Name = filepath.Join(path, filepath.Base(LibGLESv2.Name)) + LibEGL.Name = filepath.Join(path, filepath.Base(LibEGL.Name)) + } + + if err := LibGLESv2.Load(); err == nil { + if err := LibEGL.Load(); err != nil { + return false, fmt.Errorf("gl: loaded libglesv2 but not libegl: %v", err) + } + if err := LibD3DCompiler.Load(); err != nil { + return false, fmt.Errorf("gl: loaded libglesv2, libegl but not d3dcompiler: %v", err) + } + if path == "" { + debug.Printf("DLLs found") + } else { + debug.Printf("DLLs found in: %q", path) + } + return true, nil + } + + return false, nil + } + + // Look in the system directory. + if ok, err := load(""); ok || err != nil { + return err + } + + // Look in the AppData directory. + if ok, err := load(appdataPath()); ok || err != nil { + return err + } + + // Look for a Chrome installation + if dir := chromePath(); dir != "" { + if ok, err := load(dir); ok || err != nil { + return err + } + } + + // Look in GOPATH/pkg. + if ok, err := load(filepath.Join(os.Getenv("GOPATH"), "pkg")); ok || err != nil { + return err + } + + // Look in temporary directory. + if ok, err := load(os.TempDir()); ok || err != nil { + return err + } + + // Download the DLL binary. + path, err := downloadDLLs() + if err != nil { + return err + } + debug.Printf("DLLs written to %s", path) + if ok, err := load(path); !ok || err != nil { + return fmt.Errorf("gl: unable to load ANGLE after installation: %v", err) + } + return nil +} diff --git a/vendor/github.com/ebitengine/gomobile/gl/doc.go b/vendor/github.com/ebitengine/gomobile/gl/doc.go new file mode 100644 index 0000000..9b73f58 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/gl/doc.go @@ -0,0 +1,66 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* +Package gl implements Go bindings for OpenGL ES 2.0 and ES 3.0. + +The GL functions are defined on a Context object that is responsible for +tracking a GL context. Typically a windowing system package (such as +golang.org/x/exp/shiny/screen) will call NewContext and provide +a gl.Context for a user application. + +If the gl package is compiled on a platform capable of supporting ES 3.0, +the gl.Context object also implements gl.Context3. + +The bindings are deliberately minimal, staying as close the C API as +possible. The semantics of each function maps onto functions +described in the Khronos documentation: + +https://www.khronos.org/opengles/sdk/docs/man/ + +One notable departure from the C API is the introduction of types +to represent common uses of GLint: Texture, Surface, Buffer, etc. + +# Debug Logging + +A tracing version of the OpenGL bindings is behind the `gldebug` build +tag. It acts as a simplified version of apitrace. Build your Go binary +with + + -tags gldebug + +and each call to a GL function will log its input, output, and any +error messages. For example, + + I/GoLog (27668): gl.GenBuffers(1) [Buffer(70001)] + I/GoLog (27668): gl.BindBuffer(ARRAY_BUFFER, Buffer(70001)) + I/GoLog (27668): gl.BufferData(ARRAY_BUFFER, 36, len(36), STATIC_DRAW) + I/GoLog (27668): gl.BindBuffer(ARRAY_BUFFER, Buffer(70001)) + I/GoLog (27668): gl.VertexAttribPointer(Attrib(0), 6, FLOAT, false, 0, 0) error: [INVALID_VALUE] + +The gldebug tracing has very high overhead, so make sure to remove +the build tag before deploying any binaries. +*/ +package gl // import "github.com/ebitengine/gomobile/gl" + +/* +Implementation details. + +All GL function calls fill out a C.struct_fnargs and drop it on the work +queue. The Start function drains the work queue and hands over a batch +of calls to C.process which runs them. This allows multiple GL calls to +be executed in a single cgo call. + +A GL call is marked as blocking if it returns a value, or if it takes a +Go pointer. In this case the call will not return until C.process sends a +value on the retvalue channel. + +This implementation ensures any goroutine can make GL calls, but it does +not make the GL interface safe for simultaneous use by multiple goroutines. +For the purpose of analyzing this code for race conditions, picture two +separate goroutines: one blocked on gl.Start, and another making calls to +the gl package exported functions. +*/ + +//go:generate go run gendebug.go -o gldebug.go diff --git a/vendor/github.com/ebitengine/gomobile/gl/fn.go b/vendor/github.com/ebitengine/gomobile/gl/fn.go new file mode 100644 index 0000000..3f2f3ad --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/gl/fn.go @@ -0,0 +1,210 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gl + +import "unsafe" + +type call struct { + args fnargs + parg unsafe.Pointer + blocking bool +} + +type fnargs struct { + fn glfn + + a0 uintptr + a1 uintptr + a2 uintptr + a3 uintptr + a4 uintptr + a5 uintptr + a6 uintptr + a7 uintptr + a8 uintptr + a9 uintptr +} + +type glfn int + +const ( + glfnUNDEFINED glfn = iota + glfnActiveTexture + glfnAttachShader + glfnBindAttribLocation + glfnBindBuffer + glfnBindFramebuffer + glfnBindRenderbuffer + glfnBindTexture + glfnBindVertexArray + glfnBlendColor + glfnBlendEquation + glfnBlendEquationSeparate + glfnBlendFunc + glfnBlendFuncSeparate + glfnBufferData + glfnBufferSubData + glfnCheckFramebufferStatus + glfnClear + glfnClearColor + glfnClearDepthf + glfnClearStencil + glfnColorMask + glfnCompileShader + glfnCompressedTexImage2D + glfnCompressedTexSubImage2D + glfnCopyTexImage2D + glfnCopyTexSubImage2D + glfnCreateProgram + glfnCreateShader + glfnCullFace + glfnDeleteBuffer + glfnDeleteFramebuffer + glfnDeleteProgram + glfnDeleteRenderbuffer + glfnDeleteShader + glfnDeleteTexture + glfnDeleteVertexArray + glfnDepthFunc + glfnDepthRangef + glfnDepthMask + glfnDetachShader + glfnDisable + glfnDisableVertexAttribArray + glfnDrawArrays + glfnDrawElements + glfnEnable + glfnEnableVertexAttribArray + glfnFinish + glfnFlush + glfnFramebufferRenderbuffer + glfnFramebufferTexture2D + glfnFrontFace + glfnGenBuffer + glfnGenFramebuffer + glfnGenRenderbuffer + glfnGenTexture + glfnGenVertexArray + glfnGenerateMipmap + glfnGetActiveAttrib + glfnGetActiveUniform + glfnGetAttachedShaders + glfnGetAttribLocation + glfnGetBooleanv + glfnGetBufferParameteri + glfnGetError + glfnGetFloatv + glfnGetFramebufferAttachmentParameteriv + glfnGetIntegerv + glfnGetProgramInfoLog + glfnGetProgramiv + glfnGetRenderbufferParameteriv + glfnGetShaderInfoLog + glfnGetShaderPrecisionFormat + glfnGetShaderSource + glfnGetShaderiv + glfnGetString + glfnGetTexParameterfv + glfnGetTexParameteriv + glfnGetUniformLocation + glfnGetUniformfv + glfnGetUniformiv + glfnGetVertexAttribfv + glfnGetVertexAttribiv + glfnHint + glfnIsBuffer + glfnIsEnabled + glfnIsFramebuffer + glfnIsProgram + glfnIsRenderbuffer + glfnIsShader + glfnIsTexture + glfnLineWidth + glfnLinkProgram + glfnPixelStorei + glfnPolygonOffset + glfnReadPixels + glfnReleaseShaderCompiler + glfnRenderbufferStorage + glfnSampleCoverage + glfnScissor + glfnShaderSource + glfnStencilFunc + glfnStencilFuncSeparate + glfnStencilMask + glfnStencilMaskSeparate + glfnStencilOp + glfnStencilOpSeparate + glfnTexImage2D + glfnTexParameterf + glfnTexParameterfv + glfnTexParameteri + glfnTexParameteriv + glfnTexSubImage2D + glfnUniform1f + glfnUniform1fv + glfnUniform1i + glfnUniform1iv + glfnUniform2f + glfnUniform2fv + glfnUniform2i + glfnUniform2iv + glfnUniform3f + glfnUniform3fv + glfnUniform3i + glfnUniform3iv + glfnUniform4f + glfnUniform4fv + glfnUniform4i + glfnUniform4iv + glfnUniformMatrix2fv + glfnUniformMatrix3fv + glfnUniformMatrix4fv + glfnUseProgram + glfnValidateProgram + glfnVertexAttrib1f + glfnVertexAttrib1fv + glfnVertexAttrib2f + glfnVertexAttrib2fv + glfnVertexAttrib3f + glfnVertexAttrib3fv + glfnVertexAttrib4f + glfnVertexAttrib4fv + glfnVertexAttribPointer + glfnViewport + + // ES 3.0 functions + glfnUniformMatrix2x3fv + glfnUniformMatrix3x2fv + glfnUniformMatrix2x4fv + glfnUniformMatrix4x2fv + glfnUniformMatrix3x4fv + glfnUniformMatrix4x3fv + glfnBlitFramebuffer + glfnUniform1ui + glfnUniform2ui + glfnUniform3ui + glfnUniform4ui + glfnUniform1uiv + glfnUniform2uiv + glfnUniform3uiv + glfnUniform4uiv +) + +func goString(buf []byte) string { + for i, b := range buf { + if b == 0 { + return string(buf[:i]) + } + } + panic("buf is not NUL-terminated") +} + +func glBoolean(b bool) uintptr { + if b { + return TRUE + } + return FALSE +} diff --git a/vendor/github.com/ebitengine/gomobile/gl/gl.go b/vendor/github.com/ebitengine/gomobile/gl/gl.go new file mode 100644 index 0000000..28e747b --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/gl/gl.go @@ -0,0 +1,1851 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build (darwin || linux || openbsd || windows) && !gldebug + +package gl + +// TODO(crawshaw): should functions on specific types become methods? E.g. +// func (t Texture) Bind(target Enum) +// this seems natural in Go, but moves us slightly +// further away from the underlying OpenGL spec. + +import ( + "math" + "unsafe" +) + +func (ctx *context) ActiveTexture(texture Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnActiveTexture, + a0: texture.c(), + }, + }) +} + +func (ctx *context) AttachShader(p Program, s Shader) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnAttachShader, + a0: p.c(), + a1: s.c(), + }, + }) +} + +func (ctx *context) BindAttribLocation(p Program, a Attrib, name string) { + s, free := ctx.cString(name) + defer free() + ctx.enqueue(call{ + args: fnargs{ + fn: glfnBindAttribLocation, + a0: p.c(), + a1: a.c(), + a2: s, + }, + blocking: true, + }) +} + +func (ctx *context) BindBuffer(target Enum, b Buffer) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnBindBuffer, + a0: target.c(), + a1: b.c(), + }, + }) +} + +func (ctx *context) BindFramebuffer(target Enum, fb Framebuffer) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnBindFramebuffer, + a0: target.c(), + a1: fb.c(), + }, + }) +} + +func (ctx *context) BindRenderbuffer(target Enum, rb Renderbuffer) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnBindRenderbuffer, + a0: target.c(), + a1: rb.c(), + }, + }) +} + +func (ctx *context) BindTexture(target Enum, t Texture) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnBindTexture, + a0: target.c(), + a1: t.c(), + }, + }) +} + +func (ctx *context) BindVertexArray(va VertexArray) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnBindVertexArray, + a0: va.c(), + }, + }) +} + +func (ctx *context) BlendColor(red, green, blue, alpha float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnBlendColor, + a0: uintptr(math.Float32bits(red)), + a1: uintptr(math.Float32bits(green)), + a2: uintptr(math.Float32bits(blue)), + a3: uintptr(math.Float32bits(alpha)), + }, + }) +} + +func (ctx *context) BlendEquation(mode Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnBlendEquation, + a0: mode.c(), + }, + }) +} + +func (ctx *context) BlendEquationSeparate(modeRGB, modeAlpha Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnBlendEquationSeparate, + a0: modeRGB.c(), + a1: modeAlpha.c(), + }, + }) +} + +func (ctx *context) BlendFunc(sfactor, dfactor Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnBlendFunc, + a0: sfactor.c(), + a1: dfactor.c(), + }, + }) +} + +func (ctx *context) BlendFuncSeparate(sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnBlendFuncSeparate, + a0: sfactorRGB.c(), + a1: dfactorRGB.c(), + a2: sfactorAlpha.c(), + a3: dfactorAlpha.c(), + }, + }) +} + +func (ctx *context) BufferData(target Enum, src []byte, usage Enum) { + parg := unsafe.Pointer(nil) + if len(src) > 0 { + parg = unsafe.Pointer(&src[0]) + } + ctx.enqueue(call{ + args: fnargs{ + fn: glfnBufferData, + a0: target.c(), + a1: uintptr(len(src)), + a2: usage.c(), + }, + parg: parg, + blocking: true, + }) +} + +func (ctx *context) BufferInit(target Enum, size int, usage Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnBufferData, + a0: target.c(), + a1: uintptr(size), + a2: usage.c(), + }, + parg: unsafe.Pointer(nil), + }) +} + +func (ctx *context) BufferSubData(target Enum, offset int, data []byte) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnBufferSubData, + a0: target.c(), + a1: uintptr(offset), + a2: uintptr(len(data)), + }, + parg: unsafe.Pointer(&data[0]), + blocking: true, + }) +} + +func (ctx *context) CheckFramebufferStatus(target Enum) Enum { + return Enum(ctx.enqueue(call{ + args: fnargs{ + fn: glfnCheckFramebufferStatus, + a0: target.c(), + }, + blocking: true, + })) +} + +func (ctx *context) Clear(mask Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnClear, + a0: uintptr(mask), + }, + }) +} + +func (ctx *context) ClearColor(red, green, blue, alpha float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnClearColor, + a0: uintptr(math.Float32bits(red)), + a1: uintptr(math.Float32bits(green)), + a2: uintptr(math.Float32bits(blue)), + a3: uintptr(math.Float32bits(alpha)), + }, + }) +} + +func (ctx *context) ClearDepthf(d float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnClearDepthf, + a0: uintptr(math.Float32bits(d)), + }, + }) +} + +func (ctx *context) ClearStencil(s int) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnClearStencil, + a0: uintptr(s), + }, + }) +} + +func (ctx *context) ColorMask(red, green, blue, alpha bool) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnColorMask, + a0: glBoolean(red), + a1: glBoolean(green), + a2: glBoolean(blue), + a3: glBoolean(alpha), + }, + }) +} + +func (ctx *context) CompileShader(s Shader) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnCompileShader, + a0: s.c(), + }, + }) +} + +func (ctx *context) CompressedTexImage2D(target Enum, level int, internalformat Enum, width, height, border int, data []byte) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnCompressedTexImage2D, + a0: target.c(), + a1: uintptr(level), + a2: internalformat.c(), + a3: uintptr(width), + a4: uintptr(height), + a5: uintptr(border), + a6: uintptr(len(data)), + }, + parg: unsafe.Pointer(&data[0]), + blocking: true, + }) +} + +func (ctx *context) CompressedTexSubImage2D(target Enum, level, xoffset, yoffset, width, height int, format Enum, data []byte) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnCompressedTexSubImage2D, + a0: target.c(), + a1: uintptr(level), + a2: uintptr(xoffset), + a3: uintptr(yoffset), + a4: uintptr(width), + a5: uintptr(height), + a6: format.c(), + a7: uintptr(len(data)), + }, + parg: unsafe.Pointer(&data[0]), + blocking: true, + }) +} + +func (ctx *context) CopyTexImage2D(target Enum, level int, internalformat Enum, x, y, width, height, border int) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnCopyTexImage2D, + a0: target.c(), + a1: uintptr(level), + a2: internalformat.c(), + a3: uintptr(x), + a4: uintptr(y), + a5: uintptr(width), + a6: uintptr(height), + a7: uintptr(border), + }, + }) +} + +func (ctx *context) CopyTexSubImage2D(target Enum, level, xoffset, yoffset, x, y, width, height int) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnCopyTexSubImage2D, + a0: target.c(), + a1: uintptr(level), + a2: uintptr(xoffset), + a3: uintptr(yoffset), + a4: uintptr(x), + a5: uintptr(y), + a6: uintptr(width), + a7: uintptr(height), + }, + }) +} + +func (ctx *context) CreateBuffer() Buffer { + return Buffer{Value: uint32(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGenBuffer, + }, + blocking: true, + }))} +} + +func (ctx *context) CreateFramebuffer() Framebuffer { + return Framebuffer{Value: uint32(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGenFramebuffer, + }, + blocking: true, + }))} +} + +func (ctx *context) CreateProgram() Program { + return Program{ + Init: true, + Value: uint32(ctx.enqueue(call{ + args: fnargs{ + fn: glfnCreateProgram, + }, + blocking: true, + }, + ))} +} + +func (ctx *context) CreateRenderbuffer() Renderbuffer { + return Renderbuffer{Value: uint32(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGenRenderbuffer, + }, + blocking: true, + }))} +} + +func (ctx *context) CreateShader(ty Enum) Shader { + return Shader{Value: uint32(ctx.enqueue(call{ + args: fnargs{ + fn: glfnCreateShader, + a0: uintptr(ty), + }, + blocking: true, + }))} +} + +func (ctx *context) CreateTexture() Texture { + return Texture{Value: uint32(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGenTexture, + }, + blocking: true, + }))} +} + +func (ctx *context) CreateVertexArray() VertexArray { + return VertexArray{Value: uint32(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGenVertexArray, + }, + blocking: true, + }))} +} + +func (ctx *context) CullFace(mode Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnCullFace, + a0: mode.c(), + }, + }) +} + +func (ctx *context) DeleteBuffer(v Buffer) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnDeleteBuffer, + a0: v.c(), + }, + }) +} + +func (ctx *context) DeleteFramebuffer(v Framebuffer) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnDeleteFramebuffer, + a0: v.c(), + }, + }) +} + +func (ctx *context) DeleteProgram(p Program) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnDeleteProgram, + a0: p.c(), + }, + }) +} + +func (ctx *context) DeleteRenderbuffer(v Renderbuffer) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnDeleteRenderbuffer, + a0: v.c(), + }, + }) +} + +func (ctx *context) DeleteShader(s Shader) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnDeleteShader, + a0: s.c(), + }, + }) +} + +func (ctx *context) DeleteTexture(v Texture) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnDeleteTexture, + a0: v.c(), + }, + }) +} + +func (ctx *context) DeleteVertexArray(v VertexArray) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnDeleteVertexArray, + a0: v.c(), + }, + }) +} + +func (ctx *context) DepthFunc(fn Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnDepthFunc, + a0: fn.c(), + }, + }) +} + +func (ctx *context) DepthMask(flag bool) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnDepthMask, + a0: glBoolean(flag), + }, + }) +} + +func (ctx *context) DepthRangef(n, f float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnDepthRangef, + a0: uintptr(math.Float32bits(n)), + a1: uintptr(math.Float32bits(f)), + }, + }) +} + +func (ctx *context) DetachShader(p Program, s Shader) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnDetachShader, + a0: p.c(), + a1: s.c(), + }, + }) +} + +func (ctx *context) Disable(cap Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnDisable, + a0: cap.c(), + }, + }) +} + +func (ctx *context) DisableVertexAttribArray(a Attrib) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnDisableVertexAttribArray, + a0: a.c(), + }, + }) +} + +func (ctx *context) DrawArrays(mode Enum, first, count int) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnDrawArrays, + a0: mode.c(), + a1: uintptr(first), + a2: uintptr(count), + }, + }) +} + +func (ctx *context) DrawElements(mode Enum, count int, ty Enum, offset int) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnDrawElements, + a0: mode.c(), + a1: uintptr(count), + a2: ty.c(), + a3: uintptr(offset), + }, + }) +} + +func (ctx *context) Enable(cap Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnEnable, + a0: cap.c(), + }, + }) +} + +func (ctx *context) EnableVertexAttribArray(a Attrib) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnEnableVertexAttribArray, + a0: a.c(), + }, + }) +} + +func (ctx *context) Finish() { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnFinish, + }, + blocking: true, + }) +} + +func (ctx *context) Flush() { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnFlush, + }, + blocking: true, + }) +} + +func (ctx *context) FramebufferRenderbuffer(target, attachment, rbTarget Enum, rb Renderbuffer) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnFramebufferRenderbuffer, + a0: target.c(), + a1: attachment.c(), + a2: rbTarget.c(), + a3: rb.c(), + }, + }) +} + +func (ctx *context) FramebufferTexture2D(target, attachment, texTarget Enum, t Texture, level int) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnFramebufferTexture2D, + a0: target.c(), + a1: attachment.c(), + a2: texTarget.c(), + a3: t.c(), + a4: uintptr(level), + }, + }) +} + +func (ctx *context) FrontFace(mode Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnFrontFace, + a0: mode.c(), + }, + }) +} + +func (ctx *context) GenerateMipmap(target Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnGenerateMipmap, + a0: target.c(), + }, + }) +} + +func (ctx *context) GetActiveAttrib(p Program, index uint32) (name string, size int, ty Enum) { + bufSize := ctx.GetProgrami(p, ACTIVE_ATTRIBUTE_MAX_LENGTH) + buf := make([]byte, bufSize) + var cType int + + cSize := ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetActiveAttrib, + a0: p.c(), + a1: uintptr(index), + a2: uintptr(bufSize), + a3: uintptr(unsafe.Pointer(&cType)), // TODO(crawshaw): not safe for a moving collector + }, + parg: unsafe.Pointer(&buf[0]), + blocking: true, + }) + + return goString(buf), int(cSize), Enum(cType) +} + +func (ctx *context) GetActiveUniform(p Program, index uint32) (name string, size int, ty Enum) { + bufSize := ctx.GetProgrami(p, ACTIVE_UNIFORM_MAX_LENGTH) + buf := make([]byte, bufSize+8) // extra space for cType + var cType int + + cSize := ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetActiveUniform, + a0: p.c(), + a1: uintptr(index), + a2: uintptr(bufSize), + a3: uintptr(unsafe.Pointer(&cType)), // TODO(crawshaw): not safe for a moving collector + }, + parg: unsafe.Pointer(&buf[0]), + blocking: true, + }) + + return goString(buf), int(cSize), Enum(cType) +} + +func (ctx *context) GetAttachedShaders(p Program) []Shader { + shadersLen := ctx.GetProgrami(p, ATTACHED_SHADERS) + if shadersLen == 0 { + return nil + } + buf := make([]uint32, shadersLen) + + n := int(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetAttachedShaders, + a0: p.c(), + a1: uintptr(shadersLen), + }, + parg: unsafe.Pointer(&buf[0]), + blocking: true, + })) + + buf = buf[:int(n)] + shaders := make([]Shader, len(buf)) + for i, s := range buf { + shaders[i] = Shader{Value: uint32(s)} + } + return shaders +} + +func (ctx *context) GetAttribLocation(p Program, name string) Attrib { + s, free := ctx.cString(name) + defer free() + return Attrib{Value: uint(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetAttribLocation, + a0: p.c(), + a1: s, + }, + blocking: true, + }))} +} + +func (ctx *context) GetBooleanv(dst []bool, pname Enum) { + buf := make([]int32, len(dst)) + + ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetBooleanv, + a0: pname.c(), + }, + parg: unsafe.Pointer(&buf[0]), + blocking: true, + }) + + for i, v := range buf { + dst[i] = v != 0 + } +} + +func (ctx *context) GetFloatv(dst []float32, pname Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetFloatv, + a0: pname.c(), + }, + parg: unsafe.Pointer(&dst[0]), + blocking: true, + }) +} + +func (ctx *context) GetIntegerv(dst []int32, pname Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetIntegerv, + a0: pname.c(), + }, + parg: unsafe.Pointer(&dst[0]), + blocking: true, + }) +} + +func (ctx *context) GetInteger(pname Enum) int { + var v [1]int32 + ctx.GetIntegerv(v[:], pname) + return int(v[0]) +} + +func (ctx *context) GetBufferParameteri(target, value Enum) int { + return int(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetBufferParameteri, + a0: target.c(), + a1: value.c(), + }, + blocking: true, + })) +} + +func (ctx *context) GetError() Enum { + return Enum(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetError, + }, + blocking: true, + })) +} + +func (ctx *context) GetFramebufferAttachmentParameteri(target, attachment, pname Enum) int { + return int(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetFramebufferAttachmentParameteriv, + a0: target.c(), + a1: attachment.c(), + a2: pname.c(), + }, + blocking: true, + })) +} + +func (ctx *context) GetProgrami(p Program, pname Enum) int { + return int(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetProgramiv, + a0: p.c(), + a1: pname.c(), + }, + blocking: true, + })) +} + +func (ctx *context) GetProgramInfoLog(p Program) string { + infoLen := ctx.GetProgrami(p, INFO_LOG_LENGTH) + if infoLen == 0 { + return "" + } + buf := make([]byte, infoLen) + + ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetProgramInfoLog, + a0: p.c(), + a1: uintptr(infoLen), + }, + parg: unsafe.Pointer(&buf[0]), + blocking: true, + }) + + return goString(buf) +} + +func (ctx *context) GetRenderbufferParameteri(target, pname Enum) int { + return int(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetRenderbufferParameteriv, + a0: target.c(), + a1: pname.c(), + }, + blocking: true, + })) +} + +func (ctx *context) GetShaderi(s Shader, pname Enum) int { + return int(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetShaderiv, + a0: s.c(), + a1: pname.c(), + }, + blocking: true, + })) +} + +func (ctx *context) GetShaderInfoLog(s Shader) string { + infoLen := ctx.GetShaderi(s, INFO_LOG_LENGTH) + if infoLen == 0 { + return "" + } + buf := make([]byte, infoLen) + + ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetShaderInfoLog, + a0: s.c(), + a1: uintptr(infoLen), + }, + parg: unsafe.Pointer(&buf[0]), + blocking: true, + }) + + return goString(buf) +} + +func (ctx *context) GetShaderPrecisionFormat(shadertype, precisiontype Enum) (rangeLow, rangeHigh, precision int) { + var rangeAndPrec [3]int32 + + ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetShaderPrecisionFormat, + a0: shadertype.c(), + a1: precisiontype.c(), + }, + parg: unsafe.Pointer(&rangeAndPrec[0]), + blocking: true, + }) + + return int(rangeAndPrec[0]), int(rangeAndPrec[1]), int(rangeAndPrec[2]) +} + +func (ctx *context) GetShaderSource(s Shader) string { + sourceLen := ctx.GetShaderi(s, SHADER_SOURCE_LENGTH) + if sourceLen == 0 { + return "" + } + buf := make([]byte, sourceLen) + + ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetShaderSource, + a0: s.c(), + a1: uintptr(sourceLen), + }, + parg: unsafe.Pointer(&buf[0]), + blocking: true, + }) + + return goString(buf) +} + +func (ctx *context) GetString(pname Enum) string { + ret := ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetString, + a0: pname.c(), + }, + blocking: true, + }) + retp := unsafe.Pointer(ret) + buf := (*[1 << 24]byte)(retp)[:] + return goString(buf) +} + +func (ctx *context) GetTexParameterfv(dst []float32, target, pname Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetTexParameterfv, + a0: target.c(), + a1: pname.c(), + }, + parg: unsafe.Pointer(&dst[0]), + blocking: true, + }) +} + +func (ctx *context) GetTexParameteriv(dst []int32, target, pname Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetTexParameteriv, + a0: target.c(), + a1: pname.c(), + }, + blocking: true, + }) +} + +func (ctx *context) GetUniformfv(dst []float32, src Uniform, p Program) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetUniformfv, + a0: p.c(), + a1: src.c(), + }, + parg: unsafe.Pointer(&dst[0]), + blocking: true, + }) +} + +func (ctx *context) GetUniformiv(dst []int32, src Uniform, p Program) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetUniformiv, + a0: p.c(), + a1: src.c(), + }, + parg: unsafe.Pointer(&dst[0]), + blocking: true, + }) +} + +func (ctx *context) GetUniformLocation(p Program, name string) Uniform { + s, free := ctx.cString(name) + defer free() + return Uniform{Value: int32(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetUniformLocation, + a0: p.c(), + a1: s, + }, + blocking: true, + }))} +} + +func (ctx *context) GetVertexAttribf(src Attrib, pname Enum) float32 { + var params [1]float32 + ctx.GetVertexAttribfv(params[:], src, pname) + return params[0] +} + +func (ctx *context) GetVertexAttribfv(dst []float32, src Attrib, pname Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetVertexAttribfv, + a0: src.c(), + a1: pname.c(), + }, + parg: unsafe.Pointer(&dst[0]), + blocking: true, + }) +} + +func (ctx *context) GetVertexAttribi(src Attrib, pname Enum) int32 { + var params [1]int32 + ctx.GetVertexAttribiv(params[:], src, pname) + return params[0] +} + +func (ctx *context) GetVertexAttribiv(dst []int32, src Attrib, pname Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetVertexAttribiv, + a0: src.c(), + a1: pname.c(), + }, + parg: unsafe.Pointer(&dst[0]), + blocking: true, + }) +} + +func (ctx *context) Hint(target, mode Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnHint, + a0: target.c(), + a1: mode.c(), + }, + }) +} + +func (ctx *context) IsBuffer(b Buffer) bool { + return 0 != ctx.enqueue(call{ + args: fnargs{ + fn: glfnIsBuffer, + a0: b.c(), + }, + blocking: true, + }) +} + +func (ctx *context) IsEnabled(cap Enum) bool { + return 0 != ctx.enqueue(call{ + args: fnargs{ + fn: glfnIsEnabled, + a0: cap.c(), + }, + blocking: true, + }) +} + +func (ctx *context) IsFramebuffer(fb Framebuffer) bool { + return 0 != ctx.enqueue(call{ + args: fnargs{ + fn: glfnIsFramebuffer, + a0: fb.c(), + }, + blocking: true, + }) +} + +func (ctx *context) IsProgram(p Program) bool { + return 0 != ctx.enqueue(call{ + args: fnargs{ + fn: glfnIsProgram, + a0: p.c(), + }, + blocking: true, + }) +} + +func (ctx *context) IsRenderbuffer(rb Renderbuffer) bool { + return 0 != ctx.enqueue(call{ + args: fnargs{ + fn: glfnIsRenderbuffer, + a0: rb.c(), + }, + blocking: true, + }) +} + +func (ctx *context) IsShader(s Shader) bool { + return 0 != ctx.enqueue(call{ + args: fnargs{ + fn: glfnIsShader, + a0: s.c(), + }, + blocking: true, + }) +} + +func (ctx *context) IsTexture(t Texture) bool { + return 0 != ctx.enqueue(call{ + args: fnargs{ + fn: glfnIsTexture, + a0: t.c(), + }, + blocking: true, + }) +} + +func (ctx *context) LineWidth(width float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnLineWidth, + a0: uintptr(math.Float32bits(width)), + }, + }) +} + +func (ctx *context) LinkProgram(p Program) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnLinkProgram, + a0: p.c(), + }, + }) +} + +func (ctx *context) PixelStorei(pname Enum, param int32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnPixelStorei, + a0: pname.c(), + a1: uintptr(param), + }, + }) +} + +func (ctx *context) PolygonOffset(factor, units float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnPolygonOffset, + a0: uintptr(math.Float32bits(factor)), + a1: uintptr(math.Float32bits(units)), + }, + }) +} + +func (ctx *context) ReadPixels(dst []byte, x, y, width, height int, format, ty Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnReadPixels, + // TODO(crawshaw): support PIXEL_PACK_BUFFER in GLES3, uses offset. + a0: uintptr(x), + a1: uintptr(y), + a2: uintptr(width), + a3: uintptr(height), + a4: format.c(), + a5: ty.c(), + }, + parg: unsafe.Pointer(&dst[0]), + blocking: true, + }) +} + +func (ctx *context) ReleaseShaderCompiler() { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnReleaseShaderCompiler, + }, + }) +} + +func (ctx *context) RenderbufferStorage(target, internalFormat Enum, width, height int) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnRenderbufferStorage, + a0: target.c(), + a1: internalFormat.c(), + a2: uintptr(width), + a3: uintptr(height), + }, + }) +} + +func (ctx *context) SampleCoverage(value float32, invert bool) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnSampleCoverage, + a0: uintptr(math.Float32bits(value)), + a1: glBoolean(invert), + }, + }) +} + +func (ctx *context) Scissor(x, y, width, height int32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnScissor, + a0: uintptr(x), + a1: uintptr(y), + a2: uintptr(width), + a3: uintptr(height), + }, + }) +} + +func (ctx *context) ShaderSource(s Shader, src string) { + strp, free := ctx.cStringPtr(src) + defer free() + ctx.enqueue(call{ + args: fnargs{ + fn: glfnShaderSource, + a0: s.c(), + a1: 1, + a2: strp, + }, + blocking: true, + }) +} + +func (ctx *context) StencilFunc(fn Enum, ref int, mask uint32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnStencilFunc, + a0: fn.c(), + a1: uintptr(ref), + a2: uintptr(mask), + }, + }) +} + +func (ctx *context) StencilFuncSeparate(face, fn Enum, ref int, mask uint32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnStencilFuncSeparate, + a0: face.c(), + a1: fn.c(), + a2: uintptr(ref), + a3: uintptr(mask), + }, + }) +} + +func (ctx *context) StencilMask(mask uint32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnStencilMask, + a0: uintptr(mask), + }, + }) +} + +func (ctx *context) StencilMaskSeparate(face Enum, mask uint32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnStencilMaskSeparate, + a0: face.c(), + a1: uintptr(mask), + }, + }) +} + +func (ctx *context) StencilOp(fail, zfail, zpass Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnStencilOp, + a0: fail.c(), + a1: zfail.c(), + a2: zpass.c(), + }, + }) +} + +func (ctx *context) StencilOpSeparate(face, sfail, dpfail, dppass Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnStencilOpSeparate, + a0: face.c(), + a1: sfail.c(), + a2: dpfail.c(), + a3: dppass.c(), + }, + }) +} + +func (ctx *context) TexImage2D(target Enum, level int, internalFormat int, width, height int, format Enum, ty Enum, data []byte) { + // It is common to pass TexImage2D a nil data, indicating that a + // bound GL buffer is being used as the source. In that case, it + // is not necessary to block. + parg := unsafe.Pointer(nil) + if len(data) > 0 { + parg = unsafe.Pointer(&data[0]) + } + + ctx.enqueue(call{ + args: fnargs{ + fn: glfnTexImage2D, + // TODO(crawshaw): GLES3 offset for PIXEL_UNPACK_BUFFER and PIXEL_PACK_BUFFER. + a0: target.c(), + a1: uintptr(level), + a2: uintptr(internalFormat), + a3: uintptr(width), + a4: uintptr(height), + a5: format.c(), + a6: ty.c(), + }, + parg: parg, + blocking: parg != nil, + }) +} + +func (ctx *context) TexSubImage2D(target Enum, level int, x, y, width, height int, format, ty Enum, data []byte) { + // It is common to pass TexSubImage2D a nil data, indicating that a + // bound GL buffer is being used as the source. In that case, it + // is not necessary to block. + parg := unsafe.Pointer(nil) + if len(data) > 0 { + parg = unsafe.Pointer(&data[0]) + } + + ctx.enqueue(call{ + args: fnargs{ + fn: glfnTexSubImage2D, + // TODO(crawshaw): GLES3 offset for PIXEL_UNPACK_BUFFER and PIXEL_PACK_BUFFER. + a0: target.c(), + a1: uintptr(level), + a2: uintptr(x), + a3: uintptr(y), + a4: uintptr(width), + a5: uintptr(height), + a6: format.c(), + a7: ty.c(), + }, + parg: parg, + blocking: parg != nil, + }) +} + +func (ctx *context) TexParameterf(target, pname Enum, param float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnTexParameterf, + a0: target.c(), + a1: pname.c(), + a2: uintptr(math.Float32bits(param)), + }, + }) +} + +func (ctx *context) TexParameterfv(target, pname Enum, params []float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnTexParameterfv, + a0: target.c(), + a1: pname.c(), + }, + parg: unsafe.Pointer(¶ms[0]), + blocking: true, + }) +} + +func (ctx *context) TexParameteri(target, pname Enum, param int) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnTexParameteri, + a0: target.c(), + a1: pname.c(), + a2: uintptr(param), + }, + }) +} + +func (ctx *context) TexParameteriv(target, pname Enum, params []int32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnTexParameteriv, + a0: target.c(), + a1: pname.c(), + }, + parg: unsafe.Pointer(¶ms[0]), + blocking: true, + }) +} + +func (ctx *context) Uniform1f(dst Uniform, v float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniform1f, + a0: dst.c(), + a1: uintptr(math.Float32bits(v)), + }, + }) +} + +func (ctx *context) Uniform1fv(dst Uniform, src []float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniform1fv, + a0: dst.c(), + a1: uintptr(len(src)), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) Uniform1i(dst Uniform, v int) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniform1i, + a0: dst.c(), + a1: uintptr(v), + }, + }) +} + +func (ctx *context) Uniform1iv(dst Uniform, src []int32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniform1iv, + a0: dst.c(), + a1: uintptr(len(src)), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) Uniform2f(dst Uniform, v0, v1 float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniform2f, + a0: dst.c(), + a1: uintptr(math.Float32bits(v0)), + a2: uintptr(math.Float32bits(v1)), + }, + }) +} + +func (ctx *context) Uniform2fv(dst Uniform, src []float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniform2fv, + a0: dst.c(), + a1: uintptr(len(src) / 2), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) Uniform2i(dst Uniform, v0, v1 int) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniform2i, + a0: dst.c(), + a1: uintptr(v0), + a2: uintptr(v1), + }, + }) +} + +func (ctx *context) Uniform2iv(dst Uniform, src []int32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniform2iv, + a0: dst.c(), + a1: uintptr(len(src) / 2), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) Uniform3f(dst Uniform, v0, v1, v2 float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniform3f, + a0: dst.c(), + a1: uintptr(math.Float32bits(v0)), + a2: uintptr(math.Float32bits(v1)), + a3: uintptr(math.Float32bits(v2)), + }, + }) +} + +func (ctx *context) Uniform3fv(dst Uniform, src []float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniform3fv, + a0: dst.c(), + a1: uintptr(len(src) / 3), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) Uniform3i(dst Uniform, v0, v1, v2 int32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniform3i, + a0: dst.c(), + a1: uintptr(v0), + a2: uintptr(v1), + a3: uintptr(v2), + }, + }) +} + +func (ctx *context) Uniform3iv(dst Uniform, src []int32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniform3iv, + a0: dst.c(), + a1: uintptr(len(src) / 3), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) Uniform4f(dst Uniform, v0, v1, v2, v3 float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniform4f, + a0: dst.c(), + a1: uintptr(math.Float32bits(v0)), + a2: uintptr(math.Float32bits(v1)), + a3: uintptr(math.Float32bits(v2)), + a4: uintptr(math.Float32bits(v3)), + }, + }) +} + +func (ctx *context) Uniform4fv(dst Uniform, src []float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniform4fv, + a0: dst.c(), + a1: uintptr(len(src) / 4), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) Uniform4i(dst Uniform, v0, v1, v2, v3 int32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniform4i, + a0: dst.c(), + a1: uintptr(v0), + a2: uintptr(v1), + a3: uintptr(v2), + a4: uintptr(v3), + }, + }) +} + +func (ctx *context) Uniform4iv(dst Uniform, src []int32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniform4iv, + a0: dst.c(), + a1: uintptr(len(src) / 4), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) UniformMatrix2fv(dst Uniform, src []float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniformMatrix2fv, + // OpenGL ES 2 does not support transpose. + a0: dst.c(), + a1: uintptr(len(src) / 4), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) UniformMatrix3fv(dst Uniform, src []float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniformMatrix3fv, + a0: dst.c(), + a1: uintptr(len(src) / 9), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) UniformMatrix4fv(dst Uniform, src []float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniformMatrix4fv, + a0: dst.c(), + a1: uintptr(len(src) / 16), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) UseProgram(p Program) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUseProgram, + a0: p.c(), + }, + }) +} + +func (ctx *context) ValidateProgram(p Program) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnValidateProgram, + a0: p.c(), + }, + }) +} + +func (ctx *context) VertexAttrib1f(dst Attrib, x float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnVertexAttrib1f, + a0: dst.c(), + a1: uintptr(math.Float32bits(x)), + }, + }) +} + +func (ctx *context) VertexAttrib1fv(dst Attrib, src []float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnVertexAttrib1fv, + a0: dst.c(), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) VertexAttrib2f(dst Attrib, x, y float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnVertexAttrib2f, + a0: dst.c(), + a1: uintptr(math.Float32bits(x)), + a2: uintptr(math.Float32bits(y)), + }, + }) +} + +func (ctx *context) VertexAttrib2fv(dst Attrib, src []float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnVertexAttrib2fv, + a0: dst.c(), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) VertexAttrib3f(dst Attrib, x, y, z float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnVertexAttrib3f, + a0: dst.c(), + a1: uintptr(math.Float32bits(x)), + a2: uintptr(math.Float32bits(y)), + a3: uintptr(math.Float32bits(z)), + }, + }) +} + +func (ctx *context) VertexAttrib3fv(dst Attrib, src []float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnVertexAttrib3fv, + a0: dst.c(), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) VertexAttrib4f(dst Attrib, x, y, z, w float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnVertexAttrib4f, + a0: dst.c(), + a1: uintptr(math.Float32bits(x)), + a2: uintptr(math.Float32bits(y)), + a3: uintptr(math.Float32bits(z)), + a4: uintptr(math.Float32bits(w)), + }, + }) +} + +func (ctx *context) VertexAttrib4fv(dst Attrib, src []float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnVertexAttrib4fv, + a0: dst.c(), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) VertexAttribPointer(dst Attrib, size int, ty Enum, normalized bool, stride, offset int) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnVertexAttribPointer, + a0: dst.c(), + a1: uintptr(size), + a2: ty.c(), + a3: glBoolean(normalized), + a4: uintptr(stride), + a5: uintptr(offset), + }, + }) +} + +func (ctx *context) Viewport(x, y, width, height int) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnViewport, + a0: uintptr(x), + a1: uintptr(y), + a2: uintptr(width), + a3: uintptr(height), + }, + }) +} + +func (ctx context3) UniformMatrix2x3fv(dst Uniform, src []float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniformMatrix2x3fv, + a0: dst.c(), + a1: uintptr(len(src) / 6), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx context3) UniformMatrix3x2fv(dst Uniform, src []float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniformMatrix3x2fv, + a0: dst.c(), + a1: uintptr(len(src) / 6), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx context3) UniformMatrix2x4fv(dst Uniform, src []float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniformMatrix2x4fv, + a0: dst.c(), + a1: uintptr(len(src) / 8), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx context3) UniformMatrix4x2fv(dst Uniform, src []float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniformMatrix4x2fv, + a0: dst.c(), + a1: uintptr(len(src) / 8), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx context3) UniformMatrix3x4fv(dst Uniform, src []float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniformMatrix3x4fv, + a0: dst.c(), + a1: uintptr(len(src) / 12), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx context3) UniformMatrix4x3fv(dst Uniform, src []float32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniformMatrix4x3fv, + a0: dst.c(), + a1: uintptr(len(src) / 12), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx context3) BlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1 int, mask uint, filter Enum) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnBlitFramebuffer, + a0: uintptr(srcX0), + a1: uintptr(srcY0), + a2: uintptr(srcX1), + a3: uintptr(srcY1), + a4: uintptr(dstX0), + a5: uintptr(dstY0), + a6: uintptr(dstX1), + a7: uintptr(dstY1), + a8: uintptr(mask), + a9: filter.c(), + }, + }) +} + +func (ctx context3) Uniform1ui(dst Uniform, v uint32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniform1ui, + a0: dst.c(), + a1: uintptr(v), + }, + }) +} + +func (ctx context3) Uniform2ui(dst Uniform, v0, v1 uint32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniform2ui, + a0: dst.c(), + a1: uintptr(v0), + a2: uintptr(v1), + }, + }) +} + +func (ctx context3) Uniform3ui(dst Uniform, v0, v1, v2 uint) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniform3ui, + a0: dst.c(), + a1: uintptr(v0), + a2: uintptr(v1), + a3: uintptr(v2), + }, + }) +} + +func (ctx context3) Uniform4ui(dst Uniform, v0, v1, v2, v3 uint32) { + ctx.enqueue(call{ + args: fnargs{ + fn: glfnUniform4ui, + a0: dst.c(), + a1: uintptr(v0), + a2: uintptr(v1), + a3: uintptr(v2), + a4: uintptr(v3), + }, + }) +} diff --git a/vendor/github.com/ebitengine/gomobile/gl/gldebug.go b/vendor/github.com/ebitengine/gomobile/gl/gldebug.go new file mode 100644 index 0000000..fb79bb7 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/gl/gldebug.go @@ -0,0 +1,3672 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated from gl.go using go generate. DO NOT EDIT. +// See doc.go for details. + +//go:build (darwin || linux || openbsd || windows) && gldebug + +package gl + +import ( + "fmt" + "log" + "math" + "sync/atomic" + "unsafe" +) + +func (ctx *context) errDrain() string { + var errs []Enum + for { + e := ctx.GetError() + if e == 0 { + break + } + errs = append(errs, e) + } + if len(errs) > 0 { + return fmt.Sprintf(" error: %v", errs) + } + return "" +} + +func (ctx *context) enqueueDebug(c call) uintptr { + numCalls := atomic.AddInt32(&ctx.debug, 1) + if numCalls > 1 { + panic("concurrent calls made to the same GL context") + } + defer func() { + if atomic.AddInt32(&ctx.debug, -1) > 0 { + select {} // block so you see us in the panic + } + }() + + return ctx.enqueue(c) +} + +func (v Enum) String() string { + switch v { + case 0x0: + return "0" + case 0x1: + return "1" + case 0x2: + return "2" + case 0x3: + return "LINE_STRIP" + case 0x4: + return "4" + case 0x5: + return "TRIANGLE_STRIP" + case 0x6: + return "TRIANGLE_FAN" + case 0x300: + return "SRC_COLOR" + case 0x301: + return "ONE_MINUS_SRC_COLOR" + case 0x302: + return "SRC_ALPHA" + case 0x303: + return "ONE_MINUS_SRC_ALPHA" + case 0x304: + return "DST_ALPHA" + case 0x305: + return "ONE_MINUS_DST_ALPHA" + case 0x306: + return "DST_COLOR" + case 0x307: + return "ONE_MINUS_DST_COLOR" + case 0x308: + return "SRC_ALPHA_SATURATE" + case 0x8006: + return "FUNC_ADD" + case 0x8009: + return "32777" + case 0x883d: + return "BLEND_EQUATION_ALPHA" + case 0x800a: + return "FUNC_SUBTRACT" + case 0x800b: + return "FUNC_REVERSE_SUBTRACT" + case 0x80c8: + return "BLEND_DST_RGB" + case 0x80c9: + return "BLEND_SRC_RGB" + case 0x80ca: + return "BLEND_DST_ALPHA" + case 0x80cb: + return "BLEND_SRC_ALPHA" + case 0x8001: + return "CONSTANT_COLOR" + case 0x8002: + return "ONE_MINUS_CONSTANT_COLOR" + case 0x8003: + return "CONSTANT_ALPHA" + case 0x8004: + return "ONE_MINUS_CONSTANT_ALPHA" + case 0x8005: + return "BLEND_COLOR" + case 0x8892: + return "ARRAY_BUFFER" + case 0x8893: + return "ELEMENT_ARRAY_BUFFER" + case 0x8894: + return "ARRAY_BUFFER_BINDING" + case 0x8895: + return "ELEMENT_ARRAY_BUFFER_BINDING" + case 0x88e0: + return "STREAM_DRAW" + case 0x88e4: + return "STATIC_DRAW" + case 0x88e8: + return "DYNAMIC_DRAW" + case 0x8764: + return "BUFFER_SIZE" + case 0x8765: + return "BUFFER_USAGE" + case 0x8626: + return "CURRENT_VERTEX_ATTRIB" + case 0x404: + return "FRONT" + case 0x405: + return "BACK" + case 0x408: + return "FRONT_AND_BACK" + case 0xde1: + return "TEXTURE_2D" + case 0xb44: + return "CULL_FACE" + case 0xbe2: + return "BLEND" + case 0xbd0: + return "DITHER" + case 0xb90: + return "STENCIL_TEST" + case 0xb71: + return "DEPTH_TEST" + case 0xc11: + return "SCISSOR_TEST" + case 0x8037: + return "POLYGON_OFFSET_FILL" + case 0x809e: + return "SAMPLE_ALPHA_TO_COVERAGE" + case 0x80a0: + return "SAMPLE_COVERAGE" + case 0x500: + return "INVALID_ENUM" + case 0x501: + return "INVALID_VALUE" + case 0x502: + return "INVALID_OPERATION" + case 0x505: + return "OUT_OF_MEMORY" + case 0x900: + return "CW" + case 0x901: + return "CCW" + case 0xb21: + return "LINE_WIDTH" + case 0x846d: + return "ALIASED_POINT_SIZE_RANGE" + case 0x846e: + return "ALIASED_LINE_WIDTH_RANGE" + case 0xb45: + return "CULL_FACE_MODE" + case 0xb46: + return "FRONT_FACE" + case 0xb70: + return "DEPTH_RANGE" + case 0xb72: + return "DEPTH_WRITEMASK" + case 0xb73: + return "DEPTH_CLEAR_VALUE" + case 0xb74: + return "DEPTH_FUNC" + case 0xb91: + return "STENCIL_CLEAR_VALUE" + case 0xb92: + return "STENCIL_FUNC" + case 0xb94: + return "STENCIL_FAIL" + case 0xb95: + return "STENCIL_PASS_DEPTH_FAIL" + case 0xb96: + return "STENCIL_PASS_DEPTH_PASS" + case 0xb97: + return "STENCIL_REF" + case 0xb93: + return "STENCIL_VALUE_MASK" + case 0xb98: + return "STENCIL_WRITEMASK" + case 0x8800: + return "STENCIL_BACK_FUNC" + case 0x8801: + return "STENCIL_BACK_FAIL" + case 0x8802: + return "STENCIL_BACK_PASS_DEPTH_FAIL" + case 0x8803: + return "STENCIL_BACK_PASS_DEPTH_PASS" + case 0x8ca3: + return "STENCIL_BACK_REF" + case 0x8ca4: + return "STENCIL_BACK_VALUE_MASK" + case 0x8ca5: + return "STENCIL_BACK_WRITEMASK" + case 0xba2: + return "VIEWPORT" + case 0xc10: + return "SCISSOR_BOX" + case 0xc22: + return "COLOR_CLEAR_VALUE" + case 0xc23: + return "COLOR_WRITEMASK" + case 0xcf5: + return "UNPACK_ALIGNMENT" + case 0xd05: + return "PACK_ALIGNMENT" + case 0xd33: + return "MAX_TEXTURE_SIZE" + case 0xd3a: + return "MAX_VIEWPORT_DIMS" + case 0xd50: + return "SUBPIXEL_BITS" + case 0xd52: + return "RED_BITS" + case 0xd53: + return "GREEN_BITS" + case 0xd54: + return "BLUE_BITS" + case 0xd55: + return "ALPHA_BITS" + case 0xd56: + return "DEPTH_BITS" + case 0xd57: + return "STENCIL_BITS" + case 0x2a00: + return "POLYGON_OFFSET_UNITS" + case 0x8038: + return "POLYGON_OFFSET_FACTOR" + case 0x8069: + return "TEXTURE_BINDING_2D" + case 0x80a8: + return "SAMPLE_BUFFERS" + case 0x80a9: + return "SAMPLES" + case 0x80aa: + return "SAMPLE_COVERAGE_VALUE" + case 0x80ab: + return "SAMPLE_COVERAGE_INVERT" + case 0x86a2: + return "NUM_COMPRESSED_TEXTURE_FORMATS" + case 0x86a3: + return "COMPRESSED_TEXTURE_FORMATS" + case 0x1100: + return "DONT_CARE" + case 0x1101: + return "FASTEST" + case 0x1102: + return "NICEST" + case 0x8192: + return "GENERATE_MIPMAP_HINT" + case 0x1400: + return "BYTE" + case 0x1401: + return "UNSIGNED_BYTE" + case 0x1402: + return "SHORT" + case 0x1403: + return "UNSIGNED_SHORT" + case 0x1404: + return "INT" + case 0x1405: + return "UNSIGNED_INT" + case 0x1406: + return "FLOAT" + case 0x140c: + return "FIXED" + case 0x1902: + return "DEPTH_COMPONENT" + case 0x1906: + return "ALPHA" + case 0x1907: + return "RGB" + case 0x1908: + return "RGBA" + case 0x1909: + return "LUMINANCE" + case 0x190a: + return "LUMINANCE_ALPHA" + case 0x8033: + return "UNSIGNED_SHORT_4_4_4_4" + case 0x8034: + return "UNSIGNED_SHORT_5_5_5_1" + case 0x8363: + return "UNSIGNED_SHORT_5_6_5" + case 0x8869: + return "MAX_VERTEX_ATTRIBS" + case 0x8dfb: + return "MAX_VERTEX_UNIFORM_VECTORS" + case 0x8dfc: + return "MAX_VARYING_VECTORS" + case 0x8b4d: + return "MAX_COMBINED_TEXTURE_IMAGE_UNITS" + case 0x8b4c: + return "MAX_VERTEX_TEXTURE_IMAGE_UNITS" + case 0x8872: + return "MAX_TEXTURE_IMAGE_UNITS" + case 0x8dfd: + return "MAX_FRAGMENT_UNIFORM_VECTORS" + case 0x8b4f: + return "SHADER_TYPE" + case 0x8b80: + return "DELETE_STATUS" + case 0x8b82: + return "LINK_STATUS" + case 0x8b83: + return "VALIDATE_STATUS" + case 0x8b85: + return "ATTACHED_SHADERS" + case 0x8b86: + return "ACTIVE_UNIFORMS" + case 0x8b87: + return "ACTIVE_UNIFORM_MAX_LENGTH" + case 0x8b89: + return "ACTIVE_ATTRIBUTES" + case 0x8b8a: + return "ACTIVE_ATTRIBUTE_MAX_LENGTH" + case 0x8b8c: + return "SHADING_LANGUAGE_VERSION" + case 0x8b8d: + return "CURRENT_PROGRAM" + case 0x200: + return "NEVER" + case 0x201: + return "LESS" + case 0x202: + return "EQUAL" + case 0x203: + return "LEQUAL" + case 0x204: + return "GREATER" + case 0x205: + return "NOTEQUAL" + case 0x206: + return "GEQUAL" + case 0x207: + return "ALWAYS" + case 0x1e00: + return "KEEP" + case 0x1e01: + return "REPLACE" + case 0x1e02: + return "INCR" + case 0x1e03: + return "DECR" + case 0x150a: + return "INVERT" + case 0x8507: + return "INCR_WRAP" + case 0x8508: + return "DECR_WRAP" + case 0x1f00: + return "VENDOR" + case 0x1f01: + return "RENDERER" + case 0x1f02: + return "VERSION" + case 0x1f03: + return "EXTENSIONS" + case 0x2600: + return "NEAREST" + case 0x2601: + return "LINEAR" + case 0x2700: + return "NEAREST_MIPMAP_NEAREST" + case 0x2701: + return "LINEAR_MIPMAP_NEAREST" + case 0x2702: + return "NEAREST_MIPMAP_LINEAR" + case 0x2703: + return "LINEAR_MIPMAP_LINEAR" + case 0x2800: + return "TEXTURE_MAG_FILTER" + case 0x2801: + return "TEXTURE_MIN_FILTER" + case 0x2802: + return "TEXTURE_WRAP_S" + case 0x2803: + return "TEXTURE_WRAP_T" + case 0x1702: + return "TEXTURE" + case 0x8513: + return "TEXTURE_CUBE_MAP" + case 0x8514: + return "TEXTURE_BINDING_CUBE_MAP" + case 0x8515: + return "TEXTURE_CUBE_MAP_POSITIVE_X" + case 0x8516: + return "TEXTURE_CUBE_MAP_NEGATIVE_X" + case 0x8517: + return "TEXTURE_CUBE_MAP_POSITIVE_Y" + case 0x8518: + return "TEXTURE_CUBE_MAP_NEGATIVE_Y" + case 0x8519: + return "TEXTURE_CUBE_MAP_POSITIVE_Z" + case 0x851a: + return "TEXTURE_CUBE_MAP_NEGATIVE_Z" + case 0x851c: + return "MAX_CUBE_MAP_TEXTURE_SIZE" + case 0x84c0: + return "TEXTURE0" + case 0x84c1: + return "TEXTURE1" + case 0x84c2: + return "TEXTURE2" + case 0x84c3: + return "TEXTURE3" + case 0x84c4: + return "TEXTURE4" + case 0x84c5: + return "TEXTURE5" + case 0x84c6: + return "TEXTURE6" + case 0x84c7: + return "TEXTURE7" + case 0x84c8: + return "TEXTURE8" + case 0x84c9: + return "TEXTURE9" + case 0x84ca: + return "TEXTURE10" + case 0x84cb: + return "TEXTURE11" + case 0x84cc: + return "TEXTURE12" + case 0x84cd: + return "TEXTURE13" + case 0x84ce: + return "TEXTURE14" + case 0x84cf: + return "TEXTURE15" + case 0x84d0: + return "TEXTURE16" + case 0x84d1: + return "TEXTURE17" + case 0x84d2: + return "TEXTURE18" + case 0x84d3: + return "TEXTURE19" + case 0x84d4: + return "TEXTURE20" + case 0x84d5: + return "TEXTURE21" + case 0x84d6: + return "TEXTURE22" + case 0x84d7: + return "TEXTURE23" + case 0x84d8: + return "TEXTURE24" + case 0x84d9: + return "TEXTURE25" + case 0x84da: + return "TEXTURE26" + case 0x84db: + return "TEXTURE27" + case 0x84dc: + return "TEXTURE28" + case 0x84dd: + return "TEXTURE29" + case 0x84de: + return "TEXTURE30" + case 0x84df: + return "TEXTURE31" + case 0x84e0: + return "ACTIVE_TEXTURE" + case 0x2901: + return "REPEAT" + case 0x812f: + return "CLAMP_TO_EDGE" + case 0x8370: + return "MIRRORED_REPEAT" + case 0x8622: + return "VERTEX_ATTRIB_ARRAY_ENABLED" + case 0x8623: + return "VERTEX_ATTRIB_ARRAY_SIZE" + case 0x8624: + return "VERTEX_ATTRIB_ARRAY_STRIDE" + case 0x8625: + return "VERTEX_ATTRIB_ARRAY_TYPE" + case 0x886a: + return "VERTEX_ATTRIB_ARRAY_NORMALIZED" + case 0x8645: + return "VERTEX_ATTRIB_ARRAY_POINTER" + case 0x889f: + return "VERTEX_ATTRIB_ARRAY_BUFFER_BINDING" + case 0x8b9a: + return "IMPLEMENTATION_COLOR_READ_TYPE" + case 0x8b9b: + return "IMPLEMENTATION_COLOR_READ_FORMAT" + case 0x8b81: + return "COMPILE_STATUS" + case 0x8b84: + return "INFO_LOG_LENGTH" + case 0x8b88: + return "SHADER_SOURCE_LENGTH" + case 0x8dfa: + return "SHADER_COMPILER" + case 0x8df8: + return "SHADER_BINARY_FORMATS" + case 0x8df9: + return "NUM_SHADER_BINARY_FORMATS" + case 0x8df0: + return "LOW_FLOAT" + case 0x8df1: + return "MEDIUM_FLOAT" + case 0x8df2: + return "HIGH_FLOAT" + case 0x8df3: + return "LOW_INT" + case 0x8df4: + return "MEDIUM_INT" + case 0x8df5: + return "HIGH_INT" + case 0x8d40: + return "FRAMEBUFFER" + case 0x8d41: + return "RENDERBUFFER" + case 0x8056: + return "RGBA4" + case 0x8057: + return "RGB5_A1" + case 0x8d62: + return "RGB565" + case 0x81a5: + return "DEPTH_COMPONENT16" + case 0x8d48: + return "STENCIL_INDEX8" + case 0x8d42: + return "RENDERBUFFER_WIDTH" + case 0x8d43: + return "RENDERBUFFER_HEIGHT" + case 0x8d44: + return "RENDERBUFFER_INTERNAL_FORMAT" + case 0x8d50: + return "RENDERBUFFER_RED_SIZE" + case 0x8d51: + return "RENDERBUFFER_GREEN_SIZE" + case 0x8d52: + return "RENDERBUFFER_BLUE_SIZE" + case 0x8d53: + return "RENDERBUFFER_ALPHA_SIZE" + case 0x8d54: + return "RENDERBUFFER_DEPTH_SIZE" + case 0x8d55: + return "RENDERBUFFER_STENCIL_SIZE" + case 0x8cd0: + return "FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE" + case 0x8cd1: + return "FRAMEBUFFER_ATTACHMENT_OBJECT_NAME" + case 0x8cd2: + return "FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL" + case 0x8cd3: + return "FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE" + case 0x8ce0: + return "COLOR_ATTACHMENT0" + case 0x8d00: + return "DEPTH_ATTACHMENT" + case 0x8d20: + return "STENCIL_ATTACHMENT" + case 0x8cd5: + return "FRAMEBUFFER_COMPLETE" + case 0x8cd6: + return "FRAMEBUFFER_INCOMPLETE_ATTACHMENT" + case 0x8cd7: + return "FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT" + case 0x8cd9: + return "FRAMEBUFFER_INCOMPLETE_DIMENSIONS" + case 0x8cdd: + return "FRAMEBUFFER_UNSUPPORTED" + case 0x8ca6: + return "36006" + case 0x8ca7: + return "RENDERBUFFER_BINDING" + case 0x84e8: + return "MAX_RENDERBUFFER_SIZE" + case 0x506: + return "INVALID_FRAMEBUFFER_OPERATION" + case 0x100: + return "DEPTH_BUFFER_BIT" + case 0x400: + return "STENCIL_BUFFER_BIT" + case 0x4000: + return "COLOR_BUFFER_BIT" + case 0x8b50: + return "FLOAT_VEC2" + case 0x8b51: + return "FLOAT_VEC3" + case 0x8b52: + return "FLOAT_VEC4" + case 0x8b53: + return "INT_VEC2" + case 0x8b54: + return "INT_VEC3" + case 0x8b55: + return "INT_VEC4" + case 0x8b56: + return "BOOL" + case 0x8b57: + return "BOOL_VEC2" + case 0x8b58: + return "BOOL_VEC3" + case 0x8b59: + return "BOOL_VEC4" + case 0x8b5a: + return "FLOAT_MAT2" + case 0x8b5b: + return "FLOAT_MAT3" + case 0x8b5c: + return "FLOAT_MAT4" + case 0x8b5e: + return "SAMPLER_2D" + case 0x8b60: + return "SAMPLER_CUBE" + case 0x8b30: + return "FRAGMENT_SHADER" + case 0x8b31: + return "VERTEX_SHADER" + case 0x8a35: + return "ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH" + case 0x8a36: + return "ACTIVE_UNIFORM_BLOCKS" + case 0x911a: + return "ALREADY_SIGNALED" + case 0x8c2f: + return "ANY_SAMPLES_PASSED" + case 0x8d6a: + return "ANY_SAMPLES_PASSED_CONSERVATIVE" + case 0x1905: + return "BLUE" + case 0x911f: + return "BUFFER_ACCESS_FLAGS" + case 0x9120: + return "BUFFER_MAP_LENGTH" + case 0x9121: + return "BUFFER_MAP_OFFSET" + case 0x88bc: + return "BUFFER_MAPPED" + case 0x88bd: + return "BUFFER_MAP_POINTER" + case 0x1800: + return "COLOR" + case 0x8cea: + return "COLOR_ATTACHMENT10" + case 0x8ce1: + return "COLOR_ATTACHMENT1" + case 0x8ceb: + return "COLOR_ATTACHMENT11" + case 0x8cec: + return "COLOR_ATTACHMENT12" + case 0x8ced: + return "COLOR_ATTACHMENT13" + case 0x8cee: + return "COLOR_ATTACHMENT14" + case 0x8cef: + return "COLOR_ATTACHMENT15" + case 0x8ce2: + return "COLOR_ATTACHMENT2" + case 0x8ce3: + return "COLOR_ATTACHMENT3" + case 0x8ce4: + return "COLOR_ATTACHMENT4" + case 0x8ce5: + return "COLOR_ATTACHMENT5" + case 0x8ce6: + return "COLOR_ATTACHMENT6" + case 0x8ce7: + return "COLOR_ATTACHMENT7" + case 0x8ce8: + return "COLOR_ATTACHMENT8" + case 0x8ce9: + return "COLOR_ATTACHMENT9" + case 0x884e: + return "COMPARE_REF_TO_TEXTURE" + case 0x9270: + return "COMPRESSED_R11_EAC" + case 0x9272: + return "COMPRESSED_RG11_EAC" + case 0x9274: + return "COMPRESSED_RGB8_ETC2" + case 0x9276: + return "COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2" + case 0x9278: + return "COMPRESSED_RGBA8_ETC2_EAC" + case 0x9271: + return "COMPRESSED_SIGNED_R11_EAC" + case 0x9273: + return "COMPRESSED_SIGNED_RG11_EAC" + case 0x9279: + return "COMPRESSED_SRGB8_ALPHA8_ETC2_EAC" + case 0x9275: + return "COMPRESSED_SRGB8_ETC2" + case 0x9277: + return "COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2" + case 0x911c: + return "CONDITION_SATISFIED" + case 0x8f36: + return "36662" + case 0x8f37: + return "36663" + case 0x8865: + return "CURRENT_QUERY" + case 0x1801: + return "DEPTH" + case 0x88f0: + return "DEPTH24_STENCIL8" + case 0x8cad: + return "DEPTH32F_STENCIL8" + case 0x81a6: + return "DEPTH_COMPONENT24" + case 0x8cac: + return "DEPTH_COMPONENT32F" + case 0x84f9: + return "DEPTH_STENCIL" + case 0x821a: + return "DEPTH_STENCIL_ATTACHMENT" + case 0x8825: + return "DRAW_BUFFER0" + case 0x882f: + return "DRAW_BUFFER10" + case 0x8826: + return "DRAW_BUFFER1" + case 0x8830: + return "DRAW_BUFFER11" + case 0x8831: + return "DRAW_BUFFER12" + case 0x8832: + return "DRAW_BUFFER13" + case 0x8833: + return "DRAW_BUFFER14" + case 0x8834: + return "DRAW_BUFFER15" + case 0x8827: + return "DRAW_BUFFER2" + case 0x8828: + return "DRAW_BUFFER3" + case 0x8829: + return "DRAW_BUFFER4" + case 0x882a: + return "DRAW_BUFFER5" + case 0x882b: + return "DRAW_BUFFER6" + case 0x882c: + return "DRAW_BUFFER7" + case 0x882d: + return "DRAW_BUFFER8" + case 0x882e: + return "DRAW_BUFFER9" + case 0x8ca9: + return "DRAW_FRAMEBUFFER" + case 0x88ea: + return "DYNAMIC_COPY" + case 0x88e9: + return "DYNAMIC_READ" + case 0x8dad: + return "FLOAT_32_UNSIGNED_INT_24_8_REV" + case 0x8b65: + return "FLOAT_MAT2x3" + case 0x8b66: + return "FLOAT_MAT2x4" + case 0x8b67: + return "FLOAT_MAT3x2" + case 0x8b68: + return "FLOAT_MAT3x4" + case 0x8b69: + return "FLOAT_MAT4x2" + case 0x8b6a: + return "FLOAT_MAT4x3" + case 0x8b8b: + return "FRAGMENT_SHADER_DERIVATIVE_HINT" + case 0x8215: + return "FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE" + case 0x8214: + return "FRAMEBUFFER_ATTACHMENT_BLUE_SIZE" + case 0x8210: + return "FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING" + case 0x8211: + return "FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE" + case 0x8216: + return "FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE" + case 0x8213: + return "FRAMEBUFFER_ATTACHMENT_GREEN_SIZE" + case 0x8212: + return "FRAMEBUFFER_ATTACHMENT_RED_SIZE" + case 0x8217: + return "FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE" + case 0x8cd4: + return "FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER" + case 0x8218: + return "FRAMEBUFFER_DEFAULT" + case 0x8d56: + return "FRAMEBUFFER_INCOMPLETE_MULTISAMPLE" + case 0x8219: + return "FRAMEBUFFER_UNDEFINED" + case 0x1904: + return "GREEN" + case 0x140b: + return "HALF_FLOAT" + case 0x8d9f: + return "INT_2_10_10_10_REV" + case 0x8c8c: + return "INTERLEAVED_ATTRIBS" + case 0x8dca: + return "INT_SAMPLER_2D" + case 0x8dcf: + return "INT_SAMPLER_2D_ARRAY" + case 0x8dcb: + return "INT_SAMPLER_3D" + case 0x8dcc: + return "INT_SAMPLER_CUBE" + case 0xffffffff: + return "INVALID_INDEX" + case 0x821b: + return "MAJOR_VERSION" + case 0x10: + return "MAP_FLUSH_EXPLICIT_BIT" + case 0x8: + return "MAP_INVALIDATE_BUFFER_BIT" + case 0x20: + return "MAP_UNSYNCHRONIZED_BIT" + case 0x8008: + return "MAX" + case 0x8073: + return "MAX_3D_TEXTURE_SIZE" + case 0x88ff: + return "MAX_ARRAY_TEXTURE_LAYERS" + case 0x8cdf: + return "MAX_COLOR_ATTACHMENTS" + case 0x8a33: + return "MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS" + case 0x8a2e: + return "MAX_COMBINED_UNIFORM_BLOCKS" + case 0x8a31: + return "MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS" + case 0x8824: + return "MAX_DRAW_BUFFERS" + case 0x8d6b: + return "MAX_ELEMENT_INDEX" + case 0x80e9: + return "MAX_ELEMENTS_INDICES" + case 0x80e8: + return "MAX_ELEMENTS_VERTICES" + case 0x9125: + return "MAX_FRAGMENT_INPUT_COMPONENTS" + case 0x8a2d: + return "MAX_FRAGMENT_UNIFORM_BLOCKS" + case 0x8b49: + return "MAX_FRAGMENT_UNIFORM_COMPONENTS" + case 0x8905: + return "MAX_PROGRAM_TEXEL_OFFSET" + case 0x8d57: + return "MAX_SAMPLES" + case 0x9111: + return "MAX_SERVER_WAIT_TIMEOUT" + case 0x84fd: + return "MAX_TEXTURE_LOD_BIAS" + case 0x8c8a: + return "MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS" + case 0x8c8b: + return "MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS" + case 0x8c80: + return "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS" + case 0x8a30: + return "MAX_UNIFORM_BLOCK_SIZE" + case 0x8a2f: + return "MAX_UNIFORM_BUFFER_BINDINGS" + case 0x8b4b: + return "MAX_VARYING_COMPONENTS" + case 0x9122: + return "MAX_VERTEX_OUTPUT_COMPONENTS" + case 0x8a2b: + return "MAX_VERTEX_UNIFORM_BLOCKS" + case 0x8b4a: + return "MAX_VERTEX_UNIFORM_COMPONENTS" + case 0x8007: + return "MIN" + case 0x821c: + return "MINOR_VERSION" + case 0x8904: + return "MIN_PROGRAM_TEXEL_OFFSET" + case 0x821d: + return "NUM_EXTENSIONS" + case 0x87fe: + return "NUM_PROGRAM_BINARY_FORMATS" + case 0x9380: + return "NUM_SAMPLE_COUNTS" + case 0x9112: + return "OBJECT_TYPE" + case 0xd02: + return "PACK_ROW_LENGTH" + case 0xd04: + return "PACK_SKIP_PIXELS" + case 0xd03: + return "PACK_SKIP_ROWS" + case 0x88eb: + return "PIXEL_PACK_BUFFER" + case 0x88ed: + return "PIXEL_PACK_BUFFER_BINDING" + case 0x88ec: + return "PIXEL_UNPACK_BUFFER" + case 0x88ef: + return "PIXEL_UNPACK_BUFFER_BINDING" + case 0x8d69: + return "PRIMITIVE_RESTART_FIXED_INDEX" + case 0x87ff: + return "PROGRAM_BINARY_FORMATS" + case 0x8741: + return "PROGRAM_BINARY_LENGTH" + case 0x8257: + return "PROGRAM_BINARY_RETRIEVABLE_HINT" + case 0x8866: + return "QUERY_RESULT" + case 0x8867: + return "QUERY_RESULT_AVAILABLE" + case 0x8c3a: + return "R11F_G11F_B10F" + case 0x822d: + return "R16F" + case 0x8233: + return "R16I" + case 0x8234: + return "R16UI" + case 0x822e: + return "R32F" + case 0x8235: + return "R32I" + case 0x8236: + return "R32UI" + case 0x8229: + return "R8" + case 0x8231: + return "R8I" + case 0x8f94: + return "R8_SNORM" + case 0x8232: + return "R8UI" + case 0x8c89: + return "RASTERIZER_DISCARD" + case 0xc02: + return "READ_BUFFER" + case 0x8ca8: + return "READ_FRAMEBUFFER" + case 0x8caa: + return "READ_FRAMEBUFFER_BINDING" + case 0x1903: + return "RED" + case 0x8d94: + return "RED_INTEGER" + case 0x8cab: + return "RENDERBUFFER_SAMPLES" + case 0x8227: + return "RG" + case 0x822f: + return "RG16F" + case 0x8239: + return "RG16I" + case 0x823a: + return "RG16UI" + case 0x8230: + return "RG32F" + case 0x823b: + return "RG32I" + case 0x823c: + return "RG32UI" + case 0x822b: + return "RG8" + case 0x8237: + return "RG8I" + case 0x8f95: + return "RG8_SNORM" + case 0x8238: + return "RG8UI" + case 0x8059: + return "RGB10_A2" + case 0x906f: + return "RGB10_A2UI" + case 0x881b: + return "RGB16F" + case 0x8d89: + return "RGB16I" + case 0x8d77: + return "RGB16UI" + case 0x8815: + return "RGB32F" + case 0x8d83: + return "RGB32I" + case 0x8d71: + return "RGB32UI" + case 0x8051: + return "RGB8" + case 0x8d8f: + return "RGB8I" + case 0x8f96: + return "RGB8_SNORM" + case 0x8d7d: + return "RGB8UI" + case 0x8c3d: + return "RGB9_E5" + case 0x881a: + return "RGBA16F" + case 0x8d88: + return "RGBA16I" + case 0x8d76: + return "RGBA16UI" + case 0x8814: + return "RGBA32F" + case 0x8d82: + return "RGBA32I" + case 0x8d70: + return "RGBA32UI" + case 0x8058: + return "RGBA8" + case 0x8d8e: + return "RGBA8I" + case 0x8f97: + return "RGBA8_SNORM" + case 0x8d7c: + return "RGBA8UI" + case 0x8d99: + return "RGBA_INTEGER" + case 0x8d98: + return "RGB_INTEGER" + case 0x8228: + return "RG_INTEGER" + case 0x8dc1: + return "SAMPLER_2D_ARRAY" + case 0x8dc4: + return "SAMPLER_2D_ARRAY_SHADOW" + case 0x8b62: + return "SAMPLER_2D_SHADOW" + case 0x8b5f: + return "SAMPLER_3D" + case 0x8919: + return "SAMPLER_BINDING" + case 0x8dc5: + return "SAMPLER_CUBE_SHADOW" + case 0x8c8d: + return "SEPARATE_ATTRIBS" + case 0x9119: + return "SIGNALED" + case 0x8f9c: + return "SIGNED_NORMALIZED" + case 0x8c40: + return "SRGB" + case 0x8c41: + return "SRGB8" + case 0x8c43: + return "SRGB8_ALPHA8" + case 0x88e6: + return "STATIC_COPY" + case 0x88e5: + return "STATIC_READ" + case 0x1802: + return "STENCIL" + case 0x88e2: + return "STREAM_COPY" + case 0x88e1: + return "STREAM_READ" + case 0x9113: + return "SYNC_CONDITION" + case 0x9116: + return "SYNC_FENCE" + case 0x9115: + return "SYNC_FLAGS" + case 0x9117: + return "SYNC_GPU_COMMANDS_COMPLETE" + case 0x9114: + return "SYNC_STATUS" + case 0x8c1a: + return "TEXTURE_2D_ARRAY" + case 0x806f: + return "TEXTURE_3D" + case 0x813c: + return "TEXTURE_BASE_LEVEL" + case 0x8c1d: + return "TEXTURE_BINDING_2D_ARRAY" + case 0x806a: + return "TEXTURE_BINDING_3D" + case 0x884d: + return "TEXTURE_COMPARE_FUNC" + case 0x884c: + return "TEXTURE_COMPARE_MODE" + case 0x912f: + return "TEXTURE_IMMUTABLE_FORMAT" + case 0x82df: + return "TEXTURE_IMMUTABLE_LEVELS" + case 0x813d: + return "TEXTURE_MAX_LEVEL" + case 0x813b: + return "TEXTURE_MAX_LOD" + case 0x813a: + return "TEXTURE_MIN_LOD" + case 0x8e45: + return "TEXTURE_SWIZZLE_A" + case 0x8e44: + return "TEXTURE_SWIZZLE_B" + case 0x8e43: + return "TEXTURE_SWIZZLE_G" + case 0x8e42: + return "TEXTURE_SWIZZLE_R" + case 0x8072: + return "TEXTURE_WRAP_R" + case 0x911b: + return "TIMEOUT_EXPIRED" + case 0x8e22: + return "TRANSFORM_FEEDBACK" + case 0x8e24: + return "TRANSFORM_FEEDBACK_ACTIVE" + case 0x8e25: + return "TRANSFORM_FEEDBACK_BINDING" + case 0x8c8e: + return "TRANSFORM_FEEDBACK_BUFFER" + case 0x8c8f: + return "TRANSFORM_FEEDBACK_BUFFER_BINDING" + case 0x8c7f: + return "TRANSFORM_FEEDBACK_BUFFER_MODE" + case 0x8c85: + return "TRANSFORM_FEEDBACK_BUFFER_SIZE" + case 0x8c84: + return "TRANSFORM_FEEDBACK_BUFFER_START" + case 0x8e23: + return "TRANSFORM_FEEDBACK_PAUSED" + case 0x8c88: + return "TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN" + case 0x8c76: + return "TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH" + case 0x8c83: + return "TRANSFORM_FEEDBACK_VARYINGS" + case 0x8a3c: + return "UNIFORM_ARRAY_STRIDE" + case 0x8a43: + return "UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES" + case 0x8a42: + return "UNIFORM_BLOCK_ACTIVE_UNIFORMS" + case 0x8a3f: + return "UNIFORM_BLOCK_BINDING" + case 0x8a40: + return "UNIFORM_BLOCK_DATA_SIZE" + case 0x8a3a: + return "UNIFORM_BLOCK_INDEX" + case 0x8a41: + return "UNIFORM_BLOCK_NAME_LENGTH" + case 0x8a46: + return "UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER" + case 0x8a44: + return "UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER" + case 0x8a11: + return "UNIFORM_BUFFER" + case 0x8a28: + return "UNIFORM_BUFFER_BINDING" + case 0x8a34: + return "UNIFORM_BUFFER_OFFSET_ALIGNMENT" + case 0x8a2a: + return "UNIFORM_BUFFER_SIZE" + case 0x8a29: + return "UNIFORM_BUFFER_START" + case 0x8a3e: + return "UNIFORM_IS_ROW_MAJOR" + case 0x8a3d: + return "UNIFORM_MATRIX_STRIDE" + case 0x8a39: + return "UNIFORM_NAME_LENGTH" + case 0x8a3b: + return "UNIFORM_OFFSET" + case 0x8a38: + return "UNIFORM_SIZE" + case 0x8a37: + return "UNIFORM_TYPE" + case 0x806e: + return "UNPACK_IMAGE_HEIGHT" + case 0xcf2: + return "UNPACK_ROW_LENGTH" + case 0x806d: + return "UNPACK_SKIP_IMAGES" + case 0xcf4: + return "UNPACK_SKIP_PIXELS" + case 0xcf3: + return "UNPACK_SKIP_ROWS" + case 0x9118: + return "UNSIGNALED" + case 0x8c3b: + return "UNSIGNED_INT_10F_11F_11F_REV" + case 0x8368: + return "UNSIGNED_INT_2_10_10_10_REV" + case 0x84fa: + return "UNSIGNED_INT_24_8" + case 0x8c3e: + return "UNSIGNED_INT_5_9_9_9_REV" + case 0x8dd2: + return "UNSIGNED_INT_SAMPLER_2D" + case 0x8dd7: + return "UNSIGNED_INT_SAMPLER_2D_ARRAY" + case 0x8dd3: + return "UNSIGNED_INT_SAMPLER_3D" + case 0x8dd4: + return "UNSIGNED_INT_SAMPLER_CUBE" + case 0x8dc6: + return "UNSIGNED_INT_VEC2" + case 0x8dc7: + return "UNSIGNED_INT_VEC3" + case 0x8dc8: + return "UNSIGNED_INT_VEC4" + case 0x8c17: + return "UNSIGNED_NORMALIZED" + case 0x85b5: + return "VERTEX_ARRAY_BINDING" + case 0x88fe: + return "VERTEX_ATTRIB_ARRAY_DIVISOR" + case 0x88fd: + return "VERTEX_ATTRIB_ARRAY_INTEGER" + case 0x911d: + return "WAIT_FAILED" + default: + return fmt.Sprintf("gl.Enum(0x%x)", uint32(v)) + } +} + +func (ctx *context) ActiveTexture(texture Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.ActiveTexture(%v) %v", texture, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnActiveTexture, + a0: texture.c(), + }, + blocking: true}) +} + +func (ctx *context) AttachShader(p Program, s Shader) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.AttachShader(%v, %v) %v", p, s, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnAttachShader, + a0: p.c(), + a1: s.c(), + }, + blocking: true}) +} + +func (ctx *context) BindAttribLocation(p Program, a Attrib, name string) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.BindAttribLocation(%v, %v, %v) %v", p, a, name, errstr) + }() + s, free := ctx.cString(name) + defer free() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnBindAttribLocation, + a0: p.c(), + a1: a.c(), + a2: s, + }, + blocking: true, + }) +} + +func (ctx *context) BindBuffer(target Enum, b Buffer) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.BindBuffer(%v, %v) %v", target, b, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnBindBuffer, + a0: target.c(), + a1: b.c(), + }, + blocking: true}) +} + +func (ctx *context) BindFramebuffer(target Enum, fb Framebuffer) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.BindFramebuffer(%v, %v) %v", target, fb, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnBindFramebuffer, + a0: target.c(), + a1: fb.c(), + }, + blocking: true}) +} + +func (ctx *context) BindRenderbuffer(target Enum, rb Renderbuffer) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.BindRenderbuffer(%v, %v) %v", target, rb, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnBindRenderbuffer, + a0: target.c(), + a1: rb.c(), + }, + blocking: true}) +} + +func (ctx *context) BindTexture(target Enum, t Texture) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.BindTexture(%v, %v) %v", target, t, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnBindTexture, + a0: target.c(), + a1: t.c(), + }, + blocking: true}) +} + +func (ctx *context) BindVertexArray(va VertexArray) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.BindVertexArray(%v) %v", va, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnBindVertexArray, + a0: va.c(), + }, + blocking: true}) +} + +func (ctx *context) BlendColor(red, green, blue, alpha float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.BlendColor(%v, %v, %v, %v) %v", red, green, blue, alpha, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnBlendColor, + a0: uintptr(math.Float32bits(red)), + a1: uintptr(math.Float32bits(green)), + a2: uintptr(math.Float32bits(blue)), + a3: uintptr(math.Float32bits(alpha)), + }, + blocking: true}) +} + +func (ctx *context) BlendEquation(mode Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.BlendEquation(%v) %v", mode, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnBlendEquation, + a0: mode.c(), + }, + blocking: true}) +} + +func (ctx *context) BlendEquationSeparate(modeRGB, modeAlpha Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.BlendEquationSeparate(%v, %v) %v", modeRGB, modeAlpha, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnBlendEquationSeparate, + a0: modeRGB.c(), + a1: modeAlpha.c(), + }, + blocking: true}) +} + +func (ctx *context) BlendFunc(sfactor, dfactor Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.BlendFunc(%v, %v) %v", sfactor, dfactor, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnBlendFunc, + a0: sfactor.c(), + a1: dfactor.c(), + }, + blocking: true}) +} + +func (ctx *context) BlendFuncSeparate(sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.BlendFuncSeparate(%v, %v, %v, %v) %v", sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnBlendFuncSeparate, + a0: sfactorRGB.c(), + a1: dfactorRGB.c(), + a2: sfactorAlpha.c(), + a3: dfactorAlpha.c(), + }, + blocking: true}) +} + +func (ctx *context) BufferData(target Enum, src []byte, usage Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.BufferData(%v, len(%d), %v) %v", target, len(src), usage, errstr) + }() + parg := unsafe.Pointer(nil) + if len(src) > 0 { + parg = unsafe.Pointer(&src[0]) + } + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnBufferData, + a0: target.c(), + a1: uintptr(len(src)), + a2: usage.c(), + }, + parg: parg, + blocking: true, + }) +} + +func (ctx *context) BufferInit(target Enum, size int, usage Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.BufferInit(%v, %v, %v) %v", target, size, usage, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnBufferData, + a0: target.c(), + a1: uintptr(size), + a2: usage.c(), + }, + parg: unsafe.Pointer(nil), + blocking: true}) +} + +func (ctx *context) BufferSubData(target Enum, offset int, data []byte) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.BufferSubData(%v, %v, len(%d)) %v", target, offset, len(data), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnBufferSubData, + a0: target.c(), + a1: uintptr(offset), + a2: uintptr(len(data)), + }, + parg: unsafe.Pointer(&data[0]), + blocking: true, + }) +} + +func (ctx *context) CheckFramebufferStatus(target Enum) (r0 Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.CheckFramebufferStatus(%v) %v%v", target, r0, errstr) + }() + return Enum(ctx.enqueue(call{ + args: fnargs{ + fn: glfnCheckFramebufferStatus, + a0: target.c(), + }, + blocking: true, + })) +} + +func (ctx *context) Clear(mask Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Clear(%v) %v", mask, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnClear, + a0: uintptr(mask), + }, + blocking: true}) +} + +func (ctx *context) ClearColor(red, green, blue, alpha float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.ClearColor(%v, %v, %v, %v) %v", red, green, blue, alpha, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnClearColor, + a0: uintptr(math.Float32bits(red)), + a1: uintptr(math.Float32bits(green)), + a2: uintptr(math.Float32bits(blue)), + a3: uintptr(math.Float32bits(alpha)), + }, + blocking: true}) +} + +func (ctx *context) ClearDepthf(d float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.ClearDepthf(%v) %v", d, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnClearDepthf, + a0: uintptr(math.Float32bits(d)), + }, + blocking: true}) +} + +func (ctx *context) ClearStencil(s int) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.ClearStencil(%v) %v", s, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnClearStencil, + a0: uintptr(s), + }, + blocking: true}) +} + +func (ctx *context) ColorMask(red, green, blue, alpha bool) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.ColorMask(%v, %v, %v, %v) %v", red, green, blue, alpha, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnColorMask, + a0: glBoolean(red), + a1: glBoolean(green), + a2: glBoolean(blue), + a3: glBoolean(alpha), + }, + blocking: true}) +} + +func (ctx *context) CompileShader(s Shader) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.CompileShader(%v) %v", s, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnCompileShader, + a0: s.c(), + }, + blocking: true}) +} + +func (ctx *context) CompressedTexImage2D(target Enum, level int, internalformat Enum, width, height, border int, data []byte) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.CompressedTexImage2D(%v, %v, %v, %v, %v, %v, len(%d)) %v", target, level, internalformat, width, height, border, len(data), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnCompressedTexImage2D, + a0: target.c(), + a1: uintptr(level), + a2: internalformat.c(), + a3: uintptr(width), + a4: uintptr(height), + a5: uintptr(border), + a6: uintptr(len(data)), + }, + parg: unsafe.Pointer(&data[0]), + blocking: true, + }) +} + +func (ctx *context) CompressedTexSubImage2D(target Enum, level, xoffset, yoffset, width, height int, format Enum, data []byte) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.CompressedTexSubImage2D(%v, %v, %v, %v, %v, %v, %v, len(%d)) %v", target, level, xoffset, yoffset, width, height, format, len(data), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnCompressedTexSubImage2D, + a0: target.c(), + a1: uintptr(level), + a2: uintptr(xoffset), + a3: uintptr(yoffset), + a4: uintptr(width), + a5: uintptr(height), + a6: format.c(), + a7: uintptr(len(data)), + }, + parg: unsafe.Pointer(&data[0]), + blocking: true, + }) +} + +func (ctx *context) CopyTexImage2D(target Enum, level int, internalformat Enum, x, y, width, height, border int) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.CopyTexImage2D(%v, %v, %v, %v, %v, %v, %v, %v) %v", target, level, internalformat, x, y, width, height, border, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnCopyTexImage2D, + a0: target.c(), + a1: uintptr(level), + a2: internalformat.c(), + a3: uintptr(x), + a4: uintptr(y), + a5: uintptr(width), + a6: uintptr(height), + a7: uintptr(border), + }, + blocking: true}) +} + +func (ctx *context) CopyTexSubImage2D(target Enum, level, xoffset, yoffset, x, y, width, height int) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.CopyTexSubImage2D(%v, %v, %v, %v, %v, %v, %v, %v) %v", target, level, xoffset, yoffset, x, y, width, height, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnCopyTexSubImage2D, + a0: target.c(), + a1: uintptr(level), + a2: uintptr(xoffset), + a3: uintptr(yoffset), + a4: uintptr(x), + a5: uintptr(y), + a6: uintptr(width), + a7: uintptr(height), + }, + blocking: true}) +} + +func (ctx *context) CreateBuffer() (r0 Buffer) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.CreateBuffer() %v%v", r0, errstr) + }() + return Buffer{Value: uint32(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGenBuffer, + }, + blocking: true, + }))} +} + +func (ctx *context) CreateFramebuffer() (r0 Framebuffer) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.CreateFramebuffer() %v%v", r0, errstr) + }() + return Framebuffer{Value: uint32(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGenFramebuffer, + }, + blocking: true, + }))} +} + +func (ctx *context) CreateProgram() (r0 Program) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.CreateProgram() %v%v", r0, errstr) + }() + return Program{ + Init: true, + Value: uint32(ctx.enqueue(call{ + args: fnargs{ + fn: glfnCreateProgram, + }, + blocking: true, + }, + ))} +} + +func (ctx *context) CreateRenderbuffer() (r0 Renderbuffer) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.CreateRenderbuffer() %v%v", r0, errstr) + }() + return Renderbuffer{Value: uint32(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGenRenderbuffer, + }, + blocking: true, + }))} +} + +func (ctx *context) CreateShader(ty Enum) (r0 Shader) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.CreateShader(%v) %v%v", ty, r0, errstr) + }() + return Shader{Value: uint32(ctx.enqueue(call{ + args: fnargs{ + fn: glfnCreateShader, + a0: uintptr(ty), + }, + blocking: true, + }))} +} + +func (ctx *context) CreateTexture() (r0 Texture) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.CreateTexture() %v%v", r0, errstr) + }() + return Texture{Value: uint32(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGenTexture, + }, + blocking: true, + }))} +} + +func (ctx *context) CreateVertexArray() (r0 VertexArray) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.CreateVertexArray() %v%v", r0, errstr) + }() + return VertexArray{Value: uint32(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGenVertexArray, + }, + blocking: true, + }))} +} + +func (ctx *context) CullFace(mode Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.CullFace(%v) %v", mode, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnCullFace, + a0: mode.c(), + }, + blocking: true}) +} + +func (ctx *context) DeleteBuffer(v Buffer) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.DeleteBuffer(%v) %v", v, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnDeleteBuffer, + a0: v.c(), + }, + blocking: true}) +} + +func (ctx *context) DeleteFramebuffer(v Framebuffer) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.DeleteFramebuffer(%v) %v", v, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnDeleteFramebuffer, + a0: v.c(), + }, + blocking: true}) +} + +func (ctx *context) DeleteProgram(p Program) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.DeleteProgram(%v) %v", p, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnDeleteProgram, + a0: p.c(), + }, + blocking: true}) +} + +func (ctx *context) DeleteRenderbuffer(v Renderbuffer) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.DeleteRenderbuffer(%v) %v", v, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnDeleteRenderbuffer, + a0: v.c(), + }, + blocking: true}) +} + +func (ctx *context) DeleteShader(s Shader) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.DeleteShader(%v) %v", s, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnDeleteShader, + a0: s.c(), + }, + blocking: true}) +} + +func (ctx *context) DeleteTexture(v Texture) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.DeleteTexture(%v) %v", v, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnDeleteTexture, + a0: v.c(), + }, + blocking: true}) +} + +func (ctx *context) DeleteVertexArray(v VertexArray) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.DeleteVertexArray(%v) %v", v, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnDeleteVertexArray, + a0: v.c(), + }, + blocking: true}) +} + +func (ctx *context) DepthFunc(fn Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.DepthFunc(%v) %v", fn, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnDepthFunc, + a0: fn.c(), + }, + blocking: true}) +} + +func (ctx *context) DepthMask(flag bool) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.DepthMask(%v) %v", flag, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnDepthMask, + a0: glBoolean(flag), + }, + blocking: true}) +} + +func (ctx *context) DepthRangef(n, f float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.DepthRangef(%v, %v) %v", n, f, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnDepthRangef, + a0: uintptr(math.Float32bits(n)), + a1: uintptr(math.Float32bits(f)), + }, + blocking: true}) +} + +func (ctx *context) DetachShader(p Program, s Shader) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.DetachShader(%v, %v) %v", p, s, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnDetachShader, + a0: p.c(), + a1: s.c(), + }, + blocking: true}) +} + +func (ctx *context) Disable(cap Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Disable(%v) %v", cap, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnDisable, + a0: cap.c(), + }, + blocking: true}) +} + +func (ctx *context) DisableVertexAttribArray(a Attrib) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.DisableVertexAttribArray(%v) %v", a, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnDisableVertexAttribArray, + a0: a.c(), + }, + blocking: true}) +} + +func (ctx *context) DrawArrays(mode Enum, first, count int) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.DrawArrays(%v, %v, %v) %v", mode, first, count, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnDrawArrays, + a0: mode.c(), + a1: uintptr(first), + a2: uintptr(count), + }, + blocking: true}) +} + +func (ctx *context) DrawElements(mode Enum, count int, ty Enum, offset int) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.DrawElements(%v, %v, %v, %v) %v", mode, count, ty, offset, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnDrawElements, + a0: mode.c(), + a1: uintptr(count), + a2: ty.c(), + a3: uintptr(offset), + }, + blocking: true}) +} + +func (ctx *context) Enable(cap Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Enable(%v) %v", cap, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnEnable, + a0: cap.c(), + }, + blocking: true}) +} + +func (ctx *context) EnableVertexAttribArray(a Attrib) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.EnableVertexAttribArray(%v) %v", a, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnEnableVertexAttribArray, + a0: a.c(), + }, + blocking: true}) +} + +func (ctx *context) Finish() { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Finish() %v", errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnFinish, + }, + blocking: true, + }) +} + +func (ctx *context) Flush() { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Flush() %v", errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnFlush, + }, + blocking: true, + }) +} + +func (ctx *context) FramebufferRenderbuffer(target, attachment, rbTarget Enum, rb Renderbuffer) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.FramebufferRenderbuffer(%v, %v, %v, %v) %v", target, attachment, rbTarget, rb, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnFramebufferRenderbuffer, + a0: target.c(), + a1: attachment.c(), + a2: rbTarget.c(), + a3: rb.c(), + }, + blocking: true}) +} + +func (ctx *context) FramebufferTexture2D(target, attachment, texTarget Enum, t Texture, level int) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.FramebufferTexture2D(%v, %v, %v, %v, %v) %v", target, attachment, texTarget, t, level, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnFramebufferTexture2D, + a0: target.c(), + a1: attachment.c(), + a2: texTarget.c(), + a3: t.c(), + a4: uintptr(level), + }, + blocking: true}) +} + +func (ctx *context) FrontFace(mode Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.FrontFace(%v) %v", mode, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnFrontFace, + a0: mode.c(), + }, + blocking: true}) +} + +func (ctx *context) GenerateMipmap(target Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GenerateMipmap(%v) %v", target, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnGenerateMipmap, + a0: target.c(), + }, + blocking: true}) +} + +func (ctx *context) GetActiveAttrib(p Program, index uint32) (name string, size int, ty Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetActiveAttrib(%v, %v) (%v, %v, %v) %v", p, index, name, size, ty, errstr) + }() + bufSize := ctx.GetProgrami(p, ACTIVE_ATTRIBUTE_MAX_LENGTH) + buf := make([]byte, bufSize) + var cType int + cSize := ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetActiveAttrib, + a0: p.c(), + a1: uintptr(index), + a2: uintptr(bufSize), + a3: uintptr(unsafe.Pointer(&cType)), + }, + parg: unsafe.Pointer(&buf[0]), + blocking: true, + }) + return goString(buf), int(cSize), Enum(cType) +} + +func (ctx *context) GetActiveUniform(p Program, index uint32) (name string, size int, ty Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetActiveUniform(%v, %v) (%v, %v, %v) %v", p, index, name, size, ty, errstr) + }() + bufSize := ctx.GetProgrami(p, ACTIVE_UNIFORM_MAX_LENGTH) + buf := make([]byte, bufSize+8) + var cType int + cSize := ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetActiveUniform, + a0: p.c(), + a1: uintptr(index), + a2: uintptr(bufSize), + a3: uintptr(unsafe.Pointer(&cType)), + }, + parg: unsafe.Pointer(&buf[0]), + blocking: true, + }) + return goString(buf), int(cSize), Enum(cType) +} + +func (ctx *context) GetAttachedShaders(p Program) (r0 []Shader) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetAttachedShaders(%v) %v%v", p, r0, errstr) + }() + shadersLen := ctx.GetProgrami(p, ATTACHED_SHADERS) + if shadersLen == 0 { + return nil + } + buf := make([]uint32, shadersLen) + n := int(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetAttachedShaders, + a0: p.c(), + a1: uintptr(shadersLen), + }, + parg: unsafe.Pointer(&buf[0]), + blocking: true, + })) + buf = buf[:int(n)] + shaders := make([]Shader, len(buf)) + for i, s := range buf { + shaders[i] = Shader{Value: uint32(s)} + } + return shaders +} + +func (ctx *context) GetAttribLocation(p Program, name string) (r0 Attrib) { + defer func() { + errstr := ctx.errDrain() + r0.name = name + log.Printf("gl.GetAttribLocation(%v, %v) %v%v", p, name, r0, errstr) + }() + s, free := ctx.cString(name) + defer free() + return Attrib{Value: uint(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetAttribLocation, + a0: p.c(), + a1: s, + }, + blocking: true, + }))} +} + +func (ctx *context) GetBooleanv(dst []bool, pname Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetBooleanv(%v, %v) %v", dst, pname, errstr) + }() + buf := make([]int32, len(dst)) + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnGetBooleanv, + a0: pname.c(), + }, + parg: unsafe.Pointer(&buf[0]), + blocking: true, + }) + for i, v := range buf { + dst[i] = v != 0 + } +} + +func (ctx *context) GetFloatv(dst []float32, pname Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetFloatv(len(%d), %v) %v", len(dst), pname, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnGetFloatv, + a0: pname.c(), + }, + parg: unsafe.Pointer(&dst[0]), + blocking: true, + }) +} + +func (ctx *context) GetIntegerv(dst []int32, pname Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetIntegerv(%v, %v) %v", dst, pname, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnGetIntegerv, + a0: pname.c(), + }, + parg: unsafe.Pointer(&dst[0]), + blocking: true, + }) +} + +func (ctx *context) GetInteger(pname Enum) (r0 int) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetInteger(%v) %v%v", pname, r0, errstr) + }() + var v [1]int32 + ctx.GetIntegerv(v[:], pname) + return int(v[0]) +} + +func (ctx *context) GetBufferParameteri(target, value Enum) (r0 int) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetBufferParameteri(%v, %v) %v%v", target, value, r0, errstr) + }() + return int(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetBufferParameteri, + a0: target.c(), + a1: value.c(), + }, + blocking: true, + })) +} + +func (ctx *context) GetError() (r0 Enum) { + return Enum(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetError, + }, + blocking: true, + })) +} + +func (ctx *context) GetFramebufferAttachmentParameteri(target, attachment, pname Enum) (r0 int) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetFramebufferAttachmentParameteri(%v, %v, %v) %v%v", target, attachment, pname, r0, errstr) + }() + return int(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetFramebufferAttachmentParameteriv, + a0: target.c(), + a1: attachment.c(), + a2: pname.c(), + }, + blocking: true, + })) +} + +func (ctx *context) GetProgrami(p Program, pname Enum) (r0 int) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetProgrami(%v, %v) %v%v", p, pname, r0, errstr) + }() + return int(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetProgramiv, + a0: p.c(), + a1: pname.c(), + }, + blocking: true, + })) +} + +func (ctx *context) GetProgramInfoLog(p Program) (r0 string) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetProgramInfoLog(%v) %v%v", p, r0, errstr) + }() + infoLen := ctx.GetProgrami(p, INFO_LOG_LENGTH) + if infoLen == 0 { + return "" + } + buf := make([]byte, infoLen) + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnGetProgramInfoLog, + a0: p.c(), + a1: uintptr(infoLen), + }, + parg: unsafe.Pointer(&buf[0]), + blocking: true, + }) + return goString(buf) +} + +func (ctx *context) GetRenderbufferParameteri(target, pname Enum) (r0 int) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetRenderbufferParameteri(%v, %v) %v%v", target, pname, r0, errstr) + }() + return int(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetRenderbufferParameteriv, + a0: target.c(), + a1: pname.c(), + }, + blocking: true, + })) +} + +func (ctx *context) GetShaderi(s Shader, pname Enum) (r0 int) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetShaderi(%v, %v) %v%v", s, pname, r0, errstr) + }() + return int(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetShaderiv, + a0: s.c(), + a1: pname.c(), + }, + blocking: true, + })) +} + +func (ctx *context) GetShaderInfoLog(s Shader) (r0 string) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetShaderInfoLog(%v) %v%v", s, r0, errstr) + }() + infoLen := ctx.GetShaderi(s, INFO_LOG_LENGTH) + if infoLen == 0 { + return "" + } + buf := make([]byte, infoLen) + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnGetShaderInfoLog, + a0: s.c(), + a1: uintptr(infoLen), + }, + parg: unsafe.Pointer(&buf[0]), + blocking: true, + }) + return goString(buf) +} + +func (ctx *context) GetShaderPrecisionFormat(shadertype, precisiontype Enum) (rangeLow, rangeHigh, precision int) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetShaderPrecisionFormat(%v, %v) (%v, %v, %v) %v", shadertype, precisiontype, rangeLow, rangeHigh, precision, errstr) + }() + var rangeAndPrec [3]int32 + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnGetShaderPrecisionFormat, + a0: shadertype.c(), + a1: precisiontype.c(), + }, + parg: unsafe.Pointer(&rangeAndPrec[0]), + blocking: true, + }) + return int(rangeAndPrec[0]), int(rangeAndPrec[1]), int(rangeAndPrec[2]) +} + +func (ctx *context) GetShaderSource(s Shader) (r0 string) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetShaderSource(%v) %v%v", s, r0, errstr) + }() + sourceLen := ctx.GetShaderi(s, SHADER_SOURCE_LENGTH) + if sourceLen == 0 { + return "" + } + buf := make([]byte, sourceLen) + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnGetShaderSource, + a0: s.c(), + a1: uintptr(sourceLen), + }, + parg: unsafe.Pointer(&buf[0]), + blocking: true, + }) + return goString(buf) +} + +func (ctx *context) GetString(pname Enum) (r0 string) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetString(%v) %v%v", pname, r0, errstr) + }() + ret := ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetString, + a0: pname.c(), + }, + blocking: true, + }) + retp := unsafe.Pointer(ret) + buf := (*[1 << 24]byte)(retp)[:] + return goString(buf) +} + +func (ctx *context) GetTexParameterfv(dst []float32, target, pname Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetTexParameterfv(len(%d), %v, %v) %v", len(dst), target, pname, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnGetTexParameterfv, + a0: target.c(), + a1: pname.c(), + }, + parg: unsafe.Pointer(&dst[0]), + blocking: true, + }) +} + +func (ctx *context) GetTexParameteriv(dst []int32, target, pname Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetTexParameteriv(%v, %v, %v) %v", dst, target, pname, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnGetTexParameteriv, + a0: target.c(), + a1: pname.c(), + }, + blocking: true, + }) +} + +func (ctx *context) GetUniformfv(dst []float32, src Uniform, p Program) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetUniformfv(len(%d), %v, %v) %v", len(dst), src, p, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnGetUniformfv, + a0: p.c(), + a1: src.c(), + }, + parg: unsafe.Pointer(&dst[0]), + blocking: true, + }) +} + +func (ctx *context) GetUniformiv(dst []int32, src Uniform, p Program) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetUniformiv(%v, %v, %v) %v", dst, src, p, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnGetUniformiv, + a0: p.c(), + a1: src.c(), + }, + parg: unsafe.Pointer(&dst[0]), + blocking: true, + }) +} + +func (ctx *context) GetUniformLocation(p Program, name string) (r0 Uniform) { + defer func() { + errstr := ctx.errDrain() + r0.name = name + log.Printf("gl.GetUniformLocation(%v, %v) %v%v", p, name, r0, errstr) + }() + s, free := ctx.cString(name) + defer free() + return Uniform{Value: int32(ctx.enqueue(call{ + args: fnargs{ + fn: glfnGetUniformLocation, + a0: p.c(), + a1: s, + }, + blocking: true, + }))} +} + +func (ctx *context) GetVertexAttribf(src Attrib, pname Enum) (r0 float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetVertexAttribf(%v, %v) %v%v", src, pname, r0, errstr) + }() + var params [1]float32 + ctx.GetVertexAttribfv(params[:], src, pname) + return params[0] +} + +func (ctx *context) GetVertexAttribfv(dst []float32, src Attrib, pname Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetVertexAttribfv(len(%d), %v, %v) %v", len(dst), src, pname, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnGetVertexAttribfv, + a0: src.c(), + a1: pname.c(), + }, + parg: unsafe.Pointer(&dst[0]), + blocking: true, + }) +} + +func (ctx *context) GetVertexAttribi(src Attrib, pname Enum) (r0 int32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetVertexAttribi(%v, %v) %v%v", src, pname, r0, errstr) + }() + var params [1]int32 + ctx.GetVertexAttribiv(params[:], src, pname) + return params[0] +} + +func (ctx *context) GetVertexAttribiv(dst []int32, src Attrib, pname Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.GetVertexAttribiv(%v, %v, %v) %v", dst, src, pname, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnGetVertexAttribiv, + a0: src.c(), + a1: pname.c(), + }, + parg: unsafe.Pointer(&dst[0]), + blocking: true, + }) +} + +func (ctx *context) Hint(target, mode Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Hint(%v, %v) %v", target, mode, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnHint, + a0: target.c(), + a1: mode.c(), + }, + blocking: true}) +} + +func (ctx *context) IsBuffer(b Buffer) (r0 bool) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.IsBuffer(%v) %v%v", b, r0, errstr) + }() + return 0 != ctx.enqueue(call{ + args: fnargs{ + fn: glfnIsBuffer, + a0: b.c(), + }, + blocking: true, + }) +} + +func (ctx *context) IsEnabled(cap Enum) (r0 bool) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.IsEnabled(%v) %v%v", cap, r0, errstr) + }() + return 0 != ctx.enqueue(call{ + args: fnargs{ + fn: glfnIsEnabled, + a0: cap.c(), + }, + blocking: true, + }) +} + +func (ctx *context) IsFramebuffer(fb Framebuffer) (r0 bool) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.IsFramebuffer(%v) %v%v", fb, r0, errstr) + }() + return 0 != ctx.enqueue(call{ + args: fnargs{ + fn: glfnIsFramebuffer, + a0: fb.c(), + }, + blocking: true, + }) +} + +func (ctx *context) IsProgram(p Program) (r0 bool) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.IsProgram(%v) %v%v", p, r0, errstr) + }() + return 0 != ctx.enqueue(call{ + args: fnargs{ + fn: glfnIsProgram, + a0: p.c(), + }, + blocking: true, + }) +} + +func (ctx *context) IsRenderbuffer(rb Renderbuffer) (r0 bool) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.IsRenderbuffer(%v) %v%v", rb, r0, errstr) + }() + return 0 != ctx.enqueue(call{ + args: fnargs{ + fn: glfnIsRenderbuffer, + a0: rb.c(), + }, + blocking: true, + }) +} + +func (ctx *context) IsShader(s Shader) (r0 bool) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.IsShader(%v) %v%v", s, r0, errstr) + }() + return 0 != ctx.enqueue(call{ + args: fnargs{ + fn: glfnIsShader, + a0: s.c(), + }, + blocking: true, + }) +} + +func (ctx *context) IsTexture(t Texture) (r0 bool) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.IsTexture(%v) %v%v", t, r0, errstr) + }() + return 0 != ctx.enqueue(call{ + args: fnargs{ + fn: glfnIsTexture, + a0: t.c(), + }, + blocking: true, + }) +} + +func (ctx *context) LineWidth(width float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.LineWidth(%v) %v", width, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnLineWidth, + a0: uintptr(math.Float32bits(width)), + }, + blocking: true}) +} + +func (ctx *context) LinkProgram(p Program) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.LinkProgram(%v) %v", p, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnLinkProgram, + a0: p.c(), + }, + blocking: true}) +} + +func (ctx *context) PixelStorei(pname Enum, param int32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.PixelStorei(%v, %v) %v", pname, param, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnPixelStorei, + a0: pname.c(), + a1: uintptr(param), + }, + blocking: true}) +} + +func (ctx *context) PolygonOffset(factor, units float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.PolygonOffset(%v, %v) %v", factor, units, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnPolygonOffset, + a0: uintptr(math.Float32bits(factor)), + a1: uintptr(math.Float32bits(units)), + }, + blocking: true}) +} + +func (ctx *context) ReadPixels(dst []byte, x, y, width, height int, format, ty Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.ReadPixels(len(%d), %v, %v, %v, %v, %v, %v) %v", len(dst), x, y, width, height, format, ty, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnReadPixels, + + a0: uintptr(x), + a1: uintptr(y), + a2: uintptr(width), + a3: uintptr(height), + a4: format.c(), + a5: ty.c(), + }, + parg: unsafe.Pointer(&dst[0]), + blocking: true, + }) +} + +func (ctx *context) ReleaseShaderCompiler() { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.ReleaseShaderCompiler() %v", errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnReleaseShaderCompiler, + }, + blocking: true}) +} + +func (ctx *context) RenderbufferStorage(target, internalFormat Enum, width, height int) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.RenderbufferStorage(%v, %v, %v, %v) %v", target, internalFormat, width, height, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnRenderbufferStorage, + a0: target.c(), + a1: internalFormat.c(), + a2: uintptr(width), + a3: uintptr(height), + }, + blocking: true}) +} + +func (ctx *context) SampleCoverage(value float32, invert bool) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.SampleCoverage(%v, %v) %v", value, invert, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnSampleCoverage, + a0: uintptr(math.Float32bits(value)), + a1: glBoolean(invert), + }, + blocking: true}) +} + +func (ctx *context) Scissor(x, y, width, height int32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Scissor(%v, %v, %v, %v) %v", x, y, width, height, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnScissor, + a0: uintptr(x), + a1: uintptr(y), + a2: uintptr(width), + a3: uintptr(height), + }, + blocking: true}) +} + +func (ctx *context) ShaderSource(s Shader, src string) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.ShaderSource(%v, %v) %v", s, src, errstr) + }() + strp, free := ctx.cStringPtr(src) + defer free() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnShaderSource, + a0: s.c(), + a1: 1, + a2: strp, + }, + blocking: true, + }) +} + +func (ctx *context) StencilFunc(fn Enum, ref int, mask uint32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.StencilFunc(%v, %v, %v) %v", fn, ref, mask, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnStencilFunc, + a0: fn.c(), + a1: uintptr(ref), + a2: uintptr(mask), + }, + blocking: true}) +} + +func (ctx *context) StencilFuncSeparate(face, fn Enum, ref int, mask uint32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.StencilFuncSeparate(%v, %v, %v, %v) %v", face, fn, ref, mask, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnStencilFuncSeparate, + a0: face.c(), + a1: fn.c(), + a2: uintptr(ref), + a3: uintptr(mask), + }, + blocking: true}) +} + +func (ctx *context) StencilMask(mask uint32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.StencilMask(%v) %v", mask, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnStencilMask, + a0: uintptr(mask), + }, + blocking: true}) +} + +func (ctx *context) StencilMaskSeparate(face Enum, mask uint32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.StencilMaskSeparate(%v, %v) %v", face, mask, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnStencilMaskSeparate, + a0: face.c(), + a1: uintptr(mask), + }, + blocking: true}) +} + +func (ctx *context) StencilOp(fail, zfail, zpass Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.StencilOp(%v, %v, %v) %v", fail, zfail, zpass, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnStencilOp, + a0: fail.c(), + a1: zfail.c(), + a2: zpass.c(), + }, + blocking: true}) +} + +func (ctx *context) StencilOpSeparate(face, sfail, dpfail, dppass Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.StencilOpSeparate(%v, %v, %v, %v) %v", face, sfail, dpfail, dppass, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnStencilOpSeparate, + a0: face.c(), + a1: sfail.c(), + a2: dpfail.c(), + a3: dppass.c(), + }, + blocking: true}) +} + +func (ctx *context) TexImage2D(target Enum, level int, internalFormat int, width, height int, format Enum, ty Enum, data []byte) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.TexImage2D(%v, %v, %v, %v, %v, %v, %v, len(%d)) %v", target, level, internalFormat, width, height, format, ty, len(data), errstr) + }() + parg := unsafe.Pointer(nil) + if len(data) > 0 { + parg = unsafe.Pointer(&data[0]) + } + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnTexImage2D, + + a0: target.c(), + a1: uintptr(level), + a2: uintptr(internalFormat), + a3: uintptr(width), + a4: uintptr(height), + a5: format.c(), + a6: ty.c(), + }, + parg: parg, + blocking: true, + }) +} + +func (ctx *context) TexSubImage2D(target Enum, level int, x, y, width, height int, format, ty Enum, data []byte) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.TexSubImage2D(%v, %v, %v, %v, %v, %v, %v, %v, len(%d)) %v", target, level, x, y, width, height, format, ty, len(data), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnTexSubImage2D, + + a0: target.c(), + a1: uintptr(level), + a2: uintptr(x), + a3: uintptr(y), + a4: uintptr(width), + a5: uintptr(height), + a6: format.c(), + a7: ty.c(), + }, + parg: unsafe.Pointer(&data[0]), + blocking: true, + }) +} + +func (ctx *context) TexParameterf(target, pname Enum, param float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.TexParameterf(%v, %v, %v) %v", target, pname, param, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnTexParameterf, + a0: target.c(), + a1: pname.c(), + a2: uintptr(math.Float32bits(param)), + }, + blocking: true}) +} + +func (ctx *context) TexParameterfv(target, pname Enum, params []float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.TexParameterfv(%v, %v, len(%d)) %v", target, pname, len(params), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnTexParameterfv, + a0: target.c(), + a1: pname.c(), + }, + parg: unsafe.Pointer(¶ms[0]), + blocking: true, + }) +} + +func (ctx *context) TexParameteri(target, pname Enum, param int) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.TexParameteri(%v, %v, %v) %v", target, pname, param, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnTexParameteri, + a0: target.c(), + a1: pname.c(), + a2: uintptr(param), + }, + blocking: true}) +} + +func (ctx *context) TexParameteriv(target, pname Enum, params []int32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.TexParameteriv(%v, %v, %v) %v", target, pname, params, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnTexParameteriv, + a0: target.c(), + a1: pname.c(), + }, + parg: unsafe.Pointer(¶ms[0]), + blocking: true, + }) +} + +func (ctx *context) Uniform1f(dst Uniform, v float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Uniform1f(%v, %v) %v", dst, v, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniform1f, + a0: dst.c(), + a1: uintptr(math.Float32bits(v)), + }, + blocking: true}) +} + +func (ctx *context) Uniform1fv(dst Uniform, src []float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Uniform1fv(%v, len(%d)) %v", dst, len(src), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniform1fv, + a0: dst.c(), + a1: uintptr(len(src)), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) Uniform1i(dst Uniform, v int) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Uniform1i(%v, %v) %v", dst, v, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniform1i, + a0: dst.c(), + a1: uintptr(v), + }, + blocking: true}) +} + +func (ctx *context) Uniform1iv(dst Uniform, src []int32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Uniform1iv(%v, %v) %v", dst, src, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniform1iv, + a0: dst.c(), + a1: uintptr(len(src)), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) Uniform2f(dst Uniform, v0, v1 float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Uniform2f(%v, %v, %v) %v", dst, v0, v1, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniform2f, + a0: dst.c(), + a1: uintptr(math.Float32bits(v0)), + a2: uintptr(math.Float32bits(v1)), + }, + blocking: true}) +} + +func (ctx *context) Uniform2fv(dst Uniform, src []float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Uniform2fv(%v, len(%d)) %v", dst, len(src), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniform2fv, + a0: dst.c(), + a1: uintptr(len(src) / 2), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) Uniform2i(dst Uniform, v0, v1 int) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Uniform2i(%v, %v, %v) %v", dst, v0, v1, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniform2i, + a0: dst.c(), + a1: uintptr(v0), + a2: uintptr(v1), + }, + blocking: true}) +} + +func (ctx *context) Uniform2iv(dst Uniform, src []int32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Uniform2iv(%v, %v) %v", dst, src, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniform2iv, + a0: dst.c(), + a1: uintptr(len(src) / 2), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) Uniform3f(dst Uniform, v0, v1, v2 float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Uniform3f(%v, %v, %v, %v) %v", dst, v0, v1, v2, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniform3f, + a0: dst.c(), + a1: uintptr(math.Float32bits(v0)), + a2: uintptr(math.Float32bits(v1)), + a3: uintptr(math.Float32bits(v2)), + }, + blocking: true}) +} + +func (ctx *context) Uniform3fv(dst Uniform, src []float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Uniform3fv(%v, len(%d)) %v", dst, len(src), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniform3fv, + a0: dst.c(), + a1: uintptr(len(src) / 3), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) Uniform3i(dst Uniform, v0, v1, v2 int32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Uniform3i(%v, %v, %v, %v) %v", dst, v0, v1, v2, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniform3i, + a0: dst.c(), + a1: uintptr(v0), + a2: uintptr(v1), + a3: uintptr(v2), + }, + blocking: true}) +} + +func (ctx *context) Uniform3iv(dst Uniform, src []int32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Uniform3iv(%v, %v) %v", dst, src, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniform3iv, + a0: dst.c(), + a1: uintptr(len(src) / 3), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) Uniform4f(dst Uniform, v0, v1, v2, v3 float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Uniform4f(%v, %v, %v, %v, %v) %v", dst, v0, v1, v2, v3, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniform4f, + a0: dst.c(), + a1: uintptr(math.Float32bits(v0)), + a2: uintptr(math.Float32bits(v1)), + a3: uintptr(math.Float32bits(v2)), + a4: uintptr(math.Float32bits(v3)), + }, + blocking: true}) +} + +func (ctx *context) Uniform4fv(dst Uniform, src []float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Uniform4fv(%v, len(%d)) %v", dst, len(src), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniform4fv, + a0: dst.c(), + a1: uintptr(len(src) / 4), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) Uniform4i(dst Uniform, v0, v1, v2, v3 int32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Uniform4i(%v, %v, %v, %v, %v) %v", dst, v0, v1, v2, v3, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniform4i, + a0: dst.c(), + a1: uintptr(v0), + a2: uintptr(v1), + a3: uintptr(v2), + a4: uintptr(v3), + }, + blocking: true}) +} + +func (ctx *context) Uniform4iv(dst Uniform, src []int32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Uniform4iv(%v, %v) %v", dst, src, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniform4iv, + a0: dst.c(), + a1: uintptr(len(src) / 4), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) UniformMatrix2fv(dst Uniform, src []float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.UniformMatrix2fv(%v, len(%d)) %v", dst, len(src), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniformMatrix2fv, + + a0: dst.c(), + a1: uintptr(len(src) / 4), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) UniformMatrix3fv(dst Uniform, src []float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.UniformMatrix3fv(%v, len(%d)) %v", dst, len(src), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniformMatrix3fv, + a0: dst.c(), + a1: uintptr(len(src) / 9), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) UniformMatrix4fv(dst Uniform, src []float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.UniformMatrix4fv(%v, len(%d)) %v", dst, len(src), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniformMatrix4fv, + a0: dst.c(), + a1: uintptr(len(src) / 16), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) UseProgram(p Program) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.UseProgram(%v) %v", p, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUseProgram, + a0: p.c(), + }, + blocking: true}) +} + +func (ctx *context) ValidateProgram(p Program) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.ValidateProgram(%v) %v", p, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnValidateProgram, + a0: p.c(), + }, + blocking: true}) +} + +func (ctx *context) VertexAttrib1f(dst Attrib, x float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.VertexAttrib1f(%v, %v) %v", dst, x, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnVertexAttrib1f, + a0: dst.c(), + a1: uintptr(math.Float32bits(x)), + }, + blocking: true}) +} + +func (ctx *context) VertexAttrib1fv(dst Attrib, src []float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.VertexAttrib1fv(%v, len(%d)) %v", dst, len(src), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnVertexAttrib1fv, + a0: dst.c(), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) VertexAttrib2f(dst Attrib, x, y float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.VertexAttrib2f(%v, %v, %v) %v", dst, x, y, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnVertexAttrib2f, + a0: dst.c(), + a1: uintptr(math.Float32bits(x)), + a2: uintptr(math.Float32bits(y)), + }, + blocking: true}) +} + +func (ctx *context) VertexAttrib2fv(dst Attrib, src []float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.VertexAttrib2fv(%v, len(%d)) %v", dst, len(src), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnVertexAttrib2fv, + a0: dst.c(), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) VertexAttrib3f(dst Attrib, x, y, z float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.VertexAttrib3f(%v, %v, %v, %v) %v", dst, x, y, z, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnVertexAttrib3f, + a0: dst.c(), + a1: uintptr(math.Float32bits(x)), + a2: uintptr(math.Float32bits(y)), + a3: uintptr(math.Float32bits(z)), + }, + blocking: true}) +} + +func (ctx *context) VertexAttrib3fv(dst Attrib, src []float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.VertexAttrib3fv(%v, len(%d)) %v", dst, len(src), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnVertexAttrib3fv, + a0: dst.c(), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) VertexAttrib4f(dst Attrib, x, y, z, w float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.VertexAttrib4f(%v, %v, %v, %v, %v) %v", dst, x, y, z, w, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnVertexAttrib4f, + a0: dst.c(), + a1: uintptr(math.Float32bits(x)), + a2: uintptr(math.Float32bits(y)), + a3: uintptr(math.Float32bits(z)), + a4: uintptr(math.Float32bits(w)), + }, + blocking: true}) +} + +func (ctx *context) VertexAttrib4fv(dst Attrib, src []float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.VertexAttrib4fv(%v, len(%d)) %v", dst, len(src), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnVertexAttrib4fv, + a0: dst.c(), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx *context) VertexAttribPointer(dst Attrib, size int, ty Enum, normalized bool, stride, offset int) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.VertexAttribPointer(%v, %v, %v, %v, %v, %v) %v", dst, size, ty, normalized, stride, offset, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnVertexAttribPointer, + a0: dst.c(), + a1: uintptr(size), + a2: ty.c(), + a3: glBoolean(normalized), + a4: uintptr(stride), + a5: uintptr(offset), + }, + blocking: true}) +} + +func (ctx *context) Viewport(x, y, width, height int) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Viewport(%v, %v, %v, %v) %v", x, y, width, height, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnViewport, + a0: uintptr(x), + a1: uintptr(y), + a2: uintptr(width), + a3: uintptr(height), + }, + blocking: true}) +} + +func (ctx context3) UniformMatrix2x3fv(dst Uniform, src []float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.UniformMatrix2x3fv(%v, len(%d)) %v", dst, len(src), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniformMatrix2x3fv, + a0: dst.c(), + a1: uintptr(len(src) / 6), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx context3) UniformMatrix3x2fv(dst Uniform, src []float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.UniformMatrix3x2fv(%v, len(%d)) %v", dst, len(src), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniformMatrix3x2fv, + a0: dst.c(), + a1: uintptr(len(src) / 6), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx context3) UniformMatrix2x4fv(dst Uniform, src []float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.UniformMatrix2x4fv(%v, len(%d)) %v", dst, len(src), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniformMatrix2x4fv, + a0: dst.c(), + a1: uintptr(len(src) / 8), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx context3) UniformMatrix4x2fv(dst Uniform, src []float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.UniformMatrix4x2fv(%v, len(%d)) %v", dst, len(src), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniformMatrix4x2fv, + a0: dst.c(), + a1: uintptr(len(src) / 8), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx context3) UniformMatrix3x4fv(dst Uniform, src []float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.UniformMatrix3x4fv(%v, len(%d)) %v", dst, len(src), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniformMatrix3x4fv, + a0: dst.c(), + a1: uintptr(len(src) / 12), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx context3) UniformMatrix4x3fv(dst Uniform, src []float32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.UniformMatrix4x3fv(%v, len(%d)) %v", dst, len(src), errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniformMatrix4x3fv, + a0: dst.c(), + a1: uintptr(len(src) / 12), + }, + parg: unsafe.Pointer(&src[0]), + blocking: true, + }) +} + +func (ctx context3) BlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1 int, mask uint, filter Enum) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.BlitFramebuffer(%v, %v, %v, %v, %v, %v, %v, %v, %v, %v) %v", srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnBlitFramebuffer, + a0: uintptr(srcX0), + a1: uintptr(srcY0), + a2: uintptr(srcX1), + a3: uintptr(srcY1), + a4: uintptr(dstX0), + a5: uintptr(dstY0), + a6: uintptr(dstX1), + a7: uintptr(dstY1), + a8: uintptr(mask), + a9: filter.c(), + }, + blocking: true}) +} + +func (ctx context3) Uniform1ui(dst Uniform, v uint32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Uniform1ui(%v, %v) %v", dst, v, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniform1ui, + a0: dst.c(), + a1: uintptr(v), + }, + blocking: true}) +} + +func (ctx context3) Uniform2ui(dst Uniform, v0, v1 uint32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Uniform2ui(%v, %v, %v) %v", dst, v0, v1, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniform2ui, + a0: dst.c(), + a1: uintptr(v0), + a2: uintptr(v1), + }, + blocking: true}) +} + +func (ctx context3) Uniform3ui(dst Uniform, v0, v1, v2 uint) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Uniform3ui(%v, %v, %v, %v) %v", dst, v0, v1, v2, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniform3ui, + a0: dst.c(), + a1: uintptr(v0), + a2: uintptr(v1), + a3: uintptr(v2), + }, + blocking: true}) +} + +func (ctx context3) Uniform4ui(dst Uniform, v0, v1, v2, v3 uint32) { + defer func() { + errstr := ctx.errDrain() + log.Printf("gl.Uniform4ui(%v, %v, %v, %v, %v) %v", dst, v0, v1, v2, v3, errstr) + }() + ctx.enqueueDebug(call{ + args: fnargs{ + fn: glfnUniform4ui, + a0: dst.c(), + a1: uintptr(v0), + a2: uintptr(v1), + a3: uintptr(v2), + a4: uintptr(v3), + }, + blocking: true}) +} diff --git a/vendor/github.com/ebitengine/gomobile/gl/interface.go b/vendor/github.com/ebitengine/gomobile/gl/interface.go new file mode 100644 index 0000000..1b89dc7 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/gl/interface.go @@ -0,0 +1,889 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gl + +// Context is an OpenGL ES context. +// +// A Context has a method for every GL function supported by ES 2 or later. +// In a program compiled with ES 3 support, a Context is also a Context3. +// For example, a program can: +// +// func f(glctx gl.Context) { +// glctx.(gl.Context3).BlitFramebuffer(...) +// } +// +// Calls are not safe for concurrent use. However calls can be made from +// any goroutine, the gl package removes the notion of thread-local +// context. +// +// Contexts are independent. Two contexts can be used concurrently. +type Context interface { + // ActiveTexture sets the active texture unit. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glActiveTexture.xhtml + ActiveTexture(texture Enum) + + // AttachShader attaches a shader to a program. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glAttachShader.xhtml + AttachShader(p Program, s Shader) + + // BindAttribLocation binds a vertex attribute index with a named + // variable. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glBindAttribLocation.xhtml + BindAttribLocation(p Program, a Attrib, name string) + + // BindBuffer binds a buffer. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glBindBuffer.xhtml + BindBuffer(target Enum, b Buffer) + + // BindFramebuffer binds a framebuffer. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glBindFramebuffer.xhtml + BindFramebuffer(target Enum, fb Framebuffer) + + // BindRenderbuffer binds a render buffer. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glBindRenderbuffer.xhtml + BindRenderbuffer(target Enum, rb Renderbuffer) + + // BindTexture binds a texture. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glBindTexture.xhtml + BindTexture(target Enum, t Texture) + + // BindVertexArray binds a vertex array. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glBindVertexArray.xhtml + BindVertexArray(rb VertexArray) + + // BlendColor sets the blend color. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glBlendColor.xhtml + BlendColor(red, green, blue, alpha float32) + + // BlendEquation sets both RGB and alpha blend equations. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glBlendEquation.xhtml + BlendEquation(mode Enum) + + // BlendEquationSeparate sets RGB and alpha blend equations separately. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glBlendEquationSeparate.xhtml + BlendEquationSeparate(modeRGB, modeAlpha Enum) + + // BlendFunc sets the pixel blending factors. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glBlendFunc.xhtml + BlendFunc(sfactor, dfactor Enum) + + // BlendFunc sets the pixel RGB and alpha blending factors separately. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glBlendFuncSeparate.xhtml + BlendFuncSeparate(sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha Enum) + + // BufferData creates a new data store for the bound buffer object. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glBufferData.xhtml + BufferData(target Enum, src []byte, usage Enum) + + // BufferInit creates a new uninitialized data store for the bound buffer object. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glBufferData.xhtml + BufferInit(target Enum, size int, usage Enum) + + // BufferSubData sets some of data in the bound buffer object. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glBufferSubData.xhtml + BufferSubData(target Enum, offset int, data []byte) + + // CheckFramebufferStatus reports the completeness status of the + // active framebuffer. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glCheckFramebufferStatus.xhtml + CheckFramebufferStatus(target Enum) Enum + + // Clear clears the window. + // + // The behavior of Clear is influenced by the pixel ownership test, + // the scissor test, dithering, and the buffer writemasks. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glClear.xhtml + Clear(mask Enum) + + // ClearColor specifies the RGBA values used to clear color buffers. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glClearColor.xhtml + ClearColor(red, green, blue, alpha float32) + + // ClearDepthf sets the depth value used to clear the depth buffer. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glClearDepthf.xhtml + ClearDepthf(d float32) + + // ClearStencil sets the index used to clear the stencil buffer. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glClearStencil.xhtml + ClearStencil(s int) + + // ColorMask specifies whether color components in the framebuffer + // can be written. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glColorMask.xhtml + ColorMask(red, green, blue, alpha bool) + + // CompileShader compiles the source code of s. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glCompileShader.xhtml + CompileShader(s Shader) + + // CompressedTexImage2D writes a compressed 2D texture. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glCompressedTexImage2D.xhtml + CompressedTexImage2D(target Enum, level int, internalformat Enum, width, height, border int, data []byte) + + // CompressedTexSubImage2D writes a subregion of a compressed 2D texture. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glCompressedTexSubImage2D.xhtml + CompressedTexSubImage2D(target Enum, level, xoffset, yoffset, width, height int, format Enum, data []byte) + + // CopyTexImage2D writes a 2D texture from the current framebuffer. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glCopyTexImage2D.xhtml + CopyTexImage2D(target Enum, level int, internalformat Enum, x, y, width, height, border int) + + // CopyTexSubImage2D writes a 2D texture subregion from the + // current framebuffer. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glCopyTexSubImage2D.xhtml + CopyTexSubImage2D(target Enum, level, xoffset, yoffset, x, y, width, height int) + + // CreateBuffer creates a buffer object. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGenBuffers.xhtml + CreateBuffer() Buffer + + // CreateFramebuffer creates a framebuffer object. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGenFramebuffers.xhtml + CreateFramebuffer() Framebuffer + + // CreateProgram creates a new empty program object. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glCreateProgram.xhtml + CreateProgram() Program + + // CreateRenderbuffer create a renderbuffer object. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGenRenderbuffers.xhtml + CreateRenderbuffer() Renderbuffer + + // CreateShader creates a new empty shader object. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glCreateShader.xhtml + CreateShader(ty Enum) Shader + + // CreateTexture creates a texture object. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGenTextures.xhtml + CreateTexture() Texture + + // CreateTVertexArray creates a vertex array. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGenVertexArrays.xhtml + CreateVertexArray() VertexArray + + // CullFace specifies which polygons are candidates for culling. + // + // Valid modes: FRONT, BACK, FRONT_AND_BACK. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glCullFace.xhtml + CullFace(mode Enum) + + // DeleteBuffer deletes the given buffer object. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glDeleteBuffers.xhtml + DeleteBuffer(v Buffer) + + // DeleteFramebuffer deletes the given framebuffer object. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glDeleteFramebuffers.xhtml + DeleteFramebuffer(v Framebuffer) + + // DeleteProgram deletes the given program object. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glDeleteProgram.xhtml + DeleteProgram(p Program) + + // DeleteRenderbuffer deletes the given render buffer object. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glDeleteRenderbuffers.xhtml + DeleteRenderbuffer(v Renderbuffer) + + // DeleteShader deletes shader s. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glDeleteShader.xhtml + DeleteShader(s Shader) + + // DeleteTexture deletes the given texture object. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glDeleteTextures.xhtml + DeleteTexture(v Texture) + + // DeleteVertexArray deletes the given render buffer object. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glDeleteVertexArrays.xhtml + DeleteVertexArray(v VertexArray) + + // DepthFunc sets the function used for depth buffer comparisons. + // + // Valid fn values: + // NEVER + // LESS + // EQUAL + // LEQUAL + // GREATER + // NOTEQUAL + // GEQUAL + // ALWAYS + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glDepthFunc.xhtml + DepthFunc(fn Enum) + + // DepthMask sets the depth buffer enabled for writing. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glDepthMask.xhtml + DepthMask(flag bool) + + // DepthRangef sets the mapping from normalized device coordinates to + // window coordinates. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glDepthRangef.xhtml + DepthRangef(n, f float32) + + // DetachShader detaches the shader s from the program p. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glDetachShader.xhtml + DetachShader(p Program, s Shader) + + // Disable disables various GL capabilities. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glDisable.xhtml + Disable(cap Enum) + + // DisableVertexAttribArray disables a vertex attribute array. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glDisableVertexAttribArray.xhtml + DisableVertexAttribArray(a Attrib) + + // DrawArrays renders geometric primitives from the bound data. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glDrawArrays.xhtml + DrawArrays(mode Enum, first, count int) + + // DrawElements renders primitives from a bound buffer. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glDrawElements.xhtml + DrawElements(mode Enum, count int, ty Enum, offset int) + + // TODO(crawshaw): consider DrawElements8 / DrawElements16 / DrawElements32 + + // Enable enables various GL capabilities. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glEnable.xhtml + Enable(cap Enum) + + // EnableVertexAttribArray enables a vertex attribute array. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glEnableVertexAttribArray.xhtml + EnableVertexAttribArray(a Attrib) + + // Finish blocks until the effects of all previously called GL + // commands are complete. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glFinish.xhtml + Finish() + + // Flush empties all buffers. It does not block. + // + // An OpenGL implementation may buffer network communication, + // the command stream, or data inside the graphics accelerator. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glFlush.xhtml + Flush() + + // FramebufferRenderbuffer attaches rb to the current frame buffer. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glFramebufferRenderbuffer.xhtml + FramebufferRenderbuffer(target, attachment, rbTarget Enum, rb Renderbuffer) + + // FramebufferTexture2D attaches the t to the current frame buffer. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glFramebufferTexture2D.xhtml + FramebufferTexture2D(target, attachment, texTarget Enum, t Texture, level int) + + // FrontFace defines which polygons are front-facing. + // + // Valid modes: CW, CCW. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glFrontFace.xhtml + FrontFace(mode Enum) + + // GenerateMipmap generates mipmaps for the current texture. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGenerateMipmap.xhtml + GenerateMipmap(target Enum) + + // GetActiveAttrib returns details about an active attribute variable. + // A value of 0 for index selects the first active attribute variable. + // Permissible values for index range from 0 to the number of active + // attribute variables minus 1. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetActiveAttrib.xhtml + GetActiveAttrib(p Program, index uint32) (name string, size int, ty Enum) + + // GetActiveUniform returns details about an active uniform variable. + // A value of 0 for index selects the first active uniform variable. + // Permissible values for index range from 0 to the number of active + // uniform variables minus 1. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetActiveUniform.xhtml + GetActiveUniform(p Program, index uint32) (name string, size int, ty Enum) + + // GetAttachedShaders returns the shader objects attached to program p. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetAttachedShaders.xhtml + GetAttachedShaders(p Program) []Shader + + // GetAttribLocation returns the location of an attribute variable. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetAttribLocation.xhtml + GetAttribLocation(p Program, name string) Attrib + + // GetBooleanv returns the boolean values of parameter pname. + // + // Many boolean parameters can be queried more easily using IsEnabled. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGet.xhtml + GetBooleanv(dst []bool, pname Enum) + + // GetFloatv returns the float values of parameter pname. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGet.xhtml + GetFloatv(dst []float32, pname Enum) + + // GetIntegerv returns the int values of parameter pname. + // + // Single values may be queried more easily using GetInteger. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGet.xhtml + GetIntegerv(dst []int32, pname Enum) + + // GetInteger returns the int value of parameter pname. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGet.xhtml + GetInteger(pname Enum) int + + // GetBufferParameteri returns a parameter for the active buffer. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetBufferParameter.xhtml + GetBufferParameteri(target, value Enum) int + + // GetError returns the next error. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetError.xhtml + GetError() Enum + + // GetFramebufferAttachmentParameteri returns attachment parameters + // for the active framebuffer object. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetFramebufferAttachmentParameteriv.xhtml + GetFramebufferAttachmentParameteri(target, attachment, pname Enum) int + + // GetProgrami returns a parameter value for a program. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetProgramiv.xhtml + GetProgrami(p Program, pname Enum) int + + // GetProgramInfoLog returns the information log for a program. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetProgramInfoLog.xhtml + GetProgramInfoLog(p Program) string + + // GetRenderbufferParameteri returns a parameter value for a render buffer. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetRenderbufferParameteriv.xhtml + GetRenderbufferParameteri(target, pname Enum) int + + // GetShaderi returns a parameter value for a shader. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetShaderiv.xhtml + GetShaderi(s Shader, pname Enum) int + + // GetShaderInfoLog returns the information log for a shader. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetShaderInfoLog.xhtml + GetShaderInfoLog(s Shader) string + + // GetShaderPrecisionFormat returns range and precision limits for + // shader types. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetShaderPrecisionFormat.xhtml + GetShaderPrecisionFormat(shadertype, precisiontype Enum) (rangeLow, rangeHigh, precision int) + + // GetShaderSource returns source code of shader s. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetShaderSource.xhtml + GetShaderSource(s Shader) string + + // GetString reports current GL state. + // + // Valid name values: + // EXTENSIONS + // RENDERER + // SHADING_LANGUAGE_VERSION + // VENDOR + // VERSION + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetString.xhtml + GetString(pname Enum) string + + // GetTexParameterfv returns the float values of a texture parameter. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetTexParameter.xhtml + GetTexParameterfv(dst []float32, target, pname Enum) + + // GetTexParameteriv returns the int values of a texture parameter. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetTexParameter.xhtml + GetTexParameteriv(dst []int32, target, pname Enum) + + // GetUniformfv returns the float values of a uniform variable. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetUniform.xhtml + GetUniformfv(dst []float32, src Uniform, p Program) + + // GetUniformiv returns the float values of a uniform variable. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetUniform.xhtml + GetUniformiv(dst []int32, src Uniform, p Program) + + // GetUniformLocation returns the location of a uniform variable. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetUniformLocation.xhtml + GetUniformLocation(p Program, name string) Uniform + + // GetVertexAttribf reads the float value of a vertex attribute. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetVertexAttrib.xhtml + GetVertexAttribf(src Attrib, pname Enum) float32 + + // GetVertexAttribfv reads float values of a vertex attribute. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetVertexAttrib.xhtml + GetVertexAttribfv(dst []float32, src Attrib, pname Enum) + + // GetVertexAttribi reads the int value of a vertex attribute. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetVertexAttrib.xhtml + GetVertexAttribi(src Attrib, pname Enum) int32 + + // GetVertexAttribiv reads int values of a vertex attribute. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glGetVertexAttrib.xhtml + GetVertexAttribiv(dst []int32, src Attrib, pname Enum) + + // TODO(crawshaw): glGetVertexAttribPointerv + + // Hint sets implementation-specific modes. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glHint.xhtml + Hint(target, mode Enum) + + // IsBuffer reports if b is a valid buffer. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glIsBuffer.xhtml + IsBuffer(b Buffer) bool + + // IsEnabled reports if cap is an enabled capability. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glIsEnabled.xhtml + IsEnabled(cap Enum) bool + + // IsFramebuffer reports if fb is a valid frame buffer. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glIsFramebuffer.xhtml + IsFramebuffer(fb Framebuffer) bool + + // IsProgram reports if p is a valid program object. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glIsProgram.xhtml + IsProgram(p Program) bool + + // IsRenderbuffer reports if rb is a valid render buffer. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glIsRenderbuffer.xhtml + IsRenderbuffer(rb Renderbuffer) bool + + // IsShader reports if s is valid shader. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glIsShader.xhtml + IsShader(s Shader) bool + + // IsTexture reports if t is a valid texture. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glIsTexture.xhtml + IsTexture(t Texture) bool + + // LineWidth specifies the width of lines. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glLineWidth.xhtml + LineWidth(width float32) + + // LinkProgram links the specified program. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glLinkProgram.xhtml + LinkProgram(p Program) + + // PixelStorei sets pixel storage parameters. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glPixelStorei.xhtml + PixelStorei(pname Enum, param int32) + + // PolygonOffset sets the scaling factors for depth offsets. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glPolygonOffset.xhtml + PolygonOffset(factor, units float32) + + // ReadPixels returns pixel data from a buffer. + // + // In GLES 3, the source buffer is controlled with ReadBuffer. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glReadPixels.xhtml + ReadPixels(dst []byte, x, y, width, height int, format, ty Enum) + + // ReleaseShaderCompiler frees resources allocated by the shader compiler. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glReleaseShaderCompiler.xhtml + ReleaseShaderCompiler() + + // RenderbufferStorage establishes the data storage, format, and + // dimensions of a renderbuffer object's image. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glRenderbufferStorage.xhtml + RenderbufferStorage(target, internalFormat Enum, width, height int) + + // SampleCoverage sets multisample coverage parameters. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glSampleCoverage.xhtml + SampleCoverage(value float32, invert bool) + + // Scissor defines the scissor box rectangle, in window coordinates. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glScissor.xhtml + Scissor(x, y, width, height int32) + + // TODO(crawshaw): ShaderBinary + + // ShaderSource sets the source code of s to the given source code. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glShaderSource.xhtml + ShaderSource(s Shader, src string) + + // StencilFunc sets the front and back stencil test reference value. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glStencilFunc.xhtml + StencilFunc(fn Enum, ref int, mask uint32) + + // StencilFunc sets the front or back stencil test reference value. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glStencilFuncSeparate.xhtml + StencilFuncSeparate(face, fn Enum, ref int, mask uint32) + + // StencilMask controls the writing of bits in the stencil planes. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glStencilMask.xhtml + StencilMask(mask uint32) + + // StencilMaskSeparate controls the writing of bits in the stencil planes. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glStencilMaskSeparate.xhtml + StencilMaskSeparate(face Enum, mask uint32) + + // StencilOp sets front and back stencil test actions. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glStencilOp.xhtml + StencilOp(fail, zfail, zpass Enum) + + // StencilOpSeparate sets front or back stencil tests. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glStencilOpSeparate.xhtml + StencilOpSeparate(face, sfail, dpfail, dppass Enum) + + // TexImage2D writes a 2D texture image. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glTexImage2D.xhtml + TexImage2D(target Enum, level int, internalFormat int, width, height int, format Enum, ty Enum, data []byte) + + // TexSubImage2D writes a subregion of a 2D texture image. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glTexSubImage2D.xhtml + TexSubImage2D(target Enum, level int, x, y, width, height int, format, ty Enum, data []byte) + + // TexParameterf sets a float texture parameter. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glTexParameter.xhtml + TexParameterf(target, pname Enum, param float32) + + // TexParameterfv sets a float texture parameter array. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glTexParameter.xhtml + TexParameterfv(target, pname Enum, params []float32) + + // TexParameteri sets an integer texture parameter. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glTexParameter.xhtml + TexParameteri(target, pname Enum, param int) + + // TexParameteriv sets an integer texture parameter array. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glTexParameter.xhtml + TexParameteriv(target, pname Enum, params []int32) + + // Uniform1f writes a float uniform variable. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glUniform.xhtml + Uniform1f(dst Uniform, v float32) + + // Uniform1fv writes a [len(src)]float uniform array. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glUniform.xhtml + Uniform1fv(dst Uniform, src []float32) + + // Uniform1i writes an int uniform variable. + // + // Uniform1i and Uniform1iv are the only two functions that may be used + // to load uniform variables defined as sampler types. Loading samplers + // with any other function will result in a INVALID_OPERATION error. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glUniform.xhtml + Uniform1i(dst Uniform, v int) + + // Uniform1iv writes a int uniform array of len(src) elements. + // + // Uniform1i and Uniform1iv are the only two functions that may be used + // to load uniform variables defined as sampler types. Loading samplers + // with any other function will result in a INVALID_OPERATION error. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glUniform.xhtml + Uniform1iv(dst Uniform, src []int32) + + // Uniform2f writes a vec2 uniform variable. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glUniform.xhtml + Uniform2f(dst Uniform, v0, v1 float32) + + // Uniform2fv writes a vec2 uniform array of len(src)/2 elements. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glUniform.xhtml + Uniform2fv(dst Uniform, src []float32) + + // Uniform2i writes an ivec2 uniform variable. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glUniform.xhtml + Uniform2i(dst Uniform, v0, v1 int) + + // Uniform2iv writes an ivec2 uniform array of len(src)/2 elements. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glUniform.xhtml + Uniform2iv(dst Uniform, src []int32) + + // Uniform3f writes a vec3 uniform variable. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glUniform.xhtml + Uniform3f(dst Uniform, v0, v1, v2 float32) + + // Uniform3fv writes a vec3 uniform array of len(src)/3 elements. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glUniform.xhtml + Uniform3fv(dst Uniform, src []float32) + + // Uniform3i writes an ivec3 uniform variable. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glUniform.xhtml + Uniform3i(dst Uniform, v0, v1, v2 int32) + + // Uniform3iv writes an ivec3 uniform array of len(src)/3 elements. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glUniform.xhtml + Uniform3iv(dst Uniform, src []int32) + + // Uniform4f writes a vec4 uniform variable. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glUniform.xhtml + Uniform4f(dst Uniform, v0, v1, v2, v3 float32) + + // Uniform4fv writes a vec4 uniform array of len(src)/4 elements. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glUniform.xhtml + Uniform4fv(dst Uniform, src []float32) + + // Uniform4i writes an ivec4 uniform variable. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glUniform.xhtml + Uniform4i(dst Uniform, v0, v1, v2, v3 int32) + + // Uniform4i writes an ivec4 uniform array of len(src)/4 elements. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glUniform.xhtml + Uniform4iv(dst Uniform, src []int32) + + // UniformMatrix2fv writes 2x2 matrices. Each matrix uses four + // float32 values, so the number of matrices written is len(src)/4. + // + // Each matrix must be supplied in column major order. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glUniform.xhtml + UniformMatrix2fv(dst Uniform, src []float32) + + // UniformMatrix3fv writes 3x3 matrices. Each matrix uses nine + // float32 values, so the number of matrices written is len(src)/9. + // + // Each matrix must be supplied in column major order. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glUniform.xhtml + UniformMatrix3fv(dst Uniform, src []float32) + + // UniformMatrix4fv writes 4x4 matrices. Each matrix uses 16 + // float32 values, so the number of matrices written is len(src)/16. + // + // Each matrix must be supplied in column major order. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glUniform.xhtml + UniformMatrix4fv(dst Uniform, src []float32) + + // UseProgram sets the active program. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glUseProgram.xhtml + UseProgram(p Program) + + // ValidateProgram checks to see whether the executables contained in + // program can execute given the current OpenGL state. + // + // Typically only used for debugging. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glValidateProgram.xhtml + ValidateProgram(p Program) + + // VertexAttrib1f writes a float vertex attribute. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glVertexAttrib.xhtml + VertexAttrib1f(dst Attrib, x float32) + + // VertexAttrib1fv writes a float vertex attribute. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glVertexAttrib.xhtml + VertexAttrib1fv(dst Attrib, src []float32) + + // VertexAttrib2f writes a vec2 vertex attribute. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glVertexAttrib.xhtml + VertexAttrib2f(dst Attrib, x, y float32) + + // VertexAttrib2fv writes a vec2 vertex attribute. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glVertexAttrib.xhtml + VertexAttrib2fv(dst Attrib, src []float32) + + // VertexAttrib3f writes a vec3 vertex attribute. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glVertexAttrib.xhtml + VertexAttrib3f(dst Attrib, x, y, z float32) + + // VertexAttrib3fv writes a vec3 vertex attribute. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glVertexAttrib.xhtml + VertexAttrib3fv(dst Attrib, src []float32) + + // VertexAttrib4f writes a vec4 vertex attribute. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glVertexAttrib.xhtml + VertexAttrib4f(dst Attrib, x, y, z, w float32) + + // VertexAttrib4fv writes a vec4 vertex attribute. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glVertexAttrib.xhtml + VertexAttrib4fv(dst Attrib, src []float32) + + // VertexAttribPointer uses a bound buffer to define vertex attribute data. + // + // Direct use of VertexAttribPointer to load data into OpenGL is not + // supported via the Go bindings. Instead, use BindBuffer with an + // ARRAY_BUFFER and then fill it using BufferData. + // + // The size argument specifies the number of components per attribute, + // between 1-4. The stride argument specifies the byte offset between + // consecutive vertex attributes. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glVertexAttribPointer.xhtml + VertexAttribPointer(dst Attrib, size int, ty Enum, normalized bool, stride, offset int) + + // Viewport sets the viewport, an affine transformation that + // normalizes device coordinates to window coordinates. + // + // http://www.khronos.org/opengles/sdk/docs/man3/html/glViewport.xhtml + Viewport(x, y, width, height int) +} + +// Context3 is an OpenGL ES 3 context. +// +// When the gl package is compiled with GL ES 3 support, the produced +// Context object also implements the Context3 interface. +type Context3 interface { + Context + + // BlitFramebuffer copies a block of pixels between framebuffers. + // + // https://www.khronos.org/opengles/sdk/docs/man3/html/glBlitFramebuffer.xhtml + BlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1 int, mask uint, filter Enum) +} + +// Worker is used by display driver code to execute OpenGL calls. +// +// Typically display driver code creates a gl.Context for an application, +// and along with it establishes a locked OS thread to execute the cgo +// calls: +// +// go func() { +// runtime.LockOSThread() +// // ... platform-specific cgo call to bind a C OpenGL context +// // into thread-local storage. +// +// glctx, worker := gl.NewContext() +// workAvailable := worker.WorkAvailable() +// go userAppCode(glctx) +// for { +// select { +// case <-workAvailable: +// worker.DoWork() +// case <-drawEvent: +// // ... platform-specific cgo call to draw screen +// } +// } +// }() +// +// This interface is an internal implementation detail and should only be used +// by the package responsible for managing the screen, such as +// github.com/ebitengine/gomobile/app. +type Worker interface { + // WorkAvailable returns a channel that communicates when DoWork should be + // called. + WorkAvailable() <-chan struct{} + + // DoWork performs any pending OpenGL calls. + DoWork() +} diff --git a/vendor/github.com/ebitengine/gomobile/gl/types_debug.go b/vendor/github.com/ebitengine/gomobile/gl/types_debug.go new file mode 100644 index 0000000..ea01170 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/gl/types_debug.go @@ -0,0 +1,81 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build (darwin || linux || openbsd || windows) && gldebug + +package gl + +// Alternate versions of the types defined in types.go with extra +// debugging information attached. For documentation, see types.go. + +import "fmt" + +type Enum uint32 + +type Attrib struct { + Value uint + name string +} + +type Program struct { + Init bool + Value uint32 +} + +type Shader struct { + Value uint32 +} + +type Buffer struct { + Value uint32 +} + +type Framebuffer struct { + Value uint32 +} + +type Renderbuffer struct { + Value uint32 +} + +type Texture struct { + Value uint32 +} + +type Uniform struct { + Value int32 + name string +} + +type VertexArray struct { + Value uint32 +} + +func (v Attrib) c() uintptr { return uintptr(v.Value) } +func (v Enum) c() uintptr { return uintptr(v) } +func (v Program) c() uintptr { + if !v.Init { + ret := uintptr(0) + ret-- + return ret + } + return uintptr(v.Value) +} +func (v Shader) c() uintptr { return uintptr(v.Value) } +func (v Buffer) c() uintptr { return uintptr(v.Value) } +func (v Framebuffer) c() uintptr { return uintptr(v.Value) } +func (v Renderbuffer) c() uintptr { return uintptr(v.Value) } +func (v Texture) c() uintptr { return uintptr(v.Value) } +func (v Uniform) c() uintptr { return uintptr(v.Value) } +func (v VertexArray) c() uintptr { return uintptr(v.Value) } + +func (v Attrib) String() string { return fmt.Sprintf("Attrib(%d:%s)", v.Value, v.name) } +func (v Program) String() string { return fmt.Sprintf("Program(%d)", v.Value) } +func (v Shader) String() string { return fmt.Sprintf("Shader(%d)", v.Value) } +func (v Buffer) String() string { return fmt.Sprintf("Buffer(%d)", v.Value) } +func (v Framebuffer) String() string { return fmt.Sprintf("Framebuffer(%d)", v.Value) } +func (v Renderbuffer) String() string { return fmt.Sprintf("Renderbuffer(%d)", v.Value) } +func (v Texture) String() string { return fmt.Sprintf("Texture(%d)", v.Value) } +func (v Uniform) String() string { return fmt.Sprintf("Uniform(%d:%s)", v.Value, v.name) } +func (v VertexArray) String() string { return fmt.Sprintf("VertexArray(%d)", v.Value) } diff --git a/vendor/github.com/ebitengine/gomobile/gl/types_prod.go b/vendor/github.com/ebitengine/gomobile/gl/types_prod.go new file mode 100644 index 0000000..f87f91f --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/gl/types_prod.go @@ -0,0 +1,92 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build (darwin || linux || openbsd || windows) && !gldebug + +package gl + +import "fmt" + +// Enum is equivalent to GLenum, and is normally used with one of the +// constants defined in this package. +type Enum uint32 + +// Types are defined a structs so that in debug mode they can carry +// extra information, such as a string name. See typesdebug.go. + +// Attrib identifies the location of a specific attribute variable. +type Attrib struct { + Value uint +} + +// Program identifies a compiled shader program. +type Program struct { + // Init is set by CreateProgram, as some GL drivers (in particular, + // ANGLE) return true for glIsProgram(0). + Init bool + Value uint32 +} + +// Shader identifies a GLSL shader. +type Shader struct { + Value uint32 +} + +// Buffer identifies a GL buffer object. +type Buffer struct { + Value uint32 +} + +// Framebuffer identifies a GL framebuffer. +type Framebuffer struct { + Value uint32 +} + +// A Renderbuffer is a GL object that holds an image in an internal format. +type Renderbuffer struct { + Value uint32 +} + +// A Texture identifies a GL texture unit. +type Texture struct { + Value uint32 +} + +// Uniform identifies the location of a specific uniform variable. +type Uniform struct { + Value int32 +} + +// A VertexArray is a GL object that holds vertices in an internal format. +type VertexArray struct { + Value uint32 +} + +func (v Attrib) c() uintptr { return uintptr(v.Value) } +func (v Enum) c() uintptr { return uintptr(v) } +func (v Program) c() uintptr { + if !v.Init { + ret := uintptr(0) + ret-- + return ret + } + return uintptr(v.Value) +} +func (v Shader) c() uintptr { return uintptr(v.Value) } +func (v Buffer) c() uintptr { return uintptr(v.Value) } +func (v Framebuffer) c() uintptr { return uintptr(v.Value) } +func (v Renderbuffer) c() uintptr { return uintptr(v.Value) } +func (v Texture) c() uintptr { return uintptr(v.Value) } +func (v Uniform) c() uintptr { return uintptr(v.Value) } +func (v VertexArray) c() uintptr { return uintptr(v.Value) } + +func (v Attrib) String() string { return fmt.Sprintf("Attrib(%d)", v.Value) } +func (v Program) String() string { return fmt.Sprintf("Program(%d)", v.Value) } +func (v Shader) String() string { return fmt.Sprintf("Shader(%d)", v.Value) } +func (v Buffer) String() string { return fmt.Sprintf("Buffer(%d)", v.Value) } +func (v Framebuffer) String() string { return fmt.Sprintf("Framebuffer(%d)", v.Value) } +func (v Renderbuffer) String() string { return fmt.Sprintf("Renderbuffer(%d)", v.Value) } +func (v Texture) String() string { return fmt.Sprintf("Texture(%d)", v.Value) } +func (v Uniform) String() string { return fmt.Sprintf("Uniform(%d)", v.Value) } +func (v VertexArray) String() string { return fmt.Sprintf("VertexArray(%d)", v.Value) } diff --git a/vendor/github.com/ebitengine/gomobile/gl/work.c b/vendor/github.com/ebitengine/gomobile/gl/work.c new file mode 100644 index 0000000..605e0ba --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/gl/work.c @@ -0,0 +1,557 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build darwin || linux || openbsd +// +build darwin linux openbsd + +#include +#include "_cgo_export.h" +#include "work.h" + +#if defined(GL_ES_VERSION_3_0) && GL_ES_VERSION_3_0 +#else +#include +static void gles3missing() { + printf("GLES3 function is missing\n"); + exit(2); +} +static void glUniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) { gles3missing(); } +static void glUniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) { gles3missing(); } +static void glUniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) { gles3missing(); } +static void glUniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) { gles3missing(); } +static void glUniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) { gles3missing(); } +static void glUniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) { gles3missing(); } +static void glBlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) { gles3missing(); } +static void glUniform1ui(GLint location, GLuint v0) { gles3missing(); } +static void glUniform2ui(GLint location, GLuint v0, GLuint v1) { gles3missing(); } +static void glUniform3ui(GLint location, GLuint v0, GLuint v1, GLuint v2) { gles3missing(); } +static void glUniform4ui(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3) { gles3missing(); } +static void glUniform1uiv(GLint location, GLsizei count, const GLuint *value) { gles3missing(); } +static void glUniform2uiv(GLint location, GLsizei count, const GLuint *value) { gles3missing(); } +static void glUniform3uiv(GLint location, GLsizei count, const GLuint *value) { gles3missing(); } +static void glUniform4uiv(GLint location, GLsizei count, const GLuint *value) { gles3missing(); } +static void glBindVertexArray(GLuint array) { gles3missing(); } +static void glGenVertexArrays(GLsizei n, GLuint *arrays) { gles3missing(); } +static void glDeleteVertexArrays(GLsizei n, const GLuint *arrays) { gles3missing(); } +#endif + +uintptr_t processFn(struct fnargs* args, char* parg) { + uintptr_t ret = 0; + switch (args->fn) { + case glfnUNDEFINED: + abort(); // bad glfn + break; + case glfnActiveTexture: + glActiveTexture((GLenum)args->a0); + break; + case glfnAttachShader: + glAttachShader((GLint)args->a0, (GLint)args->a1); + break; + case glfnBindAttribLocation: + glBindAttribLocation((GLint)args->a0, (GLint)args->a1, (GLchar*)args->a2); + break; + case glfnBindBuffer: + glBindBuffer((GLenum)args->a0, (GLuint)args->a1); + break; + case glfnBindFramebuffer: + glBindFramebuffer((GLenum)args->a0, (GLint)args->a1); + break; + case glfnBindRenderbuffer: + glBindRenderbuffer((GLenum)args->a0, (GLint)args->a1); + break; + case glfnBindTexture: + glBindTexture((GLenum)args->a0, (GLint)args->a1); + break; + case glfnBindVertexArray: + glBindVertexArray((GLenum)args->a0); + break; + case glfnBlendColor: + glBlendColor(*(GLfloat*)&args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2, *(GLfloat*)&args->a3); + break; + case glfnBlendEquation: + glBlendEquation((GLenum)args->a0); + break; + case glfnBlendEquationSeparate: + glBlendEquationSeparate((GLenum)args->a0, (GLenum)args->a1); + break; + case glfnBlendFunc: + glBlendFunc((GLenum)args->a0, (GLenum)args->a1); + break; + case glfnBlendFuncSeparate: + glBlendFuncSeparate((GLenum)args->a0, (GLenum)args->a1, (GLenum)args->a2, (GLenum)args->a3); + break; + case glfnBlitFramebuffer: + glBlitFramebuffer((GLint)args->a0, (GLint)args->a1, (GLint)args->a2, (GLint)args->a3, (GLint)args->a4, (GLint)args->a5, (GLint)args->a6, (GLint)args->a7, (GLbitfield)args->a8, (GLenum)args->a9); + break; + case glfnBufferData: + glBufferData((GLenum)args->a0, (GLsizeiptr)args->a1, (GLvoid*)parg, (GLenum)args->a2); + break; + case glfnBufferSubData: + glBufferSubData((GLenum)args->a0, (GLint)args->a1, (GLsizeiptr)args->a2, (GLvoid*)parg); + break; + case glfnCheckFramebufferStatus: + ret = glCheckFramebufferStatus((GLenum)args->a0); + break; + case glfnClear: + glClear((GLenum)args->a0); + break; + case glfnClearColor: + glClearColor(*(GLfloat*)&args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2, *(GLfloat*)&args->a3); + break; + case glfnClearDepthf: + glClearDepthf(*(GLfloat*)&args->a0); + break; + case glfnClearStencil: + glClearStencil((GLint)args->a0); + break; + case glfnColorMask: + glColorMask((GLboolean)args->a0, (GLboolean)args->a1, (GLboolean)args->a2, (GLboolean)args->a3); + break; + case glfnCompileShader: + glCompileShader((GLint)args->a0); + break; + case glfnCompressedTexImage2D: + glCompressedTexImage2D((GLenum)args->a0, (GLint)args->a1, (GLenum)args->a2, (GLint)args->a3, (GLint)args->a4, (GLint)args->a5, (GLsizeiptr)args->a6, (GLvoid*)parg); + break; + case glfnCompressedTexSubImage2D: + glCompressedTexSubImage2D((GLenum)args->a0, (GLint)args->a1, (GLint)args->a2, (GLint)args->a3, (GLint)args->a4, (GLint)args->a5, (GLenum)args->a6, (GLsizeiptr)args->a7, (GLvoid*)parg); + break; + case glfnCopyTexImage2D: + glCopyTexImage2D((GLenum)args->a0, (GLint)args->a1, (GLenum)args->a2, (GLint)args->a3, (GLint)args->a4, (GLint)args->a5, (GLint)args->a6, (GLint)args->a7); + break; + case glfnCopyTexSubImage2D: + glCopyTexSubImage2D((GLenum)args->a0, (GLint)args->a1, (GLint)args->a2, (GLint)args->a3, (GLint)args->a4, (GLint)args->a5, (GLint)args->a6, (GLint)args->a7); + break; + case glfnCreateProgram: + ret = glCreateProgram(); + break; + case glfnCreateShader: + ret = glCreateShader((GLenum)args->a0); + break; + case glfnCullFace: + glCullFace((GLenum)args->a0); + break; + case glfnDeleteBuffer: + glDeleteBuffers(1, (const GLuint*)(&args->a0)); + break; + case glfnDeleteFramebuffer: + glDeleteFramebuffers(1, (const GLuint*)(&args->a0)); + break; + case glfnDeleteProgram: + glDeleteProgram((GLint)args->a0); + break; + case glfnDeleteRenderbuffer: + glDeleteRenderbuffers(1, (const GLuint*)(&args->a0)); + break; + case glfnDeleteShader: + glDeleteShader((GLint)args->a0); + break; + case glfnDeleteTexture: + glDeleteTextures(1, (const GLuint*)(&args->a0)); + break; + case glfnDeleteVertexArray: + glDeleteVertexArrays(1, (const GLuint*)(&args->a0)); + break; + case glfnDepthFunc: + glDepthFunc((GLenum)args->a0); + break; + case glfnDepthMask: + glDepthMask((GLboolean)args->a0); + break; + case glfnDepthRangef: + glDepthRangef(*(GLfloat*)&args->a0, *(GLfloat*)&args->a1); + break; + case glfnDetachShader: + glDetachShader((GLint)args->a0, (GLint)args->a1); + break; + case glfnDisable: + glDisable((GLenum)args->a0); + break; + case glfnDisableVertexAttribArray: + glDisableVertexAttribArray((GLint)args->a0); + break; + case glfnDrawArrays: + glDrawArrays((GLenum)args->a0, (GLint)args->a1, (GLint)args->a2); + break; + case glfnDrawElements: + glDrawElements((GLenum)args->a0, (GLint)args->a1, (GLenum)args->a2, (void*)args->a3); + break; + case glfnEnable: + glEnable((GLenum)args->a0); + break; + case glfnEnableVertexAttribArray: + glEnableVertexAttribArray((GLint)args->a0); + break; + case glfnFinish: + glFinish(); + break; + case glfnFlush: + glFlush(); + break; + case glfnFramebufferRenderbuffer: + glFramebufferRenderbuffer((GLenum)args->a0, (GLenum)args->a1, (GLenum)args->a2, (GLint)args->a3); + break; + case glfnFramebufferTexture2D: + glFramebufferTexture2D((GLenum)args->a0, (GLenum)args->a1, (GLenum)args->a2, (GLint)args->a3, (GLint)args->a4); + break; + case glfnFrontFace: + glFrontFace((GLenum)args->a0); + break; + case glfnGenBuffer: + glGenBuffers(1, (GLuint*)&ret); + break; + case glfnGenFramebuffer: + glGenFramebuffers(1, (GLuint*)&ret); + break; + case glfnGenRenderbuffer: + glGenRenderbuffers(1, (GLuint*)&ret); + break; + case glfnGenTexture: + glGenTextures(1, (GLuint*)&ret); + break; + case glfnGenVertexArray: + glGenVertexArrays(1, (GLuint*)&ret); + break; + case glfnGenerateMipmap: + glGenerateMipmap((GLenum)args->a0); + break; + case glfnGetActiveAttrib: + glGetActiveAttrib( + (GLuint)args->a0, + (GLuint)args->a1, + (GLsizei)args->a2, + NULL, + (GLint*)&ret, + (GLenum*)args->a3, + (GLchar*)parg); + break; + case glfnGetActiveUniform: + glGetActiveUniform( + (GLuint)args->a0, + (GLuint)args->a1, + (GLsizei)args->a2, + NULL, + (GLint*)&ret, + (GLenum*)args->a3, + (GLchar*)parg); + break; + case glfnGetAttachedShaders: + glGetAttachedShaders((GLuint)args->a0, (GLsizei)args->a1, (GLsizei*)&ret, (GLuint*)parg); + break; + case glfnGetAttribLocation: + ret = glGetAttribLocation((GLint)args->a0, (GLchar*)args->a1); + break; + case glfnGetBooleanv: + glGetBooleanv((GLenum)args->a0, (GLboolean*)parg); + break; + case glfnGetBufferParameteri: + glGetBufferParameteriv((GLenum)args->a0, (GLenum)args->a1, (GLint*)&ret); + break; + case glfnGetFloatv: + glGetFloatv((GLenum)args->a0, (GLfloat*)parg); + break; + case glfnGetIntegerv: + glGetIntegerv((GLenum)args->a0, (GLint*)parg); + break; + case glfnGetError: + ret = glGetError(); + break; + case glfnGetFramebufferAttachmentParameteriv: + glGetFramebufferAttachmentParameteriv((GLenum)args->a0, (GLenum)args->a1, (GLenum)args->a2, (GLint*)&ret); + break; + case glfnGetProgramiv: + glGetProgramiv((GLint)args->a0, (GLenum)args->a1, (GLint*)&ret); + break; + case glfnGetProgramInfoLog: + glGetProgramInfoLog((GLuint)args->a0, (GLsizei)args->a1, 0, (GLchar*)parg); + break; + case glfnGetRenderbufferParameteriv: + glGetRenderbufferParameteriv((GLenum)args->a0, (GLenum)args->a1, (GLint*)&ret); + break; + case glfnGetShaderiv: + glGetShaderiv((GLint)args->a0, (GLenum)args->a1, (GLint*)&ret); + break; + case glfnGetShaderInfoLog: + glGetShaderInfoLog((GLuint)args->a0, (GLsizei)args->a1, 0, (GLchar*)parg); + break; + case glfnGetShaderPrecisionFormat: + glGetShaderPrecisionFormat((GLenum)args->a0, (GLenum)args->a1, (GLint*)parg, &((GLint*)parg)[2]); + break; + case glfnGetShaderSource: + glGetShaderSource((GLuint)args->a0, (GLsizei)args->a1, 0, (GLchar*)parg); + break; + case glfnGetString: + ret = (uintptr_t)glGetString((GLenum)args->a0); + break; + case glfnGetTexParameterfv: + glGetTexParameterfv((GLenum)args->a0, (GLenum)args->a1, (GLfloat*)parg); + break; + case glfnGetTexParameteriv: + glGetTexParameteriv((GLenum)args->a0, (GLenum)args->a1, (GLint*)parg); + break; + case glfnGetUniformfv: + glGetUniformfv((GLuint)args->a0, (GLint)args->a1, (GLfloat*)parg); + break; + case glfnGetUniformiv: + glGetUniformiv((GLuint)args->a0, (GLint)args->a1, (GLint*)parg); + break; + case glfnGetUniformLocation: + ret = glGetUniformLocation((GLint)args->a0, (GLchar*)args->a1); + break; + case glfnGetVertexAttribfv: + glGetVertexAttribfv((GLuint)args->a0, (GLenum)args->a1, (GLfloat*)parg); + break; + case glfnGetVertexAttribiv: + glGetVertexAttribiv((GLuint)args->a0, (GLenum)args->a1, (GLint*)parg); + break; + case glfnHint: + glHint((GLenum)args->a0, (GLenum)args->a1); + break; + case glfnIsBuffer: + ret = glIsBuffer((GLint)args->a0); + break; + case glfnIsEnabled: + ret = glIsEnabled((GLenum)args->a0); + break; + case glfnIsFramebuffer: + ret = glIsFramebuffer((GLint)args->a0); + break; + case glfnIsProgram: + ret = glIsProgram((GLint)args->a0); + break; + case glfnIsRenderbuffer: + ret = glIsRenderbuffer((GLint)args->a0); + break; + case glfnIsShader: + ret = glIsShader((GLint)args->a0); + break; + case glfnIsTexture: + ret = glIsTexture((GLint)args->a0); + break; + case glfnLineWidth: + glLineWidth(*(GLfloat*)&args->a0); + break; + case glfnLinkProgram: + glLinkProgram((GLint)args->a0); + break; + case glfnPixelStorei: + glPixelStorei((GLenum)args->a0, (GLint)args->a1); + break; + case glfnPolygonOffset: + glPolygonOffset(*(GLfloat*)&args->a0, *(GLfloat*)&args->a1); + break; + case glfnReadPixels: + glReadPixels((GLint)args->a0, (GLint)args->a1, (GLsizei)args->a2, (GLsizei)args->a3, (GLenum)args->a4, (GLenum)args->a5, (void*)parg); + break; + case glfnReleaseShaderCompiler: + glReleaseShaderCompiler(); + break; + case glfnRenderbufferStorage: + glRenderbufferStorage((GLenum)args->a0, (GLenum)args->a1, (GLint)args->a2, (GLint)args->a3); + break; + case glfnSampleCoverage: + glSampleCoverage(*(GLfloat*)&args->a0, (GLboolean)args->a1); + break; + case glfnScissor: + glScissor((GLint)args->a0, (GLint)args->a1, (GLint)args->a2, (GLint)args->a3); + break; + case glfnShaderSource: +#if defined(os_ios) || defined(os_macos) + glShaderSource((GLuint)args->a0, (GLsizei)args->a1, (const GLchar *const *)args->a2, NULL); +#else + glShaderSource((GLuint)args->a0, (GLsizei)args->a1, (const GLchar **)args->a2, NULL); +#endif + break; + case glfnStencilFunc: + glStencilFunc((GLenum)args->a0, (GLint)args->a1, (GLuint)args->a2); + break; + case glfnStencilFuncSeparate: + glStencilFuncSeparate((GLenum)args->a0, (GLenum)args->a1, (GLint)args->a2, (GLuint)args->a3); + break; + case glfnStencilMask: + glStencilMask((GLuint)args->a0); + break; + case glfnStencilMaskSeparate: + glStencilMaskSeparate((GLenum)args->a0, (GLuint)args->a1); + break; + case glfnStencilOp: + glStencilOp((GLenum)args->a0, (GLenum)args->a1, (GLenum)args->a2); + break; + case glfnStencilOpSeparate: + glStencilOpSeparate((GLenum)args->a0, (GLenum)args->a1, (GLenum)args->a2, (GLenum)args->a3); + break; + case glfnTexImage2D: + glTexImage2D( + (GLenum)args->a0, + (GLint)args->a1, + (GLint)args->a2, + (GLsizei)args->a3, + (GLsizei)args->a4, + 0, // border + (GLenum)args->a5, + (GLenum)args->a6, + (const GLvoid*)parg); + break; + case glfnTexSubImage2D: + glTexSubImage2D( + (GLenum)args->a0, + (GLint)args->a1, + (GLint)args->a2, + (GLint)args->a3, + (GLsizei)args->a4, + (GLsizei)args->a5, + (GLenum)args->a6, + (GLenum)args->a7, + (const GLvoid*)parg); + break; + case glfnTexParameterf: + glTexParameterf((GLenum)args->a0, (GLenum)args->a1, *(GLfloat*)&args->a2); + break; + case glfnTexParameterfv: + glTexParameterfv((GLenum)args->a0, (GLenum)args->a1, (GLfloat*)parg); + break; + case glfnTexParameteri: + glTexParameteri((GLenum)args->a0, (GLenum)args->a1, (GLint)args->a2); + break; + case glfnTexParameteriv: + glTexParameteriv((GLenum)args->a0, (GLenum)args->a1, (GLint*)parg); + break; + case glfnUniform1f: + glUniform1f((GLint)args->a0, *(GLfloat*)&args->a1); + break; + case glfnUniform1fv: + glUniform1fv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)parg); + break; + case glfnUniform1i: + glUniform1i((GLint)args->a0, (GLint)args->a1); + break; + case glfnUniform1ui: + glUniform1ui((GLint)args->a0, (GLuint)args->a1); + break; + case glfnUniform1uiv: + glUniform1uiv((GLint)args->a0, (GLsizeiptr)args->a1, (GLuint*)parg); + break; + case glfnUniform1iv: + glUniform1iv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)parg); + break; + case glfnUniform2f: + glUniform2f((GLint)args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2); + break; + case glfnUniform2fv: + glUniform2fv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)parg); + break; + case glfnUniform2i: + glUniform2i((GLint)args->a0, (GLint)args->a1, (GLint)args->a2); + break; + case glfnUniform2ui: + glUniform2ui((GLint)args->a0, (GLuint)args->a1, (GLuint)args->a2); + break; + case glfnUniform2uiv: + glUniform2uiv((GLint)args->a0, (GLsizeiptr)args->a1, (GLuint*)parg); + break; + case glfnUniform2iv: + glUniform2iv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)parg); + break; + case glfnUniform3f: + glUniform3f((GLint)args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2, *(GLfloat*)&args->a3); + break; + case glfnUniform3fv: + glUniform3fv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)parg); + break; + case glfnUniform3i: + glUniform3i((GLint)args->a0, (GLint)args->a1, (GLint)args->a2, (GLint)args->a3); + break; + case glfnUniform3ui: + glUniform3ui((GLint)args->a0, (GLuint)args->a1, (GLuint)args->a2, (GLuint)args->a3); + break; + case glfnUniform3uiv: + glUniform3uiv((GLint)args->a0, (GLsizeiptr)args->a1, (GLuint*)parg); + break; + case glfnUniform3iv: + glUniform3iv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)parg); + break; + case glfnUniform4f: + glUniform4f((GLint)args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2, *(GLfloat*)&args->a3, *(GLfloat*)&args->a4); + break; + case glfnUniform4fv: + glUniform4fv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)parg); + break; + case glfnUniform4i: + glUniform4i((GLint)args->a0, (GLint)args->a1, (GLint)args->a2, (GLint)args->a3, (GLint)args->a4); + break; + case glfnUniform4ui: + glUniform4ui((GLint)args->a0, (GLuint)args->a1, (GLuint)args->a2, (GLuint)args->a3, (GLuint)args->a4); + break; + case glfnUniform4uiv: + glUniform4uiv((GLint)args->a0, (GLsizeiptr)args->a1, (GLuint*)parg); + break; + case glfnUniform4iv: + glUniform4iv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)parg); + break; + case glfnUniformMatrix2fv: + glUniformMatrix2fv((GLint)args->a0, (GLsizeiptr)args->a1, 0, (GLvoid*)parg); + break; + case glfnUniformMatrix3fv: + glUniformMatrix3fv((GLint)args->a0, (GLsizeiptr)args->a1, 0, (GLvoid*)parg); + break; + case glfnUniformMatrix4fv: + glUniformMatrix4fv((GLint)args->a0, (GLsizeiptr)args->a1, 0, (GLvoid*)parg); + break; + case glfnUniformMatrix2x3fv: + glUniformMatrix2x3fv((GLint)args->a0, (GLsizeiptr)args->a1, 0, (GLvoid*)parg); + break; + case glfnUniformMatrix3x2fv: + glUniformMatrix3x2fv((GLint)args->a0, (GLsizeiptr)args->a1, 0, (GLvoid*)parg); + break; + case glfnUniformMatrix2x4fv: + glUniformMatrix2x4fv((GLint)args->a0, (GLsizeiptr)args->a1, 0, (GLvoid*)parg); + break; + case glfnUniformMatrix4x2fv: + glUniformMatrix4x2fv((GLint)args->a0, (GLsizeiptr)args->a1, 0, (GLvoid*)parg); + break; + case glfnUniformMatrix3x4fv: + glUniformMatrix3x4fv((GLint)args->a0, (GLsizeiptr)args->a1, 0, (GLvoid*)parg); + break; + case glfnUniformMatrix4x3fv: + glUniformMatrix4x3fv((GLint)args->a0, (GLsizeiptr)args->a1, 0, (GLvoid*)parg); + break; + case glfnUseProgram: + glUseProgram((GLint)args->a0); + break; + case glfnValidateProgram: + glValidateProgram((GLint)args->a0); + break; + case glfnVertexAttrib1f: + glVertexAttrib1f((GLint)args->a0, *(GLfloat*)&args->a1); + break; + case glfnVertexAttrib1fv: + glVertexAttrib1fv((GLint)args->a0, (GLfloat*)parg); + break; + case glfnVertexAttrib2f: + glVertexAttrib2f((GLint)args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2); + break; + case glfnVertexAttrib2fv: + glVertexAttrib2fv((GLint)args->a0, (GLfloat*)parg); + break; + case glfnVertexAttrib3f: + glVertexAttrib3f((GLint)args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2, *(GLfloat*)&args->a3); + break; + case glfnVertexAttrib3fv: + glVertexAttrib3fv((GLint)args->a0, (GLfloat*)parg); + break; + case glfnVertexAttrib4f: + glVertexAttrib4f((GLint)args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2, *(GLfloat*)&args->a3, *(GLfloat*)&args->a4); + break; + case glfnVertexAttrib4fv: + glVertexAttrib4fv((GLint)args->a0, (GLfloat*)parg); + break; + case glfnVertexAttribPointer: + glVertexAttribPointer((GLuint)args->a0, (GLint)args->a1, (GLenum)args->a2, (GLboolean)args->a3, (GLsizei)args->a4, (const GLvoid*)args->a5); + break; + case glfnViewport: + glViewport((GLint)args->a0, (GLint)args->a1, (GLint)args->a2, (GLint)args->a3); + break; + } + return ret; +} diff --git a/vendor/github.com/ebitengine/gomobile/gl/work.go b/vendor/github.com/ebitengine/gomobile/gl/work.go new file mode 100644 index 0000000..c603adf --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/gl/work.go @@ -0,0 +1,173 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build darwin || linux || openbsd + +package gl + +/* +#cgo ios LDFLAGS: -framework OpenGLES +#cgo darwin,!ios LDFLAGS: -framework OpenGL +#cgo linux LDFLAGS: -lGLESv2 +#cgo openbsd LDFLAGS: -L/usr/X11R6/lib/ -lGLESv2 + +#cgo android CFLAGS: -Dos_android +#cgo ios CFLAGS: -Dos_ios +#cgo darwin,!ios CFLAGS: -Dos_macos +#cgo darwin CFLAGS: -DGL_SILENCE_DEPRECATION -DGLES_SILENCE_DEPRECATION +#cgo linux CFLAGS: -Dos_linux +#cgo openbsd CFLAGS: -Dos_openbsd + +#cgo openbsd CFLAGS: -I/usr/X11R6/include/ + +#include +#include "work.h" + +uintptr_t process(struct fnargs* cargs, char* parg0, char* parg1, char* parg2, int count) { + uintptr_t ret; + + ret = processFn(&cargs[0], parg0); + if (count > 1) { + ret = processFn(&cargs[1], parg1); + } + if (count > 2) { + ret = processFn(&cargs[2], parg2); + } + + return ret; +} +*/ +import "C" + +import "unsafe" + +const workbufLen = 3 + +type context struct { + cptr uintptr + debug int32 + + workAvailable chan struct{} + + // work is a queue of calls to execute. + work chan call + + // retvalue is sent a return value when blocking calls complete. + // It is safe to use a global unbuffered channel here as calls + // cannot currently be made concurrently. + // + // TODO: the comment above about concurrent calls isn't actually true: package + // app calls package gl, but it has to do so in a separate goroutine, which + // means that its gl calls (which may be blocking) can race with other gl calls + // in the main program. We should make it safe to issue blocking gl calls + // concurrently, or get the gl calls out of package app, or both. + retvalue chan C.uintptr_t + + cargs [workbufLen]C.struct_fnargs + parg [workbufLen]*C.char +} + +func (ctx *context) WorkAvailable() <-chan struct{} { return ctx.workAvailable } + +type context3 struct { + *context +} + +// NewContext creates a cgo OpenGL context. +// +// See the Worker interface for more details on how it is used. +func NewContext() (Context, Worker) { + glctx := &context{ + workAvailable: make(chan struct{}, 1), + work: make(chan call, workbufLen), + retvalue: make(chan C.uintptr_t), + } + if C.GLES_VERSION == "GL_ES_2_0" { + return glctx, glctx + } + return context3{glctx}, glctx +} + +// Version returns a GL ES version string, either "GL_ES_2_0" or "GL_ES_3_0". +// Future versions of the gl package may return "GL_ES_3_1". +func Version() string { + return C.GLES_VERSION +} + +func (ctx *context) enqueue(c call) uintptr { + ctx.work <- c + + select { + case ctx.workAvailable <- struct{}{}: + default: + } + + if c.blocking { + return uintptr(<-ctx.retvalue) + } + return 0 +} + +func (ctx *context) DoWork() { + queue := make([]call, 0, workbufLen) + for { + // Wait until at least one piece of work is ready. + // Accumulate work until a piece is marked as blocking. + select { + case w := <-ctx.work: + queue = append(queue, w) + default: + return + } + blocking := queue[len(queue)-1].blocking + enqueue: + for len(queue) < cap(queue) && !blocking { + select { + case w := <-ctx.work: + queue = append(queue, w) + blocking = queue[len(queue)-1].blocking + default: + break enqueue + } + } + + // Process the queued GL functions. + for i, q := range queue { + ctx.cargs[i] = *(*C.struct_fnargs)(unsafe.Pointer(&q.args)) + ctx.parg[i] = (*C.char)(q.parg) + } + ret := C.process(&ctx.cargs[0], ctx.parg[0], ctx.parg[1], ctx.parg[2], C.int(len(queue))) + + // Cleanup and signal. + queue = queue[:0] + if blocking { + ctx.retvalue <- ret + } + } +} + +func init() { + if unsafe.Sizeof(C.GLint(0)) != unsafe.Sizeof(int32(0)) { + panic("GLint is not an int32") + } +} + +// cString creates C string off the Go heap. +// ret is a *char. +func (ctx *context) cString(str string) (uintptr, func()) { + ptr := unsafe.Pointer(C.CString(str)) + return uintptr(ptr), func() { C.free(ptr) } +} + +// cString creates a pointer to a C string off the Go heap. +// ret is a **char. +func (ctx *context) cStringPtr(str string) (uintptr, func()) { + s, free := ctx.cString(str) + ptr := C.malloc(C.size_t(unsafe.Sizeof((*int)(nil)))) + *(*uintptr)(ptr) = s + return uintptr(ptr), func() { + free() + C.free(ptr) + } +} diff --git a/vendor/github.com/ebitengine/gomobile/gl/work.h b/vendor/github.com/ebitengine/gomobile/gl/work.h new file mode 100644 index 0000000..5bc093b --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/gl/work.h @@ -0,0 +1,217 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#ifdef os_android +// TODO(crawshaw): We could include and +// condition on __ANDROID_API__ to get GLES3 headers. However +// we also need to add -lGLESv3 to LDFLAGS, which we cannot do +// from inside an ifdef. +#include +#elif os_linux +#include // install on Ubuntu with: sudo apt-get install libegl1-mesa-dev libgles2-mesa-dev libx11-dev +#elif os_openbsd +#include +#endif + +#ifdef os_ios +#include +#endif + +#ifdef os_macos +#include +#define GL_ES_VERSION_3_0 1 +#endif + +#if defined(GL_ES_VERSION_3_0) && GL_ES_VERSION_3_0 +#define GLES_VERSION "GL_ES_3_0" +#else +#define GLES_VERSION "GL_ES_2_0" +#endif + +#include +#include + +// TODO: generate this enum from fn.go. +typedef enum { + glfnUNDEFINED, + + glfnActiveTexture, + glfnAttachShader, + glfnBindAttribLocation, + glfnBindBuffer, + glfnBindFramebuffer, + glfnBindRenderbuffer, + glfnBindTexture, + glfnBindVertexArray, + glfnBlendColor, + glfnBlendEquation, + glfnBlendEquationSeparate, + glfnBlendFunc, + glfnBlendFuncSeparate, + glfnBufferData, + glfnBufferSubData, + glfnCheckFramebufferStatus, + glfnClear, + glfnClearColor, + glfnClearDepthf, + glfnClearStencil, + glfnColorMask, + glfnCompileShader, + glfnCompressedTexImage2D, + glfnCompressedTexSubImage2D, + glfnCopyTexImage2D, + glfnCopyTexSubImage2D, + glfnCreateProgram, + glfnCreateShader, + glfnCullFace, + glfnDeleteBuffer, + glfnDeleteFramebuffer, + glfnDeleteProgram, + glfnDeleteRenderbuffer, + glfnDeleteShader, + glfnDeleteTexture, + glfnDeleteVertexArray, + glfnDepthFunc, + glfnDepthRangef, + glfnDepthMask, + glfnDetachShader, + glfnDisable, + glfnDisableVertexAttribArray, + glfnDrawArrays, + glfnDrawElements, + glfnEnable, + glfnEnableVertexAttribArray, + glfnFinish, + glfnFlush, + glfnFramebufferRenderbuffer, + glfnFramebufferTexture2D, + glfnFrontFace, + glfnGenBuffer, + glfnGenFramebuffer, + glfnGenRenderbuffer, + glfnGenTexture, + glfnGenVertexArray, + glfnGenerateMipmap, + glfnGetActiveAttrib, + glfnGetActiveUniform, + glfnGetAttachedShaders, + glfnGetAttribLocation, + glfnGetBooleanv, + glfnGetBufferParameteri, + glfnGetError, + glfnGetFloatv, + glfnGetFramebufferAttachmentParameteriv, + glfnGetIntegerv, + glfnGetProgramInfoLog, + glfnGetProgramiv, + glfnGetRenderbufferParameteriv, + glfnGetShaderInfoLog, + glfnGetShaderPrecisionFormat, + glfnGetShaderSource, + glfnGetShaderiv, + glfnGetString, + glfnGetTexParameterfv, + glfnGetTexParameteriv, + glfnGetUniformLocation, + glfnGetUniformfv, + glfnGetUniformiv, + glfnGetVertexAttribfv, + glfnGetVertexAttribiv, + glfnHint, + glfnIsBuffer, + glfnIsEnabled, + glfnIsFramebuffer, + glfnIsProgram, + glfnIsRenderbuffer, + glfnIsShader, + glfnIsTexture, + glfnLineWidth, + glfnLinkProgram, + glfnPixelStorei, + glfnPolygonOffset, + glfnReadPixels, + glfnReleaseShaderCompiler, + glfnRenderbufferStorage, + glfnSampleCoverage, + glfnScissor, + glfnShaderSource, + glfnStencilFunc, + glfnStencilFuncSeparate, + glfnStencilMask, + glfnStencilMaskSeparate, + glfnStencilOp, + glfnStencilOpSeparate, + glfnTexImage2D, + glfnTexParameterf, + glfnTexParameterfv, + glfnTexParameteri, + glfnTexParameteriv, + glfnTexSubImage2D, + glfnUniform1f, + glfnUniform1fv, + glfnUniform1i, + glfnUniform1iv, + glfnUniform2f, + glfnUniform2fv, + glfnUniform2i, + glfnUniform2iv, + glfnUniform3f, + glfnUniform3fv, + glfnUniform3i, + glfnUniform3iv, + glfnUniform4f, + glfnUniform4fv, + glfnUniform4i, + glfnUniform4iv, + glfnUniformMatrix2fv, + glfnUniformMatrix3fv, + glfnUniformMatrix4fv, + glfnUseProgram, + glfnValidateProgram, + glfnVertexAttrib1f, + glfnVertexAttrib1fv, + glfnVertexAttrib2f, + glfnVertexAttrib2fv, + glfnVertexAttrib3f, + glfnVertexAttrib3fv, + glfnVertexAttrib4f, + glfnVertexAttrib4fv, + glfnVertexAttribPointer, + glfnViewport, + + // ES 3.0 functions + glfnUniformMatrix2x3fv, + glfnUniformMatrix3x2fv, + glfnUniformMatrix2x4fv, + glfnUniformMatrix4x2fv, + glfnUniformMatrix3x4fv, + glfnUniformMatrix4x3fv, + glfnBlitFramebuffer, + glfnUniform1ui, + glfnUniform2ui, + glfnUniform3ui, + glfnUniform4ui, + glfnUniform1uiv, + glfnUniform2uiv, + glfnUniform3uiv, + glfnUniform4uiv, +} glfn; + +// TODO: generate this type from fn.go. +struct fnargs { + glfn fn; + + uintptr_t a0; + uintptr_t a1; + uintptr_t a2; + uintptr_t a3; + uintptr_t a4; + uintptr_t a5; + uintptr_t a6; + uintptr_t a7; + uintptr_t a8; + uintptr_t a9; +}; + +extern uintptr_t processFn(struct fnargs* args, char* parg); diff --git a/vendor/github.com/ebitengine/gomobile/gl/work_other.go b/vendor/github.com/ebitengine/gomobile/gl/work_other.go new file mode 100644 index 0000000..3bc597d --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/gl/work_other.go @@ -0,0 +1,35 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build (!cgo || (!darwin && !linux && !openbsd)) && !windows + +package gl + +// This file contains stub implementations of what the other work*.go files +// provide. These stubs don't do anything, other than compile (e.g. when cgo is +// disabled). + +type context struct{} + +func (*context) enqueue(c call) uintptr { + panic("unimplemented; GOOS/CGO combination not supported") +} + +func (*context) cString(str string) (uintptr, func()) { + panic("unimplemented; GOOS/CGO combination not supported") +} + +func (*context) cStringPtr(str string) (uintptr, func()) { + panic("unimplemented; GOOS/CGO combination not supported") +} + +type context3 = context + +func NewContext() (Context, Worker) { + panic("unimplemented; GOOS/CGO combination not supported") +} + +func Version() string { + panic("unimplemented; GOOS/CGO combination not supported") +} diff --git a/vendor/github.com/ebitengine/gomobile/gl/work_windows.go b/vendor/github.com/ebitengine/gomobile/gl/work_windows.go new file mode 100644 index 0000000..4119ac6 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/gl/work_windows.go @@ -0,0 +1,569 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gl + +import ( + "runtime" + "syscall" + "unsafe" +) + +// context is described in work.go. +type context struct { + debug int32 + workAvailable chan struct{} + work chan call + retvalue chan uintptr + + // TODO(crawshaw): will not work with a moving collector + cStringCounter int + cStrings map[int]unsafe.Pointer +} + +func (ctx *context) WorkAvailable() <-chan struct{} { return ctx.workAvailable } + +type context3 struct { + *context +} + +func NewContext() (Context, Worker) { + if err := findDLLs(); err != nil { + panic(err) + } + glctx := &context{ + workAvailable: make(chan struct{}, 1), + work: make(chan call, 3), + retvalue: make(chan uintptr), + cStrings: make(map[int]unsafe.Pointer), + } + return glctx, glctx +} + +func (ctx *context) enqueue(c call) uintptr { + ctx.work <- c + + select { + case ctx.workAvailable <- struct{}{}: + default: + } + + if c.blocking { + return <-ctx.retvalue + } + return 0 +} + +func (ctx *context) DoWork() { + // TODO: add a work queue + for { + select { + case w := <-ctx.work: + ret := ctx.doWork(w) + if w.blocking { + ctx.retvalue <- ret + } + default: + return + } + } +} + +func (ctx *context) cString(s string) (uintptr, func()) { + buf := make([]byte, len(s)+1) + for i := 0; i < len(s); i++ { + buf[i] = s[i] + } + ret := unsafe.Pointer(&buf[0]) + id := ctx.cStringCounter + ctx.cStringCounter++ + ctx.cStrings[id] = ret + return uintptr(ret), func() { delete(ctx.cStrings, id) } +} + +func (ctx *context) cStringPtr(str string) (uintptr, func()) { + s, sfree := ctx.cString(str) + sptr := [2]uintptr{s, 0} + ret := unsafe.Pointer(&sptr[0]) + id := ctx.cStringCounter + ctx.cStringCounter++ + ctx.cStrings[id] = ret + return uintptr(ret), func() { sfree(); delete(ctx.cStrings, id) } +} + +// fixFloat copies the first four arguments into the XMM registers. +// This is for the windows/amd64 calling convention, that wants +// floating point arguments to be passed in XMM. +// +// Mercifully, type information is not required to implement +// this calling convention. In particular see the mixed int/float +// examples: +// +// https://msdn.microsoft.com/en-us/library/zthk2dkh.aspx +// +// This means it could be fixed in syscall.Syscall. The relevant +// issue is +// +// https://golang.org/issue/6510 +func fixFloat(x0, x1, x2, x3 uintptr) + +func (ctx *context) doWork(c call) (ret uintptr) { + if runtime.GOARCH == "amd64" { + fixFloat(c.args.a0, c.args.a1, c.args.a2, c.args.a3) + } + + switch c.args.fn { + case glfnActiveTexture: + syscall.Syscall(glActiveTexture.Addr(), 1, c.args.a0, 0, 0) + case glfnAttachShader: + syscall.Syscall(glAttachShader.Addr(), 2, c.args.a0, c.args.a1, 0) + case glfnBindAttribLocation: + syscall.Syscall(glBindAttribLocation.Addr(), 3, c.args.a0, c.args.a1, c.args.a2) + case glfnBindBuffer: + syscall.Syscall(glBindBuffer.Addr(), 2, c.args.a0, c.args.a1, 0) + case glfnBindFramebuffer: + syscall.Syscall(glBindFramebuffer.Addr(), 2, c.args.a0, c.args.a1, 0) + case glfnBindRenderbuffer: + syscall.Syscall(glBindRenderbuffer.Addr(), 2, c.args.a0, c.args.a1, 0) + case glfnBindTexture: + syscall.Syscall(glBindTexture.Addr(), 2, c.args.a0, c.args.a1, 0) + case glfnBindVertexArray: + syscall.Syscall(glBindVertexArray.Addr(), 1, c.args.a0, 0, 0) + case glfnBlendColor: + syscall.Syscall6(glBlendColor.Addr(), 4, c.args.a0, c.args.a1, c.args.a2, c.args.a3, 0, 0) + case glfnBlendEquation: + syscall.Syscall(glBlendEquation.Addr(), 1, c.args.a0, 0, 0) + case glfnBlendEquationSeparate: + syscall.Syscall(glBlendEquationSeparate.Addr(), 2, c.args.a0, c.args.a1, 0) + case glfnBlendFunc: + syscall.Syscall(glBlendFunc.Addr(), 2, c.args.a0, c.args.a1, 0) + case glfnBlendFuncSeparate: + syscall.Syscall6(glBlendFuncSeparate.Addr(), 4, c.args.a0, c.args.a1, c.args.a2, c.args.a3, 0, 0) + case glfnBufferData: + syscall.Syscall6(glBufferData.Addr(), 4, c.args.a0, c.args.a1, uintptr(c.parg), c.args.a2, 0, 0) + case glfnBufferSubData: + syscall.Syscall6(glBufferSubData.Addr(), 4, c.args.a0, c.args.a1, c.args.a2, uintptr(c.parg), 0, 0) + case glfnCheckFramebufferStatus: + ret, _, _ = syscall.Syscall(glCheckFramebufferStatus.Addr(), 1, c.args.a0, 0, 0) + case glfnClear: + syscall.Syscall(glClear.Addr(), 1, c.args.a0, 0, 0) + case glfnClearColor: + syscall.Syscall6(glClearColor.Addr(), 4, c.args.a0, c.args.a1, c.args.a2, c.args.a3, 0, 0) + case glfnClearDepthf: + syscall.Syscall6(glClearDepthf.Addr(), 1, c.args.a0, 0, 0, 0, 0, 0) + case glfnClearStencil: + syscall.Syscall(glClearStencil.Addr(), 1, c.args.a0, 0, 0) + case glfnColorMask: + syscall.Syscall6(glColorMask.Addr(), 4, c.args.a0, c.args.a1, c.args.a2, c.args.a3, 0, 0) + case glfnCompileShader: + syscall.Syscall(glCompileShader.Addr(), 1, c.args.a0, 0, 0) + case glfnCompressedTexImage2D: + syscall.Syscall9(glCompressedTexImage2D.Addr(), 8, c.args.a0, c.args.a1, c.args.a2, c.args.a3, c.args.a4, c.args.a5, c.args.a6, uintptr(c.parg), 0) + case glfnCompressedTexSubImage2D: + syscall.Syscall9(glCompressedTexSubImage2D.Addr(), 9, c.args.a0, c.args.a1, c.args.a2, c.args.a3, c.args.a4, c.args.a5, c.args.a6, c.args.a7, uintptr(c.parg)) + case glfnCopyTexImage2D: + syscall.Syscall9(glCopyTexImage2D.Addr(), 8, c.args.a0, c.args.a1, c.args.a2, c.args.a3, c.args.a4, c.args.a5, c.args.a6, c.args.a7, 0) + case glfnCopyTexSubImage2D: + syscall.Syscall9(glCopyTexSubImage2D.Addr(), 8, c.args.a0, c.args.a1, c.args.a2, c.args.a3, c.args.a4, c.args.a5, c.args.a6, c.args.a7, 0) + case glfnCreateProgram: + ret, _, _ = syscall.Syscall(glCreateProgram.Addr(), 0, 0, 0, 0) + case glfnCreateShader: + ret, _, _ = syscall.Syscall(glCreateShader.Addr(), 1, c.args.a0, 0, 0) + case glfnCullFace: + syscall.Syscall(glCullFace.Addr(), 1, c.args.a0, 0, 0) + case glfnDeleteBuffer: + syscall.Syscall(glDeleteBuffers.Addr(), 2, 1, uintptr(unsafe.Pointer(&c.args.a0)), 0) + case glfnDeleteFramebuffer: + syscall.Syscall(glDeleteFramebuffers.Addr(), 2, 1, uintptr(unsafe.Pointer(&c.args.a0)), 0) + case glfnDeleteProgram: + syscall.Syscall(glDeleteProgram.Addr(), 1, c.args.a0, 0, 0) + case glfnDeleteRenderbuffer: + syscall.Syscall(glDeleteRenderbuffers.Addr(), 2, 1, uintptr(unsafe.Pointer(&c.args.a0)), 0) + case glfnDeleteShader: + syscall.Syscall(glDeleteShader.Addr(), 1, c.args.a0, 0, 0) + case glfnDeleteVertexArray: + syscall.Syscall(glDeleteVertexArrays.Addr(), 2, 1, uintptr(unsafe.Pointer(&c.args.a0)), 0) + case glfnDeleteTexture: + syscall.Syscall(glDeleteTextures.Addr(), 2, 1, uintptr(unsafe.Pointer(&c.args.a0)), 0) + case glfnDepthFunc: + syscall.Syscall(glDepthFunc.Addr(), 1, c.args.a0, 0, 0) + case glfnDepthRangef: + syscall.Syscall6(glDepthRangef.Addr(), 2, c.args.a0, c.args.a1, 0, 0, 0, 0) + case glfnDepthMask: + syscall.Syscall(glDepthMask.Addr(), 1, c.args.a0, 0, 0) + case glfnDetachShader: + syscall.Syscall(glDetachShader.Addr(), 2, c.args.a0, c.args.a1, 0) + case glfnDisable: + syscall.Syscall(glDisable.Addr(), 1, c.args.a0, 0, 0) + case glfnDisableVertexAttribArray: + syscall.Syscall(glDisableVertexAttribArray.Addr(), 1, c.args.a0, 0, 0) + case glfnDrawArrays: + syscall.Syscall(glDrawArrays.Addr(), 3, c.args.a0, c.args.a1, c.args.a2) + case glfnDrawElements: + syscall.Syscall6(glDrawElements.Addr(), 4, c.args.a0, c.args.a1, c.args.a2, c.args.a3, 0, 0) + case glfnEnable: + syscall.Syscall(glEnable.Addr(), 1, c.args.a0, 0, 0) + case glfnEnableVertexAttribArray: + syscall.Syscall(glEnableVertexAttribArray.Addr(), 1, c.args.a0, 0, 0) + case glfnFinish: + syscall.Syscall(glFinish.Addr(), 0, 0, 0, 0) + case glfnFlush: + syscall.Syscall(glFlush.Addr(), 0, 0, 0, 0) + case glfnFramebufferRenderbuffer: + syscall.Syscall6(glFramebufferRenderbuffer.Addr(), 4, c.args.a0, c.args.a1, c.args.a2, c.args.a3, 0, 0) + case glfnFramebufferTexture2D: + syscall.Syscall6(glFramebufferTexture2D.Addr(), 5, c.args.a0, c.args.a1, c.args.a2, c.args.a3, c.args.a4, 0) + case glfnFrontFace: + syscall.Syscall(glFrontFace.Addr(), 1, c.args.a0, 0, 0) + case glfnGenBuffer: + syscall.Syscall(glGenBuffers.Addr(), 2, 1, uintptr(unsafe.Pointer(&ret)), 0) + case glfnGenFramebuffer: + syscall.Syscall(glGenFramebuffers.Addr(), 2, 1, uintptr(unsafe.Pointer(&ret)), 0) + case glfnGenRenderbuffer: + syscall.Syscall(glGenRenderbuffers.Addr(), 2, 1, uintptr(unsafe.Pointer(&ret)), 0) + case glfnGenVertexArray: + syscall.Syscall(glGenVertexArrays.Addr(), 2, 1, uintptr(unsafe.Pointer(&ret)), 0) + case glfnGenTexture: + syscall.Syscall(glGenTextures.Addr(), 2, 1, uintptr(unsafe.Pointer(&ret)), 0) + case glfnGenerateMipmap: + syscall.Syscall(glGenerateMipmap.Addr(), 1, c.args.a0, 0, 0) + case glfnGetActiveAttrib: + syscall.Syscall9(glGetActiveAttrib.Addr(), 7, c.args.a0, c.args.a1, c.args.a2, 0, uintptr(unsafe.Pointer(&ret)), c.args.a3, uintptr(c.parg), 0, 0) + case glfnGetActiveUniform: + syscall.Syscall9(glGetActiveUniform.Addr(), 7, c.args.a0, c.args.a1, c.args.a2, 0, uintptr(unsafe.Pointer(&ret)), c.args.a3, uintptr(c.parg), 0, 0) + case glfnGetAttachedShaders: + syscall.Syscall6(glGetAttachedShaders.Addr(), 4, c.args.a0, c.args.a1, uintptr(unsafe.Pointer(&ret)), uintptr(c.parg), 0, 0) + case glfnGetAttribLocation: + ret, _, _ = syscall.Syscall(glGetAttribLocation.Addr(), 2, c.args.a0, c.args.a1, 0) + case glfnGetBooleanv: + syscall.Syscall(glGetBooleanv.Addr(), 2, c.args.a0, uintptr(c.parg), 0) + case glfnGetBufferParameteri: + syscall.Syscall(glGetBufferParameteri.Addr(), 3, c.args.a0, c.args.a1, uintptr(unsafe.Pointer(&ret))) + case glfnGetError: + ret, _, _ = syscall.Syscall(glGetError.Addr(), 0, 0, 0, 0) + case glfnGetFloatv: + syscall.Syscall(glGetFloatv.Addr(), 2, c.args.a0, uintptr(c.parg), 0) + case glfnGetFramebufferAttachmentParameteriv: + syscall.Syscall6(glGetFramebufferAttachmentParameteriv.Addr(), 4, c.args.a0, c.args.a1, c.args.a2, uintptr(unsafe.Pointer(&ret)), 0, 0) + case glfnGetIntegerv: + syscall.Syscall(glGetIntegerv.Addr(), 2, c.args.a0, uintptr(c.parg), 0) + case glfnGetProgramInfoLog: + syscall.Syscall6(glGetProgramInfoLog.Addr(), 4, c.args.a0, c.args.a1, 0, uintptr(c.parg), 0, 0) + case glfnGetProgramiv: + syscall.Syscall(glGetProgramiv.Addr(), 3, c.args.a0, c.args.a1, uintptr(unsafe.Pointer(&ret))) + case glfnGetRenderbufferParameteriv: + syscall.Syscall(glGetRenderbufferParameteriv.Addr(), 3, c.args.a0, c.args.a1, uintptr(unsafe.Pointer(&ret))) + case glfnGetShaderInfoLog: + syscall.Syscall6(glGetShaderInfoLog.Addr(), 4, c.args.a0, c.args.a1, 0, uintptr(c.parg), 0, 0) + case glfnGetShaderPrecisionFormat: + // c.parg is a [3]int32. The first [2]int32 of the array is one + // parameter, the final *int32 is another parameter. + syscall.Syscall6(glGetShaderPrecisionFormat.Addr(), 4, c.args.a0, c.args.a1, uintptr(c.parg), uintptr(c.parg)+2*unsafe.Sizeof(uintptr(0)), 0, 0) + case glfnGetShaderSource: + syscall.Syscall6(glGetShaderSource.Addr(), 4, c.args.a0, c.args.a1, 0, uintptr(c.parg), 0, 0) + case glfnGetShaderiv: + syscall.Syscall(glGetShaderiv.Addr(), 3, c.args.a0, c.args.a1, uintptr(unsafe.Pointer(&ret))) + case glfnGetString: + ret, _, _ = syscall.Syscall(glGetString.Addr(), 1, c.args.a0, 0, 0) + case glfnGetTexParameterfv: + syscall.Syscall(glGetTexParameterfv.Addr(), 3, c.args.a0, c.args.a1, uintptr(c.parg)) + case glfnGetTexParameteriv: + syscall.Syscall(glGetTexParameteriv.Addr(), 3, c.args.a0, c.args.a1, uintptr(c.parg)) + case glfnGetUniformLocation: + ret, _, _ = syscall.Syscall(glGetUniformLocation.Addr(), 2, c.args.a0, c.args.a1, 0) + case glfnGetUniformfv: + syscall.Syscall(glGetUniformfv.Addr(), 3, c.args.a0, c.args.a1, uintptr(c.parg)) + case glfnGetUniformiv: + syscall.Syscall(glGetUniformiv.Addr(), 3, c.args.a0, c.args.a1, uintptr(c.parg)) + case glfnGetVertexAttribfv: + syscall.Syscall(glGetVertexAttribfv.Addr(), 3, c.args.a0, c.args.a1, uintptr(c.parg)) + case glfnGetVertexAttribiv: + syscall.Syscall(glGetVertexAttribiv.Addr(), 3, c.args.a0, c.args.a1, uintptr(c.parg)) + case glfnHint: + syscall.Syscall(glHint.Addr(), 2, c.args.a0, c.args.a1, 0) + case glfnIsBuffer: + syscall.Syscall(glIsBuffer.Addr(), 1, c.args.a0, 0, 0) + case glfnIsEnabled: + syscall.Syscall(glIsEnabled.Addr(), 1, c.args.a0, 0, 0) + case glfnIsFramebuffer: + syscall.Syscall(glIsFramebuffer.Addr(), 1, c.args.a0, 0, 0) + case glfnIsProgram: + ret, _, _ = syscall.Syscall(glIsProgram.Addr(), 1, c.args.a0, 0, 0) + case glfnIsRenderbuffer: + syscall.Syscall(glIsRenderbuffer.Addr(), 1, c.args.a0, 0, 0) + case glfnIsShader: + syscall.Syscall(glIsShader.Addr(), 1, c.args.a0, 0, 0) + case glfnIsTexture: + syscall.Syscall(glIsTexture.Addr(), 1, c.args.a0, 0, 0) + case glfnLineWidth: + syscall.Syscall(glLineWidth.Addr(), 1, c.args.a0, 0, 0) + case glfnLinkProgram: + syscall.Syscall(glLinkProgram.Addr(), 1, c.args.a0, 0, 0) + case glfnPixelStorei: + syscall.Syscall(glPixelStorei.Addr(), 2, c.args.a0, c.args.a1, 0) + case glfnPolygonOffset: + syscall.Syscall6(glPolygonOffset.Addr(), 2, c.args.a0, c.args.a1, 0, 0, 0, 0) + case glfnReadPixels: + syscall.Syscall9(glReadPixels.Addr(), 7, c.args.a0, c.args.a1, c.args.a2, c.args.a3, c.args.a4, c.args.a5, uintptr(c.parg), 0, 0) + case glfnReleaseShaderCompiler: + syscall.Syscall(glReleaseShaderCompiler.Addr(), 0, 0, 0, 0) + case glfnRenderbufferStorage: + syscall.Syscall6(glRenderbufferStorage.Addr(), 4, c.args.a0, c.args.a1, c.args.a2, c.args.a3, 0, 0) + case glfnSampleCoverage: + syscall.Syscall6(glSampleCoverage.Addr(), 1, c.args.a0, 0, 0, 0, 0, 0) + case glfnScissor: + syscall.Syscall6(glScissor.Addr(), 4, c.args.a0, c.args.a1, c.args.a2, c.args.a3, 0, 0) + case glfnShaderSource: + syscall.Syscall6(glShaderSource.Addr(), 4, c.args.a0, c.args.a1, c.args.a2, 0, 0, 0) + case glfnStencilFunc: + syscall.Syscall(glStencilFunc.Addr(), 3, c.args.a0, c.args.a1, c.args.a2) + case glfnStencilFuncSeparate: + syscall.Syscall6(glStencilFuncSeparate.Addr(), 4, c.args.a0, c.args.a1, c.args.a2, c.args.a3, 0, 0) + case glfnStencilMask: + syscall.Syscall(glStencilMask.Addr(), 1, c.args.a0, 0, 0) + case glfnStencilMaskSeparate: + syscall.Syscall(glStencilMaskSeparate.Addr(), 2, c.args.a0, c.args.a1, 0) + case glfnStencilOp: + syscall.Syscall(glStencilOp.Addr(), 3, c.args.a0, c.args.a1, c.args.a2) + case glfnStencilOpSeparate: + syscall.Syscall6(glStencilOpSeparate.Addr(), 4, c.args.a0, c.args.a1, c.args.a2, c.args.a3, 0, 0) + case glfnTexImage2D: + syscall.Syscall9(glTexImage2D.Addr(), 9, c.args.a0, c.args.a1, c.args.a2, c.args.a3, c.args.a4, 0, c.args.a5, c.args.a6, uintptr(c.parg)) + case glfnTexParameterf: + syscall.Syscall6(glTexParameterf.Addr(), 3, c.args.a0, c.args.a1, c.args.a2, c.args.a3, c.args.a4, c.args.a5) + case glfnTexParameterfv: + syscall.Syscall(glTexParameterfv.Addr(), 3, c.args.a0, c.args.a1, uintptr(c.parg)) + case glfnTexParameteri: + syscall.Syscall(glTexParameteri.Addr(), 3, c.args.a0, c.args.a1, c.args.a2) + case glfnTexParameteriv: + syscall.Syscall(glTexParameteriv.Addr(), 3, c.args.a0, c.args.a1, uintptr(c.parg)) + case glfnTexSubImage2D: + syscall.Syscall9(glTexSubImage2D.Addr(), 9, c.args.a0, c.args.a1, c.args.a2, c.args.a3, c.args.a4, c.args.a5, c.args.a6, c.args.a7, uintptr(c.parg)) + case glfnUniform1f: + syscall.Syscall6(glUniform1f.Addr(), 2, c.args.a0, c.args.a1, c.args.a2, c.args.a3, c.args.a4, c.args.a5) + case glfnUniform1fv: + syscall.Syscall(glUniform1fv.Addr(), 3, c.args.a0, c.args.a1, uintptr(c.parg)) + case glfnUniform1i: + syscall.Syscall(glUniform1i.Addr(), 2, c.args.a0, c.args.a1, 0) + case glfnUniform1iv: + syscall.Syscall(glUniform1iv.Addr(), 3, c.args.a0, c.args.a1, uintptr(c.parg)) + case glfnUniform2f: + syscall.Syscall6(glUniform2f.Addr(), 3, c.args.a0, c.args.a1, c.args.a2, c.args.a3, c.args.a4, c.args.a5) + case glfnUniform2fv: + syscall.Syscall(glUniform2fv.Addr(), 3, c.args.a0, c.args.a1, uintptr(c.parg)) + case glfnUniform2i: + syscall.Syscall(glUniform2i.Addr(), 3, c.args.a0, c.args.a1, c.args.a2) + case glfnUniform2iv: + syscall.Syscall(glUniform2iv.Addr(), 3, c.args.a0, c.args.a1, uintptr(c.parg)) + case glfnUniform3f: + syscall.Syscall6(glUniform3f.Addr(), 4, c.args.a0, c.args.a1, c.args.a2, c.args.a3, c.args.a4, c.args.a5) + case glfnUniform3fv: + syscall.Syscall(glUniform3fv.Addr(), 3, c.args.a0, c.args.a1, uintptr(c.parg)) + case glfnUniform3i: + syscall.Syscall6(glUniform3i.Addr(), 4, c.args.a0, c.args.a1, c.args.a2, c.args.a3, 0, 0) + case glfnUniform3iv: + syscall.Syscall(glUniform3iv.Addr(), 3, c.args.a0, c.args.a1, uintptr(c.parg)) + case glfnUniform4f: + syscall.Syscall6(glUniform4f.Addr(), 5, c.args.a0, c.args.a1, c.args.a2, c.args.a3, c.args.a4, c.args.a5) + case glfnUniform4fv: + syscall.Syscall(glUniform4fv.Addr(), 3, c.args.a0, c.args.a1, uintptr(c.parg)) + case glfnUniform4i: + syscall.Syscall6(glUniform4i.Addr(), 5, c.args.a0, c.args.a1, c.args.a2, c.args.a3, c.args.a4, 0) + case glfnUniform4iv: + syscall.Syscall(glUniform4iv.Addr(), 3, c.args.a0, c.args.a1, uintptr(c.parg)) + case glfnUniformMatrix2fv: + syscall.Syscall6(glUniformMatrix2fv.Addr(), 4, c.args.a0, c.args.a1, 0, uintptr(c.parg), 0, 0) + case glfnUniformMatrix3fv: + syscall.Syscall6(glUniformMatrix3fv.Addr(), 4, c.args.a0, c.args.a1, 0, uintptr(c.parg), 0, 0) + case glfnUniformMatrix4fv: + syscall.Syscall6(glUniformMatrix4fv.Addr(), 4, c.args.a0, c.args.a1, 0, uintptr(c.parg), 0, 0) + case glfnUseProgram: + syscall.Syscall(glUseProgram.Addr(), 1, c.args.a0, 0, 0) + case glfnValidateProgram: + syscall.Syscall(glValidateProgram.Addr(), 1, c.args.a0, 0, 0) + case glfnVertexAttrib1f: + syscall.Syscall6(glVertexAttrib1f.Addr(), 2, c.args.a0, c.args.a1, c.args.a2, c.args.a3, c.args.a4, c.args.a5) + case glfnVertexAttrib1fv: + syscall.Syscall(glVertexAttrib1fv.Addr(), 2, c.args.a0, uintptr(c.parg), 0) + case glfnVertexAttrib2f: + syscall.Syscall6(glVertexAttrib2f.Addr(), 3, c.args.a0, c.args.a1, c.args.a2, c.args.a3, c.args.a4, c.args.a5) + case glfnVertexAttrib2fv: + syscall.Syscall(glVertexAttrib2fv.Addr(), 2, c.args.a0, uintptr(c.parg), 0) + case glfnVertexAttrib3f: + syscall.Syscall6(glVertexAttrib3f.Addr(), 4, c.args.a0, c.args.a1, c.args.a2, c.args.a3, c.args.a4, c.args.a5) + case glfnVertexAttrib3fv: + syscall.Syscall(glVertexAttrib3fv.Addr(), 2, c.args.a0, uintptr(c.parg), 0) + case glfnVertexAttrib4f: + syscall.Syscall6(glVertexAttrib4f.Addr(), 5, c.args.a0, c.args.a1, c.args.a2, c.args.a3, c.args.a4, c.args.a5) + case glfnVertexAttrib4fv: + syscall.Syscall(glVertexAttrib4fv.Addr(), 2, c.args.a0, uintptr(c.parg), 0) + case glfnVertexAttribPointer: + syscall.Syscall6(glVertexAttribPointer.Addr(), 6, c.args.a0, c.args.a1, c.args.a2, c.args.a3, c.args.a4, c.args.a5) + case glfnViewport: + syscall.Syscall6(glViewport.Addr(), 4, c.args.a0, c.args.a1, c.args.a2, c.args.a3, 0, 0) + default: + panic("unknown GL function") + } + + return ret +} + +// Exported libraries for a Windows GUI driver. +// +// LibEGL is not used directly by the gl package, but is needed by any +// driver hoping to use OpenGL ES. +// +// LibD3DCompiler is needed by libglesv2.dll for compiling shaders. +var ( + LibGLESv2 = syscall.NewLazyDLL("libglesv2.dll") + LibEGL = syscall.NewLazyDLL("libegl.dll") + LibD3DCompiler = syscall.NewLazyDLL("d3dcompiler_47.dll") +) + +var ( + libGLESv2 = LibGLESv2 + glActiveTexture = libGLESv2.NewProc("glActiveTexture") + glAttachShader = libGLESv2.NewProc("glAttachShader") + glBindAttribLocation = libGLESv2.NewProc("glBindAttribLocation") + glBindBuffer = libGLESv2.NewProc("glBindBuffer") + glBindFramebuffer = libGLESv2.NewProc("glBindFramebuffer") + glBindRenderbuffer = libGLESv2.NewProc("glBindRenderbuffer") + glBindTexture = libGLESv2.NewProc("glBindTexture") + glBindVertexArray = libGLESv2.NewProc("glBindVertexArray") + glBlendColor = libGLESv2.NewProc("glBlendColor") + glBlendEquation = libGLESv2.NewProc("glBlendEquation") + glBlendEquationSeparate = libGLESv2.NewProc("glBlendEquationSeparate") + glBlendFunc = libGLESv2.NewProc("glBlendFunc") + glBlendFuncSeparate = libGLESv2.NewProc("glBlendFuncSeparate") + glBufferData = libGLESv2.NewProc("glBufferData") + glBufferSubData = libGLESv2.NewProc("glBufferSubData") + glCheckFramebufferStatus = libGLESv2.NewProc("glCheckFramebufferStatus") + glClear = libGLESv2.NewProc("glClear") + glClearColor = libGLESv2.NewProc("glClearColor") + glClearDepthf = libGLESv2.NewProc("glClearDepthf") + glClearStencil = libGLESv2.NewProc("glClearStencil") + glColorMask = libGLESv2.NewProc("glColorMask") + glCompileShader = libGLESv2.NewProc("glCompileShader") + glCompressedTexImage2D = libGLESv2.NewProc("glCompressedTexImage2D") + glCompressedTexSubImage2D = libGLESv2.NewProc("glCompressedTexSubImage2D") + glCopyTexImage2D = libGLESv2.NewProc("glCopyTexImage2D") + glCopyTexSubImage2D = libGLESv2.NewProc("glCopyTexSubImage2D") + glCreateProgram = libGLESv2.NewProc("glCreateProgram") + glCreateShader = libGLESv2.NewProc("glCreateShader") + glCullFace = libGLESv2.NewProc("glCullFace") + glDeleteBuffers = libGLESv2.NewProc("glDeleteBuffers") + glDeleteFramebuffers = libGLESv2.NewProc("glDeleteFramebuffers") + glDeleteProgram = libGLESv2.NewProc("glDeleteProgram") + glDeleteRenderbuffers = libGLESv2.NewProc("glDeleteRenderbuffers") + glDeleteShader = libGLESv2.NewProc("glDeleteShader") + glDeleteTextures = libGLESv2.NewProc("glDeleteTextures") + glDeleteVertexArrays = libGLESv2.NewProc("glDeleteVertexArrays") + glDepthFunc = libGLESv2.NewProc("glDepthFunc") + glDepthRangef = libGLESv2.NewProc("glDepthRangef") + glDepthMask = libGLESv2.NewProc("glDepthMask") + glDetachShader = libGLESv2.NewProc("glDetachShader") + glDisable = libGLESv2.NewProc("glDisable") + glDisableVertexAttribArray = libGLESv2.NewProc("glDisableVertexAttribArray") + glDrawArrays = libGLESv2.NewProc("glDrawArrays") + glDrawElements = libGLESv2.NewProc("glDrawElements") + glEnable = libGLESv2.NewProc("glEnable") + glEnableVertexAttribArray = libGLESv2.NewProc("glEnableVertexAttribArray") + glFinish = libGLESv2.NewProc("glFinish") + glFlush = libGLESv2.NewProc("glFlush") + glFramebufferRenderbuffer = libGLESv2.NewProc("glFramebufferRenderbuffer") + glFramebufferTexture2D = libGLESv2.NewProc("glFramebufferTexture2D") + glFrontFace = libGLESv2.NewProc("glFrontFace") + glGenBuffers = libGLESv2.NewProc("glGenBuffers") + glGenFramebuffers = libGLESv2.NewProc("glGenFramebuffers") + glGenRenderbuffers = libGLESv2.NewProc("glGenRenderbuffers") + glGenTextures = libGLESv2.NewProc("glGenTextures") + glGenVertexArrays = libGLESv2.NewProc("glGenVertexArrays") + glGenerateMipmap = libGLESv2.NewProc("glGenerateMipmap") + glGetActiveAttrib = libGLESv2.NewProc("glGetActiveAttrib") + glGetActiveUniform = libGLESv2.NewProc("glGetActiveUniform") + glGetAttachedShaders = libGLESv2.NewProc("glGetAttachedShaders") + glGetAttribLocation = libGLESv2.NewProc("glGetAttribLocation") + glGetBooleanv = libGLESv2.NewProc("glGetBooleanv") + glGetBufferParameteri = libGLESv2.NewProc("glGetBufferParameteri") + glGetError = libGLESv2.NewProc("glGetError") + glGetFloatv = libGLESv2.NewProc("glGetFloatv") + glGetFramebufferAttachmentParameteriv = libGLESv2.NewProc("glGetFramebufferAttachmentParameteriv") + glGetIntegerv = libGLESv2.NewProc("glGetIntegerv") + glGetProgramInfoLog = libGLESv2.NewProc("glGetProgramInfoLog") + glGetProgramiv = libGLESv2.NewProc("glGetProgramiv") + glGetRenderbufferParameteriv = libGLESv2.NewProc("glGetRenderbufferParameteriv") + glGetShaderInfoLog = libGLESv2.NewProc("glGetShaderInfoLog") + glGetShaderPrecisionFormat = libGLESv2.NewProc("glGetShaderPrecisionFormat") + glGetShaderSource = libGLESv2.NewProc("glGetShaderSource") + glGetShaderiv = libGLESv2.NewProc("glGetShaderiv") + glGetString = libGLESv2.NewProc("glGetString") + glGetTexParameterfv = libGLESv2.NewProc("glGetTexParameterfv") + glGetTexParameteriv = libGLESv2.NewProc("glGetTexParameteriv") + glGetUniformLocation = libGLESv2.NewProc("glGetUniformLocation") + glGetUniformfv = libGLESv2.NewProc("glGetUniformfv") + glGetUniformiv = libGLESv2.NewProc("glGetUniformiv") + glGetVertexAttribfv = libGLESv2.NewProc("glGetVertexAttribfv") + glGetVertexAttribiv = libGLESv2.NewProc("glGetVertexAttribiv") + glHint = libGLESv2.NewProc("glHint") + glIsBuffer = libGLESv2.NewProc("glIsBuffer") + glIsEnabled = libGLESv2.NewProc("glIsEnabled") + glIsFramebuffer = libGLESv2.NewProc("glIsFramebuffer") + glIsProgram = libGLESv2.NewProc("glIsProgram") + glIsRenderbuffer = libGLESv2.NewProc("glIsRenderbuffer") + glIsShader = libGLESv2.NewProc("glIsShader") + glIsTexture = libGLESv2.NewProc("glIsTexture") + glLineWidth = libGLESv2.NewProc("glLineWidth") + glLinkProgram = libGLESv2.NewProc("glLinkProgram") + glPixelStorei = libGLESv2.NewProc("glPixelStorei") + glPolygonOffset = libGLESv2.NewProc("glPolygonOffset") + glReadPixels = libGLESv2.NewProc("glReadPixels") + glReleaseShaderCompiler = libGLESv2.NewProc("glReleaseShaderCompiler") + glRenderbufferStorage = libGLESv2.NewProc("glRenderbufferStorage") + glSampleCoverage = libGLESv2.NewProc("glSampleCoverage") + glScissor = libGLESv2.NewProc("glScissor") + glShaderSource = libGLESv2.NewProc("glShaderSource") + glStencilFunc = libGLESv2.NewProc("glStencilFunc") + glStencilFuncSeparate = libGLESv2.NewProc("glStencilFuncSeparate") + glStencilMask = libGLESv2.NewProc("glStencilMask") + glStencilMaskSeparate = libGLESv2.NewProc("glStencilMaskSeparate") + glStencilOp = libGLESv2.NewProc("glStencilOp") + glStencilOpSeparate = libGLESv2.NewProc("glStencilOpSeparate") + glTexImage2D = libGLESv2.NewProc("glTexImage2D") + glTexParameterf = libGLESv2.NewProc("glTexParameterf") + glTexParameterfv = libGLESv2.NewProc("glTexParameterfv") + glTexParameteri = libGLESv2.NewProc("glTexParameteri") + glTexParameteriv = libGLESv2.NewProc("glTexParameteriv") + glTexSubImage2D = libGLESv2.NewProc("glTexSubImage2D") + glUniform1f = libGLESv2.NewProc("glUniform1f") + glUniform1fv = libGLESv2.NewProc("glUniform1fv") + glUniform1i = libGLESv2.NewProc("glUniform1i") + glUniform1iv = libGLESv2.NewProc("glUniform1iv") + glUniform2f = libGLESv2.NewProc("glUniform2f") + glUniform2fv = libGLESv2.NewProc("glUniform2fv") + glUniform2i = libGLESv2.NewProc("glUniform2i") + glUniform2iv = libGLESv2.NewProc("glUniform2iv") + glUniform3f = libGLESv2.NewProc("glUniform3f") + glUniform3fv = libGLESv2.NewProc("glUniform3fv") + glUniform3i = libGLESv2.NewProc("glUniform3i") + glUniform3iv = libGLESv2.NewProc("glUniform3iv") + glUniform4f = libGLESv2.NewProc("glUniform4f") + glUniform4fv = libGLESv2.NewProc("glUniform4fv") + glUniform4i = libGLESv2.NewProc("glUniform4i") + glUniform4iv = libGLESv2.NewProc("glUniform4iv") + glUniformMatrix2fv = libGLESv2.NewProc("glUniformMatrix2fv") + glUniformMatrix3fv = libGLESv2.NewProc("glUniformMatrix3fv") + glUniformMatrix4fv = libGLESv2.NewProc("glUniformMatrix4fv") + glUseProgram = libGLESv2.NewProc("glUseProgram") + glValidateProgram = libGLESv2.NewProc("glValidateProgram") + glVertexAttrib1f = libGLESv2.NewProc("glVertexAttrib1f") + glVertexAttrib1fv = libGLESv2.NewProc("glVertexAttrib1fv") + glVertexAttrib2f = libGLESv2.NewProc("glVertexAttrib2f") + glVertexAttrib2fv = libGLESv2.NewProc("glVertexAttrib2fv") + glVertexAttrib3f = libGLESv2.NewProc("glVertexAttrib3f") + glVertexAttrib3fv = libGLESv2.NewProc("glVertexAttrib3fv") + glVertexAttrib4f = libGLESv2.NewProc("glVertexAttrib4f") + glVertexAttrib4fv = libGLESv2.NewProc("glVertexAttrib4fv") + glVertexAttribPointer = libGLESv2.NewProc("glVertexAttribPointer") + glViewport = libGLESv2.NewProc("glViewport") +) diff --git a/vendor/github.com/ebitengine/gomobile/gl/work_windows_386.s b/vendor/github.com/ebitengine/gomobile/gl/work_windows_386.s new file mode 100644 index 0000000..c80e98a --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/gl/work_windows_386.s @@ -0,0 +1,9 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// fixFloat is unnecessary for windows/386 +TEXT ·fixFloat(SB),NOSPLIT,$0-16 + RET diff --git a/vendor/github.com/ebitengine/gomobile/gl/work_windows_amd64.s b/vendor/github.com/ebitengine/gomobile/gl/work_windows_amd64.s new file mode 100644 index 0000000..e74ac5c --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/gl/work_windows_amd64.s @@ -0,0 +1,12 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +TEXT ·fixFloat(SB),NOSPLIT,$0-32 + MOVQ x0+0(FP), X0 + MOVQ x1+8(FP), X1 + MOVQ x2+16(FP), X2 + MOVQ x3+24(FP), X3 + RET diff --git a/vendor/github.com/ebitengine/gomobile/internal/mobileinit/ctx_android.go b/vendor/github.com/ebitengine/gomobile/internal/mobileinit/ctx_android.go new file mode 100644 index 0000000..b58881a --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/internal/mobileinit/ctx_android.go @@ -0,0 +1,124 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mobileinit + +/* +#include +#include + +static char* lockJNI(JavaVM *vm, uintptr_t* envp, int* attachedp) { + JNIEnv* env; + + if (vm == NULL) { + return "no current JVM"; + } + + *attachedp = 0; + switch ((*vm)->GetEnv(vm, (void**)&env, JNI_VERSION_1_6)) { + case JNI_OK: + break; + case JNI_EDETACHED: + if ((*vm)->AttachCurrentThread(vm, &env, 0) != 0) { + return "cannot attach to JVM"; + } + *attachedp = 1; + break; + case JNI_EVERSION: + return "bad JNI version"; + default: + return "unknown JNI error from GetEnv"; + } + + *envp = (uintptr_t)env; + return NULL; +} + +static char* checkException(uintptr_t jnienv) { + jthrowable exc; + JNIEnv* env = (JNIEnv*)jnienv; + + if (!(*env)->ExceptionCheck(env)) { + return NULL; + } + + exc = (*env)->ExceptionOccurred(env); + (*env)->ExceptionClear(env); + + jclass clazz = (*env)->FindClass(env, "java/lang/Throwable"); + jmethodID toString = (*env)->GetMethodID(env, clazz, "toString", "()Ljava/lang/String;"); + jobject msgStr = (*env)->CallObjectMethod(env, exc, toString); + return (char*)(*env)->GetStringUTFChars(env, msgStr, 0); +} + +static void unlockJNI(JavaVM *vm) { + (*vm)->DetachCurrentThread(vm); +} +*/ +import "C" + +import ( + "errors" + "runtime" + "unsafe" +) + +// currentVM is stored to initialize other cgo packages. +// +// As all the Go packages in a program form a single shared library, +// there can only be one JNI_OnLoad function for initialization. In +// OpenJDK there is JNI_GetCreatedJavaVMs, but this is not available +// on android. +var currentVM *C.JavaVM + +// currentCtx is Android's android.context.Context. May be NULL. +var currentCtx C.jobject + +// SetCurrentContext populates the global Context object with the specified +// current JavaVM instance (vm) and android.context.Context object (ctx). +// The android.context.Context object must be a global reference. +func SetCurrentContext(vm unsafe.Pointer, ctx uintptr) { + currentVM = (*C.JavaVM)(vm) + currentCtx = (C.jobject)(ctx) +} + +// RunOnJVM runs fn on a new goroutine locked to an OS thread with a JNIEnv. +// +// RunOnJVM blocks until the call to fn is complete. Any Java +// exception or failure to attach to the JVM is returned as an error. +// +// The function fn takes vm, the current JavaVM*, +// env, the current JNIEnv*, and +// ctx, a jobject representing the global android.context.Context. +func RunOnJVM(fn func(vm, env, ctx uintptr) error) error { + errch := make(chan error) + go func() { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + env := C.uintptr_t(0) + attached := C.int(0) + if errStr := C.lockJNI(currentVM, &env, &attached); errStr != nil { + errch <- errors.New(C.GoString(errStr)) + return + } + if attached != 0 { + defer C.unlockJNI(currentVM) + } + + vm := uintptr(unsafe.Pointer(currentVM)) + if err := fn(vm, uintptr(env), uintptr(currentCtx)); err != nil { + errch <- err + return + } + + if exc := C.checkException(env); exc != nil { + errch <- errors.New(C.GoString(exc)) + C.free(unsafe.Pointer(exc)) + return + } + errch <- nil + }() + return <-errch +} diff --git a/vendor/github.com/ebitengine/gomobile/internal/mobileinit/mobileinit.go b/vendor/github.com/ebitengine/gomobile/internal/mobileinit/mobileinit.go new file mode 100644 index 0000000..65c0912 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/internal/mobileinit/mobileinit.go @@ -0,0 +1,11 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package mobileinit contains common initialization logic for mobile platforms +// that is relevant to both all-Go apps and gobind-based apps. +// +// Long-term, some code in this package should consider moving into Go stdlib. +package mobileinit + +import "C" diff --git a/vendor/github.com/ebitengine/gomobile/internal/mobileinit/mobileinit_android.go b/vendor/github.com/ebitengine/gomobile/internal/mobileinit/mobileinit_android.go new file mode 100644 index 0000000..cd73f43 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/internal/mobileinit/mobileinit_android.go @@ -0,0 +1,93 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mobileinit + +/* +To view the log output run: +adb logcat GoLog:I *:S +*/ + +// Android redirects stdout and stderr to /dev/null. +// As these are common debugging utilities in Go, +// we redirect them to logcat. +// +// Unfortunately, logcat is line oriented, so we must buffer. + +/* +#cgo LDFLAGS: -landroid -llog + +#include +#include +#include +*/ +import "C" + +import ( + "bufio" + "log" + "os" + "syscall" + "unsafe" +) + +var ( + ctag = C.CString("GoLog") + // Store the writer end of the redirected stderr and stdout + // so that they are not garbage collected and closed. + stderr, stdout *os.File +) + +type infoWriter struct{} + +func (infoWriter) Write(p []byte) (n int, err error) { + cstr := C.CString(string(p)) + C.__android_log_write(C.ANDROID_LOG_INFO, ctag, cstr) + C.free(unsafe.Pointer(cstr)) + return len(p), nil +} + +func lineLog(f *os.File, priority C.int) { + const logSize = 1024 // matches android/log.h. + r := bufio.NewReaderSize(f, logSize) + for { + line, _, err := r.ReadLine() + str := string(line) + if err != nil { + str += " " + err.Error() + } + cstr := C.CString(str) + C.__android_log_write(priority, ctag, cstr) + C.free(unsafe.Pointer(cstr)) + if err != nil { + break + } + } +} + +func init() { + log.SetOutput(infoWriter{}) + // android logcat includes all of log.LstdFlags + log.SetFlags(log.Flags() &^ log.LstdFlags) + + r, w, err := os.Pipe() + if err != nil { + panic(err) + } + stderr = w + if err := syscall.Dup3(int(w.Fd()), int(os.Stderr.Fd()), 0); err != nil { + panic(err) + } + go lineLog(r, C.ANDROID_LOG_ERROR) + + r, w, err = os.Pipe() + if err != nil { + panic(err) + } + stdout = w + if err := syscall.Dup3(int(w.Fd()), int(os.Stdout.Fd()), 0); err != nil { + panic(err) + } + go lineLog(r, C.ANDROID_LOG_INFO) +} diff --git a/vendor/github.com/ebitengine/gomobile/internal/mobileinit/mobileinit_ios.go b/vendor/github.com/ebitengine/gomobile/internal/mobileinit/mobileinit_ios.go new file mode 100644 index 0000000..d41b228 --- /dev/null +++ b/vendor/github.com/ebitengine/gomobile/internal/mobileinit/mobileinit_ios.go @@ -0,0 +1,41 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mobileinit + +import ( + "io" + "log" + "os" + "unsafe" +) + +/* +#include +#include + +os_log_t create_os_log() { + return os_log_create("org.golang.mobile", "os_log"); +} + +void os_log_wrap(os_log_t log, const char *str) { + os_log(log, "%s", str); +} +*/ +import "C" + +type osWriter struct { + w C.os_log_t +} + +func (o osWriter) Write(p []byte) (n int, err error) { + cstr := C.CString(string(p)) + C.os_log_wrap(o.w, cstr) + C.free(unsafe.Pointer(cstr)) + return len(p), nil +} + +func init() { + log.SetOutput(io.MultiWriter(os.Stderr, osWriter{C.create_os_log()})) +} diff --git a/vendor/github.com/ebitengine/hideconsole/.gitignore b/vendor/github.com/ebitengine/hideconsole/.gitignore new file mode 100644 index 0000000..b25c15b --- /dev/null +++ b/vendor/github.com/ebitengine/hideconsole/.gitignore @@ -0,0 +1 @@ +*~ diff --git a/vendor/github.com/ebitengine/hideconsole/LICENSE b/vendor/github.com/ebitengine/hideconsole/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/vendor/github.com/ebitengine/hideconsole/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/vendor/github.com/ebitengine/hideconsole/README.md b/vendor/github.com/ebitengine/hideconsole/README.md new file mode 100644 index 0000000..69bf26b --- /dev/null +++ b/vendor/github.com/ebitengine/hideconsole/README.md @@ -0,0 +1,15 @@ +# HideConsole + +Package hideconsole is a utility package to hide a console automatically even without `-ldflags "-Hwindowsgui"` on Windows. + +On non-Windows, this package does nothing. + +## Usage + +Import this package with a blank identifier. + +```go +import ( + _ "github.com/ebitengine/hideconsole" +) +``` diff --git a/vendor/github.com/ebitengine/hideconsole/doc.go b/vendor/github.com/ebitengine/hideconsole/doc.go new file mode 100644 index 0000000..165b284 --- /dev/null +++ b/vendor/github.com/ebitengine/hideconsole/doc.go @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2024 The Ebitengine Authors + +// Package hideconsole is a utility package to hide a console automatically +// even without `-ldflags "-Hwindowsgui"` on Windows. +// +// On non-Windows, this package does nothing. +// +// # Usage +// +// Import this package with a blank identifier: +// +// import ( +// _ "github.com/ebitengine/hideconsole" +// ) +package hideconsole diff --git a/vendor/github.com/ebitengine/hideconsole/hideconsole_windows.go b/vendor/github.com/ebitengine/hideconsole/hideconsole_windows.go new file mode 100644 index 0000000..747f6a0 --- /dev/null +++ b/vendor/github.com/ebitengine/hideconsole/hideconsole_windows.go @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2024 The Ebitengine Authors + +package hideconsole + +import ( + "fmt" + + "golang.org/x/sys/windows" +) + +var ( + kernel32 = windows.NewLazySystemDLL("kernel32.dll") + user32 = windows.NewLazySystemDLL("user32.dll") + + procFreeConsoleWindow = kernel32.NewProc("FreeConsole") + procGetConsoleWindow = kernel32.NewProc("GetConsoleWindow") +) + +func freeConsole() error { + r, _, e := procFreeConsoleWindow.Call() + if int32(r) == 0 { + if e != nil && e != windows.ERROR_SUCCESS { + return fmt.Errorf("FreeConsole failed: %w", e) + } + return fmt.Errorf("FreeConsole returned 0") + } + return nil +} + +func getConsoleWindow() windows.HWND { + r, _, _ := procGetConsoleWindow.Call() + return windows.HWND(r) +} + +// hideConsoleWindow will hide the console window that is showing when +// compiling on Windows without specifying the '-ldflags "-Hwindowsgui"' flag. +func hideConsoleWindow() { + // In Xbox, GetWindowThreadProcessId might not exist. + if user32.NewProc("GetWindowThreadProcessId").Find() != nil { + return + } + + pid := windows.GetCurrentProcessId() + + // Get the process ID of the console's creator. + var cpid uint32 + if _, err := windows.GetWindowThreadProcessId(getConsoleWindow(), &cpid); err != nil { + // Even if closing the console fails, this is not harmful. + // Ignore error. + return + } + + if pid == cpid { + // The current process created its own console. Hide this. + // Ignore error. + _ = freeConsole() + } +} + +func init() { + hideConsoleWindow() +} diff --git a/vendor/github.com/ebitengine/purego/.gitignore b/vendor/github.com/ebitengine/purego/.gitignore new file mode 100644 index 0000000..b25c15b --- /dev/null +++ b/vendor/github.com/ebitengine/purego/.gitignore @@ -0,0 +1 @@ +*~ diff --git a/vendor/github.com/ebitengine/purego/LICENSE b/vendor/github.com/ebitengine/purego/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/vendor/github.com/ebitengine/purego/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/vendor/github.com/ebitengine/purego/README.md b/vendor/github.com/ebitengine/purego/README.md new file mode 100644 index 0000000..f1ff905 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/README.md @@ -0,0 +1,97 @@ +# purego +[![Go Reference](https://pkg.go.dev/badge/github.com/ebitengine/purego?GOOS=darwin.svg)](https://pkg.go.dev/github.com/ebitengine/purego?GOOS=darwin) + +A library for calling C functions from Go without Cgo. + +> This is beta software so expect bugs and potentially API breaking changes +> but each release will be tagged to avoid breaking people's code. +> Bug reports are encouraged. + +## Motivation + +The [Ebitengine](https://github.com/hajimehoshi/ebiten) game engine was ported to use only Go on Windows. This enabled +cross-compiling to Windows from any other operating system simply by setting `GOOS=windows`. The purego project was +born to bring that same vision to the other platforms supported by Ebitengine. + +## Benefits + +- **Simple Cross-Compilation**: No C means you can build for other platforms easily without a C compiler. +- **Faster Compilation**: Efficiently cache your entirely Go builds. +- **Smaller Binaries**: Using Cgo generates a C wrapper function for each C function called. Purego doesn't! +- **Dynamic Linking**: Load symbols at runtime and use it as a plugin system. +- **Foreign Function Interface**: Call into other languages that are compiled into shared objects. +- **Cgo Fallback**: Works even with CGO_ENABLED=1 so incremental porting is possible. +This also means unsupported GOARCHs (freebsd/riscv64, linux/mips, etc.) will still work +except for float arguments and return values. + +## Supported Platforms + +- **FreeBSD**: amd64, arm64 +- **Linux**: amd64, arm64 +- **macOS / iOS**: amd64, arm64 +- **Windows**: 386*, amd64, arm*, arm64 + +`*` These architectures only support SyscallN and NewCallback + +## Example + +The example below only showcases purego use for macOS and Linux. The other platforms require special handling which can +be seen in the complete example at [examples/libc](https://github.com/ebitengine/purego/tree/main/examples/libc) which supports Windows and FreeBSD. + +```go +package main + +import ( + "fmt" + "runtime" + + "github.com/ebitengine/purego" +) + +func getSystemLibrary() string { + switch runtime.GOOS { + case "darwin": + return "/usr/lib/libSystem.B.dylib" + case "linux": + return "libc.so.6" + default: + panic(fmt.Errorf("GOOS=%s is not supported", runtime.GOOS)) + } +} + +func main() { + libc, err := purego.Dlopen(getSystemLibrary(), purego.RTLD_NOW|purego.RTLD_GLOBAL) + if err != nil { + panic(err) + } + var puts func(string) + purego.RegisterLibFunc(&puts, libc, "puts") + puts("Calling C from Go without Cgo!") +} +``` + +Then to run: `CGO_ENABLED=0 go run main.go` + +## Questions + +If you have questions about how to incorporate purego in your project or want to discuss +how it works join the [Discord](https://discord.gg/HzGZVD6BkY)! + +### External Code + +Purego uses code that originates from the Go runtime. These files are under the BSD-3 +License that can be found [in the Go Source](https://github.com/golang/go/blob/master/LICENSE). +This is a list of the copied files: + +* `abi_*.h` from package `runtime/cgo` +* `zcallback_darwin_*.s` from package `runtime` +* `internal/fakecgo/abi_*.h` from package `runtime/cgo` +* `internal/fakecgo/asm_GOARCH.s` from package `runtime/cgo` +* `internal/fakecgo/callbacks.go` from package `runtime/cgo` +* `internal/fakecgo/go_GOOS_GOARCH.go` from package `runtime/cgo` +* `internal/fakecgo/iscgo.go` from package `runtime/cgo` +* `internal/fakecgo/setenv.go` from package `runtime/cgo` +* `internal/fakecgo/freebsd.go` from package `runtime/cgo` + +The files `abi_*.h` and `internal/fakecgo/abi_*.h` are the same because Bazel does not support cross-package use of +`#include` so we need each one once per package. (cf. [issue](https://github.com/bazelbuild/rules_go/issues/3636)) diff --git a/vendor/github.com/ebitengine/purego/abi_amd64.h b/vendor/github.com/ebitengine/purego/abi_amd64.h new file mode 100644 index 0000000..9949435 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/abi_amd64.h @@ -0,0 +1,99 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Macros for transitioning from the host ABI to Go ABI0. +// +// These save the frame pointer, so in general, functions that use +// these should have zero frame size to suppress the automatic frame +// pointer, though it's harmless to not do this. + +#ifdef GOOS_windows + +// REGS_HOST_TO_ABI0_STACK is the stack bytes used by +// PUSH_REGS_HOST_TO_ABI0. +#define REGS_HOST_TO_ABI0_STACK (28*8 + 8) + +// PUSH_REGS_HOST_TO_ABI0 prepares for transitioning from +// the host ABI to Go ABI0 code. It saves all registers that are +// callee-save in the host ABI and caller-save in Go ABI0 and prepares +// for entry to Go. +// +// Save DI SI BP BX R12 R13 R14 R15 X6-X15 registers and the DF flag. +// Clear the DF flag for the Go ABI. +// MXCSR matches the Go ABI, so we don't have to set that, +// and Go doesn't modify it, so we don't have to save it. +#define PUSH_REGS_HOST_TO_ABI0() \ + PUSHFQ \ + CLD \ + ADJSP $(REGS_HOST_TO_ABI0_STACK - 8) \ + MOVQ DI, (0*0)(SP) \ + MOVQ SI, (1*8)(SP) \ + MOVQ BP, (2*8)(SP) \ + MOVQ BX, (3*8)(SP) \ + MOVQ R12, (4*8)(SP) \ + MOVQ R13, (5*8)(SP) \ + MOVQ R14, (6*8)(SP) \ + MOVQ R15, (7*8)(SP) \ + MOVUPS X6, (8*8)(SP) \ + MOVUPS X7, (10*8)(SP) \ + MOVUPS X8, (12*8)(SP) \ + MOVUPS X9, (14*8)(SP) \ + MOVUPS X10, (16*8)(SP) \ + MOVUPS X11, (18*8)(SP) \ + MOVUPS X12, (20*8)(SP) \ + MOVUPS X13, (22*8)(SP) \ + MOVUPS X14, (24*8)(SP) \ + MOVUPS X15, (26*8)(SP) + +#define POP_REGS_HOST_TO_ABI0() \ + MOVQ (0*0)(SP), DI \ + MOVQ (1*8)(SP), SI \ + MOVQ (2*8)(SP), BP \ + MOVQ (3*8)(SP), BX \ + MOVQ (4*8)(SP), R12 \ + MOVQ (5*8)(SP), R13 \ + MOVQ (6*8)(SP), R14 \ + MOVQ (7*8)(SP), R15 \ + MOVUPS (8*8)(SP), X6 \ + MOVUPS (10*8)(SP), X7 \ + MOVUPS (12*8)(SP), X8 \ + MOVUPS (14*8)(SP), X9 \ + MOVUPS (16*8)(SP), X10 \ + MOVUPS (18*8)(SP), X11 \ + MOVUPS (20*8)(SP), X12 \ + MOVUPS (22*8)(SP), X13 \ + MOVUPS (24*8)(SP), X14 \ + MOVUPS (26*8)(SP), X15 \ + ADJSP $-(REGS_HOST_TO_ABI0_STACK - 8) \ + POPFQ + +#else +// SysV ABI + +#define REGS_HOST_TO_ABI0_STACK (6*8) + +// SysV MXCSR matches the Go ABI, so we don't have to set that, +// and Go doesn't modify it, so we don't have to save it. +// Both SysV and Go require DF to be cleared, so that's already clear. +// The SysV and Go frame pointer conventions are compatible. +#define PUSH_REGS_HOST_TO_ABI0() \ + ADJSP $(REGS_HOST_TO_ABI0_STACK) \ + MOVQ BP, (5*8)(SP) \ + LEAQ (5*8)(SP), BP \ + MOVQ BX, (0*8)(SP) \ + MOVQ R12, (1*8)(SP) \ + MOVQ R13, (2*8)(SP) \ + MOVQ R14, (3*8)(SP) \ + MOVQ R15, (4*8)(SP) + +#define POP_REGS_HOST_TO_ABI0() \ + MOVQ (0*8)(SP), BX \ + MOVQ (1*8)(SP), R12 \ + MOVQ (2*8)(SP), R13 \ + MOVQ (3*8)(SP), R14 \ + MOVQ (4*8)(SP), R15 \ + MOVQ (5*8)(SP), BP \ + ADJSP $-(REGS_HOST_TO_ABI0_STACK) + +#endif diff --git a/vendor/github.com/ebitengine/purego/abi_arm64.h b/vendor/github.com/ebitengine/purego/abi_arm64.h new file mode 100644 index 0000000..5d5061e --- /dev/null +++ b/vendor/github.com/ebitengine/purego/abi_arm64.h @@ -0,0 +1,39 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Macros for transitioning from the host ABI to Go ABI0. +// +// These macros save and restore the callee-saved registers +// from the stack, but they don't adjust stack pointer, so +// the user should prepare stack space in advance. +// SAVE_R19_TO_R28(offset) saves R19 ~ R28 to the stack space +// of ((offset)+0*8)(RSP) ~ ((offset)+9*8)(RSP). +// +// SAVE_F8_TO_F15(offset) saves F8 ~ F15 to the stack space +// of ((offset)+0*8)(RSP) ~ ((offset)+7*8)(RSP). +// +// R29 is not saved because Go will save and restore it. + +#define SAVE_R19_TO_R28(offset) \ + STP (R19, R20), ((offset)+0*8)(RSP) \ + STP (R21, R22), ((offset)+2*8)(RSP) \ + STP (R23, R24), ((offset)+4*8)(RSP) \ + STP (R25, R26), ((offset)+6*8)(RSP) \ + STP (R27, g), ((offset)+8*8)(RSP) +#define RESTORE_R19_TO_R28(offset) \ + LDP ((offset)+0*8)(RSP), (R19, R20) \ + LDP ((offset)+2*8)(RSP), (R21, R22) \ + LDP ((offset)+4*8)(RSP), (R23, R24) \ + LDP ((offset)+6*8)(RSP), (R25, R26) \ + LDP ((offset)+8*8)(RSP), (R27, g) /* R28 */ +#define SAVE_F8_TO_F15(offset) \ + FSTPD (F8, F9), ((offset)+0*8)(RSP) \ + FSTPD (F10, F11), ((offset)+2*8)(RSP) \ + FSTPD (F12, F13), ((offset)+4*8)(RSP) \ + FSTPD (F14, F15), ((offset)+6*8)(RSP) +#define RESTORE_F8_TO_F15(offset) \ + FLDPD ((offset)+0*8)(RSP), (F8, F9) \ + FLDPD ((offset)+2*8)(RSP), (F10, F11) \ + FLDPD ((offset)+4*8)(RSP), (F12, F13) \ + FLDPD ((offset)+6*8)(RSP), (F14, F15) diff --git a/vendor/github.com/ebitengine/purego/cgo.go b/vendor/github.com/ebitengine/purego/cgo.go new file mode 100644 index 0000000..7d5abef --- /dev/null +++ b/vendor/github.com/ebitengine/purego/cgo.go @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build cgo && (darwin || freebsd || linux) + +package purego + +// if CGO_ENABLED=1 import the Cgo runtime to ensure that it is set up properly. +// This is required since some frameworks need TLS setup the C way which Go doesn't do. +// We currently don't support ios in fakecgo mode so force Cgo or fail +// Even if CGO_ENABLED=1 the Cgo runtime is not imported unless `import "C"` is used. +// which will import this package automatically. Normally this isn't an issue since it +// usually isn't possible to call into C without using that import. However, with purego +// it is since we don't use `import "C"`! +import ( + _ "runtime/cgo" + + _ "github.com/ebitengine/purego/internal/cgo" +) diff --git a/vendor/github.com/ebitengine/purego/dlerror.go b/vendor/github.com/ebitengine/purego/dlerror.go new file mode 100644 index 0000000..95cdfe1 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/dlerror.go @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2023 The Ebitengine Authors + +//go:build darwin || freebsd || linux + +package purego + +// Dlerror represents an error value returned from Dlopen, Dlsym, or Dlclose. +// +// This type is not available on Windows as there is no counterpart to it on Windows. +type Dlerror struct { + s string +} + +func (e Dlerror) Error() string { + return e.s +} diff --git a/vendor/github.com/ebitengine/purego/dlfcn.go b/vendor/github.com/ebitengine/purego/dlfcn.go new file mode 100644 index 0000000..f70a245 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/dlfcn.go @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build (darwin || freebsd || linux) && !android && !faketime + +package purego + +import ( + "unsafe" +) + +// Unix Specification for dlfcn.h: https://pubs.opengroup.org/onlinepubs/7908799/xsh/dlfcn.h.html + +var ( + fnDlopen func(path string, mode int) uintptr + fnDlsym func(handle uintptr, name string) uintptr + fnDlerror func() string + fnDlclose func(handle uintptr) bool +) + +func init() { + RegisterFunc(&fnDlopen, dlopenABI0) + RegisterFunc(&fnDlsym, dlsymABI0) + RegisterFunc(&fnDlerror, dlerrorABI0) + RegisterFunc(&fnDlclose, dlcloseABI0) +} + +// Dlopen examines the dynamic library or bundle file specified by path. If the file is compatible +// with the current process and has not already been loaded into the +// current process, it is loaded and linked. After being linked, if it contains +// any initializer functions, they are called, before Dlopen +// returns. It returns a handle that can be used with Dlsym and Dlclose. +// A second call to Dlopen with the same path will return the same handle, but the internal +// reference count for the handle will be incremented. Therefore, all +// Dlopen calls should be balanced with a Dlclose call. +// +// This function is not available on Windows. +// Use [golang.org/x/sys/windows.LoadLibrary], [golang.org/x/sys/windows.LoadLibraryEx], +// [golang.org/x/sys/windows.NewLazyDLL], or [golang.org/x/sys/windows.NewLazySystemDLL] for Windows instead. +func Dlopen(path string, mode int) (uintptr, error) { + u := fnDlopen(path, mode) + if u == 0 { + return 0, Dlerror{fnDlerror()} + } + return u, nil +} + +// Dlsym takes a "handle" of a dynamic library returned by Dlopen and the symbol name. +// It returns the address where that symbol is loaded into memory. If the symbol is not found, +// in the specified library or any of the libraries that were automatically loaded by Dlopen +// when that library was loaded, Dlsym returns zero. +// +// This function is not available on Windows. +// Use [golang.org/x/sys/windows.GetProcAddress] for Windows instead. +func Dlsym(handle uintptr, name string) (uintptr, error) { + u := fnDlsym(handle, name) + if u == 0 { + return 0, Dlerror{fnDlerror()} + } + return u, nil +} + +// Dlclose decrements the reference count on the dynamic library handle. +// If the reference count drops to zero and no other loaded libraries +// use symbols in it, then the dynamic library is unloaded. +// +// This function is not available on Windows. +// Use [golang.org/x/sys/windows.FreeLibrary] for Windows instead. +func Dlclose(handle uintptr) error { + if fnDlclose(handle) { + return Dlerror{fnDlerror()} + } + return nil +} + +func loadSymbol(handle uintptr, name string) (uintptr, error) { + return Dlsym(handle, name) +} + +// these functions exist in dlfcn_stubs.s and are calling C functions linked to in dlfcn_GOOS.go +// the indirection is necessary because a function is actually a pointer to the pointer to the code. +// sadly, I do not know of anyway to remove the assembly stubs entirely because //go:linkname doesn't +// appear to work if you link directly to the C function on darwin arm64. + +//go:linkname dlopen dlopen +var dlopen uintptr +var dlopenABI0 = uintptr(unsafe.Pointer(&dlopen)) + +//go:linkname dlsym dlsym +var dlsym uintptr +var dlsymABI0 = uintptr(unsafe.Pointer(&dlsym)) + +//go:linkname dlclose dlclose +var dlclose uintptr +var dlcloseABI0 = uintptr(unsafe.Pointer(&dlclose)) + +//go:linkname dlerror dlerror +var dlerror uintptr +var dlerrorABI0 = uintptr(unsafe.Pointer(&dlerror)) diff --git a/vendor/github.com/ebitengine/purego/dlfcn_android.go b/vendor/github.com/ebitengine/purego/dlfcn_android.go new file mode 100644 index 0000000..0d53417 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/dlfcn_android.go @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2024 The Ebitengine Authors + +package purego + +import "github.com/ebitengine/purego/internal/cgo" + +// Source for constants: https://android.googlesource.com/platform/bionic/+/refs/heads/main/libc/include/dlfcn.h + +const ( + is64bit = 1 << (^uintptr(0) >> 63) / 2 + is32bit = 1 - is64bit + RTLD_DEFAULT = is32bit * 0xffffffff + RTLD_LAZY = 0x00000001 + RTLD_NOW = is64bit * 0x00000002 + RTLD_LOCAL = 0x00000000 + RTLD_GLOBAL = is64bit*0x00100 | is32bit*0x00000002 +) + +func Dlopen(path string, mode int) (uintptr, error) { + return cgo.Dlopen(path, mode) +} + +func Dlsym(handle uintptr, name string) (uintptr, error) { + return cgo.Dlsym(handle, name) +} + +func Dlclose(handle uintptr) error { + return cgo.Dlclose(handle) +} + +func loadSymbol(handle uintptr, name string) (uintptr, error) { + return Dlsym(handle, name) +} diff --git a/vendor/github.com/ebitengine/purego/dlfcn_darwin.go b/vendor/github.com/ebitengine/purego/dlfcn_darwin.go new file mode 100644 index 0000000..5f87627 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/dlfcn_darwin.go @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +package purego + +// Source for constants: https://opensource.apple.com/source/dyld/dyld-360.14/include/dlfcn.h.auto.html + +const ( + RTLD_DEFAULT = 1<<64 - 2 // Pseudo-handle for dlsym so search for any loaded symbol + RTLD_LAZY = 0x1 // Relocations are performed at an implementation-dependent time. + RTLD_NOW = 0x2 // Relocations are performed when the object is loaded. + RTLD_LOCAL = 0x4 // All symbols are not made available for relocation processing by other modules. + RTLD_GLOBAL = 0x8 // All symbols are available for relocation processing of other modules. +) + +//go:cgo_import_dynamic purego_dlopen dlopen "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_dlsym dlsym "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_dlerror dlerror "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_dlclose dlclose "/usr/lib/libSystem.B.dylib" + +//go:cgo_import_dynamic purego_dlopen dlopen "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_dlsym dlsym "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_dlerror dlerror "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_dlclose dlclose "/usr/lib/libSystem.B.dylib" diff --git a/vendor/github.com/ebitengine/purego/dlfcn_freebsd.go b/vendor/github.com/ebitengine/purego/dlfcn_freebsd.go new file mode 100644 index 0000000..6b37162 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/dlfcn_freebsd.go @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +package purego + +// Constants as defined in https://github.com/freebsd/freebsd-src/blob/main/include/dlfcn.h +const ( + intSize = 32 << (^uint(0) >> 63) // 32 or 64 + RTLD_DEFAULT = 1< C) +// +// string <=> char* +// bool <=> _Bool +// uintptr <=> uintptr_t +// uint <=> uint32_t or uint64_t +// uint8 <=> uint8_t +// uint16 <=> uint16_t +// uint32 <=> uint32_t +// uint64 <=> uint64_t +// int <=> int32_t or int64_t +// int8 <=> int8_t +// int16 <=> int16_t +// int32 <=> int32_t +// int64 <=> int64_t +// float32 <=> float +// float64 <=> double +// struct <=> struct (WIP - darwin only) +// func <=> C function +// unsafe.Pointer, *T <=> void* +// []T => void* +// +// There is a special case when the last argument of fptr is a variadic interface (or []interface} +// it will be expanded into a call to the C function as if it had the arguments in that slice. +// This means that using arg ...interface{} is like a cast to the function with the arguments inside arg. +// This is not the same as C variadic. +// +// # Memory +// +// In general it is not possible for purego to guarantee the lifetimes of objects returned or received from +// calling functions using RegisterFunc. For arguments to a C function it is important that the C function doesn't +// hold onto a reference to Go memory. This is the same as the [Cgo rules]. +// +// However, there are some special cases. When passing a string as an argument if the string does not end in a null +// terminated byte (\x00) then the string will be copied into memory maintained by purego. The memory is only valid for +// that specific call. Therefore, if the C code keeps a reference to that string it may become invalid at some +// undefined time. However, if the string does already contain a null-terminated byte then no copy is done. +// It is then the responsibility of the caller to ensure the string stays alive as long as it's needed in C memory. +// This can be done using runtime.KeepAlive or allocating the string in C memory using malloc. When a C function +// returns a null-terminated pointer to char a Go string can be used. Purego will allocate a new string in Go memory +// and copy the data over. This string will be garbage collected whenever Go decides it's no longer referenced. +// This C created string will not be freed by purego. If the pointer to char is not null-terminated or must continue +// to point to C memory (because it's a buffer for example) then use a pointer to byte and then convert that to a slice +// using unsafe.Slice. Doing this means that it becomes the responsibility of the caller to care about the lifetime +// of the pointer +// +// # Structs +// +// Purego can handle the most common structs that have fields of builtin types like int8, uint16, float32, etc. However, +// it does not support aligning fields properly. It is therefore the responsibility of the caller to ensure +// that all padding is added to the Go struct to match the C one. See `BoolStructFn` in struct_test.go for an example. +// +// # Example +// +// All functions below call this C function: +// +// char *foo(char *str); +// +// // Let purego convert types +// var foo func(s string) string +// goString := foo("copied") +// // Go will garbage collect this string +// +// // Manually, handle allocations +// var foo2 func(b string) *byte +// mustFree := foo2("not copied\x00") +// defer free(mustFree) +// +// [Cgo rules]: https://pkg.go.dev/cmd/cgo#hdr-Go_references_to_C +func RegisterFunc(fptr interface{}, cfn uintptr) { + fn := reflect.ValueOf(fptr).Elem() + ty := fn.Type() + if ty.Kind() != reflect.Func { + panic("purego: fptr must be a function pointer") + } + if ty.NumOut() > 1 { + panic("purego: function can only return zero or one values") + } + if cfn == 0 { + panic("purego: cfn is nil") + } + if ty.NumOut() == 1 && (ty.Out(0).Kind() == reflect.Float32 || ty.Out(0).Kind() == reflect.Float64) && + runtime.GOARCH != "arm64" && runtime.GOARCH != "amd64" { + panic("purego: float returns are not supported") + } + { + // this code checks how many registers and stack this function will use + // to avoid crashing with too many arguments + var ints int + var floats int + var stack int + for i := 0; i < ty.NumIn(); i++ { + arg := ty.In(i) + switch arg.Kind() { + case reflect.Func: + // This only does preliminary testing to ensure the CDecl argument + // is the first argument. Full testing is done when the callback is actually + // created in NewCallback. + for j := 0; j < arg.NumIn(); j++ { + in := arg.In(j) + if !in.AssignableTo(reflect.TypeOf(CDecl{})) { + continue + } + if j != 0 { + panic("purego: CDecl must be the first argument") + } + } + case reflect.String, reflect.Uintptr, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, + reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Ptr, reflect.UnsafePointer, + reflect.Slice, reflect.Bool: + if ints < numOfIntegerRegisters() { + ints++ + } else { + stack++ + } + case reflect.Float32, reflect.Float64: + const is32bit = unsafe.Sizeof(uintptr(0)) == 4 + if is32bit { + panic("purego: floats only supported on 64bit platforms") + } + if floats < numOfFloats { + floats++ + } else { + stack++ + } + case reflect.Struct: + if runtime.GOOS != "darwin" || (runtime.GOARCH != "amd64" && runtime.GOARCH != "arm64") { + panic("purego: struct arguments are only supported on darwin amd64 & arm64") + } + if arg.Size() == 0 { + continue + } + addInt := func(u uintptr) { + ints++ + } + addFloat := func(u uintptr) { + floats++ + } + addStack := func(u uintptr) { + stack++ + } + _ = addStruct(reflect.New(arg).Elem(), &ints, &floats, &stack, addInt, addFloat, addStack, nil) + default: + panic("purego: unsupported kind " + arg.Kind().String()) + } + } + if ty.NumOut() == 1 && ty.Out(0).Kind() == reflect.Struct { + if runtime.GOOS != "darwin" { + panic("purego: struct return values only supported on darwin arm64 & amd64") + } + outType := ty.Out(0) + checkStructFieldsSupported(outType) + if runtime.GOARCH == "amd64" && outType.Size() > maxRegAllocStructSize { + // on amd64 if struct is bigger than 16 bytes allocate the return struct + // and pass it in as a hidden first argument. + ints++ + } + } + sizeOfStack := maxArgs - numOfIntegerRegisters() + if stack > sizeOfStack { + panic("purego: too many arguments") + } + } + v := reflect.MakeFunc(ty, func(args []reflect.Value) (results []reflect.Value) { + if len(args) > 0 { + if variadic, ok := args[len(args)-1].Interface().([]interface{}); ok { + // subtract one from args bc the last argument in args is []interface{} + // which we are currently expanding + tmp := make([]reflect.Value, len(args)-1+len(variadic)) + n := copy(tmp, args[:len(args)-1]) + for i, v := range variadic { + tmp[n+i] = reflect.ValueOf(v) + } + args = tmp + } + } + var sysargs [maxArgs]uintptr + stack := sysargs[numOfIntegerRegisters():] + var floats [numOfFloats]uintptr + var numInts int + var numFloats int + var numStack int + var addStack, addInt, addFloat func(x uintptr) + if runtime.GOARCH == "arm64" || runtime.GOOS != "windows" { + // Windows arm64 uses the same calling convention as macOS and Linux + addStack = func(x uintptr) { + stack[numStack] = x + numStack++ + } + addInt = func(x uintptr) { + if numInts >= numOfIntegerRegisters() { + addStack(x) + } else { + sysargs[numInts] = x + numInts++ + } + } + addFloat = func(x uintptr) { + if numFloats < len(floats) { + floats[numFloats] = x + numFloats++ + } else { + addStack(x) + } + } + } else { + // On Windows amd64 the arguments are passed in the numbered registered. + // So the first int is in the first integer register and the first float + // is in the second floating register if there is already a first int. + // This is in contrast to how macOS and Linux pass arguments which + // tries to use as many registers as possible in the calling convention. + addStack = func(x uintptr) { + sysargs[numStack] = x + numStack++ + } + addInt = addStack + addFloat = addStack + } + + var keepAlive []interface{} + defer func() { + runtime.KeepAlive(keepAlive) + runtime.KeepAlive(args) + }() + var syscall syscall15Args + if ty.NumOut() == 1 && ty.Out(0).Kind() == reflect.Struct { + outType := ty.Out(0) + if runtime.GOARCH == "amd64" && outType.Size() > maxRegAllocStructSize { + val := reflect.New(outType) + keepAlive = append(keepAlive, val) + addInt(val.Pointer()) + } else if runtime.GOARCH == "arm64" && outType.Size() > maxRegAllocStructSize { + isAllFloats, numFields := isAllSameFloat(outType) + if !isAllFloats || numFields > 4 { + val := reflect.New(outType) + keepAlive = append(keepAlive, val) + syscall.arm64_r8 = val.Pointer() + } + } + } + for _, v := range args { + switch v.Kind() { + case reflect.String: + ptr := strings.CString(v.String()) + keepAlive = append(keepAlive, ptr) + addInt(uintptr(unsafe.Pointer(ptr))) + case reflect.Uintptr, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + addInt(uintptr(v.Uint())) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + addInt(uintptr(v.Int())) + case reflect.Ptr, reflect.UnsafePointer, reflect.Slice: + // There is no need to keepAlive this pointer separately because it is kept alive in the args variable + addInt(v.Pointer()) + case reflect.Func: + addInt(NewCallback(v.Interface())) + case reflect.Bool: + if v.Bool() { + addInt(1) + } else { + addInt(0) + } + case reflect.Float32: + addFloat(uintptr(math.Float32bits(float32(v.Float())))) + case reflect.Float64: + addFloat(uintptr(math.Float64bits(v.Float()))) + case reflect.Struct: + keepAlive = addStruct(v, &numInts, &numFloats, &numStack, addInt, addFloat, addStack, keepAlive) + default: + panic("purego: unsupported kind: " + v.Kind().String()) + } + } + if runtime.GOARCH == "arm64" || runtime.GOOS != "windows" { + // Use the normal arm64 calling convention even on Windows + syscall = syscall15Args{ + cfn, + sysargs[0], sysargs[1], sysargs[2], sysargs[3], sysargs[4], sysargs[5], + sysargs[6], sysargs[7], sysargs[8], sysargs[9], sysargs[10], sysargs[11], + sysargs[12], sysargs[13], sysargs[14], + floats[0], floats[1], floats[2], floats[3], floats[4], floats[5], floats[6], floats[7], + syscall.arm64_r8, + } + runtime_cgocall(syscall15XABI0, unsafe.Pointer(&syscall)) + } else { + // This is a fallback for Windows amd64, 386, and arm. Note this may not support floats + syscall.a1, syscall.a2, _ = syscall_syscall15X(cfn, sysargs[0], sysargs[1], sysargs[2], sysargs[3], sysargs[4], + sysargs[5], sysargs[6], sysargs[7], sysargs[8], sysargs[9], sysargs[10], sysargs[11], + sysargs[12], sysargs[13], sysargs[14]) + syscall.f1 = syscall.a2 // on amd64 a2 stores the float return. On 32bit platforms floats aren't support + } + if ty.NumOut() == 0 { + return nil + } + outType := ty.Out(0) + v := reflect.New(outType).Elem() + switch outType.Kind() { + case reflect.Uintptr, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + v.SetUint(uint64(syscall.a1)) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + v.SetInt(int64(syscall.a1)) + case reflect.Bool: + v.SetBool(byte(syscall.a1) != 0) + case reflect.UnsafePointer: + // We take the address and then dereference it to trick go vet from creating a possible miss-use of unsafe.Pointer + v.SetPointer(*(*unsafe.Pointer)(unsafe.Pointer(&syscall.a1))) + case reflect.Ptr: + v = reflect.NewAt(outType, unsafe.Pointer(&syscall.a1)).Elem() + case reflect.Func: + // wrap this C function in a nicely typed Go function + v = reflect.New(outType) + RegisterFunc(v.Interface(), syscall.a1) + case reflect.String: + v.SetString(strings.GoString(syscall.a1)) + case reflect.Float32: + // NOTE: syscall.r2 is only the floating return value on 64bit platforms. + // On 32bit platforms syscall.r2 is the upper part of a 64bit return. + v.SetFloat(float64(math.Float32frombits(uint32(syscall.f1)))) + case reflect.Float64: + // NOTE: syscall.r2 is only the floating return value on 64bit platforms. + // On 32bit platforms syscall.r2 is the upper part of a 64bit return. + v.SetFloat(math.Float64frombits(uint64(syscall.f1))) + case reflect.Struct: + v = getStruct(outType, syscall) + default: + panic("purego: unsupported return kind: " + outType.Kind().String()) + } + return []reflect.Value{v} + }) + fn.Set(v) +} + +// maxRegAllocStructSize is the biggest a struct can be while still fitting in registers. +// if it is bigger than this than enough space must be allocated on the heap and then passed into +// the function as the first parameter on amd64 or in R8 on arm64. +// +// If you change this make sure to update it in objc_runtime_darwin.go +const maxRegAllocStructSize = 16 + +func isAllSameFloat(ty reflect.Type) (allFloats bool, numFields int) { + allFloats = true + root := ty.Field(0).Type + for root.Kind() == reflect.Struct { + root = root.Field(0).Type + } + first := root.Kind() + if first != reflect.Float32 && first != reflect.Float64 { + allFloats = false + } + for i := 0; i < ty.NumField(); i++ { + f := ty.Field(i).Type + if f.Kind() == reflect.Struct { + var structNumFields int + allFloats, structNumFields = isAllSameFloat(f) + numFields += structNumFields + continue + } + numFields++ + if f.Kind() != first { + allFloats = false + } + } + return allFloats, numFields +} + +func checkStructFieldsSupported(ty reflect.Type) { + for i := 0; i < ty.NumField(); i++ { + f := ty.Field(i).Type + if f.Kind() == reflect.Array { + f = f.Elem() + } else if f.Kind() == reflect.Struct { + checkStructFieldsSupported(f) + continue + } + switch f.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, + reflect.Uintptr, reflect.Ptr, reflect.UnsafePointer, reflect.Float64, reflect.Float32: + default: + panic(fmt.Sprintf("purego: struct field type %s is not supported", f)) + } + } +} + +func roundUpTo8(val uintptr) uintptr { + return (val + 7) &^ 7 +} + +func numOfIntegerRegisters() int { + switch runtime.GOARCH { + case "arm64": + return 8 + case "amd64": + return 6 + default: + // since this platform isn't supported and can therefore only access + // integer registers it is fine to return the maxArgs + return maxArgs + } +} diff --git a/vendor/github.com/ebitengine/purego/go_runtime.go b/vendor/github.com/ebitengine/purego/go_runtime.go new file mode 100644 index 0000000..13671ff --- /dev/null +++ b/vendor/github.com/ebitengine/purego/go_runtime.go @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build darwin || freebsd || linux || windows + +package purego + +import ( + "unsafe" +) + +//go:linkname runtime_cgocall runtime.cgocall +func runtime_cgocall(fn uintptr, arg unsafe.Pointer) int32 // from runtime/sys_libc.go diff --git a/vendor/github.com/ebitengine/purego/internal/cgo/dlfcn_cgo_unix.go b/vendor/github.com/ebitengine/purego/internal/cgo/dlfcn_cgo_unix.go new file mode 100644 index 0000000..b09ecac --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/cgo/dlfcn_cgo_unix.go @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2024 The Ebitengine Authors + +//go:build freebsd || linux + +package cgo + +/* + #cgo LDFLAGS: -ldl + +#include +#include +*/ +import "C" + +import ( + "errors" + "unsafe" +) + +func Dlopen(filename string, flag int) (uintptr, error) { + cfilename := C.CString(filename) + defer C.free(unsafe.Pointer(cfilename)) + handle := C.dlopen(cfilename, C.int(flag)) + if handle == nil { + return 0, errors.New(C.GoString(C.dlerror())) + } + return uintptr(handle), nil +} + +func Dlsym(handle uintptr, symbol string) (uintptr, error) { + csymbol := C.CString(symbol) + defer C.free(unsafe.Pointer(csymbol)) + symbolAddr := C.dlsym(*(*unsafe.Pointer)(unsafe.Pointer(&handle)), csymbol) + if symbolAddr == nil { + return 0, errors.New(C.GoString(C.dlerror())) + } + return uintptr(symbolAddr), nil +} + +func Dlclose(handle uintptr) error { + result := C.dlclose(*(*unsafe.Pointer)(unsafe.Pointer(&handle))) + if result != 0 { + return errors.New(C.GoString(C.dlerror())) + } + return nil +} + +// all that is needed is to assign each dl function because then its +// symbol will then be made available to the linker and linked to inside dlfcn.go +var ( + _ = C.dlopen + _ = C.dlsym + _ = C.dlerror + _ = C.dlclose +) diff --git a/vendor/github.com/ebitengine/purego/internal/cgo/empty.go b/vendor/github.com/ebitengine/purego/internal/cgo/empty.go new file mode 100644 index 0000000..1d7cffe --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/cgo/empty.go @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2024 The Ebitengine Authors + +package cgo + +// Empty so that importing this package doesn't cause issue for certain platforms. diff --git a/vendor/github.com/ebitengine/purego/internal/cgo/syscall_cgo_unix.go b/vendor/github.com/ebitengine/purego/internal/cgo/syscall_cgo_unix.go new file mode 100644 index 0000000..37ff24d --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/cgo/syscall_cgo_unix.go @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build freebsd || (linux && !(arm64 || amd64)) + +package cgo + +// this file is placed inside internal/cgo and not package purego +// because Cgo and assembly files can't be in the same package. + +/* + #cgo LDFLAGS: -ldl + +#include +#include +#include +#include + +typedef struct syscall15Args { + uintptr_t fn; + uintptr_t a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15; + uintptr_t f1, f2, f3, f4, f5, f6, f7, f8; + uintptr_t err; +} syscall15Args; + +void syscall15(struct syscall15Args *args) { + assert((args->f1|args->f2|args->f3|args->f4|args->f5|args->f6|args->f7|args->f8) == 0); + uintptr_t (*func_name)(uintptr_t a1, uintptr_t a2, uintptr_t a3, uintptr_t a4, uintptr_t a5, uintptr_t a6, + uintptr_t a7, uintptr_t a8, uintptr_t a9, uintptr_t a10, uintptr_t a11, uintptr_t a12, + uintptr_t a13, uintptr_t a14, uintptr_t a15); + *(void**)(&func_name) = (void*)(args->fn); + uintptr_t r1 = func_name(args->a1,args->a2,args->a3,args->a4,args->a5,args->a6,args->a7,args->a8,args->a9, + args->a10,args->a11,args->a12,args->a13,args->a14,args->a15); + args->a1 = r1; + args->err = errno; +} + +*/ +import "C" +import "unsafe" + +// assign purego.syscall15XABI0 to the C version of this function. +var Syscall15XABI0 = unsafe.Pointer(C.syscall15) + +//go:nosplit +func Syscall15X(fn, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15 uintptr) (r1, r2, err uintptr) { + args := C.syscall15Args{ + C.uintptr_t(fn), C.uintptr_t(a1), C.uintptr_t(a2), C.uintptr_t(a3), + C.uintptr_t(a4), C.uintptr_t(a5), C.uintptr_t(a6), + C.uintptr_t(a7), C.uintptr_t(a8), C.uintptr_t(a9), C.uintptr_t(a10), C.uintptr_t(a11), C.uintptr_t(a12), + C.uintptr_t(a13), C.uintptr_t(a14), C.uintptr_t(a15), 0, 0, 0, 0, 0, 0, 0, 0, 0, + } + C.syscall15(&args) + return uintptr(args.a1), 0, uintptr(args.err) +} diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/abi_amd64.h b/vendor/github.com/ebitengine/purego/internal/fakecgo/abi_amd64.h new file mode 100644 index 0000000..9949435 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/abi_amd64.h @@ -0,0 +1,99 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Macros for transitioning from the host ABI to Go ABI0. +// +// These save the frame pointer, so in general, functions that use +// these should have zero frame size to suppress the automatic frame +// pointer, though it's harmless to not do this. + +#ifdef GOOS_windows + +// REGS_HOST_TO_ABI0_STACK is the stack bytes used by +// PUSH_REGS_HOST_TO_ABI0. +#define REGS_HOST_TO_ABI0_STACK (28*8 + 8) + +// PUSH_REGS_HOST_TO_ABI0 prepares for transitioning from +// the host ABI to Go ABI0 code. It saves all registers that are +// callee-save in the host ABI and caller-save in Go ABI0 and prepares +// for entry to Go. +// +// Save DI SI BP BX R12 R13 R14 R15 X6-X15 registers and the DF flag. +// Clear the DF flag for the Go ABI. +// MXCSR matches the Go ABI, so we don't have to set that, +// and Go doesn't modify it, so we don't have to save it. +#define PUSH_REGS_HOST_TO_ABI0() \ + PUSHFQ \ + CLD \ + ADJSP $(REGS_HOST_TO_ABI0_STACK - 8) \ + MOVQ DI, (0*0)(SP) \ + MOVQ SI, (1*8)(SP) \ + MOVQ BP, (2*8)(SP) \ + MOVQ BX, (3*8)(SP) \ + MOVQ R12, (4*8)(SP) \ + MOVQ R13, (5*8)(SP) \ + MOVQ R14, (6*8)(SP) \ + MOVQ R15, (7*8)(SP) \ + MOVUPS X6, (8*8)(SP) \ + MOVUPS X7, (10*8)(SP) \ + MOVUPS X8, (12*8)(SP) \ + MOVUPS X9, (14*8)(SP) \ + MOVUPS X10, (16*8)(SP) \ + MOVUPS X11, (18*8)(SP) \ + MOVUPS X12, (20*8)(SP) \ + MOVUPS X13, (22*8)(SP) \ + MOVUPS X14, (24*8)(SP) \ + MOVUPS X15, (26*8)(SP) + +#define POP_REGS_HOST_TO_ABI0() \ + MOVQ (0*0)(SP), DI \ + MOVQ (1*8)(SP), SI \ + MOVQ (2*8)(SP), BP \ + MOVQ (3*8)(SP), BX \ + MOVQ (4*8)(SP), R12 \ + MOVQ (5*8)(SP), R13 \ + MOVQ (6*8)(SP), R14 \ + MOVQ (7*8)(SP), R15 \ + MOVUPS (8*8)(SP), X6 \ + MOVUPS (10*8)(SP), X7 \ + MOVUPS (12*8)(SP), X8 \ + MOVUPS (14*8)(SP), X9 \ + MOVUPS (16*8)(SP), X10 \ + MOVUPS (18*8)(SP), X11 \ + MOVUPS (20*8)(SP), X12 \ + MOVUPS (22*8)(SP), X13 \ + MOVUPS (24*8)(SP), X14 \ + MOVUPS (26*8)(SP), X15 \ + ADJSP $-(REGS_HOST_TO_ABI0_STACK - 8) \ + POPFQ + +#else +// SysV ABI + +#define REGS_HOST_TO_ABI0_STACK (6*8) + +// SysV MXCSR matches the Go ABI, so we don't have to set that, +// and Go doesn't modify it, so we don't have to save it. +// Both SysV and Go require DF to be cleared, so that's already clear. +// The SysV and Go frame pointer conventions are compatible. +#define PUSH_REGS_HOST_TO_ABI0() \ + ADJSP $(REGS_HOST_TO_ABI0_STACK) \ + MOVQ BP, (5*8)(SP) \ + LEAQ (5*8)(SP), BP \ + MOVQ BX, (0*8)(SP) \ + MOVQ R12, (1*8)(SP) \ + MOVQ R13, (2*8)(SP) \ + MOVQ R14, (3*8)(SP) \ + MOVQ R15, (4*8)(SP) + +#define POP_REGS_HOST_TO_ABI0() \ + MOVQ (0*8)(SP), BX \ + MOVQ (1*8)(SP), R12 \ + MOVQ (2*8)(SP), R13 \ + MOVQ (3*8)(SP), R14 \ + MOVQ (4*8)(SP), R15 \ + MOVQ (5*8)(SP), BP \ + ADJSP $-(REGS_HOST_TO_ABI0_STACK) + +#endif diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/abi_arm64.h b/vendor/github.com/ebitengine/purego/internal/fakecgo/abi_arm64.h new file mode 100644 index 0000000..5d5061e --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/abi_arm64.h @@ -0,0 +1,39 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Macros for transitioning from the host ABI to Go ABI0. +// +// These macros save and restore the callee-saved registers +// from the stack, but they don't adjust stack pointer, so +// the user should prepare stack space in advance. +// SAVE_R19_TO_R28(offset) saves R19 ~ R28 to the stack space +// of ((offset)+0*8)(RSP) ~ ((offset)+9*8)(RSP). +// +// SAVE_F8_TO_F15(offset) saves F8 ~ F15 to the stack space +// of ((offset)+0*8)(RSP) ~ ((offset)+7*8)(RSP). +// +// R29 is not saved because Go will save and restore it. + +#define SAVE_R19_TO_R28(offset) \ + STP (R19, R20), ((offset)+0*8)(RSP) \ + STP (R21, R22), ((offset)+2*8)(RSP) \ + STP (R23, R24), ((offset)+4*8)(RSP) \ + STP (R25, R26), ((offset)+6*8)(RSP) \ + STP (R27, g), ((offset)+8*8)(RSP) +#define RESTORE_R19_TO_R28(offset) \ + LDP ((offset)+0*8)(RSP), (R19, R20) \ + LDP ((offset)+2*8)(RSP), (R21, R22) \ + LDP ((offset)+4*8)(RSP), (R23, R24) \ + LDP ((offset)+6*8)(RSP), (R25, R26) \ + LDP ((offset)+8*8)(RSP), (R27, g) /* R28 */ +#define SAVE_F8_TO_F15(offset) \ + FSTPD (F8, F9), ((offset)+0*8)(RSP) \ + FSTPD (F10, F11), ((offset)+2*8)(RSP) \ + FSTPD (F12, F13), ((offset)+4*8)(RSP) \ + FSTPD (F14, F15), ((offset)+6*8)(RSP) +#define RESTORE_F8_TO_F15(offset) \ + FLDPD ((offset)+0*8)(RSP), (F8, F9) \ + FLDPD ((offset)+2*8)(RSP), (F10, F11) \ + FLDPD ((offset)+4*8)(RSP), (F12, F13) \ + FLDPD ((offset)+6*8)(RSP), (F14, F15) diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/asm_amd64.s b/vendor/github.com/ebitengine/purego/internal/fakecgo/asm_amd64.s new file mode 100644 index 0000000..2b7eb57 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/asm_amd64.s @@ -0,0 +1,39 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" +#include "abi_amd64.h" + +// Called by C code generated by cmd/cgo. +// func crosscall2(fn, a unsafe.Pointer, n int32, ctxt uintptr) +// Saves C callee-saved registers and calls cgocallback with three arguments. +// fn is the PC of a func(a unsafe.Pointer) function. +// This signature is known to SWIG, so we can't change it. +TEXT crosscall2(SB), NOSPLIT, $0-0 + PUSH_REGS_HOST_TO_ABI0() + + // Make room for arguments to cgocallback. + ADJSP $0x18 + +#ifndef GOOS_windows + MOVQ DI, 0x0(SP) // fn + MOVQ SI, 0x8(SP) // arg + + // Skip n in DX. + MOVQ CX, 0x10(SP) // ctxt + +#else + MOVQ CX, 0x0(SP) // fn + MOVQ DX, 0x8(SP) // arg + + // Skip n in R8. + MOVQ R9, 0x10(SP) // ctxt + +#endif + + CALL runtime·cgocallback(SB) + + ADJSP $-0x18 + POP_REGS_HOST_TO_ABI0() + RET diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/asm_arm64.s b/vendor/github.com/ebitengine/purego/internal/fakecgo/asm_arm64.s new file mode 100644 index 0000000..50e5261 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/asm_arm64.s @@ -0,0 +1,36 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" +#include "abi_arm64.h" + +// Called by C code generated by cmd/cgo. +// func crosscall2(fn, a unsafe.Pointer, n int32, ctxt uintptr) +// Saves C callee-saved registers and calls cgocallback with three arguments. +// fn is the PC of a func(a unsafe.Pointer) function. +TEXT crosscall2(SB), NOSPLIT|NOFRAME, $0 +/* + * We still need to save all callee save register as before, and then + * push 3 args for fn (R0, R1, R3), skipping R2. + * Also note that at procedure entry in gc world, 8(RSP) will be the + * first arg. + */ + SUB $(8*24), RSP + STP (R0, R1), (8*1)(RSP) + MOVD R3, (8*3)(RSP) + + SAVE_R19_TO_R28(8*4) + SAVE_F8_TO_F15(8*14) + STP (R29, R30), (8*22)(RSP) + + // Initialize Go ABI environment + BL runtime·load_g(SB) + BL runtime·cgocallback(SB) + + RESTORE_R19_TO_R28(8*4) + RESTORE_F8_TO_F15(8*14) + LDP (8*22)(RSP), (R29, R30) + + ADD $(8*24), RSP + RET diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/callbacks.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/callbacks.go new file mode 100644 index 0000000..f29e690 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/callbacks.go @@ -0,0 +1,93 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !cgo && (darwin || freebsd || linux) + +package fakecgo + +import ( + _ "unsafe" +) + +// TODO: decide if we need _runtime_cgo_panic_internal + +//go:linkname x_cgo_init_trampoline x_cgo_init_trampoline +//go:linkname _cgo_init _cgo_init +var x_cgo_init_trampoline byte +var _cgo_init = &x_cgo_init_trampoline + +// Creates a new system thread without updating any Go state. +// +// This method is invoked during shared library loading to create a new OS +// thread to perform the runtime initialization. This method is similar to +// _cgo_sys_thread_start except that it doesn't update any Go state. + +//go:linkname x_cgo_thread_start_trampoline x_cgo_thread_start_trampoline +//go:linkname _cgo_thread_start _cgo_thread_start +var x_cgo_thread_start_trampoline byte +var _cgo_thread_start = &x_cgo_thread_start_trampoline + +// Notifies that the runtime has been initialized. +// +// We currently block at every CGO entry point (via _cgo_wait_runtime_init_done) +// to ensure that the runtime has been initialized before the CGO call is +// executed. This is necessary for shared libraries where we kickoff runtime +// initialization in a separate thread and return without waiting for this +// thread to complete the init. + +//go:linkname x_cgo_notify_runtime_init_done_trampoline x_cgo_notify_runtime_init_done_trampoline +//go:linkname _cgo_notify_runtime_init_done _cgo_notify_runtime_init_done +var x_cgo_notify_runtime_init_done_trampoline byte +var _cgo_notify_runtime_init_done = &x_cgo_notify_runtime_init_done_trampoline + +// Indicates whether a dummy thread key has been created or not. +// +// When calling go exported function from C, we register a destructor +// callback, for a dummy thread key, by using pthread_key_create. + +//go:linkname _cgo_pthread_key_created _cgo_pthread_key_created +var x_cgo_pthread_key_created uintptr +var _cgo_pthread_key_created = &x_cgo_pthread_key_created + +// Set the x_crosscall2_ptr C function pointer variable point to crosscall2. +// It's for the runtime package to call at init time. +func set_crosscall2() { + // nothing needs to be done here for fakecgo + // because it's possible to just call cgocallback directly +} + +//go:linkname _set_crosscall2 runtime.set_crosscall2 +var _set_crosscall2 = set_crosscall2 + +// Store the g into the thread-specific value. +// So that pthread_key_destructor will dropm when the thread is exiting. + +//go:linkname x_cgo_bindm_trampoline x_cgo_bindm_trampoline +//go:linkname _cgo_bindm _cgo_bindm +var x_cgo_bindm_trampoline byte +var _cgo_bindm = &x_cgo_bindm_trampoline + +// TODO: decide if we need x_cgo_set_context_function +// TODO: decide if we need _cgo_yield + +var ( + // In Go 1.20 the race detector was rewritten to pure Go + // on darwin. This means that when CGO_ENABLED=0 is set + // fakecgo is built with race detector code. This is not + // good since this code is pretending to be C. The go:norace + // pragma is not enough, since it only applies to the native + // ABIInternal function. The ABIO wrapper (which is necessary, + // since all references to text symbols from assembly will use it) + // does not inherit the go:norace pragma, so it will still be + // instrumented by the race detector. + // + // To circumvent this issue, using closure calls in the + // assembly, which forces the compiler to use the ABIInternal + // native implementation (which has go:norace) instead. + threadentry_call = threadentry + x_cgo_init_call = x_cgo_init + x_cgo_setenv_call = x_cgo_setenv + x_cgo_unsetenv_call = x_cgo_unsetenv + x_cgo_thread_start_call = x_cgo_thread_start +) diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/doc.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/doc.go new file mode 100644 index 0000000..be82f7d --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/doc.go @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build !cgo && (darwin || freebsd || linux) + +// Package fakecgo implements the Cgo runtime (runtime/cgo) entirely in Go. +// This allows code that calls into C to function properly when CGO_ENABLED=0. +// +// # Goals +// +// fakecgo attempts to replicate the same naming structure as in the runtime. +// For example, functions that have the prefix "gcc_*" are named "go_*". +// This makes it easier to port other GOOSs and GOARCHs as well as to keep +// it in sync with runtime/cgo. +// +// # Support +// +// Currently, fakecgo only supports macOS on amd64 & arm64. It also cannot +// be used with -buildmode=c-archive because that requires special initialization +// that fakecgo does not implement at the moment. +// +// # Usage +// +// Using fakecgo is easy just import _ "github.com/ebitengine/purego" and then +// set the environment variable CGO_ENABLED=0. +// The recommended usage for fakecgo is to prefer using runtime/cgo if possible +// but if cross-compiling or fast build times are important fakecgo is available. +// Purego will pick which ever Cgo runtime is available and prefer the one that +// comes with Go (runtime/cgo). +package fakecgo + +//go:generate go run gen.go diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/freebsd.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/freebsd.go new file mode 100644 index 0000000..bb73a70 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/freebsd.go @@ -0,0 +1,27 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build freebsd && !cgo + +package fakecgo + +import _ "unsafe" // for go:linkname + +// Supply environ and __progname, because we don't +// link against the standard FreeBSD crt0.o and the +// libc dynamic library needs them. + +// Note: when building with cross-compiling or CGO_ENABLED=0, add +// the following argument to `go` so that these symbols are defined by +// making fakecgo the Cgo. +// -gcflags="github.com/ebitengine/purego/internal/fakecgo=-std" + +//go:linkname _environ environ +//go:linkname _progname __progname + +//go:cgo_export_dynamic environ +//go:cgo_export_dynamic __progname + +var _environ uintptr +var _progname uintptr diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/go_darwin_amd64.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/go_darwin_amd64.go new file mode 100644 index 0000000..39f5ff1 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/go_darwin_amd64.go @@ -0,0 +1,73 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !cgo + +package fakecgo + +import "unsafe" + +//go:nosplit +//go:norace +func _cgo_sys_thread_start(ts *ThreadStart) { + var attr pthread_attr_t + var ign, oset sigset_t + var p pthread_t + var size size_t + var err int + + sigfillset(&ign) + pthread_sigmask(SIG_SETMASK, &ign, &oset) + + size = pthread_get_stacksize_np(pthread_self()) + pthread_attr_init(&attr) + pthread_attr_setstacksize(&attr, size) + // Leave stacklo=0 and set stackhi=size; mstart will do the rest. + ts.g.stackhi = uintptr(size) + + err = _cgo_try_pthread_create(&p, &attr, unsafe.Pointer(threadentry_trampolineABI0), ts) + + pthread_sigmask(SIG_SETMASK, &oset, nil) + + if err != 0 { + print("fakecgo: pthread_create failed: ") + println(err) + abort() + } +} + +// threadentry_trampolineABI0 maps the C ABI to Go ABI then calls the Go function +// +//go:linkname x_threadentry_trampoline threadentry_trampoline +var x_threadentry_trampoline byte +var threadentry_trampolineABI0 = &x_threadentry_trampoline + +//go:nosplit +//go:norace +func threadentry(v unsafe.Pointer) unsafe.Pointer { + ts := *(*ThreadStart)(v) + free(v) + + setg_trampoline(setg_func, uintptr(unsafe.Pointer(ts.g))) + + // faking funcs in go is a bit a... involved - but the following works :) + fn := uintptr(unsafe.Pointer(&ts.fn)) + (*(*func())(unsafe.Pointer(&fn)))() + + return nil +} + +// here we will store a pointer to the provided setg func +var setg_func uintptr + +//go:nosplit +//go:norace +func x_cgo_init(g *G, setg uintptr) { + var size size_t + + setg_func = setg + + size = pthread_get_stacksize_np(pthread_self()) + g.stacklo = uintptr(unsafe.Add(unsafe.Pointer(&size), -size+4096)) +} diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/go_darwin_arm64.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/go_darwin_arm64.go new file mode 100644 index 0000000..d0868f0 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/go_darwin_arm64.go @@ -0,0 +1,88 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !cgo + +package fakecgo + +import "unsafe" + +//go:nosplit +//go:norace +func _cgo_sys_thread_start(ts *ThreadStart) { + var attr pthread_attr_t + var ign, oset sigset_t + var p pthread_t + var size size_t + var err int + + sigfillset(&ign) + pthread_sigmask(SIG_SETMASK, &ign, &oset) + + size = pthread_get_stacksize_np(pthread_self()) + pthread_attr_init(&attr) + pthread_attr_setstacksize(&attr, size) + // Leave stacklo=0 and set stackhi=size; mstart will do the rest. + ts.g.stackhi = uintptr(size) + + err = _cgo_try_pthread_create(&p, &attr, unsafe.Pointer(threadentry_trampolineABI0), ts) + + pthread_sigmask(SIG_SETMASK, &oset, nil) + + if err != 0 { + print("fakecgo: pthread_create failed: ") + println(err) + abort() + } +} + +// threadentry_trampolineABI0 maps the C ABI to Go ABI then calls the Go function +// +//go:linkname x_threadentry_trampoline threadentry_trampoline +var x_threadentry_trampoline byte +var threadentry_trampolineABI0 = &x_threadentry_trampoline + +//go:nosplit +//go:norace +func threadentry(v unsafe.Pointer) unsafe.Pointer { + ts := *(*ThreadStart)(v) + free(v) + + // TODO: support ios + //#if TARGET_OS_IPHONE + // darwin_arm_init_thread_exception_port(); + //#endif + setg_trampoline(setg_func, uintptr(unsafe.Pointer(ts.g))) + + // faking funcs in go is a bit a... involved - but the following works :) + fn := uintptr(unsafe.Pointer(&ts.fn)) + (*(*func())(unsafe.Pointer(&fn)))() + + return nil +} + +// here we will store a pointer to the provided setg func +var setg_func uintptr + +// x_cgo_init(G *g, void (*setg)(void*)) (runtime/cgo/gcc_linux_amd64.c) +// This get's called during startup, adjusts stacklo, and provides a pointer to setg_gcc for us +// Additionally, if we set _cgo_init to non-null, go won't do it's own TLS setup +// This function can't be go:systemstack since go is not in a state where the systemcheck would work. +// +//go:nosplit +//go:norace +func x_cgo_init(g *G, setg uintptr) { + var size size_t + + setg_func = setg + size = pthread_get_stacksize_np(pthread_self()) + g.stacklo = uintptr(unsafe.Add(unsafe.Pointer(&size), -size+4096)) + + //TODO: support ios + //#if TARGET_OS_IPHONE + // darwin_arm_init_mach_exception_handler(); + // darwin_arm_init_thread_exception_port(); + // init_working_dir(); + //#endif +} diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/go_freebsd_amd64.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/go_freebsd_amd64.go new file mode 100644 index 0000000..c9ff715 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/go_freebsd_amd64.go @@ -0,0 +1,95 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !cgo + +package fakecgo + +import "unsafe" + +//go:nosplit +func _cgo_sys_thread_start(ts *ThreadStart) { + var attr pthread_attr_t + var ign, oset sigset_t + var p pthread_t + var size size_t + var err int + + //fprintf(stderr, "runtime/cgo: _cgo_sys_thread_start: fn=%p, g=%p\n", ts->fn, ts->g); // debug + sigfillset(&ign) + pthread_sigmask(SIG_SETMASK, &ign, &oset) + + pthread_attr_init(&attr) + pthread_attr_getstacksize(&attr, &size) + // Leave stacklo=0 and set stackhi=size; mstart will do the rest. + ts.g.stackhi = uintptr(size) + + err = _cgo_try_pthread_create(&p, &attr, unsafe.Pointer(threadentry_trampolineABI0), ts) + + pthread_sigmask(SIG_SETMASK, &oset, nil) + + if err != 0 { + print("fakecgo: pthread_create failed: ") + println(err) + abort() + } +} + +// threadentry_trampolineABI0 maps the C ABI to Go ABI then calls the Go function +// +//go:linkname x_threadentry_trampoline threadentry_trampoline +var x_threadentry_trampoline byte +var threadentry_trampolineABI0 = &x_threadentry_trampoline + +//go:nosplit +func threadentry(v unsafe.Pointer) unsafe.Pointer { + ts := *(*ThreadStart)(v) + free(v) + + setg_trampoline(setg_func, uintptr(unsafe.Pointer(ts.g))) + + // faking funcs in go is a bit a... involved - but the following works :) + fn := uintptr(unsafe.Pointer(&ts.fn)) + (*(*func())(unsafe.Pointer(&fn)))() + + return nil +} + +// here we will store a pointer to the provided setg func +var setg_func uintptr + +//go:nosplit +func x_cgo_init(g *G, setg uintptr) { + var size size_t + var attr *pthread_attr_t + + /* The memory sanitizer distributed with versions of clang + before 3.8 has a bug: if you call mmap before malloc, mmap + may return an address that is later overwritten by the msan + library. Avoid this problem by forcing a call to malloc + here, before we ever call malloc. + + This is only required for the memory sanitizer, so it's + unfortunate that we always run it. It should be possible + to remove this when we no longer care about versions of + clang before 3.8. The test for this is + misc/cgo/testsanitizers. + + GCC works hard to eliminate a seemingly unnecessary call to + malloc, so we actually use the memory we allocate. */ + + setg_func = setg + attr = (*pthread_attr_t)(malloc(unsafe.Sizeof(*attr))) + if attr == nil { + println("fakecgo: malloc failed") + abort() + } + pthread_attr_init(attr) + pthread_attr_getstacksize(attr, &size) + // runtime/cgo uses __builtin_frame_address(0) instead of `uintptr(unsafe.Pointer(&size))` + // but this should be OK since we are taking the address of the first variable in this function. + g.stacklo = uintptr(unsafe.Pointer(&size)) - uintptr(size) + 4096 + pthread_attr_destroy(attr) + free(unsafe.Pointer(attr)) +} diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/go_freebsd_arm64.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/go_freebsd_arm64.go new file mode 100644 index 0000000..e3a060b --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/go_freebsd_arm64.go @@ -0,0 +1,98 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !cgo + +package fakecgo + +import "unsafe" + +//go:nosplit +func _cgo_sys_thread_start(ts *ThreadStart) { + var attr pthread_attr_t + var ign, oset sigset_t + var p pthread_t + var size size_t + var err int + + // fprintf(stderr, "runtime/cgo: _cgo_sys_thread_start: fn=%p, g=%p\n", ts->fn, ts->g); // debug + sigfillset(&ign) + pthread_sigmask(SIG_SETMASK, &ign, &oset) + + pthread_attr_init(&attr) + pthread_attr_getstacksize(&attr, &size) + // Leave stacklo=0 and set stackhi=size; mstart will do the rest. + ts.g.stackhi = uintptr(size) + + err = _cgo_try_pthread_create(&p, &attr, unsafe.Pointer(threadentry_trampolineABI0), ts) + + pthread_sigmask(SIG_SETMASK, &oset, nil) + + if err != 0 { + print("fakecgo: pthread_create failed: ") + println(err) + abort() + } +} + +// threadentry_trampolineABI0 maps the C ABI to Go ABI then calls the Go function +// +//go:linkname x_threadentry_trampoline threadentry_trampoline +var x_threadentry_trampoline byte +var threadentry_trampolineABI0 = &x_threadentry_trampoline + +//go:nosplit +func threadentry(v unsafe.Pointer) unsafe.Pointer { + ts := *(*ThreadStart)(v) + free(v) + + setg_trampoline(setg_func, uintptr(unsafe.Pointer(ts.g))) + + // faking funcs in go is a bit a... involved - but the following works :) + fn := uintptr(unsafe.Pointer(&ts.fn)) + (*(*func())(unsafe.Pointer(&fn)))() + + return nil +} + +// here we will store a pointer to the provided setg func +var setg_func uintptr + +// x_cgo_init(G *g, void (*setg)(void*)) (runtime/cgo/gcc_linux_amd64.c) +// This get's called during startup, adjusts stacklo, and provides a pointer to setg_gcc for us +// Additionally, if we set _cgo_init to non-null, go won't do it's own TLS setup +// This function can't be go:systemstack since go is not in a state where the systemcheck would work. +// +//go:nosplit +func x_cgo_init(g *G, setg uintptr) { + var size size_t + var attr *pthread_attr_t + + /* The memory sanitizer distributed with versions of clang + before 3.8 has a bug: if you call mmap before malloc, mmap + may return an address that is later overwritten by the msan + library. Avoid this problem by forcing a call to malloc + here, before we ever call malloc. + + This is only required for the memory sanitizer, so it's + unfortunate that we always run it. It should be possible + to remove this when we no longer care about versions of + clang before 3.8. The test for this is + misc/cgo/testsanitizers. + + GCC works hard to eliminate a seemingly unnecessary call to + malloc, so we actually use the memory we allocate. */ + + setg_func = setg + attr = (*pthread_attr_t)(malloc(unsafe.Sizeof(*attr))) + if attr == nil { + println("fakecgo: malloc failed") + abort() + } + pthread_attr_init(attr) + pthread_attr_getstacksize(attr, &size) + g.stacklo = uintptr(unsafe.Pointer(&size)) - uintptr(size) + 4096 + pthread_attr_destroy(attr) + free(unsafe.Pointer(attr)) +} diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/go_libinit.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/go_libinit.go new file mode 100644 index 0000000..e5cb46b --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/go_libinit.go @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build !cgo && (darwin || freebsd || linux) + +package fakecgo + +import ( + "syscall" + "unsafe" +) + +var ( + pthread_g pthread_key_t + + runtime_init_cond = PTHREAD_COND_INITIALIZER + runtime_init_mu = PTHREAD_MUTEX_INITIALIZER + runtime_init_done int +) + +//go:nosplit +func x_cgo_notify_runtime_init_done() { + pthread_mutex_lock(&runtime_init_mu) + runtime_init_done = 1 + pthread_cond_broadcast(&runtime_init_cond) + pthread_mutex_unlock(&runtime_init_mu) +} + +// Store the g into a thread-specific value associated with the pthread key pthread_g. +// And pthread_key_destructor will dropm when the thread is exiting. +func x_cgo_bindm(g unsafe.Pointer) { + // We assume this will always succeed, otherwise, there might be extra M leaking, + // when a C thread exits after a cgo call. + // We only invoke this function once per thread in runtime.needAndBindM, + // and the next calls just reuse the bound m. + pthread_setspecific(pthread_g, g) +} + +// _cgo_try_pthread_create retries pthread_create if it fails with +// EAGAIN. +// +//go:nosplit +//go:norace +func _cgo_try_pthread_create(thread *pthread_t, attr *pthread_attr_t, pfn unsafe.Pointer, arg *ThreadStart) int { + var ts syscall.Timespec + // tries needs to be the same type as syscall.Timespec.Nsec + // but the fields are int32 on 32bit and int64 on 64bit. + // tries is assigned to syscall.Timespec.Nsec in order to match its type. + tries := ts.Nsec + var err int + + for tries = 0; tries < 20; tries++ { + err = int(pthread_create(thread, attr, pfn, unsafe.Pointer(arg))) + if err == 0 { + pthread_detach(*thread) + return 0 + } + if err != int(syscall.EAGAIN) { + return err + } + ts.Sec = 0 + ts.Nsec = (tries + 1) * 1000 * 1000 // Milliseconds. + nanosleep(&ts, nil) + } + return int(syscall.EAGAIN) +} diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/go_linux_amd64.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/go_linux_amd64.go new file mode 100644 index 0000000..c9ff715 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/go_linux_amd64.go @@ -0,0 +1,95 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !cgo + +package fakecgo + +import "unsafe" + +//go:nosplit +func _cgo_sys_thread_start(ts *ThreadStart) { + var attr pthread_attr_t + var ign, oset sigset_t + var p pthread_t + var size size_t + var err int + + //fprintf(stderr, "runtime/cgo: _cgo_sys_thread_start: fn=%p, g=%p\n", ts->fn, ts->g); // debug + sigfillset(&ign) + pthread_sigmask(SIG_SETMASK, &ign, &oset) + + pthread_attr_init(&attr) + pthread_attr_getstacksize(&attr, &size) + // Leave stacklo=0 and set stackhi=size; mstart will do the rest. + ts.g.stackhi = uintptr(size) + + err = _cgo_try_pthread_create(&p, &attr, unsafe.Pointer(threadentry_trampolineABI0), ts) + + pthread_sigmask(SIG_SETMASK, &oset, nil) + + if err != 0 { + print("fakecgo: pthread_create failed: ") + println(err) + abort() + } +} + +// threadentry_trampolineABI0 maps the C ABI to Go ABI then calls the Go function +// +//go:linkname x_threadentry_trampoline threadentry_trampoline +var x_threadentry_trampoline byte +var threadentry_trampolineABI0 = &x_threadentry_trampoline + +//go:nosplit +func threadentry(v unsafe.Pointer) unsafe.Pointer { + ts := *(*ThreadStart)(v) + free(v) + + setg_trampoline(setg_func, uintptr(unsafe.Pointer(ts.g))) + + // faking funcs in go is a bit a... involved - but the following works :) + fn := uintptr(unsafe.Pointer(&ts.fn)) + (*(*func())(unsafe.Pointer(&fn)))() + + return nil +} + +// here we will store a pointer to the provided setg func +var setg_func uintptr + +//go:nosplit +func x_cgo_init(g *G, setg uintptr) { + var size size_t + var attr *pthread_attr_t + + /* The memory sanitizer distributed with versions of clang + before 3.8 has a bug: if you call mmap before malloc, mmap + may return an address that is later overwritten by the msan + library. Avoid this problem by forcing a call to malloc + here, before we ever call malloc. + + This is only required for the memory sanitizer, so it's + unfortunate that we always run it. It should be possible + to remove this when we no longer care about versions of + clang before 3.8. The test for this is + misc/cgo/testsanitizers. + + GCC works hard to eliminate a seemingly unnecessary call to + malloc, so we actually use the memory we allocate. */ + + setg_func = setg + attr = (*pthread_attr_t)(malloc(unsafe.Sizeof(*attr))) + if attr == nil { + println("fakecgo: malloc failed") + abort() + } + pthread_attr_init(attr) + pthread_attr_getstacksize(attr, &size) + // runtime/cgo uses __builtin_frame_address(0) instead of `uintptr(unsafe.Pointer(&size))` + // but this should be OK since we are taking the address of the first variable in this function. + g.stacklo = uintptr(unsafe.Pointer(&size)) - uintptr(size) + 4096 + pthread_attr_destroy(attr) + free(unsafe.Pointer(attr)) +} diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/go_linux_arm64.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/go_linux_arm64.go new file mode 100644 index 0000000..a3b1cca --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/go_linux_arm64.go @@ -0,0 +1,98 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !cgo + +package fakecgo + +import "unsafe" + +//go:nosplit +func _cgo_sys_thread_start(ts *ThreadStart) { + var attr pthread_attr_t + var ign, oset sigset_t + var p pthread_t + var size size_t + var err int + + //fprintf(stderr, "runtime/cgo: _cgo_sys_thread_start: fn=%p, g=%p\n", ts->fn, ts->g); // debug + sigfillset(&ign) + pthread_sigmask(SIG_SETMASK, &ign, &oset) + + pthread_attr_init(&attr) + pthread_attr_getstacksize(&attr, &size) + // Leave stacklo=0 and set stackhi=size; mstart will do the rest. + ts.g.stackhi = uintptr(size) + + err = _cgo_try_pthread_create(&p, &attr, unsafe.Pointer(threadentry_trampolineABI0), ts) + + pthread_sigmask(SIG_SETMASK, &oset, nil) + + if err != 0 { + print("fakecgo: pthread_create failed: ") + println(err) + abort() + } +} + +// threadentry_trampolineABI0 maps the C ABI to Go ABI then calls the Go function +// +//go:linkname x_threadentry_trampoline threadentry_trampoline +var x_threadentry_trampoline byte +var threadentry_trampolineABI0 = &x_threadentry_trampoline + +//go:nosplit +func threadentry(v unsafe.Pointer) unsafe.Pointer { + ts := *(*ThreadStart)(v) + free(v) + + setg_trampoline(setg_func, uintptr(unsafe.Pointer(ts.g))) + + // faking funcs in go is a bit a... involved - but the following works :) + fn := uintptr(unsafe.Pointer(&ts.fn)) + (*(*func())(unsafe.Pointer(&fn)))() + + return nil +} + +// here we will store a pointer to the provided setg func +var setg_func uintptr + +// x_cgo_init(G *g, void (*setg)(void*)) (runtime/cgo/gcc_linux_amd64.c) +// This get's called during startup, adjusts stacklo, and provides a pointer to setg_gcc for us +// Additionally, if we set _cgo_init to non-null, go won't do it's own TLS setup +// This function can't be go:systemstack since go is not in a state where the systemcheck would work. +// +//go:nosplit +func x_cgo_init(g *G, setg uintptr) { + var size size_t + var attr *pthread_attr_t + + /* The memory sanitizer distributed with versions of clang + before 3.8 has a bug: if you call mmap before malloc, mmap + may return an address that is later overwritten by the msan + library. Avoid this problem by forcing a call to malloc + here, before we ever call malloc. + + This is only required for the memory sanitizer, so it's + unfortunate that we always run it. It should be possible + to remove this when we no longer care about versions of + clang before 3.8. The test for this is + misc/cgo/testsanitizers. + + GCC works hard to eliminate a seemingly unnecessary call to + malloc, so we actually use the memory we allocate. */ + + setg_func = setg + attr = (*pthread_attr_t)(malloc(unsafe.Sizeof(*attr))) + if attr == nil { + println("fakecgo: malloc failed") + abort() + } + pthread_attr_init(attr) + pthread_attr_getstacksize(attr, &size) + g.stacklo = uintptr(unsafe.Pointer(&size)) - uintptr(size) + 4096 + pthread_attr_destroy(attr) + free(unsafe.Pointer(attr)) +} diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/go_setenv.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/go_setenv.go new file mode 100644 index 0000000..e42d84f --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/go_setenv.go @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build !cgo && (darwin || freebsd || linux) + +package fakecgo + +//go:nosplit +//go:norace +func x_cgo_setenv(arg *[2]*byte) { + setenv(arg[0], arg[1], 1) +} + +//go:nosplit +//go:norace +func x_cgo_unsetenv(arg *[1]*byte) { + unsetenv(arg[0]) +} diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/go_util.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/go_util.go new file mode 100644 index 0000000..0ac10d1 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/go_util.go @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build !cgo && (darwin || freebsd || linux) + +package fakecgo + +import "unsafe" + +// _cgo_thread_start is split into three parts in cgo since only one part is system dependent (keep it here for easier handling) + +// _cgo_thread_start(ThreadStart *arg) (runtime/cgo/gcc_util.c) +// This get's called instead of the go code for creating new threads +// -> pthread_* stuff is used, so threads are setup correctly for C +// If this is missing, TLS is only setup correctly on thread 1! +// This function should be go:systemstack instead of go:nosplit (but that requires runtime) +// +//go:nosplit +//go:norace +func x_cgo_thread_start(arg *ThreadStart) { + var ts *ThreadStart + // Make our own copy that can persist after we return. + // _cgo_tsan_acquire(); + ts = (*ThreadStart)(malloc(unsafe.Sizeof(*ts))) + // _cgo_tsan_release(); + if ts == nil { + println("fakecgo: out of memory in thread_start") + abort() + } + // *ts = *arg would cause a writebarrier so copy using slices + s1 := unsafe.Slice((*uintptr)(unsafe.Pointer(ts)), unsafe.Sizeof(*ts)/8) + s2 := unsafe.Slice((*uintptr)(unsafe.Pointer(arg)), unsafe.Sizeof(*arg)/8) + for i := range s2 { + s1[i] = s2[i] + } + _cgo_sys_thread_start(ts) // OS-dependent half +} diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/iscgo.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/iscgo.go new file mode 100644 index 0000000..28af41c --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/iscgo.go @@ -0,0 +1,19 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !cgo && (darwin || freebsd || linux) + +// The runtime package contains an uninitialized definition +// for runtime·iscgo. Override it to tell the runtime we're here. +// There are various function pointers that should be set too, +// but those depend on dynamic linker magic to get initialized +// correctly, and sometimes they break. This variable is a +// backup: it depends only on old C style static linking rules. + +package fakecgo + +import _ "unsafe" // for go:linkname + +//go:linkname _iscgo runtime.iscgo +var _iscgo bool = true diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo.go new file mode 100644 index 0000000..74626c6 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo.go @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build !cgo && (darwin || freebsd || linux) + +package fakecgo + +type ( + size_t uintptr + sigset_t [128]byte + pthread_attr_t [64]byte + pthread_t int + pthread_key_t uint64 +) + +// for pthread_sigmask: + +type sighow int32 + +const ( + SIG_BLOCK sighow = 0 + SIG_UNBLOCK sighow = 1 + SIG_SETMASK sighow = 2 +) + +type G struct { + stacklo uintptr + stackhi uintptr +} + +type ThreadStart struct { + g *G + tls *uintptr + fn uintptr +} diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_darwin.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_darwin.go new file mode 100644 index 0000000..af14833 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_darwin.go @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build !cgo + +package fakecgo + +type ( + pthread_mutex_t struct { + sig int64 + opaque [56]byte + } + pthread_cond_t struct { + sig int64 + opaque [40]byte + } +) + +var ( + PTHREAD_COND_INITIALIZER = pthread_cond_t{sig: 0x3CB0B1BB} + PTHREAD_MUTEX_INITIALIZER = pthread_mutex_t{sig: 0x32AAABA7} +) diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_freebsd.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_freebsd.go new file mode 100644 index 0000000..ca1f722 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_freebsd.go @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build !cgo + +package fakecgo + +type ( + pthread_cond_t uintptr + pthread_mutex_t uintptr +) + +var ( + PTHREAD_COND_INITIALIZER = pthread_cond_t(0) + PTHREAD_MUTEX_INITIALIZER = pthread_mutex_t(0) +) diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_linux.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_linux.go new file mode 100644 index 0000000..c4b6e9e --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_linux.go @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build !cgo + +package fakecgo + +type ( + pthread_cond_t [48]byte + pthread_mutex_t [48]byte +) + +var ( + PTHREAD_COND_INITIALIZER = pthread_cond_t{} + PTHREAD_MUTEX_INITIALIZER = pthread_mutex_t{} +) diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/setenv.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/setenv.go new file mode 100644 index 0000000..f30af0e --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/setenv.go @@ -0,0 +1,19 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !cgo && (darwin || freebsd || linux) + +package fakecgo + +import _ "unsafe" // for go:linkname + +//go:linkname x_cgo_setenv_trampoline x_cgo_setenv_trampoline +//go:linkname _cgo_setenv runtime._cgo_setenv +var x_cgo_setenv_trampoline byte +var _cgo_setenv = &x_cgo_setenv_trampoline + +//go:linkname x_cgo_unsetenv_trampoline x_cgo_unsetenv_trampoline +//go:linkname _cgo_unsetenv runtime._cgo_unsetenv +var x_cgo_unsetenv_trampoline byte +var _cgo_unsetenv = &x_cgo_unsetenv_trampoline diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/symbols.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/symbols.go new file mode 100644 index 0000000..3d19fd8 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/symbols.go @@ -0,0 +1,181 @@ +// Code generated by 'go generate' with gen.go. DO NOT EDIT. + +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build !cgo && (darwin || freebsd || linux) + +package fakecgo + +import ( + "syscall" + "unsafe" +) + +// setg_trampoline calls setg with the G provided +func setg_trampoline(setg uintptr, G uintptr) + +// call5 takes fn the C function and 5 arguments and calls the function with those arguments +func call5(fn, a1, a2, a3, a4, a5 uintptr) uintptr + +func malloc(size uintptr) unsafe.Pointer { + ret := call5(mallocABI0, uintptr(size), 0, 0, 0, 0) + // this indirection is to avoid go vet complaining about possible misuse of unsafe.Pointer + return *(*unsafe.Pointer)(unsafe.Pointer(&ret)) +} + +func free(ptr unsafe.Pointer) { + call5(freeABI0, uintptr(ptr), 0, 0, 0, 0) +} + +func setenv(name *byte, value *byte, overwrite int32) int32 { + return int32(call5(setenvABI0, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(value)), uintptr(overwrite), 0, 0)) +} + +func unsetenv(name *byte) int32 { + return int32(call5(unsetenvABI0, uintptr(unsafe.Pointer(name)), 0, 0, 0, 0)) +} + +func sigfillset(set *sigset_t) int32 { + return int32(call5(sigfillsetABI0, uintptr(unsafe.Pointer(set)), 0, 0, 0, 0)) +} + +func nanosleep(ts *syscall.Timespec, rem *syscall.Timespec) int32 { + return int32(call5(nanosleepABI0, uintptr(unsafe.Pointer(ts)), uintptr(unsafe.Pointer(rem)), 0, 0, 0)) +} + +func abort() { + call5(abortABI0, 0, 0, 0, 0, 0) +} + +func pthread_attr_init(attr *pthread_attr_t) int32 { + return int32(call5(pthread_attr_initABI0, uintptr(unsafe.Pointer(attr)), 0, 0, 0, 0)) +} + +func pthread_create(thread *pthread_t, attr *pthread_attr_t, start unsafe.Pointer, arg unsafe.Pointer) int32 { + return int32(call5(pthread_createABI0, uintptr(unsafe.Pointer(thread)), uintptr(unsafe.Pointer(attr)), uintptr(start), uintptr(arg), 0)) +} + +func pthread_detach(thread pthread_t) int32 { + return int32(call5(pthread_detachABI0, uintptr(thread), 0, 0, 0, 0)) +} + +func pthread_sigmask(how sighow, ign *sigset_t, oset *sigset_t) int32 { + return int32(call5(pthread_sigmaskABI0, uintptr(how), uintptr(unsafe.Pointer(ign)), uintptr(unsafe.Pointer(oset)), 0, 0)) +} + +func pthread_self() pthread_t { + return pthread_t(call5(pthread_selfABI0, 0, 0, 0, 0, 0)) +} + +func pthread_get_stacksize_np(thread pthread_t) size_t { + return size_t(call5(pthread_get_stacksize_npABI0, uintptr(thread), 0, 0, 0, 0)) +} + +func pthread_attr_getstacksize(attr *pthread_attr_t, stacksize *size_t) int32 { + return int32(call5(pthread_attr_getstacksizeABI0, uintptr(unsafe.Pointer(attr)), uintptr(unsafe.Pointer(stacksize)), 0, 0, 0)) +} + +func pthread_attr_setstacksize(attr *pthread_attr_t, size size_t) int32 { + return int32(call5(pthread_attr_setstacksizeABI0, uintptr(unsafe.Pointer(attr)), uintptr(size), 0, 0, 0)) +} + +func pthread_attr_destroy(attr *pthread_attr_t) int32 { + return int32(call5(pthread_attr_destroyABI0, uintptr(unsafe.Pointer(attr)), 0, 0, 0, 0)) +} + +func pthread_mutex_lock(mutex *pthread_mutex_t) int32 { + return int32(call5(pthread_mutex_lockABI0, uintptr(unsafe.Pointer(mutex)), 0, 0, 0, 0)) +} + +func pthread_mutex_unlock(mutex *pthread_mutex_t) int32 { + return int32(call5(pthread_mutex_unlockABI0, uintptr(unsafe.Pointer(mutex)), 0, 0, 0, 0)) +} + +func pthread_cond_broadcast(cond *pthread_cond_t) int32 { + return int32(call5(pthread_cond_broadcastABI0, uintptr(unsafe.Pointer(cond)), 0, 0, 0, 0)) +} + +func pthread_setspecific(key pthread_key_t, value unsafe.Pointer) int32 { + return int32(call5(pthread_setspecificABI0, uintptr(key), uintptr(value), 0, 0, 0)) +} + +//go:linkname _malloc _malloc +var _malloc uintptr +var mallocABI0 = uintptr(unsafe.Pointer(&_malloc)) + +//go:linkname _free _free +var _free uintptr +var freeABI0 = uintptr(unsafe.Pointer(&_free)) + +//go:linkname _setenv _setenv +var _setenv uintptr +var setenvABI0 = uintptr(unsafe.Pointer(&_setenv)) + +//go:linkname _unsetenv _unsetenv +var _unsetenv uintptr +var unsetenvABI0 = uintptr(unsafe.Pointer(&_unsetenv)) + +//go:linkname _sigfillset _sigfillset +var _sigfillset uintptr +var sigfillsetABI0 = uintptr(unsafe.Pointer(&_sigfillset)) + +//go:linkname _nanosleep _nanosleep +var _nanosleep uintptr +var nanosleepABI0 = uintptr(unsafe.Pointer(&_nanosleep)) + +//go:linkname _abort _abort +var _abort uintptr +var abortABI0 = uintptr(unsafe.Pointer(&_abort)) + +//go:linkname _pthread_attr_init _pthread_attr_init +var _pthread_attr_init uintptr +var pthread_attr_initABI0 = uintptr(unsafe.Pointer(&_pthread_attr_init)) + +//go:linkname _pthread_create _pthread_create +var _pthread_create uintptr +var pthread_createABI0 = uintptr(unsafe.Pointer(&_pthread_create)) + +//go:linkname _pthread_detach _pthread_detach +var _pthread_detach uintptr +var pthread_detachABI0 = uintptr(unsafe.Pointer(&_pthread_detach)) + +//go:linkname _pthread_sigmask _pthread_sigmask +var _pthread_sigmask uintptr +var pthread_sigmaskABI0 = uintptr(unsafe.Pointer(&_pthread_sigmask)) + +//go:linkname _pthread_self _pthread_self +var _pthread_self uintptr +var pthread_selfABI0 = uintptr(unsafe.Pointer(&_pthread_self)) + +//go:linkname _pthread_get_stacksize_np _pthread_get_stacksize_np +var _pthread_get_stacksize_np uintptr +var pthread_get_stacksize_npABI0 = uintptr(unsafe.Pointer(&_pthread_get_stacksize_np)) + +//go:linkname _pthread_attr_getstacksize _pthread_attr_getstacksize +var _pthread_attr_getstacksize uintptr +var pthread_attr_getstacksizeABI0 = uintptr(unsafe.Pointer(&_pthread_attr_getstacksize)) + +//go:linkname _pthread_attr_setstacksize _pthread_attr_setstacksize +var _pthread_attr_setstacksize uintptr +var pthread_attr_setstacksizeABI0 = uintptr(unsafe.Pointer(&_pthread_attr_setstacksize)) + +//go:linkname _pthread_attr_destroy _pthread_attr_destroy +var _pthread_attr_destroy uintptr +var pthread_attr_destroyABI0 = uintptr(unsafe.Pointer(&_pthread_attr_destroy)) + +//go:linkname _pthread_mutex_lock _pthread_mutex_lock +var _pthread_mutex_lock uintptr +var pthread_mutex_lockABI0 = uintptr(unsafe.Pointer(&_pthread_mutex_lock)) + +//go:linkname _pthread_mutex_unlock _pthread_mutex_unlock +var _pthread_mutex_unlock uintptr +var pthread_mutex_unlockABI0 = uintptr(unsafe.Pointer(&_pthread_mutex_unlock)) + +//go:linkname _pthread_cond_broadcast _pthread_cond_broadcast +var _pthread_cond_broadcast uintptr +var pthread_cond_broadcastABI0 = uintptr(unsafe.Pointer(&_pthread_cond_broadcast)) + +//go:linkname _pthread_setspecific _pthread_setspecific +var _pthread_setspecific uintptr +var pthread_setspecificABI0 = uintptr(unsafe.Pointer(&_pthread_setspecific)) diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/symbols_darwin.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/symbols_darwin.go new file mode 100644 index 0000000..54aaa46 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/symbols_darwin.go @@ -0,0 +1,29 @@ +// Code generated by 'go generate' with gen.go. DO NOT EDIT. + +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build !cgo + +package fakecgo + +//go:cgo_import_dynamic purego_malloc malloc "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_free free "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_setenv setenv "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_unsetenv unsetenv "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_sigfillset sigfillset "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_nanosleep nanosleep "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_abort abort "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_pthread_attr_init pthread_attr_init "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_pthread_create pthread_create "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_pthread_detach pthread_detach "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_pthread_sigmask pthread_sigmask "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_pthread_self pthread_self "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_pthread_get_stacksize_np pthread_get_stacksize_np "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_pthread_attr_getstacksize pthread_attr_getstacksize "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_pthread_attr_setstacksize pthread_attr_setstacksize "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_pthread_attr_destroy pthread_attr_destroy "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_pthread_mutex_lock pthread_mutex_lock "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_pthread_mutex_unlock pthread_mutex_unlock "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_pthread_cond_broadcast pthread_cond_broadcast "/usr/lib/libSystem.B.dylib" +//go:cgo_import_dynamic purego_pthread_setspecific pthread_setspecific "/usr/lib/libSystem.B.dylib" diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/symbols_freebsd.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/symbols_freebsd.go new file mode 100644 index 0000000..8153811 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/symbols_freebsd.go @@ -0,0 +1,29 @@ +// Code generated by 'go generate' with gen.go. DO NOT EDIT. + +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build !cgo + +package fakecgo + +//go:cgo_import_dynamic purego_malloc malloc "libc.so.7" +//go:cgo_import_dynamic purego_free free "libc.so.7" +//go:cgo_import_dynamic purego_setenv setenv "libc.so.7" +//go:cgo_import_dynamic purego_unsetenv unsetenv "libc.so.7" +//go:cgo_import_dynamic purego_sigfillset sigfillset "libc.so.7" +//go:cgo_import_dynamic purego_nanosleep nanosleep "libc.so.7" +//go:cgo_import_dynamic purego_abort abort "libc.so.7" +//go:cgo_import_dynamic purego_pthread_attr_init pthread_attr_init "libpthread.so" +//go:cgo_import_dynamic purego_pthread_create pthread_create "libpthread.so" +//go:cgo_import_dynamic purego_pthread_detach pthread_detach "libpthread.so" +//go:cgo_import_dynamic purego_pthread_sigmask pthread_sigmask "libpthread.so" +//go:cgo_import_dynamic purego_pthread_self pthread_self "libpthread.so" +//go:cgo_import_dynamic purego_pthread_get_stacksize_np pthread_get_stacksize_np "libpthread.so" +//go:cgo_import_dynamic purego_pthread_attr_getstacksize pthread_attr_getstacksize "libpthread.so" +//go:cgo_import_dynamic purego_pthread_attr_setstacksize pthread_attr_setstacksize "libpthread.so" +//go:cgo_import_dynamic purego_pthread_attr_destroy pthread_attr_destroy "libpthread.so" +//go:cgo_import_dynamic purego_pthread_mutex_lock pthread_mutex_lock "libpthread.so" +//go:cgo_import_dynamic purego_pthread_mutex_unlock pthread_mutex_unlock "libpthread.so" +//go:cgo_import_dynamic purego_pthread_cond_broadcast pthread_cond_broadcast "libpthread.so" +//go:cgo_import_dynamic purego_pthread_setspecific pthread_setspecific "libpthread.so" diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/symbols_linux.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/symbols_linux.go new file mode 100644 index 0000000..180057d --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/symbols_linux.go @@ -0,0 +1,29 @@ +// Code generated by 'go generate' with gen.go. DO NOT EDIT. + +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build !cgo + +package fakecgo + +//go:cgo_import_dynamic purego_malloc malloc "libc.so.6" +//go:cgo_import_dynamic purego_free free "libc.so.6" +//go:cgo_import_dynamic purego_setenv setenv "libc.so.6" +//go:cgo_import_dynamic purego_unsetenv unsetenv "libc.so.6" +//go:cgo_import_dynamic purego_sigfillset sigfillset "libc.so.6" +//go:cgo_import_dynamic purego_nanosleep nanosleep "libc.so.6" +//go:cgo_import_dynamic purego_abort abort "libc.so.6" +//go:cgo_import_dynamic purego_pthread_attr_init pthread_attr_init "libpthread.so.0" +//go:cgo_import_dynamic purego_pthread_create pthread_create "libpthread.so.0" +//go:cgo_import_dynamic purego_pthread_detach pthread_detach "libpthread.so.0" +//go:cgo_import_dynamic purego_pthread_sigmask pthread_sigmask "libpthread.so.0" +//go:cgo_import_dynamic purego_pthread_self pthread_self "libpthread.so.0" +//go:cgo_import_dynamic purego_pthread_get_stacksize_np pthread_get_stacksize_np "libpthread.so.0" +//go:cgo_import_dynamic purego_pthread_attr_getstacksize pthread_attr_getstacksize "libpthread.so.0" +//go:cgo_import_dynamic purego_pthread_attr_setstacksize pthread_attr_setstacksize "libpthread.so.0" +//go:cgo_import_dynamic purego_pthread_attr_destroy pthread_attr_destroy "libpthread.so.0" +//go:cgo_import_dynamic purego_pthread_mutex_lock pthread_mutex_lock "libpthread.so.0" +//go:cgo_import_dynamic purego_pthread_mutex_unlock pthread_mutex_unlock "libpthread.so.0" +//go:cgo_import_dynamic purego_pthread_cond_broadcast pthread_cond_broadcast "libpthread.so.0" +//go:cgo_import_dynamic purego_pthread_setspecific pthread_setspecific "libpthread.so.0" diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/trampolines_amd64.s b/vendor/github.com/ebitengine/purego/internal/fakecgo/trampolines_amd64.s new file mode 100644 index 0000000..c9a3cc0 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/trampolines_amd64.s @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build !cgo && (darwin || linux || freebsd) + +/* +trampoline for emulating required C functions for cgo in go (see cgo.go) +(we convert cdecl calling convention to go and vice-versa) + +Since we're called from go and call into C we can cheat a bit with the calling conventions: + - in go all the registers are caller saved + - in C we have a couple of callee saved registers + +=> we can use BX, R12, R13, R14, R15 instead of the stack + +C Calling convention cdecl used here (we only need integer args): +1. arg: DI +2. arg: SI +3. arg: DX +4. arg: CX +5. arg: R8 +6. arg: R9 +We don't need floats with these functions -> AX=0 +return value will be in AX +*/ +#include "textflag.h" +#include "go_asm.h" + +// these trampolines map the gcc ABI to Go ABI and then calls into the Go equivalent functions. + +TEXT x_cgo_init_trampoline(SB), NOSPLIT, $16 + MOVQ DI, AX + MOVQ SI, BX + MOVQ ·x_cgo_init_call(SB), DX + MOVQ (DX), CX + CALL CX + RET + +TEXT x_cgo_thread_start_trampoline(SB), NOSPLIT, $8 + MOVQ DI, AX + MOVQ ·x_cgo_thread_start_call(SB), DX + MOVQ (DX), CX + CALL CX + RET + +TEXT x_cgo_setenv_trampoline(SB), NOSPLIT, $8 + MOVQ DI, AX + MOVQ ·x_cgo_setenv_call(SB), DX + MOVQ (DX), CX + CALL CX + RET + +TEXT x_cgo_unsetenv_trampoline(SB), NOSPLIT, $8 + MOVQ DI, AX + MOVQ ·x_cgo_unsetenv_call(SB), DX + MOVQ (DX), CX + CALL CX + RET + +TEXT x_cgo_notify_runtime_init_done_trampoline(SB), NOSPLIT, $0 + CALL ·x_cgo_notify_runtime_init_done(SB) + RET + +TEXT x_cgo_bindm_trampoline(SB), NOSPLIT, $0 + CALL ·x_cgo_bindm(SB) + RET + +// func setg_trampoline(setg uintptr, g uintptr) +TEXT ·setg_trampoline(SB), NOSPLIT, $0-16 + MOVQ G+8(FP), DI + MOVQ setg+0(FP), BX + XORL AX, AX + CALL BX + RET + +TEXT threadentry_trampoline(SB), NOSPLIT, $16 + MOVQ DI, AX + MOVQ ·threadentry_call(SB), DX + MOVQ (DX), CX + CALL CX + RET + +TEXT ·call5(SB), NOSPLIT, $0-56 + MOVQ fn+0(FP), BX + MOVQ a1+8(FP), DI + MOVQ a2+16(FP), SI + MOVQ a3+24(FP), DX + MOVQ a4+32(FP), CX + MOVQ a5+40(FP), R8 + + XORL AX, AX // no floats + + PUSHQ BP // save BP + MOVQ SP, BP // save SP inside BP bc BP is callee-saved + SUBQ $16, SP // allocate space for alignment + ANDQ $-16, SP // align on 16 bytes for SSE + + CALL BX + + MOVQ BP, SP // get SP back + POPQ BP // restore BP + + MOVQ AX, ret+48(FP) + RET diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/trampolines_arm64.s b/vendor/github.com/ebitengine/purego/internal/fakecgo/trampolines_arm64.s new file mode 100644 index 0000000..9dbdbc0 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/trampolines_arm64.s @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build !cgo && (darwin || freebsd || linux) + +#include "textflag.h" +#include "go_asm.h" + +// these trampolines map the gcc ABI to Go ABI and then calls into the Go equivalent functions. + +TEXT x_cgo_init_trampoline(SB), NOSPLIT, $0-0 + MOVD R0, 8(RSP) + MOVD R1, 16(RSP) + MOVD ·x_cgo_init_call(SB), R26 + MOVD (R26), R2 + CALL (R2) + RET + +TEXT x_cgo_thread_start_trampoline(SB), NOSPLIT, $0-0 + MOVD R0, 8(RSP) + MOVD ·x_cgo_thread_start_call(SB), R26 + MOVD (R26), R2 + CALL (R2) + RET + +TEXT x_cgo_setenv_trampoline(SB), NOSPLIT, $0-0 + MOVD R0, 8(RSP) + MOVD ·x_cgo_setenv_call(SB), R26 + MOVD (R26), R2 + CALL (R2) + RET + +TEXT x_cgo_unsetenv_trampoline(SB), NOSPLIT, $0-0 + MOVD R0, 8(RSP) + MOVD ·x_cgo_unsetenv_call(SB), R26 + MOVD (R26), R2 + CALL (R2) + RET + +TEXT x_cgo_notify_runtime_init_done_trampoline(SB), NOSPLIT, $0-0 + CALL ·x_cgo_notify_runtime_init_done(SB) + RET + +TEXT x_cgo_bindm_trampoline(SB), NOSPLIT, $0 + CALL ·x_cgo_bindm(SB) + RET + +// func setg_trampoline(setg uintptr, g uintptr) +TEXT ·setg_trampoline(SB), NOSPLIT, $0-16 + MOVD G+8(FP), R0 + MOVD setg+0(FP), R1 + CALL R1 + RET + +TEXT threadentry_trampoline(SB), NOSPLIT, $0-0 + MOVD R0, 8(RSP) + MOVD ·threadentry_call(SB), R26 + MOVD (R26), R2 + CALL (R2) + MOVD $0, R0 // TODO: get the return value from threadentry + RET + +TEXT ·call5(SB), NOSPLIT, $0-0 + MOVD fn+0(FP), R6 + MOVD a1+8(FP), R0 + MOVD a2+16(FP), R1 + MOVD a3+24(FP), R2 + MOVD a4+32(FP), R3 + MOVD a5+40(FP), R4 + CALL R6 + MOVD R0, ret+48(FP) + RET diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/trampolines_stubs.s b/vendor/github.com/ebitengine/purego/internal/fakecgo/trampolines_stubs.s new file mode 100644 index 0000000..a65b201 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/trampolines_stubs.s @@ -0,0 +1,90 @@ +// Code generated by 'go generate' with gen.go. DO NOT EDIT. + +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build !cgo && (darwin || freebsd || linux) + +#include "textflag.h" + +// these stubs are here because it is not possible to go:linkname directly the C functions on darwin arm64 + +TEXT _malloc(SB), NOSPLIT|NOFRAME, $0-0 + JMP purego_malloc(SB) + RET + +TEXT _free(SB), NOSPLIT|NOFRAME, $0-0 + JMP purego_free(SB) + RET + +TEXT _setenv(SB), NOSPLIT|NOFRAME, $0-0 + JMP purego_setenv(SB) + RET + +TEXT _unsetenv(SB), NOSPLIT|NOFRAME, $0-0 + JMP purego_unsetenv(SB) + RET + +TEXT _sigfillset(SB), NOSPLIT|NOFRAME, $0-0 + JMP purego_sigfillset(SB) + RET + +TEXT _nanosleep(SB), NOSPLIT|NOFRAME, $0-0 + JMP purego_nanosleep(SB) + RET + +TEXT _abort(SB), NOSPLIT|NOFRAME, $0-0 + JMP purego_abort(SB) + RET + +TEXT _pthread_attr_init(SB), NOSPLIT|NOFRAME, $0-0 + JMP purego_pthread_attr_init(SB) + RET + +TEXT _pthread_create(SB), NOSPLIT|NOFRAME, $0-0 + JMP purego_pthread_create(SB) + RET + +TEXT _pthread_detach(SB), NOSPLIT|NOFRAME, $0-0 + JMP purego_pthread_detach(SB) + RET + +TEXT _pthread_sigmask(SB), NOSPLIT|NOFRAME, $0-0 + JMP purego_pthread_sigmask(SB) + RET + +TEXT _pthread_self(SB), NOSPLIT|NOFRAME, $0-0 + JMP purego_pthread_self(SB) + RET + +TEXT _pthread_get_stacksize_np(SB), NOSPLIT|NOFRAME, $0-0 + JMP purego_pthread_get_stacksize_np(SB) + RET + +TEXT _pthread_attr_getstacksize(SB), NOSPLIT|NOFRAME, $0-0 + JMP purego_pthread_attr_getstacksize(SB) + RET + +TEXT _pthread_attr_setstacksize(SB), NOSPLIT|NOFRAME, $0-0 + JMP purego_pthread_attr_setstacksize(SB) + RET + +TEXT _pthread_attr_destroy(SB), NOSPLIT|NOFRAME, $0-0 + JMP purego_pthread_attr_destroy(SB) + RET + +TEXT _pthread_mutex_lock(SB), NOSPLIT|NOFRAME, $0-0 + JMP purego_pthread_mutex_lock(SB) + RET + +TEXT _pthread_mutex_unlock(SB), NOSPLIT|NOFRAME, $0-0 + JMP purego_pthread_mutex_unlock(SB) + RET + +TEXT _pthread_cond_broadcast(SB), NOSPLIT|NOFRAME, $0-0 + JMP purego_pthread_cond_broadcast(SB) + RET + +TEXT _pthread_setspecific(SB), NOSPLIT|NOFRAME, $0-0 + JMP purego_pthread_setspecific(SB) + RET diff --git a/vendor/github.com/ebitengine/purego/internal/strings/strings.go b/vendor/github.com/ebitengine/purego/internal/strings/strings.go new file mode 100644 index 0000000..5b0d252 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/internal/strings/strings.go @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +package strings + +import ( + "unsafe" +) + +// hasSuffix tests whether the string s ends with suffix. +func hasSuffix(s, suffix string) bool { + return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix +} + +// CString converts a go string to *byte that can be passed to C code. +func CString(name string) *byte { + if hasSuffix(name, "\x00") { + return &(*(*[]byte)(unsafe.Pointer(&name)))[0] + } + b := make([]byte, len(name)+1) + copy(b, name) + return &b[0] +} + +// GoString copies a null-terminated char* to a Go string. +func GoString(c uintptr) string { + // We take the address and then dereference it to trick go vet from creating a possible misuse of unsafe.Pointer + ptr := *(*unsafe.Pointer)(unsafe.Pointer(&c)) + if ptr == nil { + return "" + } + var length int + for { + if *(*byte)(unsafe.Add(ptr, uintptr(length))) == '\x00' { + break + } + length++ + } + return string(unsafe.Slice((*byte)(ptr), length)) +} diff --git a/vendor/github.com/ebitengine/purego/is_ios.go b/vendor/github.com/ebitengine/purego/is_ios.go new file mode 100644 index 0000000..ed31da9 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/is_ios.go @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build !cgo + +package purego + +// if you are getting this error it means that you have +// CGO_ENABLED=0 while trying to build for ios. +// purego does not support this mode yet. +// the fix is to set CGO_ENABLED=1 which will require +// a C compiler. +var _ = _PUREGO_REQUIRES_CGO_ON_IOS diff --git a/vendor/github.com/ebitengine/purego/nocgo.go b/vendor/github.com/ebitengine/purego/nocgo.go new file mode 100644 index 0000000..5b989ea --- /dev/null +++ b/vendor/github.com/ebitengine/purego/nocgo.go @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build !cgo && (darwin || freebsd || linux) + +package purego + +// if CGO_ENABLED=0 import fakecgo to setup the Cgo runtime correctly. +// This is required since some frameworks need TLS setup the C way which Go doesn't do. +// We currently don't support ios in fakecgo mode so force Cgo or fail +// +// The way that the Cgo runtime (runtime/cgo) works is by setting some variables found +// in runtime with non-null GCC compiled functions. The variables that are replaced are +// var ( +// iscgo bool // in runtime/cgo.go +// _cgo_init unsafe.Pointer // in runtime/cgo.go +// _cgo_thread_start unsafe.Pointer // in runtime/cgo.go +// _cgo_notify_runtime_init_done unsafe.Pointer // in runtime/cgo.go +// _cgo_setenv unsafe.Pointer // in runtime/env_posix.go +// _cgo_unsetenv unsafe.Pointer // in runtime/env_posix.go +// ) +// importing fakecgo will set these (using //go:linkname) with functions written +// entirely in Go (except for some assembly trampolines to change GCC ABI to Go ABI). +// Doing so makes it possible to build applications that call into C without CGO_ENABLED=1. +import _ "github.com/ebitengine/purego/internal/fakecgo" diff --git a/vendor/github.com/ebitengine/purego/objc/objc_runtime_darwin.go b/vendor/github.com/ebitengine/purego/objc/objc_runtime_darwin.go new file mode 100644 index 0000000..73e1e88 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/objc/objc_runtime_darwin.go @@ -0,0 +1,570 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +// Package objc is a low-level pure Go objective-c runtime. This package is easy to use incorrectly, so it is best +// to use a wrapper that provides the functionality you need in a safer way. +package objc + +import ( + "errors" + "fmt" + "math" + "reflect" + "regexp" + "runtime" + "unicode" + "unsafe" + + "github.com/ebitengine/purego" +) + +// TODO: support try/catch? +// https://stackoverflow.com/questions/7062599/example-of-how-objective-cs-try-catch-implementation-is-executed-at-runtime +var ( + objc_msgSend_fn uintptr + objc_msgSend_stret_fn uintptr + objc_msgSend func(obj ID, cmd SEL, args ...interface{}) ID + objc_msgSendSuper2_fn uintptr + objc_msgSendSuper2_stret_fn uintptr + objc_msgSendSuper2 func(super *objc_super, cmd SEL, args ...interface{}) ID + objc_getClass func(name string) Class + objc_getProtocol func(name string) *Protocol + objc_allocateClassPair func(super Class, name string, extraBytes uintptr) Class + objc_registerClassPair func(class Class) + sel_registerName func(name string) SEL + class_getSuperclass func(class Class) Class + class_getInstanceVariable func(class Class, name string) Ivar + class_getInstanceSize func(class Class) uintptr + class_addMethod func(class Class, name SEL, imp IMP, types string) bool + class_addIvar func(class Class, name string, size uintptr, alignment uint8, types string) bool + class_addProtocol func(class Class, protocol *Protocol) bool + ivar_getOffset func(ivar Ivar) uintptr + ivar_getName func(ivar Ivar) string + object_getClass func(obj ID) Class + object_getIvar func(obj ID, ivar Ivar) ID + object_setIvar func(obj ID, ivar Ivar, value ID) + protocol_getName func(protocol *Protocol) string + protocol_isEqual func(p *Protocol, p2 *Protocol) bool +) + +func init() { + objc, err := purego.Dlopen("/usr/lib/libobjc.A.dylib", purego.RTLD_GLOBAL) + if err != nil { + panic(fmt.Errorf("objc: %w", err)) + } + objc_msgSend_fn, err = purego.Dlsym(objc, "objc_msgSend") + if err != nil { + panic(fmt.Errorf("objc: %w", err)) + } + if runtime.GOARCH == "amd64" { + objc_msgSend_stret_fn, err = purego.Dlsym(objc, "objc_msgSend_stret") + if err != nil { + panic(fmt.Errorf("objc: %w", err)) + } + objc_msgSendSuper2_stret_fn, err = purego.Dlsym(objc, "objc_msgSendSuper2_stret") + if err != nil { + panic(fmt.Errorf("objc: %w", err)) + } + } + purego.RegisterFunc(&objc_msgSend, objc_msgSend_fn) + objc_msgSendSuper2_fn, err = purego.Dlsym(objc, "objc_msgSendSuper2") + if err != nil { + panic(fmt.Errorf("objc: %w", err)) + } + purego.RegisterFunc(&objc_msgSendSuper2, objc_msgSendSuper2_fn) + purego.RegisterLibFunc(&object_getClass, objc, "object_getClass") + purego.RegisterLibFunc(&objc_getClass, objc, "objc_getClass") + purego.RegisterLibFunc(&objc_getProtocol, objc, "objc_getProtocol") + purego.RegisterLibFunc(&objc_allocateClassPair, objc, "objc_allocateClassPair") + purego.RegisterLibFunc(&objc_registerClassPair, objc, "objc_registerClassPair") + purego.RegisterLibFunc(&sel_registerName, objc, "sel_registerName") + purego.RegisterLibFunc(&class_getSuperclass, objc, "class_getSuperclass") + purego.RegisterLibFunc(&class_getInstanceVariable, objc, "class_getInstanceVariable") + purego.RegisterLibFunc(&class_addMethod, objc, "class_addMethod") + purego.RegisterLibFunc(&class_addIvar, objc, "class_addIvar") + purego.RegisterLibFunc(&class_addProtocol, objc, "class_addProtocol") + purego.RegisterLibFunc(&class_getInstanceSize, objc, "class_getInstanceSize") + purego.RegisterLibFunc(&ivar_getOffset, objc, "ivar_getOffset") + purego.RegisterLibFunc(&ivar_getName, objc, "ivar_getName") + purego.RegisterLibFunc(&protocol_getName, objc, "protocol_getName") + purego.RegisterLibFunc(&protocol_isEqual, objc, "protocol_isEqual") + purego.RegisterLibFunc(&object_getIvar, objc, "object_getIvar") + purego.RegisterLibFunc(&object_setIvar, objc, "object_setIvar") +} + +// ID is an opaque pointer to some Objective-C object +type ID uintptr + +// Class returns the class of the object. +func (id ID) Class() Class { + return object_getClass(id) +} + +// Send is a convenience method for sending messages to objects. This function takes a SEL +// instead of a string since RegisterName grabs the global Objective-C lock. It is best to cache the result +// of RegisterName. +func (id ID) Send(sel SEL, args ...interface{}) ID { + return objc_msgSend(id, sel, args...) +} + +// GetIvar reads the value of an instance variable in an object. +func (id ID) GetIvar(ivar Ivar) ID { + return object_getIvar(id, ivar) +} + +// SetIvar sets the value of an instance variable in an object. +func (id ID) SetIvar(ivar Ivar, value ID) { + object_setIvar(id, ivar, value) +} + +// keep in sync with func.go +const maxRegAllocStructSize = 16 + +// Send is a convenience method for sending messages to objects that can return any type. +// This function takes a SEL instead of a string since RegisterName grabs the global Objective-C lock. +// It is best to cache the result of RegisterName. +func Send[T any](id ID, sel SEL, args ...any) T { + var fn func(id ID, sel SEL, args ...any) T + var zero T + if runtime.GOARCH == "amd64" && + reflect.ValueOf(zero).Kind() == reflect.Struct && + reflect.ValueOf(zero).Type().Size() > maxRegAllocStructSize { + purego.RegisterFunc(&fn, objc_msgSend_stret_fn) + } else { + purego.RegisterFunc(&fn, objc_msgSend_fn) + } + return fn(id, sel, args...) +} + +// objc_super data structure is generated by the Objective-C compiler when it encounters the super keyword +// as the receiver of a message. It specifies the class definition of the particular superclass that should +// be messaged. +type objc_super struct { + receiver ID + superClass Class +} + +// SendSuper is a convenience method for sending message to object's super. This function takes a SEL +// instead of a string since RegisterName grabs the global Objective-C lock. It is best to cache the result +// of RegisterName. +func (id ID) SendSuper(sel SEL, args ...interface{}) ID { + super := &objc_super{ + receiver: id, + superClass: id.Class(), + } + return objc_msgSendSuper2(super, sel, args...) +} + +// SendSuper is a convenience method for sending message to object's super that can return any type. +// This function takes a SEL instead of a string since RegisterName grabs the global Objective-C lock. +// It is best to cache the result of RegisterName. +func SendSuper[T any](id ID, sel SEL, args ...any) T { + super := &objc_super{ + receiver: id, + superClass: id.Class(), + } + var fn func(objcSuper *objc_super, sel SEL, args ...any) T + var zero T + if runtime.GOARCH == "amd64" && + reflect.ValueOf(zero).Kind() == reflect.Struct && + reflect.ValueOf(zero).Type().Size() > maxRegAllocStructSize { + purego.RegisterFunc(&fn, objc_msgSendSuper2_stret_fn) + } else { + purego.RegisterFunc(&fn, objc_msgSendSuper2_fn) + } + return fn(super, sel, args...) +} + +// SEL is an opaque type that represents a method selector +type SEL uintptr + +// RegisterName registers a method with the Objective-C runtime system, maps the method name to a selector, +// and returns the selector value. This function grabs the global Objective-c lock. It is best the cache the +// result of this function. +func RegisterName(name string) SEL { + return sel_registerName(name) +} + +// Class is an opaque type that represents an Objective-C class. +type Class uintptr + +// GetClass returns the Class object for the named class, or nil if the class is not registered with the Objective-C runtime. +func GetClass(name string) Class { + return objc_getClass(name) +} + +// MethodDef represents the Go function and the selector that ObjC uses to access that function. +type MethodDef struct { + Cmd SEL + Fn any +} + +// IvarAttrib is the attribute that an ivar has. It affects if and which methods are automatically +// generated when creating a class with RegisterClass. See [Apple Docs] for an understanding of these attributes. +// The fields are still accessible using objc.GetIvar and objc.SetIvar regardless of the value of IvarAttrib. +// +// Take for example this Objective-C code: +// +// @property (readwrite) float value; +// +// In Go, the functions can be accessed as followed: +// +// var value = purego.Send[float32](id, purego.RegisterName("value")) +// id.Send(purego.RegisterName("setValue:"), 3.46) +// +// [Apple Docs]: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html +type IvarAttrib int + +const ( + ReadOnly IvarAttrib = 1 << iota + ReadWrite +) + +// FieldDef is a definition of a field to add to an Objective-C class. +// The name of the field is what will be used to access it through the Ivar. If the type is bool +// the name cannot start with `is` since a getter will be generated with the name `isBoolName`. +// The name also cannot contain any spaces. +// The type is the Go equivalent type of the Ivar. +// Attribute determines if a getter and or setter method is generated for this field. +type FieldDef struct { + Name string + Type reflect.Type + Attribute IvarAttrib +} + +// ivarRegex checks to make sure the Ivar is correctly formatted +var ivarRegex = regexp.MustCompile("[a-z_][a-zA-Z0-9_]*") + +// RegisterClass takes the name of the class to create, the superclass, a list of protocols this class +// implements, a list of fields this class has and a list of methods. It returns the created class or an error +// describing what went wrong. +func RegisterClass(name string, superClass Class, protocols []*Protocol, ivars []FieldDef, methods []MethodDef) (Class, error) { + class := objc_allocateClassPair(superClass, name, 0) + if class == 0 { + return 0, fmt.Errorf("objc: failed to create class with name '%s'", name) + } + // Add Protocols + for _, p := range protocols { + if !class.AddProtocol(p) { + return 0, fmt.Errorf("objc: couldn't add Protocol %s", protocol_getName(p)) + } + } + // Add exported methods based on the selectors returned from ClassDef(string) SEL + for idx, def := range methods { + imp, err := func() (imp IMP, err error) { + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("objc: failed to create IMP: %s", r) + } + }() + return NewIMP(def.Fn), nil + }() + if err != nil { + return 0, fmt.Errorf("objc: couldn't add Method at index %d: %w", idx, err) + } + encoding, err := encodeFunc(def.Fn) + if err != nil { + return 0, fmt.Errorf("objc: couldn't add Method at index %d: %w", idx, err) + } + if !class.AddMethod(def.Cmd, imp, encoding) { + return 0, fmt.Errorf("objc: couldn't add Method at index %d", idx) + } + } + // Add Ivars + for _, instVar := range ivars { + ivar := instVar + if !ivarRegex.MatchString(ivar.Name) { + return 0, fmt.Errorf("objc: Ivar must start with a lowercase letter and only contain ASCII letters and numbers: '%s'", ivar.Name) + } + size := ivar.Type.Size() + alignment := uint8(math.Log2(float64(ivar.Type.Align()))) + enc, err := encodeType(ivar.Type, false) + if err != nil { + return 0, fmt.Errorf("objc: couldn't add Ivar %s: %w", ivar.Name, err) + } + if !class_addIvar(class, ivar.Name, size, alignment, enc) { + return 0, fmt.Errorf("objc: couldn't add Ivar %s", ivar.Name) + } + offset := class.InstanceVariable(ivar.Name).Offset() + switch ivar.Attribute { + case ReadWrite: + ty := reflect.FuncOf( + []reflect.Type{ + reflect.TypeOf(ID(0)), reflect.TypeOf(SEL(0)), ivar.Type, + }, + nil, false, + ) + var encoding string + if encoding, err = encodeFunc(reflect.New(ty).Elem().Interface()); err != nil { + return 0, fmt.Errorf("objc: failed to create read method for '%s': %w", ivar.Name, err) + } + val := reflect.MakeFunc(ty, func(args []reflect.Value) (results []reflect.Value) { + // on entry the first and second arguments are ID and SEL followed by the value + if len(args) != 3 { + panic(fmt.Sprintf("objc: incorrect number of args. expected 3 got %d", len(args))) + } + // The following reflect code does the equivalent of this: + // + // ((*struct { + // Padding [offset]byte + // Value int + // })(unsafe.Pointer(args[0].Interface().(ID)))).v = 123 + // + // However, since the type of the variable is unknown reflection is used to actually assign the value + id := args[0].Interface().(ID) + ptr := *(*unsafe.Pointer)(unsafe.Pointer(&id)) // circumvent go vet + reflect.NewAt(ivar.Type, unsafe.Add(ptr, offset)).Elem().Set(args[2]) + return nil + }).Interface() + // this code only works for ascii but that shouldn't be a problem + selector := "set" + string(unicode.ToUpper(rune(ivar.Name[0]))) + ivar.Name[1:] + ":\x00" + class.AddMethod(RegisterName(selector), NewIMP(val), encoding) + fallthrough // also implement the read method + case ReadOnly: + ty := reflect.FuncOf( + []reflect.Type{ + reflect.TypeOf(ID(0)), reflect.TypeOf(SEL(0)), + }, + []reflect.Type{ivar.Type}, false, + ) + var encoding string + if encoding, err = encodeFunc(reflect.New(ty).Elem().Interface()); err != nil { + return 0, fmt.Errorf("objc: failed to create read method for '%s': %w", ivar.Name, err) + } + val := reflect.MakeFunc(ty, func(args []reflect.Value) (results []reflect.Value) { + // on entry the first and second arguments are ID and SEL + if len(args) != 2 { + panic(fmt.Sprintf("objc: incorrect number of args. expected 2 got %d", len(args))) + } + id := args[0].Interface().(ID) + ptr := *(*unsafe.Pointer)(unsafe.Pointer(&id)) // circumvent go vet + // the variable is located at an offset from the id + return []reflect.Value{reflect.NewAt(ivar.Type, unsafe.Add(ptr, offset)).Elem()} + }).Interface() + if ivar.Type.Kind() == reflect.Bool { + // this code only works for ascii but that shouldn't be a problem + ivar.Name = "is" + string(unicode.ToUpper(rune(ivar.Name[0]))) + ivar.Name[1:] + } + class.AddMethod(RegisterName(ivar.Name), NewIMP(val), encoding) + default: + return 0, fmt.Errorf("objc: unknown Ivar Attribute (%d)", ivar.Attribute) + } + } + objc_registerClassPair(class) + return class, nil +} + +const ( + encId = "@" + encClass = "#" + encSelector = ":" + encChar = "c" + encUChar = "C" + encShort = "s" + encUShort = "S" + encInt = "i" + encUInt = "I" + encLong = "l" + encULong = "L" + encFloat = "f" + encDouble = "d" + encBool = "B" + encVoid = "v" + encPtr = "^" + encCharPtr = "*" + encStructBegin = "{" + encStructEnd = "}" + encUnsafePtr = "^v" +) + +// encodeType returns a string representing a type as if it was given to @encode(typ) +// Source: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html#//apple_ref/doc/uid/TP40008048-CH100 +func encodeType(typ reflect.Type, insidePtr bool) (string, error) { + switch typ { + case reflect.TypeOf(Class(0)): + return encClass, nil + case reflect.TypeOf(ID(0)): + return encId, nil + case reflect.TypeOf(SEL(0)): + return encSelector, nil + } + + kind := typ.Kind() + switch kind { + case reflect.Bool: + return encBool, nil + case reflect.Int: + return encLong, nil + case reflect.Int8: + return encChar, nil + case reflect.Int16: + return encShort, nil + case reflect.Int32: + return encInt, nil + case reflect.Int64: + return encULong, nil + case reflect.Uint: + return encULong, nil + case reflect.Uint8: + return encUChar, nil + case reflect.Uint16: + return encUShort, nil + case reflect.Uint32: + return encUInt, nil + case reflect.Uint64: + return encULong, nil + case reflect.Uintptr: + return encPtr, nil + case reflect.Float32: + return encFloat, nil + case reflect.Float64: + return encDouble, nil + case reflect.Ptr: + enc, err := encodeType(typ.Elem(), true) + return encPtr + enc, err + case reflect.Struct: + if insidePtr { + return encStructBegin + typ.Name() + encStructEnd, nil + } + encoding := encStructBegin + encoding += typ.Name() + encoding += "=" + for i := 0; i < typ.NumField(); i++ { + f := typ.Field(i) + tmp, err := encodeType(f.Type, false) + if err != nil { + return "", err + } + encoding += tmp + } + encoding = encStructEnd + return encoding, nil + case reflect.UnsafePointer: + return encUnsafePtr, nil + case reflect.String: + return encCharPtr, nil + } + + return "", errors.New(fmt.Sprintf("unhandled/invalid kind %v typed %v", kind, typ)) +} + +// encodeFunc returns a functions type as if it was given to @encode(fn) +func encodeFunc(fn interface{}) (string, error) { + typ := reflect.TypeOf(fn) + if typ.Kind() != reflect.Func { + return "", errors.New("not a func") + } + + encoding := "" + switch typ.NumOut() { + case 0: + encoding += encVoid + case 1: + tmp, err := encodeType(typ.Out(0), false) + if err != nil { + return "", err + } + encoding += tmp + default: + return "", errors.New("too many output parameters") + } + + if typ.NumIn() < 2 { + return "", errors.New("func doesn't take ID and SEL as its first two parameters") + } + + encoding += encId + + for i := 1; i < typ.NumIn(); i++ { + tmp, err := encodeType(typ.In(i), false) + if err != nil { + return "", err + } + encoding += tmp + } + return encoding, nil +} + +// SuperClass returns the superclass of a class. +// You should usually use NSObject‘s superclass method instead of this function. +func (c Class) SuperClass() Class { + return class_getSuperclass(c) +} + +// AddMethod adds a new method to a class with a given name and implementation. +// The types argument is a string containing the mapping of parameters and return type. +// Since the function must take at least two arguments—self and _cmd, the second and third +// characters must be “@:” (the first character is the return type). +func (c Class) AddMethod(name SEL, imp IMP, types string) bool { + return class_addMethod(c, name, imp, types) +} + +// AddProtocol adds a protocol to a class. +// Returns true if the protocol was added successfully, otherwise false (for example, +// the class already conforms to that protocol). +func (c Class) AddProtocol(protocol *Protocol) bool { + return class_addProtocol(c, protocol) +} + +// InstanceSize returns the size in bytes of instances of the class or 0 if cls is nil +func (c Class) InstanceSize() uintptr { + return class_getInstanceSize(c) +} + +// InstanceVariable returns an Ivar data structure containing information about the instance variable specified by name. +func (c Class) InstanceVariable(name string) Ivar { + return class_getInstanceVariable(c, name) +} + +// Ivar an opaque type that represents an instance variable. +type Ivar uintptr + +// Offset returns the offset of an instance variable that can be used to assign and read the Ivar's value. +// +// For instance variables of type ID or other object types, call Ivar and SetIvar instead +// of using this offset to access the instance variable data directly. +func (i Ivar) Offset() uintptr { + return ivar_getOffset(i) +} + +func (i Ivar) Name() string { + return ivar_getName(i) +} + +// Protocol is a type that declares methods that can be implemented by any class. +type Protocol [0]func() + +// GetProtocol returns the protocol for the given name or nil if there is no protocol by that name. +func GetProtocol(name string) *Protocol { + return objc_getProtocol(name) +} + +// Equals return true if the two protocols are the same. +func (p *Protocol) Equals(p2 *Protocol) bool { + return protocol_isEqual(p, p2) +} + +// IMP is a function pointer that can be called by Objective-C code. +type IMP uintptr + +// NewIMP takes a Go function that takes (ID, SEL) as its first two arguments. +// It returns an IMP function pointer that can be called by Objective-C code. +// The function panics if an error occurs. +// The function pointer is never deallocated. +func NewIMP(fn interface{}) IMP { + ty := reflect.TypeOf(fn) + if ty.Kind() != reflect.Func { + panic("objc: not a function") + } + // IMP is stricter than a normal callback + // id (*IMP)(id, SEL, ...) + switch { + case ty.NumIn() < 2: + fallthrough + case ty.In(0) != reflect.TypeOf(ID(0)): + fallthrough + case ty.In(1) != reflect.TypeOf(SEL(0)): + panic("objc: NewIMP must take a (id, SEL) as its first two arguments; got " + ty.String()) + } + return IMP(purego.NewCallback(fn)) +} diff --git a/vendor/github.com/ebitengine/purego/struct_amd64.go b/vendor/github.com/ebitengine/purego/struct_amd64.go new file mode 100644 index 0000000..06a82dd --- /dev/null +++ b/vendor/github.com/ebitengine/purego/struct_amd64.go @@ -0,0 +1,272 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2024 The Ebitengine Authors + +package purego + +import ( + "math" + "reflect" + "unsafe" +) + +func getStruct(outType reflect.Type, syscall syscall15Args) (v reflect.Value) { + outSize := outType.Size() + switch { + case outSize == 0: + return reflect.New(outType).Elem() + case outSize <= 8: + if isAllFloats(outType) { + // 2 float32s or 1 float64s are return in the float register + return reflect.NewAt(outType, unsafe.Pointer(&struct{ a uintptr }{syscall.f1})).Elem() + } + // up to 8 bytes is returned in RAX + return reflect.NewAt(outType, unsafe.Pointer(&struct{ a uintptr }{syscall.a1})).Elem() + case outSize <= 16: + r1, r2 := syscall.a1, syscall.a2 + if isAllFloats(outType) { + r1 = syscall.f1 + r2 = syscall.f2 + } else { + // check first 8 bytes if it's floats + hasFirstFloat := false + f1 := outType.Field(0).Type + if f1.Kind() == reflect.Float64 || f1.Kind() == reflect.Float32 && outType.Field(1).Type.Kind() == reflect.Float32 { + r1 = syscall.f1 + hasFirstFloat = true + } + + // find index of the field that starts the second 8 bytes + var i int + for i = 0; i < outType.NumField(); i++ { + if outType.Field(i).Offset == 8 { + break + } + } + + // check last 8 bytes if they are floats + f1 = outType.Field(i).Type + if f1.Kind() == reflect.Float64 || f1.Kind() == reflect.Float32 && i+1 == outType.NumField() { + r2 = syscall.f1 + } else if hasFirstFloat { + // if the first field was a float then that means the second integer field + // comes from the first integer register + r2 = syscall.a1 + } + } + return reflect.NewAt(outType, unsafe.Pointer(&struct{ a, b uintptr }{r1, r2})).Elem() + default: + // create struct from the Go pointer created above + // weird pointer dereference to circumvent go vet + return reflect.NewAt(outType, *(*unsafe.Pointer)(unsafe.Pointer(&syscall.a1))).Elem() + } +} + +func isAllFloats(ty reflect.Type) bool { + for i := 0; i < ty.NumField(); i++ { + f := ty.Field(i) + switch f.Type.Kind() { + case reflect.Float64, reflect.Float32: + default: + return false + } + } + return true +} + +// https://refspecs.linuxbase.org/elf/x86_64-abi-0.99.pdf +// https://gitlab.com/x86-psABIs/x86-64-ABI +// Class determines where the 8 byte value goes. +// Higher value classes win over lower value classes +const ( + _NO_CLASS = 0b0000 + _SSE = 0b0001 + _X87 = 0b0011 // long double not used in Go + _INTEGER = 0b0111 + _MEMORY = 0b1111 +) + +func addStruct(v reflect.Value, numInts, numFloats, numStack *int, addInt, addFloat, addStack func(uintptr), keepAlive []interface{}) []interface{} { + if v.Type().Size() == 0 { + return keepAlive + } + + // if greater than 64 bytes place on stack + if v.Type().Size() > 8*8 { + placeStack(v, addStack) + return keepAlive + } + var ( + savedNumFloats = *numFloats + savedNumInts = *numInts + savedNumStack = *numStack + ) + placeOnStack := postMerger(v.Type()) || !tryPlaceRegister(v, addFloat, addInt) + if placeOnStack { + // reset any values placed in registers + *numFloats = savedNumFloats + *numInts = savedNumInts + *numStack = savedNumStack + placeStack(v, addStack) + } + return keepAlive +} + +func postMerger(t reflect.Type) bool { + // (c) If the size of the aggregate exceeds two eightbytes and the first eight- byte isn’t SSE or any other + // eightbyte isn’t SSEUP, the whole argument is passed in memory. + if t.Kind() != reflect.Struct { + return false + } + if t.Size() <= 2*8 { + return false + } + first := getFirst(t).Kind() + if first != reflect.Float32 && first != reflect.Float64 { + return false + } + return true +} + +func getFirst(t reflect.Type) reflect.Type { + first := t.Field(0).Type + if first.Kind() == reflect.Struct { + return getFirst(first) + } + return first +} + +func tryPlaceRegister(v reflect.Value, addFloat func(uintptr), addInt func(uintptr)) (ok bool) { + ok = true + var val uint64 + var shift byte // # of bits to shift + var flushed bool + class := _NO_CLASS + flushIfNeeded := func() { + if flushed { + return + } + flushed = true + if class == _SSE { + addFloat(uintptr(val)) + } else { + addInt(uintptr(val)) + } + val = 0 + shift = 0 + class = _NO_CLASS + } + var place func(v reflect.Value) + place = func(v reflect.Value) { + var numFields int + if v.Kind() == reflect.Struct { + numFields = v.Type().NumField() + } else { + numFields = v.Type().Len() + } + + for i := 0; i < numFields; i++ { + flushed = false + var f reflect.Value + if v.Kind() == reflect.Struct { + f = v.Field(i) + } else { + f = v.Index(i) + } + switch f.Kind() { + case reflect.Struct: + place(f) + case reflect.Bool: + if f.Bool() { + val |= 1 + } + shift += 8 + class |= _INTEGER + case reflect.Pointer: + ok = false + return + case reflect.Int8: + val |= uint64(f.Int()&0xFF) << shift + shift += 8 + class |= _INTEGER + case reflect.Int16: + val |= uint64(f.Int()&0xFFFF) << shift + shift += 16 + class |= _INTEGER + case reflect.Int32: + val |= uint64(f.Int()&0xFFFF_FFFF) << shift + shift += 32 + class |= _INTEGER + case reflect.Int64: + val = uint64(f.Int()) + shift = 64 + class = _INTEGER + case reflect.Uint8: + val |= f.Uint() << shift + shift += 8 + class |= _INTEGER + case reflect.Uint16: + val |= f.Uint() << shift + shift += 16 + class |= _INTEGER + case reflect.Uint32: + val |= f.Uint() << shift + shift += 32 + class |= _INTEGER + case reflect.Uint64: + val = f.Uint() + shift = 64 + class = _INTEGER + case reflect.Float32: + val |= uint64(math.Float32bits(float32(f.Float()))) << shift + shift += 32 + class |= _SSE + case reflect.Float64: + if v.Type().Size() > 16 { + ok = false + return + } + val = uint64(math.Float64bits(f.Float())) + shift = 64 + class = _SSE + case reflect.Array: + place(f) + default: + panic("purego: unsupported kind " + f.Kind().String()) + } + + if shift == 64 { + flushIfNeeded() + } else if shift > 64 { + // Should never happen, but may if we forget to reset shift after flush (or forget to flush), + // better fall apart here, than corrupt arguments. + panic("purego: tryPlaceRegisters shift > 64") + } + } + } + + place(v) + flushIfNeeded() + return ok +} + +func placeStack(v reflect.Value, addStack func(uintptr)) { + for i := 0; i < v.Type().NumField(); i++ { + f := v.Field(i) + switch f.Kind() { + case reflect.Pointer: + addStack(f.Pointer()) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + addStack(uintptr(f.Int())) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + addStack(uintptr(f.Uint())) + case reflect.Float32: + addStack(uintptr(math.Float32bits(float32(f.Float())))) + case reflect.Float64: + addStack(uintptr(math.Float64bits(f.Float()))) + case reflect.Struct: + placeStack(f, addStack) + default: + panic("purego: unsupported kind " + f.Kind().String()) + } + } +} diff --git a/vendor/github.com/ebitengine/purego/struct_arm64.go b/vendor/github.com/ebitengine/purego/struct_arm64.go new file mode 100644 index 0000000..11c36bd --- /dev/null +++ b/vendor/github.com/ebitengine/purego/struct_arm64.go @@ -0,0 +1,274 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2024 The Ebitengine Authors + +package purego + +import ( + "math" + "reflect" + "unsafe" +) + +func getStruct(outType reflect.Type, syscall syscall15Args) (v reflect.Value) { + outSize := outType.Size() + switch { + case outSize == 0: + return reflect.New(outType).Elem() + case outSize <= 8: + r1 := syscall.a1 + if isAllFloats, numFields := isAllSameFloat(outType); isAllFloats { + r1 = syscall.f1 + if numFields == 2 { + r1 = syscall.f2<<32 | syscall.f1 + } + } + return reflect.NewAt(outType, unsafe.Pointer(&struct{ a uintptr }{r1})).Elem() + case outSize <= 16: + r1, r2 := syscall.a1, syscall.a2 + if isAllFloats, numFields := isAllSameFloat(outType); isAllFloats { + switch numFields { + case 4: + r1 = syscall.f2<<32 | syscall.f1 + r2 = syscall.f4<<32 | syscall.f3 + case 3: + r1 = syscall.f2<<32 | syscall.f1 + r2 = syscall.f3 + case 2: + r1 = syscall.f1 + r2 = syscall.f2 + default: + panic("unreachable") + } + } + return reflect.NewAt(outType, unsafe.Pointer(&struct{ a, b uintptr }{r1, r2})).Elem() + default: + if isAllFloats, numFields := isAllSameFloat(outType); isAllFloats && numFields <= 4 { + switch numFields { + case 4: + return reflect.NewAt(outType, unsafe.Pointer(&struct{ a, b, c, d uintptr }{syscall.f1, syscall.f2, syscall.f3, syscall.f4})).Elem() + case 3: + return reflect.NewAt(outType, unsafe.Pointer(&struct{ a, b, c uintptr }{syscall.f1, syscall.f2, syscall.f3})).Elem() + default: + panic("unreachable") + } + } + // create struct from the Go pointer created in arm64_r8 + // weird pointer dereference to circumvent go vet + return reflect.NewAt(outType, *(*unsafe.Pointer)(unsafe.Pointer(&syscall.arm64_r8))).Elem() + } +} + +// https://github.com/ARM-software/abi-aa/blob/main/sysvabi64/sysvabi64.rst +const ( + _NO_CLASS = 0b00 + _FLOAT = 0b01 + _INT = 0b11 +) + +func addStruct(v reflect.Value, numInts, numFloats, numStack *int, addInt, addFloat, addStack func(uintptr), keepAlive []interface{}) []interface{} { + if v.Type().Size() == 0 { + return keepAlive + } + + if hva, hfa, size := isHVA(v.Type()), isHFA(v.Type()), v.Type().Size(); hva || hfa || size <= 16 { + // if this doesn't fit entirely in registers then + // each element goes onto the stack + if hfa && *numFloats+v.NumField() > numOfFloats { + *numFloats = numOfFloats + } else if hva && *numInts+v.NumField() > numOfIntegerRegisters() { + *numInts = numOfIntegerRegisters() + } + + placeRegisters(v, addFloat, addInt) + } else { + keepAlive = placeStack(v, keepAlive, addInt) + } + return keepAlive // the struct was allocated so don't panic +} + +func placeRegisters(v reflect.Value, addFloat func(uintptr), addInt func(uintptr)) { + var val uint64 + var shift byte + var flushed bool + class := _NO_CLASS + var place func(v reflect.Value) + place = func(v reflect.Value) { + var numFields int + if v.Kind() == reflect.Struct { + numFields = v.Type().NumField() + } else { + numFields = v.Type().Len() + } + for k := 0; k < numFields; k++ { + flushed = false + var f reflect.Value + if v.Kind() == reflect.Struct { + f = v.Field(k) + } else { + f = v.Index(k) + } + if shift >= 64 { + shift = 0 + flushed = true + if class == _FLOAT { + addFloat(uintptr(val)) + } else { + addInt(uintptr(val)) + } + } + switch f.Type().Kind() { + case reflect.Struct: + place(f) + case reflect.Bool: + if f.Bool() { + val |= 1 + } + shift += 8 + class |= _INT + case reflect.Uint8: + val |= f.Uint() << shift + shift += 8 + class |= _INT + case reflect.Uint16: + val |= f.Uint() << shift + shift += 16 + class |= _INT + case reflect.Uint32: + val |= f.Uint() << shift + shift += 32 + class |= _INT + case reflect.Uint64: + addInt(uintptr(f.Uint())) + shift = 0 + flushed = true + case reflect.Int8: + val |= uint64(f.Int()&0xFF) << shift + shift += 8 + class |= _INT + case reflect.Int16: + val |= uint64(f.Int()&0xFFFF) << shift + shift += 16 + class |= _INT + case reflect.Int32: + val |= uint64(f.Int()&0xFFFF_FFFF) << shift + shift += 32 + class |= _INT + case reflect.Int64: + addInt(uintptr(f.Int())) + shift = 0 + flushed = true + case reflect.Float32: + if class == _FLOAT { + addFloat(uintptr(val)) + val = 0 + shift = 0 + } + val |= uint64(math.Float32bits(float32(f.Float()))) << shift + shift += 32 + class |= _FLOAT + case reflect.Float64: + addFloat(uintptr(math.Float64bits(float64(f.Float())))) + shift = 0 + flushed = true + case reflect.Array: + place(f) + default: + panic("purego: unsupported kind " + f.Kind().String()) + } + } + } + place(v) + if !flushed { + if class == _FLOAT { + addFloat(uintptr(val)) + } else { + addInt(uintptr(val)) + } + } +} + +func placeStack(v reflect.Value, keepAlive []interface{}, addInt func(uintptr)) []interface{} { + // Struct is too big to be placed in registers. + // Copy to heap and place the pointer in register + ptrStruct := reflect.New(v.Type()) + ptrStruct.Elem().Set(v) + ptr := ptrStruct.Elem().Addr().UnsafePointer() + keepAlive = append(keepAlive, ptr) + addInt(uintptr(ptr)) + return keepAlive +} + +// isHFA reports a Homogeneous Floating-point Aggregate (HFA) which is a Fundamental Data Type that is a +// Floating-Point type and at most four uniquely addressable members (5.9.5.1 in [Arm64 Calling Convention]). +// This type of struct will be placed more compactly than the individual fields. +// +// [Arm64 Calling Convention]: https://github.com/ARM-software/abi-aa/blob/main/sysvabi64/sysvabi64.rst +func isHFA(t reflect.Type) bool { + // round up struct size to nearest 8 see section B.4 + structSize := roundUpTo8(t.Size()) + if structSize == 0 || t.NumField() > 4 { + return false + } + first := t.Field(0) + switch first.Type.Kind() { + case reflect.Float32, reflect.Float64: + firstKind := first.Type.Kind() + for i := 0; i < t.NumField(); i++ { + if t.Field(i).Type.Kind() != firstKind { + return false + } + } + return true + case reflect.Array: + switch first.Type.Elem().Kind() { + case reflect.Float32, reflect.Float64: + return true + default: + return false + } + case reflect.Struct: + for i := 0; i < first.Type.NumField(); i++ { + if !isHFA(first.Type) { + return false + } + } + return true + default: + return false + } +} + +// isHVA reports a Homogeneous Aggregate with a Fundamental Data Type that is a Short-Vector type +// and at most four uniquely addressable members (5.9.5.2 in [Arm64 Calling Convention]). +// A short vector is a machine type that is composed of repeated instances of one fundamental integral or +// floating-point type. It may be 8 or 16 bytes in total size (5.4 in [Arm64 Calling Convention]). +// This type of struct will be placed more compactly than the individual fields. +// +// [Arm64 Calling Convention]: https://github.com/ARM-software/abi-aa/blob/main/sysvabi64/sysvabi64.rst +func isHVA(t reflect.Type) bool { + // round up struct size to nearest 8 see section B.4 + structSize := roundUpTo8(t.Size()) + if structSize == 0 || (structSize != 8 && structSize != 16) { + return false + } + first := t.Field(0) + switch first.Type.Kind() { + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Int8, reflect.Int16, reflect.Int32: + firstKind := first.Type.Kind() + for i := 0; i < t.NumField(); i++ { + if t.Field(i).Type.Kind() != firstKind { + return false + } + } + return true + case reflect.Array: + switch first.Type.Elem().Kind() { + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Int8, reflect.Int16, reflect.Int32: + return true + default: + return false + } + default: + return false + } +} diff --git a/vendor/github.com/ebitengine/purego/struct_other.go b/vendor/github.com/ebitengine/purego/struct_other.go new file mode 100644 index 0000000..9d42ada --- /dev/null +++ b/vendor/github.com/ebitengine/purego/struct_other.go @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2024 The Ebitengine Authors + +//go:build !amd64 && !arm64 + +package purego + +import "reflect" + +func addStruct(v reflect.Value, numInts, numFloats, numStack *int, addInt, addFloat, addStack func(uintptr), keepAlive []interface{}) []interface{} { + panic("purego: struct arguments are not supported") +} + +func getStruct(outType reflect.Type, syscall syscall15Args) (v reflect.Value) { + panic("purego: struct returns are not supported") +} diff --git a/vendor/github.com/ebitengine/purego/sys_amd64.s b/vendor/github.com/ebitengine/purego/sys_amd64.s new file mode 100644 index 0000000..cabde1a --- /dev/null +++ b/vendor/github.com/ebitengine/purego/sys_amd64.s @@ -0,0 +1,164 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build darwin || freebsd || linux + +#include "textflag.h" +#include "abi_amd64.h" +#include "go_asm.h" +#include "funcdata.h" + +#define STACK_SIZE 80 +#define PTR_ADDRESS (STACK_SIZE - 8) + +// syscall15X calls a function in libc on behalf of the syscall package. +// syscall15X takes a pointer to a struct like: +// struct { +// fn uintptr +// a1 uintptr +// a2 uintptr +// a3 uintptr +// a4 uintptr +// a5 uintptr +// a6 uintptr +// a7 uintptr +// a8 uintptr +// a9 uintptr +// a10 uintptr +// a11 uintptr +// a12 uintptr +// a13 uintptr +// a14 uintptr +// a15 uintptr +// r1 uintptr +// r2 uintptr +// err uintptr +// } +// syscall15X must be called on the g0 stack with the +// C calling convention (use libcCall). +GLOBL ·syscall15XABI0(SB), NOPTR|RODATA, $8 +DATA ·syscall15XABI0(SB)/8, $syscall15X(SB) +TEXT syscall15X(SB), NOSPLIT|NOFRAME, $0 + PUSHQ BP + MOVQ SP, BP + SUBQ $STACK_SIZE, SP + MOVQ DI, PTR_ADDRESS(BP) // save the pointer + MOVQ DI, R11 + + MOVQ syscall15Args_f1(R11), X0 // f1 + MOVQ syscall15Args_f2(R11), X1 // f2 + MOVQ syscall15Args_f3(R11), X2 // f3 + MOVQ syscall15Args_f4(R11), X3 // f4 + MOVQ syscall15Args_f5(R11), X4 // f5 + MOVQ syscall15Args_f6(R11), X5 // f6 + MOVQ syscall15Args_f7(R11), X6 // f7 + MOVQ syscall15Args_f8(R11), X7 // f8 + + MOVQ syscall15Args_a1(R11), DI // a1 + MOVQ syscall15Args_a2(R11), SI // a2 + MOVQ syscall15Args_a3(R11), DX // a3 + MOVQ syscall15Args_a4(R11), CX // a4 + MOVQ syscall15Args_a5(R11), R8 // a5 + MOVQ syscall15Args_a6(R11), R9 // a6 + + // push the remaining paramters onto the stack + MOVQ syscall15Args_a7(R11), R12 + MOVQ R12, 0(SP) // push a7 + MOVQ syscall15Args_a8(R11), R12 + MOVQ R12, 8(SP) // push a8 + MOVQ syscall15Args_a9(R11), R12 + MOVQ R12, 16(SP) // push a9 + MOVQ syscall15Args_a10(R11), R12 + MOVQ R12, 24(SP) // push a10 + MOVQ syscall15Args_a11(R11), R12 + MOVQ R12, 32(SP) // push a11 + MOVQ syscall15Args_a12(R11), R12 + MOVQ R12, 40(SP) // push a12 + MOVQ syscall15Args_a13(R11), R12 + MOVQ R12, 48(SP) // push a13 + MOVQ syscall15Args_a14(R11), R12 + MOVQ R12, 56(SP) // push a14 + MOVQ syscall15Args_a15(R11), R12 + MOVQ R12, 64(SP) // push a15 + XORL AX, AX // vararg: say "no float args" + + MOVQ syscall15Args_fn(R11), R10 // fn + CALL R10 + + MOVQ PTR_ADDRESS(BP), DI // get the pointer back + MOVQ AX, syscall15Args_a1(DI) // r1 + MOVQ DX, syscall15Args_a2(DI) // r3 + MOVQ X0, syscall15Args_f1(DI) // f1 + MOVQ X1, syscall15Args_f2(DI) // f2 + + XORL AX, AX // no error (it's ignored anyway) + ADDQ $STACK_SIZE, SP + MOVQ BP, SP + POPQ BP + RET + +TEXT callbackasm1(SB), NOSPLIT|NOFRAME, $0 + MOVQ 0(SP), AX // save the return address to calculate the cb index + MOVQ 8(SP), R10 // get the return SP so that we can align register args with stack args + ADDQ $8, SP // remove return address from stack, we are not returning to callbackasm, but to its caller. + + // make space for first six int and 8 float arguments below the frame + ADJSP $14*8, SP + MOVSD X0, (1*8)(SP) + MOVSD X1, (2*8)(SP) + MOVSD X2, (3*8)(SP) + MOVSD X3, (4*8)(SP) + MOVSD X4, (5*8)(SP) + MOVSD X5, (6*8)(SP) + MOVSD X6, (7*8)(SP) + MOVSD X7, (8*8)(SP) + MOVQ DI, (9*8)(SP) + MOVQ SI, (10*8)(SP) + MOVQ DX, (11*8)(SP) + MOVQ CX, (12*8)(SP) + MOVQ R8, (13*8)(SP) + MOVQ R9, (14*8)(SP) + LEAQ 8(SP), R8 // R8 = address of args vector + + PUSHQ R10 // push the stack pointer below registers + + // Switch from the host ABI to the Go ABI. + PUSH_REGS_HOST_TO_ABI0() + + // determine index into runtime·cbs table + MOVQ $callbackasm(SB), DX + SUBQ DX, AX + MOVQ $0, DX + MOVQ $5, CX // divide by 5 because each call instruction in ·callbacks is 5 bytes long + DIVL CX + SUBQ $1, AX // subtract 1 because return PC is to the next slot + + // Create a struct callbackArgs on our stack to be passed as + // the "frame" to cgocallback and on to callbackWrap. + // $24 to make enough room for the arguments to runtime.cgocallback + SUBQ $(24+callbackArgs__size), SP + MOVQ AX, (24+callbackArgs_index)(SP) // callback index + MOVQ R8, (24+callbackArgs_args)(SP) // address of args vector + MOVQ $0, (24+callbackArgs_result)(SP) // result + LEAQ 24(SP), AX // take the address of callbackArgs + + // Call cgocallback, which will call callbackWrap(frame). + MOVQ ·callbackWrap_call(SB), DI // Get the ABIInternal function pointer + MOVQ (DI), DI // without by using a closure. + MOVQ AX, SI // frame (address of callbackArgs) + MOVQ $0, CX // context + + CALL crosscall2(SB) // runtime.cgocallback(fn, frame, ctxt uintptr) + + // Get callback result. + MOVQ (24+callbackArgs_result)(SP), AX + ADDQ $(24+callbackArgs__size), SP // remove callbackArgs struct + + POP_REGS_HOST_TO_ABI0() + + POPQ R10 // get the SP back + ADJSP $-14*8, SP // remove arguments + + MOVQ R10, 0(SP) + + RET diff --git a/vendor/github.com/ebitengine/purego/sys_arm64.s b/vendor/github.com/ebitengine/purego/sys_arm64.s new file mode 100644 index 0000000..a68fdb9 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/sys_arm64.s @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build darwin || freebsd || linux || windows + +#include "textflag.h" +#include "go_asm.h" +#include "funcdata.h" + +#define STACK_SIZE 64 +#define PTR_ADDRESS (STACK_SIZE - 8) + +// syscall15X calls a function in libc on behalf of the syscall package. +// syscall15X takes a pointer to a struct like: +// struct { +// fn uintptr +// a1 uintptr +// a2 uintptr +// a3 uintptr +// a4 uintptr +// a5 uintptr +// a6 uintptr +// a7 uintptr +// a8 uintptr +// a9 uintptr +// a10 uintptr +// a11 uintptr +// a12 uintptr +// a13 uintptr +// a14 uintptr +// a15 uintptr +// r1 uintptr +// r2 uintptr +// err uintptr +// } +// syscall15X must be called on the g0 stack with the +// C calling convention (use libcCall). +GLOBL ·syscall15XABI0(SB), NOPTR|RODATA, $8 +DATA ·syscall15XABI0(SB)/8, $syscall15X(SB) +TEXT syscall15X(SB), NOSPLIT, $0 + SUB $STACK_SIZE, RSP // push structure pointer + MOVD R0, PTR_ADDRESS(RSP) + MOVD R0, R9 + + FMOVD syscall15Args_f1(R9), F0 // f1 + FMOVD syscall15Args_f2(R9), F1 // f2 + FMOVD syscall15Args_f3(R9), F2 // f3 + FMOVD syscall15Args_f4(R9), F3 // f4 + FMOVD syscall15Args_f5(R9), F4 // f5 + FMOVD syscall15Args_f6(R9), F5 // f6 + FMOVD syscall15Args_f7(R9), F6 // f7 + FMOVD syscall15Args_f8(R9), F7 // f8 + + MOVD syscall15Args_a1(R9), R0 // a1 + MOVD syscall15Args_a2(R9), R1 // a2 + MOVD syscall15Args_a3(R9), R2 // a3 + MOVD syscall15Args_a4(R9), R3 // a4 + MOVD syscall15Args_a5(R9), R4 // a5 + MOVD syscall15Args_a6(R9), R5 // a6 + MOVD syscall15Args_a7(R9), R6 // a7 + MOVD syscall15Args_a8(R9), R7 // a8 + MOVD syscall15Args_arm64_r8(R9), R8 // r8 + + MOVD syscall15Args_a9(R9), R10 + MOVD R10, 0(RSP) // push a9 onto stack + MOVD syscall15Args_a10(R9), R10 + MOVD R10, 8(RSP) // push a10 onto stack + MOVD syscall15Args_a11(R9), R10 + MOVD R10, 16(RSP) // push a11 onto stack + MOVD syscall15Args_a12(R9), R10 + MOVD R10, 24(RSP) // push a12 onto stack + MOVD syscall15Args_a13(R9), R10 + MOVD R10, 32(RSP) // push a13 onto stack + MOVD syscall15Args_a14(R9), R10 + MOVD R10, 40(RSP) // push a14 onto stack + MOVD syscall15Args_a15(R9), R10 + MOVD R10, 48(RSP) // push a15 onto stack + + MOVD syscall15Args_fn(R9), R10 // fn + BL (R10) + + MOVD PTR_ADDRESS(RSP), R2 // pop structure pointer + ADD $STACK_SIZE, RSP + + MOVD R0, syscall15Args_a1(R2) // save r1 + MOVD R1, syscall15Args_a2(R2) // save r3 + FMOVD F0, syscall15Args_f1(R2) // save f0 + FMOVD F1, syscall15Args_f2(R2) // save f1 + FMOVD F2, syscall15Args_f3(R2) // save f2 + FMOVD F3, syscall15Args_f4(R2) // save f3 + + RET diff --git a/vendor/github.com/ebitengine/purego/sys_unix_arm64.s b/vendor/github.com/ebitengine/purego/sys_unix_arm64.s new file mode 100644 index 0000000..6da06b4 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/sys_unix_arm64.s @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2023 The Ebitengine Authors + +//go:build darwin || freebsd || linux + +#include "textflag.h" +#include "go_asm.h" +#include "funcdata.h" +#include "abi_arm64.h" + +TEXT callbackasm1(SB), NOSPLIT|NOFRAME, $0 + NO_LOCAL_POINTERS + + // On entry, the trampoline in zcallback_darwin_arm64.s left + // the callback index in R12 (which is volatile in the C ABI). + + // Save callback register arguments R0-R7 and F0-F7. + // We do this at the top of the frame so they're contiguous with stack arguments. + SUB $(16*8), RSP, R14 + FSTPD (F0, F1), (0*8)(R14) + FSTPD (F2, F3), (2*8)(R14) + FSTPD (F4, F5), (4*8)(R14) + FSTPD (F6, F7), (6*8)(R14) + STP (R0, R1), (8*8)(R14) + STP (R2, R3), (10*8)(R14) + STP (R4, R5), (12*8)(R14) + STP (R6, R7), (14*8)(R14) + + // Adjust SP by frame size. + SUB $(26*8), RSP + + // It is important to save R27 because the go assembler + // uses it for move instructions for a variable. + // This line: + // MOVD ·callbackWrap_call(SB), R0 + // Creates the instructions: + // ADRP 14335(PC), R27 + // MOVD 388(27), R0 + // R27 is a callee saved register so we are responsible + // for ensuring its value doesn't change. So save it and + // restore it at the end of this function. + // R30 is the link register. crosscall2 doesn't save it + // so it's saved here. + STP (R27, R30), 0(RSP) + + // Create a struct callbackArgs on our stack. + MOVD $(callbackArgs__size)(RSP), R13 + MOVD R12, callbackArgs_index(R13) // callback index + MOVD R14, callbackArgs_args(R13) // address of args vector + MOVD ZR, callbackArgs_result(R13) // result + + // Move parameters into registers + // Get the ABIInternal function pointer + // without by using a closure. + MOVD ·callbackWrap_call(SB), R0 + MOVD (R0), R0 // fn unsafe.Pointer + MOVD R13, R1 // frame (&callbackArgs{...}) + MOVD $0, R3 // ctxt uintptr + + BL crosscall2(SB) + + // Get callback result. + MOVD $(callbackArgs__size)(RSP), R13 + MOVD callbackArgs_result(R13), R0 + + // Restore LR and R27 + LDP 0(RSP), (R27, R30) + ADD $(26*8), RSP + + RET diff --git a/vendor/github.com/ebitengine/purego/syscall.go b/vendor/github.com/ebitengine/purego/syscall.go new file mode 100644 index 0000000..c30688d --- /dev/null +++ b/vendor/github.com/ebitengine/purego/syscall.go @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build darwin || freebsd || linux || windows + +package purego + +// CDecl marks a function as being called using the __cdecl calling convention as defined in +// the [MSDocs] when passed to NewCallback. It must be the first argument to the function. +// This is only useful on 386 Windows, but it is safe to use on other platforms. +// +// [MSDocs]: https://learn.microsoft.com/en-us/cpp/cpp/cdecl?view=msvc-170 +type CDecl struct{} + +const ( + maxArgs = 15 + numOfFloats = 8 // arm64 and amd64 both have 8 float registers +) + +type syscall15Args struct { + fn, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15 uintptr + f1, f2, f3, f4, f5, f6, f7, f8 uintptr + arm64_r8 uintptr +} + +// SyscallN takes fn, a C function pointer and a list of arguments as uintptr. +// There is an internal maximum number of arguments that SyscallN can take. It panics +// when the maximum is exceeded. It returns the result and the libc error code if there is one. +// +// NOTE: SyscallN does not properly call functions that have both integer and float parameters. +// See discussion comment https://github.com/ebiten/purego/pull/1#issuecomment-1128057607 +// for an explanation of why that is. +// +// On amd64, if there are more than 8 floats the 9th and so on will be placed incorrectly on the +// stack. +// +// The pragma go:nosplit is not needed at this function declaration because it uses go:uintptrescapes +// which forces all the objects that the uintptrs point to onto the heap where a stack split won't affect +// their memory location. +// +//go:uintptrescapes +func SyscallN(fn uintptr, args ...uintptr) (r1, r2, err uintptr) { + if fn == 0 { + panic("purego: fn is nil") + } + if len(args) > maxArgs { + panic("purego: too many arguments to SyscallN") + } + // add padding so there is no out-of-bounds slicing + var tmp [maxArgs]uintptr + copy(tmp[:], args) + return syscall_syscall15X(fn, tmp[0], tmp[1], tmp[2], tmp[3], tmp[4], tmp[5], tmp[6], tmp[7], tmp[8], tmp[9], tmp[10], tmp[11], tmp[12], tmp[13], tmp[14]) +} diff --git a/vendor/github.com/ebitengine/purego/syscall_cgo_linux.go b/vendor/github.com/ebitengine/purego/syscall_cgo_linux.go new file mode 100644 index 0000000..36ee14e --- /dev/null +++ b/vendor/github.com/ebitengine/purego/syscall_cgo_linux.go @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build cgo && !(amd64 || arm64) + +package purego + +import ( + "github.com/ebitengine/purego/internal/cgo" +) + +var syscall15XABI0 = uintptr(cgo.Syscall15XABI0) + +//go:nosplit +func syscall_syscall15X(fn, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15 uintptr) (r1, r2, err uintptr) { + return cgo.Syscall15X(fn, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15) +} + +func NewCallback(_ interface{}) uintptr { + panic("purego: NewCallback on Linux is only supported on amd64/arm64") +} diff --git a/vendor/github.com/ebitengine/purego/syscall_sysv.go b/vendor/github.com/ebitengine/purego/syscall_sysv.go new file mode 100644 index 0000000..cce171c --- /dev/null +++ b/vendor/github.com/ebitengine/purego/syscall_sysv.go @@ -0,0 +1,223 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +//go:build darwin || freebsd || (linux && (amd64 || arm64)) + +package purego + +import ( + "reflect" + "runtime" + "sync" + "unsafe" +) + +var syscall15XABI0 uintptr + +//go:nosplit +func syscall_syscall15X(fn, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15 uintptr) (r1, r2, err uintptr) { + args := syscall15Args{ + fn, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, + a1, a2, a3, a4, a5, a6, a7, a8, + 0, + } + runtime_cgocall(syscall15XABI0, unsafe.Pointer(&args)) + return args.a1, args.a2, 0 +} + +// NewCallback converts a Go function to a function pointer conforming to the C calling convention. +// This is useful when interoperating with C code requiring callbacks. The argument is expected to be a +// function with zero or one uintptr-sized result. The function must not have arguments with size larger than the size +// of uintptr. Only a limited number of callbacks may be created in a single Go process, and any memory allocated +// for these callbacks is never released. At least 2000 callbacks can always be created. Although this function +// provides similar functionality to windows.NewCallback it is distinct. +func NewCallback(fn interface{}) uintptr { + ty := reflect.TypeOf(fn) + for i := 0; i < ty.NumIn(); i++ { + in := ty.In(i) + if !in.AssignableTo(reflect.TypeOf(CDecl{})) { + continue + } + if i != 0 { + panic("purego: CDecl must be the first argument") + } + } + return compileCallback(fn) +} + +// maxCb is the maximum number of callbacks +// only increase this if you have added more to the callbackasm function +const maxCB = 2000 + +var cbs struct { + lock sync.Mutex + numFn int // the number of functions currently in cbs.funcs + funcs [maxCB]reflect.Value // the saved callbacks +} + +type callbackArgs struct { + index uintptr + // args points to the argument block. + // + // The structure of the arguments goes + // float registers followed by the + // integer registers followed by the stack. + // + // This variable is treated as a continuous + // block of memory containing all of the arguments + // for this callback. + args unsafe.Pointer + // Below are out-args from callbackWrap + result uintptr +} + +func compileCallback(fn interface{}) uintptr { + val := reflect.ValueOf(fn) + if val.Kind() != reflect.Func { + panic("purego: the type must be a function but was not") + } + if val.IsNil() { + panic("purego: function must not be nil") + } + ty := val.Type() + for i := 0; i < ty.NumIn(); i++ { + in := ty.In(i) + switch in.Kind() { + case reflect.Struct: + if i == 0 && in.AssignableTo(reflect.TypeOf(CDecl{})) { + continue + } + fallthrough + case reflect.Interface, reflect.Func, reflect.Slice, + reflect.Chan, reflect.Complex64, reflect.Complex128, + reflect.String, reflect.Map, reflect.Invalid: + panic("purego: unsupported argument type: " + in.Kind().String()) + } + } +output: + switch { + case ty.NumOut() == 1: + switch ty.Out(0).Kind() { + case reflect.Pointer, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, + reflect.Bool, reflect.UnsafePointer: + break output + } + panic("purego: unsupported return type: " + ty.String()) + case ty.NumOut() > 1: + panic("purego: callbacks can only have one return") + } + cbs.lock.Lock() + defer cbs.lock.Unlock() + if cbs.numFn >= maxCB { + panic("purego: the maximum number of callbacks has been reached") + } + cbs.funcs[cbs.numFn] = val + cbs.numFn++ + return callbackasmAddr(cbs.numFn - 1) +} + +const ptrSize = unsafe.Sizeof((*int)(nil)) + +const callbackMaxFrame = 64 * ptrSize + +// callbackasm is implemented in zcallback_GOOS_GOARCH.s +// +//go:linkname __callbackasm callbackasm +var __callbackasm byte +var callbackasmABI0 = uintptr(unsafe.Pointer(&__callbackasm)) + +// callbackWrap_call allows the calling of the ABIInternal wrapper +// which is required for runtime.cgocallback without the +// tag which is only allowed in the runtime. +// This closure is used inside sys_darwin_GOARCH.s +var callbackWrap_call = callbackWrap + +// callbackWrap is called by assembly code which determines which Go function to call. +// This function takes the arguments and passes them to the Go function and returns the result. +func callbackWrap(a *callbackArgs) { + cbs.lock.Lock() + fn := cbs.funcs[a.index] + cbs.lock.Unlock() + fnType := fn.Type() + args := make([]reflect.Value, fnType.NumIn()) + frame := (*[callbackMaxFrame]uintptr)(a.args) + var floatsN int // floatsN represents the number of float arguments processed + var intsN int // intsN represents the number of integer arguments processed + // stack points to the index into frame of the current stack element. + // The stack begins after the float and integer registers. + stack := numOfIntegerRegisters() + numOfFloats + for i := range args { + var pos int + switch fnType.In(i).Kind() { + case reflect.Float32, reflect.Float64: + if floatsN >= numOfFloats { + pos = stack + stack++ + } else { + pos = floatsN + } + floatsN++ + case reflect.Struct: + // This is the CDecl field + args[i] = reflect.Zero(fnType.In(i)) + continue + default: + + if intsN >= numOfIntegerRegisters() { + pos = stack + stack++ + } else { + // the integers begin after the floats in frame + pos = intsN + numOfFloats + } + intsN++ + } + args[i] = reflect.NewAt(fnType.In(i), unsafe.Pointer(&frame[pos])).Elem() + } + ret := fn.Call(args) + if len(ret) > 0 { + switch k := ret[0].Kind(); k { + case reflect.Uint, reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uintptr: + a.result = uintptr(ret[0].Uint()) + case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8: + a.result = uintptr(ret[0].Int()) + case reflect.Bool: + if ret[0].Bool() { + a.result = 1 + } else { + a.result = 0 + } + case reflect.Pointer: + a.result = ret[0].Pointer() + case reflect.UnsafePointer: + a.result = ret[0].Pointer() + default: + panic("purego: unsupported kind: " + k.String()) + } + } +} + +// callbackasmAddr returns address of runtime.callbackasm +// function adjusted by i. +// On x86 and amd64, runtime.callbackasm is a series of CALL instructions, +// and we want callback to arrive at +// correspondent call instruction instead of start of +// runtime.callbackasm. +// On ARM, runtime.callbackasm is a series of mov and branch instructions. +// R12 is loaded with the callback index. Each entry is two instructions, +// hence 8 bytes. +func callbackasmAddr(i int) uintptr { + var entrySize int + switch runtime.GOARCH { + default: + panic("purego: unsupported architecture") + case "386", "amd64": + entrySize = 5 + case "arm", "arm64": + // On ARM and ARM64, each entry is a MOV instruction + // followed by a branch instruction + entrySize = 8 + } + return callbackasmABI0 + uintptr(i*entrySize) +} diff --git a/vendor/github.com/ebitengine/purego/syscall_windows.go b/vendor/github.com/ebitengine/purego/syscall_windows.go new file mode 100644 index 0000000..5fbfcab --- /dev/null +++ b/vendor/github.com/ebitengine/purego/syscall_windows.go @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2022 The Ebitengine Authors + +package purego + +import ( + "reflect" + "syscall" +) + +var syscall15XABI0 uintptr + +func syscall_syscall15X(fn, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15 uintptr) (r1, r2, err uintptr) { + r1, r2, errno := syscall.Syscall15(fn, 15, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15) + return r1, r2, uintptr(errno) +} + +// NewCallback converts a Go function to a function pointer conforming to the stdcall calling convention. +// This is useful when interoperating with Windows code requiring callbacks. The argument is expected to be a +// function with one uintptr-sized result. The function must not have arguments with size larger than the +// size of uintptr. Only a limited number of callbacks may be created in a single Go process, and any memory +// allocated for these callbacks is never released. Between NewCallback and NewCallbackCDecl, at least 1024 +// callbacks can always be created. Although this function is similiar to the darwin version it may act +// differently. +func NewCallback(fn interface{}) uintptr { + isCDecl := false + ty := reflect.TypeOf(fn) + for i := 0; i < ty.NumIn(); i++ { + in := ty.In(i) + if !in.AssignableTo(reflect.TypeOf(CDecl{})) { + continue + } + if i != 0 { + panic("purego: CDecl must be the first argument") + } + isCDecl = true + } + if isCDecl { + return syscall.NewCallbackCDecl(fn) + } + return syscall.NewCallback(fn) +} + +func loadSymbol(handle uintptr, name string) (uintptr, error) { + return syscall.GetProcAddress(syscall.Handle(handle), name) +} diff --git a/vendor/github.com/ebitengine/purego/zcallback_amd64.s b/vendor/github.com/ebitengine/purego/zcallback_amd64.s new file mode 100644 index 0000000..6a778bf --- /dev/null +++ b/vendor/github.com/ebitengine/purego/zcallback_amd64.s @@ -0,0 +1,2014 @@ +// Code generated by wincallback.go using 'go generate'. DO NOT EDIT. + +//go:build darwin || freebsd || linux + +// runtime·callbackasm is called by external code to +// execute Go implemented callback function. It is not +// called from the start, instead runtime·compilecallback +// always returns address into runtime·callbackasm offset +// appropriately so different callbacks start with different +// CALL instruction in runtime·callbackasm. This determines +// which Go callback function is executed later on. +#include "textflag.h" + +TEXT callbackasm(SB), NOSPLIT|NOFRAME, $0 + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) + CALL callbackasm1(SB) diff --git a/vendor/github.com/ebitengine/purego/zcallback_arm64.s b/vendor/github.com/ebitengine/purego/zcallback_arm64.s new file mode 100644 index 0000000..c079b80 --- /dev/null +++ b/vendor/github.com/ebitengine/purego/zcallback_arm64.s @@ -0,0 +1,4014 @@ +// Code generated by wincallback.go using 'go generate'. DO NOT EDIT. + +//go:build darwin || freebsd || linux + +// External code calls into callbackasm at an offset corresponding +// to the callback index. Callbackasm is a table of MOV and B instructions. +// The MOV instruction loads R12 with the callback index, and the +// B instruction branches to callbackasm1. +// callbackasm1 takes the callback index from R12 and +// indexes into an array that stores information about each callback. +// It then calls the Go implementation for that callback. +#include "textflag.h" + +TEXT callbackasm(SB), NOSPLIT|NOFRAME, $0 + MOVD $0, R12 + B callbackasm1(SB) + MOVD $1, R12 + B callbackasm1(SB) + MOVD $2, R12 + B callbackasm1(SB) + MOVD $3, R12 + B callbackasm1(SB) + MOVD $4, R12 + B callbackasm1(SB) + MOVD $5, R12 + B callbackasm1(SB) + MOVD $6, R12 + B callbackasm1(SB) + MOVD $7, R12 + B callbackasm1(SB) + MOVD $8, R12 + B callbackasm1(SB) + MOVD $9, R12 + B callbackasm1(SB) + MOVD $10, R12 + B callbackasm1(SB) + MOVD $11, R12 + B callbackasm1(SB) + MOVD $12, R12 + B callbackasm1(SB) + MOVD $13, R12 + B callbackasm1(SB) + MOVD $14, R12 + B callbackasm1(SB) + MOVD $15, R12 + B callbackasm1(SB) + MOVD $16, R12 + B callbackasm1(SB) + MOVD $17, R12 + B callbackasm1(SB) + MOVD $18, R12 + B callbackasm1(SB) + MOVD $19, R12 + B callbackasm1(SB) + MOVD $20, R12 + B callbackasm1(SB) + MOVD $21, R12 + B callbackasm1(SB) + MOVD $22, R12 + B callbackasm1(SB) + MOVD $23, R12 + B callbackasm1(SB) + MOVD $24, R12 + B callbackasm1(SB) + MOVD $25, R12 + B callbackasm1(SB) + MOVD $26, R12 + B callbackasm1(SB) + MOVD $27, R12 + B callbackasm1(SB) + MOVD $28, R12 + B callbackasm1(SB) + MOVD $29, R12 + B callbackasm1(SB) + MOVD $30, R12 + B callbackasm1(SB) + MOVD $31, R12 + B callbackasm1(SB) + MOVD $32, R12 + B callbackasm1(SB) + MOVD $33, R12 + B callbackasm1(SB) + MOVD $34, R12 + B callbackasm1(SB) + MOVD $35, R12 + B callbackasm1(SB) + MOVD $36, R12 + B callbackasm1(SB) + MOVD $37, R12 + B callbackasm1(SB) + MOVD $38, R12 + B callbackasm1(SB) + MOVD $39, R12 + B callbackasm1(SB) + MOVD $40, R12 + B callbackasm1(SB) + MOVD $41, R12 + B callbackasm1(SB) + MOVD $42, R12 + B callbackasm1(SB) + MOVD $43, R12 + B callbackasm1(SB) + MOVD $44, R12 + B callbackasm1(SB) + MOVD $45, R12 + B callbackasm1(SB) + MOVD $46, R12 + B callbackasm1(SB) + MOVD $47, R12 + B callbackasm1(SB) + MOVD $48, R12 + B callbackasm1(SB) + MOVD $49, R12 + B callbackasm1(SB) + MOVD $50, R12 + B callbackasm1(SB) + MOVD $51, R12 + B callbackasm1(SB) + MOVD $52, R12 + B callbackasm1(SB) + MOVD $53, R12 + B callbackasm1(SB) + MOVD $54, R12 + B callbackasm1(SB) + MOVD $55, R12 + B callbackasm1(SB) + MOVD $56, R12 + B callbackasm1(SB) + MOVD $57, R12 + B callbackasm1(SB) + MOVD $58, R12 + B callbackasm1(SB) + MOVD $59, R12 + B callbackasm1(SB) + MOVD $60, R12 + B callbackasm1(SB) + MOVD $61, R12 + B callbackasm1(SB) + MOVD $62, R12 + B callbackasm1(SB) + MOVD $63, R12 + B callbackasm1(SB) + MOVD $64, R12 + B callbackasm1(SB) + MOVD $65, R12 + B callbackasm1(SB) + MOVD $66, R12 + B callbackasm1(SB) + MOVD $67, R12 + B callbackasm1(SB) + MOVD $68, R12 + B callbackasm1(SB) + MOVD $69, R12 + B callbackasm1(SB) + MOVD $70, R12 + B callbackasm1(SB) + MOVD $71, R12 + B callbackasm1(SB) + MOVD $72, R12 + B callbackasm1(SB) + MOVD $73, R12 + B callbackasm1(SB) + MOVD $74, R12 + B callbackasm1(SB) + MOVD $75, R12 + B callbackasm1(SB) + MOVD $76, R12 + B callbackasm1(SB) + MOVD $77, R12 + B callbackasm1(SB) + MOVD $78, R12 + B callbackasm1(SB) + MOVD $79, R12 + B callbackasm1(SB) + MOVD $80, R12 + B callbackasm1(SB) + MOVD $81, R12 + B callbackasm1(SB) + MOVD $82, R12 + B callbackasm1(SB) + MOVD $83, R12 + B callbackasm1(SB) + MOVD $84, R12 + B callbackasm1(SB) + MOVD $85, R12 + B callbackasm1(SB) + MOVD $86, R12 + B callbackasm1(SB) + MOVD $87, R12 + B callbackasm1(SB) + MOVD $88, R12 + B callbackasm1(SB) + MOVD $89, R12 + B callbackasm1(SB) + MOVD $90, R12 + B callbackasm1(SB) + MOVD $91, R12 + B callbackasm1(SB) + MOVD $92, R12 + B callbackasm1(SB) + MOVD $93, R12 + B callbackasm1(SB) + MOVD $94, R12 + B callbackasm1(SB) + MOVD $95, R12 + B callbackasm1(SB) + MOVD $96, R12 + B callbackasm1(SB) + MOVD $97, R12 + B callbackasm1(SB) + MOVD $98, R12 + B callbackasm1(SB) + MOVD $99, R12 + B callbackasm1(SB) + MOVD $100, R12 + B callbackasm1(SB) + MOVD $101, R12 + B callbackasm1(SB) + MOVD $102, R12 + B callbackasm1(SB) + MOVD $103, R12 + B callbackasm1(SB) + MOVD $104, R12 + B callbackasm1(SB) + MOVD $105, R12 + B callbackasm1(SB) + MOVD $106, R12 + B callbackasm1(SB) + MOVD $107, R12 + B callbackasm1(SB) + MOVD $108, R12 + B callbackasm1(SB) + MOVD $109, R12 + B callbackasm1(SB) + MOVD $110, R12 + B callbackasm1(SB) + MOVD $111, R12 + B callbackasm1(SB) + MOVD $112, R12 + B callbackasm1(SB) + MOVD $113, R12 + B callbackasm1(SB) + MOVD $114, R12 + B callbackasm1(SB) + MOVD $115, R12 + B callbackasm1(SB) + MOVD $116, R12 + B callbackasm1(SB) + MOVD $117, R12 + B callbackasm1(SB) + MOVD $118, R12 + B callbackasm1(SB) + MOVD $119, R12 + B callbackasm1(SB) + MOVD $120, R12 + B callbackasm1(SB) + MOVD $121, R12 + B callbackasm1(SB) + MOVD $122, R12 + B callbackasm1(SB) + MOVD $123, R12 + B callbackasm1(SB) + MOVD $124, R12 + B callbackasm1(SB) + MOVD $125, R12 + B callbackasm1(SB) + MOVD $126, R12 + B callbackasm1(SB) + MOVD $127, R12 + B callbackasm1(SB) + MOVD $128, R12 + B callbackasm1(SB) + MOVD $129, R12 + B callbackasm1(SB) + MOVD $130, R12 + B callbackasm1(SB) + MOVD $131, R12 + B callbackasm1(SB) + MOVD $132, R12 + B callbackasm1(SB) + MOVD $133, R12 + B callbackasm1(SB) + MOVD $134, R12 + B callbackasm1(SB) + MOVD $135, R12 + B callbackasm1(SB) + MOVD $136, R12 + B callbackasm1(SB) + MOVD $137, R12 + B callbackasm1(SB) + MOVD $138, R12 + B callbackasm1(SB) + MOVD $139, R12 + B callbackasm1(SB) + MOVD $140, R12 + B callbackasm1(SB) + MOVD $141, R12 + B callbackasm1(SB) + MOVD $142, R12 + B callbackasm1(SB) + MOVD $143, R12 + B callbackasm1(SB) + MOVD $144, R12 + B callbackasm1(SB) + MOVD $145, R12 + B callbackasm1(SB) + MOVD $146, R12 + B callbackasm1(SB) + MOVD $147, R12 + B callbackasm1(SB) + MOVD $148, R12 + B callbackasm1(SB) + MOVD $149, R12 + B callbackasm1(SB) + MOVD $150, R12 + B callbackasm1(SB) + MOVD $151, R12 + B callbackasm1(SB) + MOVD $152, R12 + B callbackasm1(SB) + MOVD $153, R12 + B callbackasm1(SB) + MOVD $154, R12 + B callbackasm1(SB) + MOVD $155, R12 + B callbackasm1(SB) + MOVD $156, R12 + B callbackasm1(SB) + MOVD $157, R12 + B callbackasm1(SB) + MOVD $158, R12 + B callbackasm1(SB) + MOVD $159, R12 + B callbackasm1(SB) + MOVD $160, R12 + B callbackasm1(SB) + MOVD $161, R12 + B callbackasm1(SB) + MOVD $162, R12 + B callbackasm1(SB) + MOVD $163, R12 + B callbackasm1(SB) + MOVD $164, R12 + B callbackasm1(SB) + MOVD $165, R12 + B callbackasm1(SB) + MOVD $166, R12 + B callbackasm1(SB) + MOVD $167, R12 + B callbackasm1(SB) + MOVD $168, R12 + B callbackasm1(SB) + MOVD $169, R12 + B callbackasm1(SB) + MOVD $170, R12 + B callbackasm1(SB) + MOVD $171, R12 + B callbackasm1(SB) + MOVD $172, R12 + B callbackasm1(SB) + MOVD $173, R12 + B callbackasm1(SB) + MOVD $174, R12 + B callbackasm1(SB) + MOVD $175, R12 + B callbackasm1(SB) + MOVD $176, R12 + B callbackasm1(SB) + MOVD $177, R12 + B callbackasm1(SB) + MOVD $178, R12 + B callbackasm1(SB) + MOVD $179, R12 + B callbackasm1(SB) + MOVD $180, R12 + B callbackasm1(SB) + MOVD $181, R12 + B callbackasm1(SB) + MOVD $182, R12 + B callbackasm1(SB) + MOVD $183, R12 + B callbackasm1(SB) + MOVD $184, R12 + B callbackasm1(SB) + MOVD $185, R12 + B callbackasm1(SB) + MOVD $186, R12 + B callbackasm1(SB) + MOVD $187, R12 + B callbackasm1(SB) + MOVD $188, R12 + B callbackasm1(SB) + MOVD $189, R12 + B callbackasm1(SB) + MOVD $190, R12 + B callbackasm1(SB) + MOVD $191, R12 + B callbackasm1(SB) + MOVD $192, R12 + B callbackasm1(SB) + MOVD $193, R12 + B callbackasm1(SB) + MOVD $194, R12 + B callbackasm1(SB) + MOVD $195, R12 + B callbackasm1(SB) + MOVD $196, R12 + B callbackasm1(SB) + MOVD $197, R12 + B callbackasm1(SB) + MOVD $198, R12 + B callbackasm1(SB) + MOVD $199, R12 + B callbackasm1(SB) + MOVD $200, R12 + B callbackasm1(SB) + MOVD $201, R12 + B callbackasm1(SB) + MOVD $202, R12 + B callbackasm1(SB) + MOVD $203, R12 + B callbackasm1(SB) + MOVD $204, R12 + B callbackasm1(SB) + MOVD $205, R12 + B callbackasm1(SB) + MOVD $206, R12 + B callbackasm1(SB) + MOVD $207, R12 + B callbackasm1(SB) + MOVD $208, R12 + B callbackasm1(SB) + MOVD $209, R12 + B callbackasm1(SB) + MOVD $210, R12 + B callbackasm1(SB) + MOVD $211, R12 + B callbackasm1(SB) + MOVD $212, R12 + B callbackasm1(SB) + MOVD $213, R12 + B callbackasm1(SB) + MOVD $214, R12 + B callbackasm1(SB) + MOVD $215, R12 + B callbackasm1(SB) + MOVD $216, R12 + B callbackasm1(SB) + MOVD $217, R12 + B callbackasm1(SB) + MOVD $218, R12 + B callbackasm1(SB) + MOVD $219, R12 + B callbackasm1(SB) + MOVD $220, R12 + B callbackasm1(SB) + MOVD $221, R12 + B callbackasm1(SB) + MOVD $222, R12 + B callbackasm1(SB) + MOVD $223, R12 + B callbackasm1(SB) + MOVD $224, R12 + B callbackasm1(SB) + MOVD $225, R12 + B callbackasm1(SB) + MOVD $226, R12 + B callbackasm1(SB) + MOVD $227, R12 + B callbackasm1(SB) + MOVD $228, R12 + B callbackasm1(SB) + MOVD $229, R12 + B callbackasm1(SB) + MOVD $230, R12 + B callbackasm1(SB) + MOVD $231, R12 + B callbackasm1(SB) + MOVD $232, R12 + B callbackasm1(SB) + MOVD $233, R12 + B callbackasm1(SB) + MOVD $234, R12 + B callbackasm1(SB) + MOVD $235, R12 + B callbackasm1(SB) + MOVD $236, R12 + B callbackasm1(SB) + MOVD $237, R12 + B callbackasm1(SB) + MOVD $238, R12 + B callbackasm1(SB) + MOVD $239, R12 + B callbackasm1(SB) + MOVD $240, R12 + B callbackasm1(SB) + MOVD $241, R12 + B callbackasm1(SB) + MOVD $242, R12 + B callbackasm1(SB) + MOVD $243, R12 + B callbackasm1(SB) + MOVD $244, R12 + B callbackasm1(SB) + MOVD $245, R12 + B callbackasm1(SB) + MOVD $246, R12 + B callbackasm1(SB) + MOVD $247, R12 + B callbackasm1(SB) + MOVD $248, R12 + B callbackasm1(SB) + MOVD $249, R12 + B callbackasm1(SB) + MOVD $250, R12 + B callbackasm1(SB) + MOVD $251, R12 + B callbackasm1(SB) + MOVD $252, R12 + B callbackasm1(SB) + MOVD $253, R12 + B callbackasm1(SB) + MOVD $254, R12 + B callbackasm1(SB) + MOVD $255, R12 + B callbackasm1(SB) + MOVD $256, R12 + B callbackasm1(SB) + MOVD $257, R12 + B callbackasm1(SB) + MOVD $258, R12 + B callbackasm1(SB) + MOVD $259, R12 + B callbackasm1(SB) + MOVD $260, R12 + B callbackasm1(SB) + MOVD $261, R12 + B callbackasm1(SB) + MOVD $262, R12 + B callbackasm1(SB) + MOVD $263, R12 + B callbackasm1(SB) + MOVD $264, R12 + B callbackasm1(SB) + MOVD $265, R12 + B callbackasm1(SB) + MOVD $266, R12 + B callbackasm1(SB) + MOVD $267, R12 + B callbackasm1(SB) + MOVD $268, R12 + B callbackasm1(SB) + MOVD $269, R12 + B callbackasm1(SB) + MOVD $270, R12 + B callbackasm1(SB) + MOVD $271, R12 + B callbackasm1(SB) + MOVD $272, R12 + B callbackasm1(SB) + MOVD $273, R12 + B callbackasm1(SB) + MOVD $274, R12 + B callbackasm1(SB) + MOVD $275, R12 + B callbackasm1(SB) + MOVD $276, R12 + B callbackasm1(SB) + MOVD $277, R12 + B callbackasm1(SB) + MOVD $278, R12 + B callbackasm1(SB) + MOVD $279, R12 + B callbackasm1(SB) + MOVD $280, R12 + B callbackasm1(SB) + MOVD $281, R12 + B callbackasm1(SB) + MOVD $282, R12 + B callbackasm1(SB) + MOVD $283, R12 + B callbackasm1(SB) + MOVD $284, R12 + B callbackasm1(SB) + MOVD $285, R12 + B callbackasm1(SB) + MOVD $286, R12 + B callbackasm1(SB) + MOVD $287, R12 + B callbackasm1(SB) + MOVD $288, R12 + B callbackasm1(SB) + MOVD $289, R12 + B callbackasm1(SB) + MOVD $290, R12 + B callbackasm1(SB) + MOVD $291, R12 + B callbackasm1(SB) + MOVD $292, R12 + B callbackasm1(SB) + MOVD $293, R12 + B callbackasm1(SB) + MOVD $294, R12 + B callbackasm1(SB) + MOVD $295, R12 + B callbackasm1(SB) + MOVD $296, R12 + B callbackasm1(SB) + MOVD $297, R12 + B callbackasm1(SB) + MOVD $298, R12 + B callbackasm1(SB) + MOVD $299, R12 + B callbackasm1(SB) + MOVD $300, R12 + B callbackasm1(SB) + MOVD $301, R12 + B callbackasm1(SB) + MOVD $302, R12 + B callbackasm1(SB) + MOVD $303, R12 + B callbackasm1(SB) + MOVD $304, R12 + B callbackasm1(SB) + MOVD $305, R12 + B callbackasm1(SB) + MOVD $306, R12 + B callbackasm1(SB) + MOVD $307, R12 + B callbackasm1(SB) + MOVD $308, R12 + B callbackasm1(SB) + MOVD $309, R12 + B callbackasm1(SB) + MOVD $310, R12 + B callbackasm1(SB) + MOVD $311, R12 + B callbackasm1(SB) + MOVD $312, R12 + B callbackasm1(SB) + MOVD $313, R12 + B callbackasm1(SB) + MOVD $314, R12 + B callbackasm1(SB) + MOVD $315, R12 + B callbackasm1(SB) + MOVD $316, R12 + B callbackasm1(SB) + MOVD $317, R12 + B callbackasm1(SB) + MOVD $318, R12 + B callbackasm1(SB) + MOVD $319, R12 + B callbackasm1(SB) + MOVD $320, R12 + B callbackasm1(SB) + MOVD $321, R12 + B callbackasm1(SB) + MOVD $322, R12 + B callbackasm1(SB) + MOVD $323, R12 + B callbackasm1(SB) + MOVD $324, R12 + B callbackasm1(SB) + MOVD $325, R12 + B callbackasm1(SB) + MOVD $326, R12 + B callbackasm1(SB) + MOVD $327, R12 + B callbackasm1(SB) + MOVD $328, R12 + B callbackasm1(SB) + MOVD $329, R12 + B callbackasm1(SB) + MOVD $330, R12 + B callbackasm1(SB) + MOVD $331, R12 + B callbackasm1(SB) + MOVD $332, R12 + B callbackasm1(SB) + MOVD $333, R12 + B callbackasm1(SB) + MOVD $334, R12 + B callbackasm1(SB) + MOVD $335, R12 + B callbackasm1(SB) + MOVD $336, R12 + B callbackasm1(SB) + MOVD $337, R12 + B callbackasm1(SB) + MOVD $338, R12 + B callbackasm1(SB) + MOVD $339, R12 + B callbackasm1(SB) + MOVD $340, R12 + B callbackasm1(SB) + MOVD $341, R12 + B callbackasm1(SB) + MOVD $342, R12 + B callbackasm1(SB) + MOVD $343, R12 + B callbackasm1(SB) + MOVD $344, R12 + B callbackasm1(SB) + MOVD $345, R12 + B callbackasm1(SB) + MOVD $346, R12 + B callbackasm1(SB) + MOVD $347, R12 + B callbackasm1(SB) + MOVD $348, R12 + B callbackasm1(SB) + MOVD $349, R12 + B callbackasm1(SB) + MOVD $350, R12 + B callbackasm1(SB) + MOVD $351, R12 + B callbackasm1(SB) + MOVD $352, R12 + B callbackasm1(SB) + MOVD $353, R12 + B callbackasm1(SB) + MOVD $354, R12 + B callbackasm1(SB) + MOVD $355, R12 + B callbackasm1(SB) + MOVD $356, R12 + B callbackasm1(SB) + MOVD $357, R12 + B callbackasm1(SB) + MOVD $358, R12 + B callbackasm1(SB) + MOVD $359, R12 + B callbackasm1(SB) + MOVD $360, R12 + B callbackasm1(SB) + MOVD $361, R12 + B callbackasm1(SB) + MOVD $362, R12 + B callbackasm1(SB) + MOVD $363, R12 + B callbackasm1(SB) + MOVD $364, R12 + B callbackasm1(SB) + MOVD $365, R12 + B callbackasm1(SB) + MOVD $366, R12 + B callbackasm1(SB) + MOVD $367, R12 + B callbackasm1(SB) + MOVD $368, R12 + B callbackasm1(SB) + MOVD $369, R12 + B callbackasm1(SB) + MOVD $370, R12 + B callbackasm1(SB) + MOVD $371, R12 + B callbackasm1(SB) + MOVD $372, R12 + B callbackasm1(SB) + MOVD $373, R12 + B callbackasm1(SB) + MOVD $374, R12 + B callbackasm1(SB) + MOVD $375, R12 + B callbackasm1(SB) + MOVD $376, R12 + B callbackasm1(SB) + MOVD $377, R12 + B callbackasm1(SB) + MOVD $378, R12 + B callbackasm1(SB) + MOVD $379, R12 + B callbackasm1(SB) + MOVD $380, R12 + B callbackasm1(SB) + MOVD $381, R12 + B callbackasm1(SB) + MOVD $382, R12 + B callbackasm1(SB) + MOVD $383, R12 + B callbackasm1(SB) + MOVD $384, R12 + B callbackasm1(SB) + MOVD $385, R12 + B callbackasm1(SB) + MOVD $386, R12 + B callbackasm1(SB) + MOVD $387, R12 + B callbackasm1(SB) + MOVD $388, R12 + B callbackasm1(SB) + MOVD $389, R12 + B callbackasm1(SB) + MOVD $390, R12 + B callbackasm1(SB) + MOVD $391, R12 + B callbackasm1(SB) + MOVD $392, R12 + B callbackasm1(SB) + MOVD $393, R12 + B callbackasm1(SB) + MOVD $394, R12 + B callbackasm1(SB) + MOVD $395, R12 + B callbackasm1(SB) + MOVD $396, R12 + B callbackasm1(SB) + MOVD $397, R12 + B callbackasm1(SB) + MOVD $398, R12 + B callbackasm1(SB) + MOVD $399, R12 + B callbackasm1(SB) + MOVD $400, R12 + B callbackasm1(SB) + MOVD $401, R12 + B callbackasm1(SB) + MOVD $402, R12 + B callbackasm1(SB) + MOVD $403, R12 + B callbackasm1(SB) + MOVD $404, R12 + B callbackasm1(SB) + MOVD $405, R12 + B callbackasm1(SB) + MOVD $406, R12 + B callbackasm1(SB) + MOVD $407, R12 + B callbackasm1(SB) + MOVD $408, R12 + B callbackasm1(SB) + MOVD $409, R12 + B callbackasm1(SB) + MOVD $410, R12 + B callbackasm1(SB) + MOVD $411, R12 + B callbackasm1(SB) + MOVD $412, R12 + B callbackasm1(SB) + MOVD $413, R12 + B callbackasm1(SB) + MOVD $414, R12 + B callbackasm1(SB) + MOVD $415, R12 + B callbackasm1(SB) + MOVD $416, R12 + B callbackasm1(SB) + MOVD $417, R12 + B callbackasm1(SB) + MOVD $418, R12 + B callbackasm1(SB) + MOVD $419, R12 + B callbackasm1(SB) + MOVD $420, R12 + B callbackasm1(SB) + MOVD $421, R12 + B callbackasm1(SB) + MOVD $422, R12 + B callbackasm1(SB) + MOVD $423, R12 + B callbackasm1(SB) + MOVD $424, R12 + B callbackasm1(SB) + MOVD $425, R12 + B callbackasm1(SB) + MOVD $426, R12 + B callbackasm1(SB) + MOVD $427, R12 + B callbackasm1(SB) + MOVD $428, R12 + B callbackasm1(SB) + MOVD $429, R12 + B callbackasm1(SB) + MOVD $430, R12 + B callbackasm1(SB) + MOVD $431, R12 + B callbackasm1(SB) + MOVD $432, R12 + B callbackasm1(SB) + MOVD $433, R12 + B callbackasm1(SB) + MOVD $434, R12 + B callbackasm1(SB) + MOVD $435, R12 + B callbackasm1(SB) + MOVD $436, R12 + B callbackasm1(SB) + MOVD $437, R12 + B callbackasm1(SB) + MOVD $438, R12 + B callbackasm1(SB) + MOVD $439, R12 + B callbackasm1(SB) + MOVD $440, R12 + B callbackasm1(SB) + MOVD $441, R12 + B callbackasm1(SB) + MOVD $442, R12 + B callbackasm1(SB) + MOVD $443, R12 + B callbackasm1(SB) + MOVD $444, R12 + B callbackasm1(SB) + MOVD $445, R12 + B callbackasm1(SB) + MOVD $446, R12 + B callbackasm1(SB) + MOVD $447, R12 + B callbackasm1(SB) + MOVD $448, R12 + B callbackasm1(SB) + MOVD $449, R12 + B callbackasm1(SB) + MOVD $450, R12 + B callbackasm1(SB) + MOVD $451, R12 + B callbackasm1(SB) + MOVD $452, R12 + B callbackasm1(SB) + MOVD $453, R12 + B callbackasm1(SB) + MOVD $454, R12 + B callbackasm1(SB) + MOVD $455, R12 + B callbackasm1(SB) + MOVD $456, R12 + B callbackasm1(SB) + MOVD $457, R12 + B callbackasm1(SB) + MOVD $458, R12 + B callbackasm1(SB) + MOVD $459, R12 + B callbackasm1(SB) + MOVD $460, R12 + B callbackasm1(SB) + MOVD $461, R12 + B callbackasm1(SB) + MOVD $462, R12 + B callbackasm1(SB) + MOVD $463, R12 + B callbackasm1(SB) + MOVD $464, R12 + B callbackasm1(SB) + MOVD $465, R12 + B callbackasm1(SB) + MOVD $466, R12 + B callbackasm1(SB) + MOVD $467, R12 + B callbackasm1(SB) + MOVD $468, R12 + B callbackasm1(SB) + MOVD $469, R12 + B callbackasm1(SB) + MOVD $470, R12 + B callbackasm1(SB) + MOVD $471, R12 + B callbackasm1(SB) + MOVD $472, R12 + B callbackasm1(SB) + MOVD $473, R12 + B callbackasm1(SB) + MOVD $474, R12 + B callbackasm1(SB) + MOVD $475, R12 + B callbackasm1(SB) + MOVD $476, R12 + B callbackasm1(SB) + MOVD $477, R12 + B callbackasm1(SB) + MOVD $478, R12 + B callbackasm1(SB) + MOVD $479, R12 + B callbackasm1(SB) + MOVD $480, R12 + B callbackasm1(SB) + MOVD $481, R12 + B callbackasm1(SB) + MOVD $482, R12 + B callbackasm1(SB) + MOVD $483, R12 + B callbackasm1(SB) + MOVD $484, R12 + B callbackasm1(SB) + MOVD $485, R12 + B callbackasm1(SB) + MOVD $486, R12 + B callbackasm1(SB) + MOVD $487, R12 + B callbackasm1(SB) + MOVD $488, R12 + B callbackasm1(SB) + MOVD $489, R12 + B callbackasm1(SB) + MOVD $490, R12 + B callbackasm1(SB) + MOVD $491, R12 + B callbackasm1(SB) + MOVD $492, R12 + B callbackasm1(SB) + MOVD $493, R12 + B callbackasm1(SB) + MOVD $494, R12 + B callbackasm1(SB) + MOVD $495, R12 + B callbackasm1(SB) + MOVD $496, R12 + B callbackasm1(SB) + MOVD $497, R12 + B callbackasm1(SB) + MOVD $498, R12 + B callbackasm1(SB) + MOVD $499, R12 + B callbackasm1(SB) + MOVD $500, R12 + B callbackasm1(SB) + MOVD $501, R12 + B callbackasm1(SB) + MOVD $502, R12 + B callbackasm1(SB) + MOVD $503, R12 + B callbackasm1(SB) + MOVD $504, R12 + B callbackasm1(SB) + MOVD $505, R12 + B callbackasm1(SB) + MOVD $506, R12 + B callbackasm1(SB) + MOVD $507, R12 + B callbackasm1(SB) + MOVD $508, R12 + B callbackasm1(SB) + MOVD $509, R12 + B callbackasm1(SB) + MOVD $510, R12 + B callbackasm1(SB) + MOVD $511, R12 + B callbackasm1(SB) + MOVD $512, R12 + B callbackasm1(SB) + MOVD $513, R12 + B callbackasm1(SB) + MOVD $514, R12 + B callbackasm1(SB) + MOVD $515, R12 + B callbackasm1(SB) + MOVD $516, R12 + B callbackasm1(SB) + MOVD $517, R12 + B callbackasm1(SB) + MOVD $518, R12 + B callbackasm1(SB) + MOVD $519, R12 + B callbackasm1(SB) + MOVD $520, R12 + B callbackasm1(SB) + MOVD $521, R12 + B callbackasm1(SB) + MOVD $522, R12 + B callbackasm1(SB) + MOVD $523, R12 + B callbackasm1(SB) + MOVD $524, R12 + B callbackasm1(SB) + MOVD $525, R12 + B callbackasm1(SB) + MOVD $526, R12 + B callbackasm1(SB) + MOVD $527, R12 + B callbackasm1(SB) + MOVD $528, R12 + B callbackasm1(SB) + MOVD $529, R12 + B callbackasm1(SB) + MOVD $530, R12 + B callbackasm1(SB) + MOVD $531, R12 + B callbackasm1(SB) + MOVD $532, R12 + B callbackasm1(SB) + MOVD $533, R12 + B callbackasm1(SB) + MOVD $534, R12 + B callbackasm1(SB) + MOVD $535, R12 + B callbackasm1(SB) + MOVD $536, R12 + B callbackasm1(SB) + MOVD $537, R12 + B callbackasm1(SB) + MOVD $538, R12 + B callbackasm1(SB) + MOVD $539, R12 + B callbackasm1(SB) + MOVD $540, R12 + B callbackasm1(SB) + MOVD $541, R12 + B callbackasm1(SB) + MOVD $542, R12 + B callbackasm1(SB) + MOVD $543, R12 + B callbackasm1(SB) + MOVD $544, R12 + B callbackasm1(SB) + MOVD $545, R12 + B callbackasm1(SB) + MOVD $546, R12 + B callbackasm1(SB) + MOVD $547, R12 + B callbackasm1(SB) + MOVD $548, R12 + B callbackasm1(SB) + MOVD $549, R12 + B callbackasm1(SB) + MOVD $550, R12 + B callbackasm1(SB) + MOVD $551, R12 + B callbackasm1(SB) + MOVD $552, R12 + B callbackasm1(SB) + MOVD $553, R12 + B callbackasm1(SB) + MOVD $554, R12 + B callbackasm1(SB) + MOVD $555, R12 + B callbackasm1(SB) + MOVD $556, R12 + B callbackasm1(SB) + MOVD $557, R12 + B callbackasm1(SB) + MOVD $558, R12 + B callbackasm1(SB) + MOVD $559, R12 + B callbackasm1(SB) + MOVD $560, R12 + B callbackasm1(SB) + MOVD $561, R12 + B callbackasm1(SB) + MOVD $562, R12 + B callbackasm1(SB) + MOVD $563, R12 + B callbackasm1(SB) + MOVD $564, R12 + B callbackasm1(SB) + MOVD $565, R12 + B callbackasm1(SB) + MOVD $566, R12 + B callbackasm1(SB) + MOVD $567, R12 + B callbackasm1(SB) + MOVD $568, R12 + B callbackasm1(SB) + MOVD $569, R12 + B callbackasm1(SB) + MOVD $570, R12 + B callbackasm1(SB) + MOVD $571, R12 + B callbackasm1(SB) + MOVD $572, R12 + B callbackasm1(SB) + MOVD $573, R12 + B callbackasm1(SB) + MOVD $574, R12 + B callbackasm1(SB) + MOVD $575, R12 + B callbackasm1(SB) + MOVD $576, R12 + B callbackasm1(SB) + MOVD $577, R12 + B callbackasm1(SB) + MOVD $578, R12 + B callbackasm1(SB) + MOVD $579, R12 + B callbackasm1(SB) + MOVD $580, R12 + B callbackasm1(SB) + MOVD $581, R12 + B callbackasm1(SB) + MOVD $582, R12 + B callbackasm1(SB) + MOVD $583, R12 + B callbackasm1(SB) + MOVD $584, R12 + B callbackasm1(SB) + MOVD $585, R12 + B callbackasm1(SB) + MOVD $586, R12 + B callbackasm1(SB) + MOVD $587, R12 + B callbackasm1(SB) + MOVD $588, R12 + B callbackasm1(SB) + MOVD $589, R12 + B callbackasm1(SB) + MOVD $590, R12 + B callbackasm1(SB) + MOVD $591, R12 + B callbackasm1(SB) + MOVD $592, R12 + B callbackasm1(SB) + MOVD $593, R12 + B callbackasm1(SB) + MOVD $594, R12 + B callbackasm1(SB) + MOVD $595, R12 + B callbackasm1(SB) + MOVD $596, R12 + B callbackasm1(SB) + MOVD $597, R12 + B callbackasm1(SB) + MOVD $598, R12 + B callbackasm1(SB) + MOVD $599, R12 + B callbackasm1(SB) + MOVD $600, R12 + B callbackasm1(SB) + MOVD $601, R12 + B callbackasm1(SB) + MOVD $602, R12 + B callbackasm1(SB) + MOVD $603, R12 + B callbackasm1(SB) + MOVD $604, R12 + B callbackasm1(SB) + MOVD $605, R12 + B callbackasm1(SB) + MOVD $606, R12 + B callbackasm1(SB) + MOVD $607, R12 + B callbackasm1(SB) + MOVD $608, R12 + B callbackasm1(SB) + MOVD $609, R12 + B callbackasm1(SB) + MOVD $610, R12 + B callbackasm1(SB) + MOVD $611, R12 + B callbackasm1(SB) + MOVD $612, R12 + B callbackasm1(SB) + MOVD $613, R12 + B callbackasm1(SB) + MOVD $614, R12 + B callbackasm1(SB) + MOVD $615, R12 + B callbackasm1(SB) + MOVD $616, R12 + B callbackasm1(SB) + MOVD $617, R12 + B callbackasm1(SB) + MOVD $618, R12 + B callbackasm1(SB) + MOVD $619, R12 + B callbackasm1(SB) + MOVD $620, R12 + B callbackasm1(SB) + MOVD $621, R12 + B callbackasm1(SB) + MOVD $622, R12 + B callbackasm1(SB) + MOVD $623, R12 + B callbackasm1(SB) + MOVD $624, R12 + B callbackasm1(SB) + MOVD $625, R12 + B callbackasm1(SB) + MOVD $626, R12 + B callbackasm1(SB) + MOVD $627, R12 + B callbackasm1(SB) + MOVD $628, R12 + B callbackasm1(SB) + MOVD $629, R12 + B callbackasm1(SB) + MOVD $630, R12 + B callbackasm1(SB) + MOVD $631, R12 + B callbackasm1(SB) + MOVD $632, R12 + B callbackasm1(SB) + MOVD $633, R12 + B callbackasm1(SB) + MOVD $634, R12 + B callbackasm1(SB) + MOVD $635, R12 + B callbackasm1(SB) + MOVD $636, R12 + B callbackasm1(SB) + MOVD $637, R12 + B callbackasm1(SB) + MOVD $638, R12 + B callbackasm1(SB) + MOVD $639, R12 + B callbackasm1(SB) + MOVD $640, R12 + B callbackasm1(SB) + MOVD $641, R12 + B callbackasm1(SB) + MOVD $642, R12 + B callbackasm1(SB) + MOVD $643, R12 + B callbackasm1(SB) + MOVD $644, R12 + B callbackasm1(SB) + MOVD $645, R12 + B callbackasm1(SB) + MOVD $646, R12 + B callbackasm1(SB) + MOVD $647, R12 + B callbackasm1(SB) + MOVD $648, R12 + B callbackasm1(SB) + MOVD $649, R12 + B callbackasm1(SB) + MOVD $650, R12 + B callbackasm1(SB) + MOVD $651, R12 + B callbackasm1(SB) + MOVD $652, R12 + B callbackasm1(SB) + MOVD $653, R12 + B callbackasm1(SB) + MOVD $654, R12 + B callbackasm1(SB) + MOVD $655, R12 + B callbackasm1(SB) + MOVD $656, R12 + B callbackasm1(SB) + MOVD $657, R12 + B callbackasm1(SB) + MOVD $658, R12 + B callbackasm1(SB) + MOVD $659, R12 + B callbackasm1(SB) + MOVD $660, R12 + B callbackasm1(SB) + MOVD $661, R12 + B callbackasm1(SB) + MOVD $662, R12 + B callbackasm1(SB) + MOVD $663, R12 + B callbackasm1(SB) + MOVD $664, R12 + B callbackasm1(SB) + MOVD $665, R12 + B callbackasm1(SB) + MOVD $666, R12 + B callbackasm1(SB) + MOVD $667, R12 + B callbackasm1(SB) + MOVD $668, R12 + B callbackasm1(SB) + MOVD $669, R12 + B callbackasm1(SB) + MOVD $670, R12 + B callbackasm1(SB) + MOVD $671, R12 + B callbackasm1(SB) + MOVD $672, R12 + B callbackasm1(SB) + MOVD $673, R12 + B callbackasm1(SB) + MOVD $674, R12 + B callbackasm1(SB) + MOVD $675, R12 + B callbackasm1(SB) + MOVD $676, R12 + B callbackasm1(SB) + MOVD $677, R12 + B callbackasm1(SB) + MOVD $678, R12 + B callbackasm1(SB) + MOVD $679, R12 + B callbackasm1(SB) + MOVD $680, R12 + B callbackasm1(SB) + MOVD $681, R12 + B callbackasm1(SB) + MOVD $682, R12 + B callbackasm1(SB) + MOVD $683, R12 + B callbackasm1(SB) + MOVD $684, R12 + B callbackasm1(SB) + MOVD $685, R12 + B callbackasm1(SB) + MOVD $686, R12 + B callbackasm1(SB) + MOVD $687, R12 + B callbackasm1(SB) + MOVD $688, R12 + B callbackasm1(SB) + MOVD $689, R12 + B callbackasm1(SB) + MOVD $690, R12 + B callbackasm1(SB) + MOVD $691, R12 + B callbackasm1(SB) + MOVD $692, R12 + B callbackasm1(SB) + MOVD $693, R12 + B callbackasm1(SB) + MOVD $694, R12 + B callbackasm1(SB) + MOVD $695, R12 + B callbackasm1(SB) + MOVD $696, R12 + B callbackasm1(SB) + MOVD $697, R12 + B callbackasm1(SB) + MOVD $698, R12 + B callbackasm1(SB) + MOVD $699, R12 + B callbackasm1(SB) + MOVD $700, R12 + B callbackasm1(SB) + MOVD $701, R12 + B callbackasm1(SB) + MOVD $702, R12 + B callbackasm1(SB) + MOVD $703, R12 + B callbackasm1(SB) + MOVD $704, R12 + B callbackasm1(SB) + MOVD $705, R12 + B callbackasm1(SB) + MOVD $706, R12 + B callbackasm1(SB) + MOVD $707, R12 + B callbackasm1(SB) + MOVD $708, R12 + B callbackasm1(SB) + MOVD $709, R12 + B callbackasm1(SB) + MOVD $710, R12 + B callbackasm1(SB) + MOVD $711, R12 + B callbackasm1(SB) + MOVD $712, R12 + B callbackasm1(SB) + MOVD $713, R12 + B callbackasm1(SB) + MOVD $714, R12 + B callbackasm1(SB) + MOVD $715, R12 + B callbackasm1(SB) + MOVD $716, R12 + B callbackasm1(SB) + MOVD $717, R12 + B callbackasm1(SB) + MOVD $718, R12 + B callbackasm1(SB) + MOVD $719, R12 + B callbackasm1(SB) + MOVD $720, R12 + B callbackasm1(SB) + MOVD $721, R12 + B callbackasm1(SB) + MOVD $722, R12 + B callbackasm1(SB) + MOVD $723, R12 + B callbackasm1(SB) + MOVD $724, R12 + B callbackasm1(SB) + MOVD $725, R12 + B callbackasm1(SB) + MOVD $726, R12 + B callbackasm1(SB) + MOVD $727, R12 + B callbackasm1(SB) + MOVD $728, R12 + B callbackasm1(SB) + MOVD $729, R12 + B callbackasm1(SB) + MOVD $730, R12 + B callbackasm1(SB) + MOVD $731, R12 + B callbackasm1(SB) + MOVD $732, R12 + B callbackasm1(SB) + MOVD $733, R12 + B callbackasm1(SB) + MOVD $734, R12 + B callbackasm1(SB) + MOVD $735, R12 + B callbackasm1(SB) + MOVD $736, R12 + B callbackasm1(SB) + MOVD $737, R12 + B callbackasm1(SB) + MOVD $738, R12 + B callbackasm1(SB) + MOVD $739, R12 + B callbackasm1(SB) + MOVD $740, R12 + B callbackasm1(SB) + MOVD $741, R12 + B callbackasm1(SB) + MOVD $742, R12 + B callbackasm1(SB) + MOVD $743, R12 + B callbackasm1(SB) + MOVD $744, R12 + B callbackasm1(SB) + MOVD $745, R12 + B callbackasm1(SB) + MOVD $746, R12 + B callbackasm1(SB) + MOVD $747, R12 + B callbackasm1(SB) + MOVD $748, R12 + B callbackasm1(SB) + MOVD $749, R12 + B callbackasm1(SB) + MOVD $750, R12 + B callbackasm1(SB) + MOVD $751, R12 + B callbackasm1(SB) + MOVD $752, R12 + B callbackasm1(SB) + MOVD $753, R12 + B callbackasm1(SB) + MOVD $754, R12 + B callbackasm1(SB) + MOVD $755, R12 + B callbackasm1(SB) + MOVD $756, R12 + B callbackasm1(SB) + MOVD $757, R12 + B callbackasm1(SB) + MOVD $758, R12 + B callbackasm1(SB) + MOVD $759, R12 + B callbackasm1(SB) + MOVD $760, R12 + B callbackasm1(SB) + MOVD $761, R12 + B callbackasm1(SB) + MOVD $762, R12 + B callbackasm1(SB) + MOVD $763, R12 + B callbackasm1(SB) + MOVD $764, R12 + B callbackasm1(SB) + MOVD $765, R12 + B callbackasm1(SB) + MOVD $766, R12 + B callbackasm1(SB) + MOVD $767, R12 + B callbackasm1(SB) + MOVD $768, R12 + B callbackasm1(SB) + MOVD $769, R12 + B callbackasm1(SB) + MOVD $770, R12 + B callbackasm1(SB) + MOVD $771, R12 + B callbackasm1(SB) + MOVD $772, R12 + B callbackasm1(SB) + MOVD $773, R12 + B callbackasm1(SB) + MOVD $774, R12 + B callbackasm1(SB) + MOVD $775, R12 + B callbackasm1(SB) + MOVD $776, R12 + B callbackasm1(SB) + MOVD $777, R12 + B callbackasm1(SB) + MOVD $778, R12 + B callbackasm1(SB) + MOVD $779, R12 + B callbackasm1(SB) + MOVD $780, R12 + B callbackasm1(SB) + MOVD $781, R12 + B callbackasm1(SB) + MOVD $782, R12 + B callbackasm1(SB) + MOVD $783, R12 + B callbackasm1(SB) + MOVD $784, R12 + B callbackasm1(SB) + MOVD $785, R12 + B callbackasm1(SB) + MOVD $786, R12 + B callbackasm1(SB) + MOVD $787, R12 + B callbackasm1(SB) + MOVD $788, R12 + B callbackasm1(SB) + MOVD $789, R12 + B callbackasm1(SB) + MOVD $790, R12 + B callbackasm1(SB) + MOVD $791, R12 + B callbackasm1(SB) + MOVD $792, R12 + B callbackasm1(SB) + MOVD $793, R12 + B callbackasm1(SB) + MOVD $794, R12 + B callbackasm1(SB) + MOVD $795, R12 + B callbackasm1(SB) + MOVD $796, R12 + B callbackasm1(SB) + MOVD $797, R12 + B callbackasm1(SB) + MOVD $798, R12 + B callbackasm1(SB) + MOVD $799, R12 + B callbackasm1(SB) + MOVD $800, R12 + B callbackasm1(SB) + MOVD $801, R12 + B callbackasm1(SB) + MOVD $802, R12 + B callbackasm1(SB) + MOVD $803, R12 + B callbackasm1(SB) + MOVD $804, R12 + B callbackasm1(SB) + MOVD $805, R12 + B callbackasm1(SB) + MOVD $806, R12 + B callbackasm1(SB) + MOVD $807, R12 + B callbackasm1(SB) + MOVD $808, R12 + B callbackasm1(SB) + MOVD $809, R12 + B callbackasm1(SB) + MOVD $810, R12 + B callbackasm1(SB) + MOVD $811, R12 + B callbackasm1(SB) + MOVD $812, R12 + B callbackasm1(SB) + MOVD $813, R12 + B callbackasm1(SB) + MOVD $814, R12 + B callbackasm1(SB) + MOVD $815, R12 + B callbackasm1(SB) + MOVD $816, R12 + B callbackasm1(SB) + MOVD $817, R12 + B callbackasm1(SB) + MOVD $818, R12 + B callbackasm1(SB) + MOVD $819, R12 + B callbackasm1(SB) + MOVD $820, R12 + B callbackasm1(SB) + MOVD $821, R12 + B callbackasm1(SB) + MOVD $822, R12 + B callbackasm1(SB) + MOVD $823, R12 + B callbackasm1(SB) + MOVD $824, R12 + B callbackasm1(SB) + MOVD $825, R12 + B callbackasm1(SB) + MOVD $826, R12 + B callbackasm1(SB) + MOVD $827, R12 + B callbackasm1(SB) + MOVD $828, R12 + B callbackasm1(SB) + MOVD $829, R12 + B callbackasm1(SB) + MOVD $830, R12 + B callbackasm1(SB) + MOVD $831, R12 + B callbackasm1(SB) + MOVD $832, R12 + B callbackasm1(SB) + MOVD $833, R12 + B callbackasm1(SB) + MOVD $834, R12 + B callbackasm1(SB) + MOVD $835, R12 + B callbackasm1(SB) + MOVD $836, R12 + B callbackasm1(SB) + MOVD $837, R12 + B callbackasm1(SB) + MOVD $838, R12 + B callbackasm1(SB) + MOVD $839, R12 + B callbackasm1(SB) + MOVD $840, R12 + B callbackasm1(SB) + MOVD $841, R12 + B callbackasm1(SB) + MOVD $842, R12 + B callbackasm1(SB) + MOVD $843, R12 + B callbackasm1(SB) + MOVD $844, R12 + B callbackasm1(SB) + MOVD $845, R12 + B callbackasm1(SB) + MOVD $846, R12 + B callbackasm1(SB) + MOVD $847, R12 + B callbackasm1(SB) + MOVD $848, R12 + B callbackasm1(SB) + MOVD $849, R12 + B callbackasm1(SB) + MOVD $850, R12 + B callbackasm1(SB) + MOVD $851, R12 + B callbackasm1(SB) + MOVD $852, R12 + B callbackasm1(SB) + MOVD $853, R12 + B callbackasm1(SB) + MOVD $854, R12 + B callbackasm1(SB) + MOVD $855, R12 + B callbackasm1(SB) + MOVD $856, R12 + B callbackasm1(SB) + MOVD $857, R12 + B callbackasm1(SB) + MOVD $858, R12 + B callbackasm1(SB) + MOVD $859, R12 + B callbackasm1(SB) + MOVD $860, R12 + B callbackasm1(SB) + MOVD $861, R12 + B callbackasm1(SB) + MOVD $862, R12 + B callbackasm1(SB) + MOVD $863, R12 + B callbackasm1(SB) + MOVD $864, R12 + B callbackasm1(SB) + MOVD $865, R12 + B callbackasm1(SB) + MOVD $866, R12 + B callbackasm1(SB) + MOVD $867, R12 + B callbackasm1(SB) + MOVD $868, R12 + B callbackasm1(SB) + MOVD $869, R12 + B callbackasm1(SB) + MOVD $870, R12 + B callbackasm1(SB) + MOVD $871, R12 + B callbackasm1(SB) + MOVD $872, R12 + B callbackasm1(SB) + MOVD $873, R12 + B callbackasm1(SB) + MOVD $874, R12 + B callbackasm1(SB) + MOVD $875, R12 + B callbackasm1(SB) + MOVD $876, R12 + B callbackasm1(SB) + MOVD $877, R12 + B callbackasm1(SB) + MOVD $878, R12 + B callbackasm1(SB) + MOVD $879, R12 + B callbackasm1(SB) + MOVD $880, R12 + B callbackasm1(SB) + MOVD $881, R12 + B callbackasm1(SB) + MOVD $882, R12 + B callbackasm1(SB) + MOVD $883, R12 + B callbackasm1(SB) + MOVD $884, R12 + B callbackasm1(SB) + MOVD $885, R12 + B callbackasm1(SB) + MOVD $886, R12 + B callbackasm1(SB) + MOVD $887, R12 + B callbackasm1(SB) + MOVD $888, R12 + B callbackasm1(SB) + MOVD $889, R12 + B callbackasm1(SB) + MOVD $890, R12 + B callbackasm1(SB) + MOVD $891, R12 + B callbackasm1(SB) + MOVD $892, R12 + B callbackasm1(SB) + MOVD $893, R12 + B callbackasm1(SB) + MOVD $894, R12 + B callbackasm1(SB) + MOVD $895, R12 + B callbackasm1(SB) + MOVD $896, R12 + B callbackasm1(SB) + MOVD $897, R12 + B callbackasm1(SB) + MOVD $898, R12 + B callbackasm1(SB) + MOVD $899, R12 + B callbackasm1(SB) + MOVD $900, R12 + B callbackasm1(SB) + MOVD $901, R12 + B callbackasm1(SB) + MOVD $902, R12 + B callbackasm1(SB) + MOVD $903, R12 + B callbackasm1(SB) + MOVD $904, R12 + B callbackasm1(SB) + MOVD $905, R12 + B callbackasm1(SB) + MOVD $906, R12 + B callbackasm1(SB) + MOVD $907, R12 + B callbackasm1(SB) + MOVD $908, R12 + B callbackasm1(SB) + MOVD $909, R12 + B callbackasm1(SB) + MOVD $910, R12 + B callbackasm1(SB) + MOVD $911, R12 + B callbackasm1(SB) + MOVD $912, R12 + B callbackasm1(SB) + MOVD $913, R12 + B callbackasm1(SB) + MOVD $914, R12 + B callbackasm1(SB) + MOVD $915, R12 + B callbackasm1(SB) + MOVD $916, R12 + B callbackasm1(SB) + MOVD $917, R12 + B callbackasm1(SB) + MOVD $918, R12 + B callbackasm1(SB) + MOVD $919, R12 + B callbackasm1(SB) + MOVD $920, R12 + B callbackasm1(SB) + MOVD $921, R12 + B callbackasm1(SB) + MOVD $922, R12 + B callbackasm1(SB) + MOVD $923, R12 + B callbackasm1(SB) + MOVD $924, R12 + B callbackasm1(SB) + MOVD $925, R12 + B callbackasm1(SB) + MOVD $926, R12 + B callbackasm1(SB) + MOVD $927, R12 + B callbackasm1(SB) + MOVD $928, R12 + B callbackasm1(SB) + MOVD $929, R12 + B callbackasm1(SB) + MOVD $930, R12 + B callbackasm1(SB) + MOVD $931, R12 + B callbackasm1(SB) + MOVD $932, R12 + B callbackasm1(SB) + MOVD $933, R12 + B callbackasm1(SB) + MOVD $934, R12 + B callbackasm1(SB) + MOVD $935, R12 + B callbackasm1(SB) + MOVD $936, R12 + B callbackasm1(SB) + MOVD $937, R12 + B callbackasm1(SB) + MOVD $938, R12 + B callbackasm1(SB) + MOVD $939, R12 + B callbackasm1(SB) + MOVD $940, R12 + B callbackasm1(SB) + MOVD $941, R12 + B callbackasm1(SB) + MOVD $942, R12 + B callbackasm1(SB) + MOVD $943, R12 + B callbackasm1(SB) + MOVD $944, R12 + B callbackasm1(SB) + MOVD $945, R12 + B callbackasm1(SB) + MOVD $946, R12 + B callbackasm1(SB) + MOVD $947, R12 + B callbackasm1(SB) + MOVD $948, R12 + B callbackasm1(SB) + MOVD $949, R12 + B callbackasm1(SB) + MOVD $950, R12 + B callbackasm1(SB) + MOVD $951, R12 + B callbackasm1(SB) + MOVD $952, R12 + B callbackasm1(SB) + MOVD $953, R12 + B callbackasm1(SB) + MOVD $954, R12 + B callbackasm1(SB) + MOVD $955, R12 + B callbackasm1(SB) + MOVD $956, R12 + B callbackasm1(SB) + MOVD $957, R12 + B callbackasm1(SB) + MOVD $958, R12 + B callbackasm1(SB) + MOVD $959, R12 + B callbackasm1(SB) + MOVD $960, R12 + B callbackasm1(SB) + MOVD $961, R12 + B callbackasm1(SB) + MOVD $962, R12 + B callbackasm1(SB) + MOVD $963, R12 + B callbackasm1(SB) + MOVD $964, R12 + B callbackasm1(SB) + MOVD $965, R12 + B callbackasm1(SB) + MOVD $966, R12 + B callbackasm1(SB) + MOVD $967, R12 + B callbackasm1(SB) + MOVD $968, R12 + B callbackasm1(SB) + MOVD $969, R12 + B callbackasm1(SB) + MOVD $970, R12 + B callbackasm1(SB) + MOVD $971, R12 + B callbackasm1(SB) + MOVD $972, R12 + B callbackasm1(SB) + MOVD $973, R12 + B callbackasm1(SB) + MOVD $974, R12 + B callbackasm1(SB) + MOVD $975, R12 + B callbackasm1(SB) + MOVD $976, R12 + B callbackasm1(SB) + MOVD $977, R12 + B callbackasm1(SB) + MOVD $978, R12 + B callbackasm1(SB) + MOVD $979, R12 + B callbackasm1(SB) + MOVD $980, R12 + B callbackasm1(SB) + MOVD $981, R12 + B callbackasm1(SB) + MOVD $982, R12 + B callbackasm1(SB) + MOVD $983, R12 + B callbackasm1(SB) + MOVD $984, R12 + B callbackasm1(SB) + MOVD $985, R12 + B callbackasm1(SB) + MOVD $986, R12 + B callbackasm1(SB) + MOVD $987, R12 + B callbackasm1(SB) + MOVD $988, R12 + B callbackasm1(SB) + MOVD $989, R12 + B callbackasm1(SB) + MOVD $990, R12 + B callbackasm1(SB) + MOVD $991, R12 + B callbackasm1(SB) + MOVD $992, R12 + B callbackasm1(SB) + MOVD $993, R12 + B callbackasm1(SB) + MOVD $994, R12 + B callbackasm1(SB) + MOVD $995, R12 + B callbackasm1(SB) + MOVD $996, R12 + B callbackasm1(SB) + MOVD $997, R12 + B callbackasm1(SB) + MOVD $998, R12 + B callbackasm1(SB) + MOVD $999, R12 + B callbackasm1(SB) + MOVD $1000, R12 + B callbackasm1(SB) + MOVD $1001, R12 + B callbackasm1(SB) + MOVD $1002, R12 + B callbackasm1(SB) + MOVD $1003, R12 + B callbackasm1(SB) + MOVD $1004, R12 + B callbackasm1(SB) + MOVD $1005, R12 + B callbackasm1(SB) + MOVD $1006, R12 + B callbackasm1(SB) + MOVD $1007, R12 + B callbackasm1(SB) + MOVD $1008, R12 + B callbackasm1(SB) + MOVD $1009, R12 + B callbackasm1(SB) + MOVD $1010, R12 + B callbackasm1(SB) + MOVD $1011, R12 + B callbackasm1(SB) + MOVD $1012, R12 + B callbackasm1(SB) + MOVD $1013, R12 + B callbackasm1(SB) + MOVD $1014, R12 + B callbackasm1(SB) + MOVD $1015, R12 + B callbackasm1(SB) + MOVD $1016, R12 + B callbackasm1(SB) + MOVD $1017, R12 + B callbackasm1(SB) + MOVD $1018, R12 + B callbackasm1(SB) + MOVD $1019, R12 + B callbackasm1(SB) + MOVD $1020, R12 + B callbackasm1(SB) + MOVD $1021, R12 + B callbackasm1(SB) + MOVD $1022, R12 + B callbackasm1(SB) + MOVD $1023, R12 + B callbackasm1(SB) + MOVD $1024, R12 + B callbackasm1(SB) + MOVD $1025, R12 + B callbackasm1(SB) + MOVD $1026, R12 + B callbackasm1(SB) + MOVD $1027, R12 + B callbackasm1(SB) + MOVD $1028, R12 + B callbackasm1(SB) + MOVD $1029, R12 + B callbackasm1(SB) + MOVD $1030, R12 + B callbackasm1(SB) + MOVD $1031, R12 + B callbackasm1(SB) + MOVD $1032, R12 + B callbackasm1(SB) + MOVD $1033, R12 + B callbackasm1(SB) + MOVD $1034, R12 + B callbackasm1(SB) + MOVD $1035, R12 + B callbackasm1(SB) + MOVD $1036, R12 + B callbackasm1(SB) + MOVD $1037, R12 + B callbackasm1(SB) + MOVD $1038, R12 + B callbackasm1(SB) + MOVD $1039, R12 + B callbackasm1(SB) + MOVD $1040, R12 + B callbackasm1(SB) + MOVD $1041, R12 + B callbackasm1(SB) + MOVD $1042, R12 + B callbackasm1(SB) + MOVD $1043, R12 + B callbackasm1(SB) + MOVD $1044, R12 + B callbackasm1(SB) + MOVD $1045, R12 + B callbackasm1(SB) + MOVD $1046, R12 + B callbackasm1(SB) + MOVD $1047, R12 + B callbackasm1(SB) + MOVD $1048, R12 + B callbackasm1(SB) + MOVD $1049, R12 + B callbackasm1(SB) + MOVD $1050, R12 + B callbackasm1(SB) + MOVD $1051, R12 + B callbackasm1(SB) + MOVD $1052, R12 + B callbackasm1(SB) + MOVD $1053, R12 + B callbackasm1(SB) + MOVD $1054, R12 + B callbackasm1(SB) + MOVD $1055, R12 + B callbackasm1(SB) + MOVD $1056, R12 + B callbackasm1(SB) + MOVD $1057, R12 + B callbackasm1(SB) + MOVD $1058, R12 + B callbackasm1(SB) + MOVD $1059, R12 + B callbackasm1(SB) + MOVD $1060, R12 + B callbackasm1(SB) + MOVD $1061, R12 + B callbackasm1(SB) + MOVD $1062, R12 + B callbackasm1(SB) + MOVD $1063, R12 + B callbackasm1(SB) + MOVD $1064, R12 + B callbackasm1(SB) + MOVD $1065, R12 + B callbackasm1(SB) + MOVD $1066, R12 + B callbackasm1(SB) + MOVD $1067, R12 + B callbackasm1(SB) + MOVD $1068, R12 + B callbackasm1(SB) + MOVD $1069, R12 + B callbackasm1(SB) + MOVD $1070, R12 + B callbackasm1(SB) + MOVD $1071, R12 + B callbackasm1(SB) + MOVD $1072, R12 + B callbackasm1(SB) + MOVD $1073, R12 + B callbackasm1(SB) + MOVD $1074, R12 + B callbackasm1(SB) + MOVD $1075, R12 + B callbackasm1(SB) + MOVD $1076, R12 + B callbackasm1(SB) + MOVD $1077, R12 + B callbackasm1(SB) + MOVD $1078, R12 + B callbackasm1(SB) + MOVD $1079, R12 + B callbackasm1(SB) + MOVD $1080, R12 + B callbackasm1(SB) + MOVD $1081, R12 + B callbackasm1(SB) + MOVD $1082, R12 + B callbackasm1(SB) + MOVD $1083, R12 + B callbackasm1(SB) + MOVD $1084, R12 + B callbackasm1(SB) + MOVD $1085, R12 + B callbackasm1(SB) + MOVD $1086, R12 + B callbackasm1(SB) + MOVD $1087, R12 + B callbackasm1(SB) + MOVD $1088, R12 + B callbackasm1(SB) + MOVD $1089, R12 + B callbackasm1(SB) + MOVD $1090, R12 + B callbackasm1(SB) + MOVD $1091, R12 + B callbackasm1(SB) + MOVD $1092, R12 + B callbackasm1(SB) + MOVD $1093, R12 + B callbackasm1(SB) + MOVD $1094, R12 + B callbackasm1(SB) + MOVD $1095, R12 + B callbackasm1(SB) + MOVD $1096, R12 + B callbackasm1(SB) + MOVD $1097, R12 + B callbackasm1(SB) + MOVD $1098, R12 + B callbackasm1(SB) + MOVD $1099, R12 + B callbackasm1(SB) + MOVD $1100, R12 + B callbackasm1(SB) + MOVD $1101, R12 + B callbackasm1(SB) + MOVD $1102, R12 + B callbackasm1(SB) + MOVD $1103, R12 + B callbackasm1(SB) + MOVD $1104, R12 + B callbackasm1(SB) + MOVD $1105, R12 + B callbackasm1(SB) + MOVD $1106, R12 + B callbackasm1(SB) + MOVD $1107, R12 + B callbackasm1(SB) + MOVD $1108, R12 + B callbackasm1(SB) + MOVD $1109, R12 + B callbackasm1(SB) + MOVD $1110, R12 + B callbackasm1(SB) + MOVD $1111, R12 + B callbackasm1(SB) + MOVD $1112, R12 + B callbackasm1(SB) + MOVD $1113, R12 + B callbackasm1(SB) + MOVD $1114, R12 + B callbackasm1(SB) + MOVD $1115, R12 + B callbackasm1(SB) + MOVD $1116, R12 + B callbackasm1(SB) + MOVD $1117, R12 + B callbackasm1(SB) + MOVD $1118, R12 + B callbackasm1(SB) + MOVD $1119, R12 + B callbackasm1(SB) + MOVD $1120, R12 + B callbackasm1(SB) + MOVD $1121, R12 + B callbackasm1(SB) + MOVD $1122, R12 + B callbackasm1(SB) + MOVD $1123, R12 + B callbackasm1(SB) + MOVD $1124, R12 + B callbackasm1(SB) + MOVD $1125, R12 + B callbackasm1(SB) + MOVD $1126, R12 + B callbackasm1(SB) + MOVD $1127, R12 + B callbackasm1(SB) + MOVD $1128, R12 + B callbackasm1(SB) + MOVD $1129, R12 + B callbackasm1(SB) + MOVD $1130, R12 + B callbackasm1(SB) + MOVD $1131, R12 + B callbackasm1(SB) + MOVD $1132, R12 + B callbackasm1(SB) + MOVD $1133, R12 + B callbackasm1(SB) + MOVD $1134, R12 + B callbackasm1(SB) + MOVD $1135, R12 + B callbackasm1(SB) + MOVD $1136, R12 + B callbackasm1(SB) + MOVD $1137, R12 + B callbackasm1(SB) + MOVD $1138, R12 + B callbackasm1(SB) + MOVD $1139, R12 + B callbackasm1(SB) + MOVD $1140, R12 + B callbackasm1(SB) + MOVD $1141, R12 + B callbackasm1(SB) + MOVD $1142, R12 + B callbackasm1(SB) + MOVD $1143, R12 + B callbackasm1(SB) + MOVD $1144, R12 + B callbackasm1(SB) + MOVD $1145, R12 + B callbackasm1(SB) + MOVD $1146, R12 + B callbackasm1(SB) + MOVD $1147, R12 + B callbackasm1(SB) + MOVD $1148, R12 + B callbackasm1(SB) + MOVD $1149, R12 + B callbackasm1(SB) + MOVD $1150, R12 + B callbackasm1(SB) + MOVD $1151, R12 + B callbackasm1(SB) + MOVD $1152, R12 + B callbackasm1(SB) + MOVD $1153, R12 + B callbackasm1(SB) + MOVD $1154, R12 + B callbackasm1(SB) + MOVD $1155, R12 + B callbackasm1(SB) + MOVD $1156, R12 + B callbackasm1(SB) + MOVD $1157, R12 + B callbackasm1(SB) + MOVD $1158, R12 + B callbackasm1(SB) + MOVD $1159, R12 + B callbackasm1(SB) + MOVD $1160, R12 + B callbackasm1(SB) + MOVD $1161, R12 + B callbackasm1(SB) + MOVD $1162, R12 + B callbackasm1(SB) + MOVD $1163, R12 + B callbackasm1(SB) + MOVD $1164, R12 + B callbackasm1(SB) + MOVD $1165, R12 + B callbackasm1(SB) + MOVD $1166, R12 + B callbackasm1(SB) + MOVD $1167, R12 + B callbackasm1(SB) + MOVD $1168, R12 + B callbackasm1(SB) + MOVD $1169, R12 + B callbackasm1(SB) + MOVD $1170, R12 + B callbackasm1(SB) + MOVD $1171, R12 + B callbackasm1(SB) + MOVD $1172, R12 + B callbackasm1(SB) + MOVD $1173, R12 + B callbackasm1(SB) + MOVD $1174, R12 + B callbackasm1(SB) + MOVD $1175, R12 + B callbackasm1(SB) + MOVD $1176, R12 + B callbackasm1(SB) + MOVD $1177, R12 + B callbackasm1(SB) + MOVD $1178, R12 + B callbackasm1(SB) + MOVD $1179, R12 + B callbackasm1(SB) + MOVD $1180, R12 + B callbackasm1(SB) + MOVD $1181, R12 + B callbackasm1(SB) + MOVD $1182, R12 + B callbackasm1(SB) + MOVD $1183, R12 + B callbackasm1(SB) + MOVD $1184, R12 + B callbackasm1(SB) + MOVD $1185, R12 + B callbackasm1(SB) + MOVD $1186, R12 + B callbackasm1(SB) + MOVD $1187, R12 + B callbackasm1(SB) + MOVD $1188, R12 + B callbackasm1(SB) + MOVD $1189, R12 + B callbackasm1(SB) + MOVD $1190, R12 + B callbackasm1(SB) + MOVD $1191, R12 + B callbackasm1(SB) + MOVD $1192, R12 + B callbackasm1(SB) + MOVD $1193, R12 + B callbackasm1(SB) + MOVD $1194, R12 + B callbackasm1(SB) + MOVD $1195, R12 + B callbackasm1(SB) + MOVD $1196, R12 + B callbackasm1(SB) + MOVD $1197, R12 + B callbackasm1(SB) + MOVD $1198, R12 + B callbackasm1(SB) + MOVD $1199, R12 + B callbackasm1(SB) + MOVD $1200, R12 + B callbackasm1(SB) + MOVD $1201, R12 + B callbackasm1(SB) + MOVD $1202, R12 + B callbackasm1(SB) + MOVD $1203, R12 + B callbackasm1(SB) + MOVD $1204, R12 + B callbackasm1(SB) + MOVD $1205, R12 + B callbackasm1(SB) + MOVD $1206, R12 + B callbackasm1(SB) + MOVD $1207, R12 + B callbackasm1(SB) + MOVD $1208, R12 + B callbackasm1(SB) + MOVD $1209, R12 + B callbackasm1(SB) + MOVD $1210, R12 + B callbackasm1(SB) + MOVD $1211, R12 + B callbackasm1(SB) + MOVD $1212, R12 + B callbackasm1(SB) + MOVD $1213, R12 + B callbackasm1(SB) + MOVD $1214, R12 + B callbackasm1(SB) + MOVD $1215, R12 + B callbackasm1(SB) + MOVD $1216, R12 + B callbackasm1(SB) + MOVD $1217, R12 + B callbackasm1(SB) + MOVD $1218, R12 + B callbackasm1(SB) + MOVD $1219, R12 + B callbackasm1(SB) + MOVD $1220, R12 + B callbackasm1(SB) + MOVD $1221, R12 + B callbackasm1(SB) + MOVD $1222, R12 + B callbackasm1(SB) + MOVD $1223, R12 + B callbackasm1(SB) + MOVD $1224, R12 + B callbackasm1(SB) + MOVD $1225, R12 + B callbackasm1(SB) + MOVD $1226, R12 + B callbackasm1(SB) + MOVD $1227, R12 + B callbackasm1(SB) + MOVD $1228, R12 + B callbackasm1(SB) + MOVD $1229, R12 + B callbackasm1(SB) + MOVD $1230, R12 + B callbackasm1(SB) + MOVD $1231, R12 + B callbackasm1(SB) + MOVD $1232, R12 + B callbackasm1(SB) + MOVD $1233, R12 + B callbackasm1(SB) + MOVD $1234, R12 + B callbackasm1(SB) + MOVD $1235, R12 + B callbackasm1(SB) + MOVD $1236, R12 + B callbackasm1(SB) + MOVD $1237, R12 + B callbackasm1(SB) + MOVD $1238, R12 + B callbackasm1(SB) + MOVD $1239, R12 + B callbackasm1(SB) + MOVD $1240, R12 + B callbackasm1(SB) + MOVD $1241, R12 + B callbackasm1(SB) + MOVD $1242, R12 + B callbackasm1(SB) + MOVD $1243, R12 + B callbackasm1(SB) + MOVD $1244, R12 + B callbackasm1(SB) + MOVD $1245, R12 + B callbackasm1(SB) + MOVD $1246, R12 + B callbackasm1(SB) + MOVD $1247, R12 + B callbackasm1(SB) + MOVD $1248, R12 + B callbackasm1(SB) + MOVD $1249, R12 + B callbackasm1(SB) + MOVD $1250, R12 + B callbackasm1(SB) + MOVD $1251, R12 + B callbackasm1(SB) + MOVD $1252, R12 + B callbackasm1(SB) + MOVD $1253, R12 + B callbackasm1(SB) + MOVD $1254, R12 + B callbackasm1(SB) + MOVD $1255, R12 + B callbackasm1(SB) + MOVD $1256, R12 + B callbackasm1(SB) + MOVD $1257, R12 + B callbackasm1(SB) + MOVD $1258, R12 + B callbackasm1(SB) + MOVD $1259, R12 + B callbackasm1(SB) + MOVD $1260, R12 + B callbackasm1(SB) + MOVD $1261, R12 + B callbackasm1(SB) + MOVD $1262, R12 + B callbackasm1(SB) + MOVD $1263, R12 + B callbackasm1(SB) + MOVD $1264, R12 + B callbackasm1(SB) + MOVD $1265, R12 + B callbackasm1(SB) + MOVD $1266, R12 + B callbackasm1(SB) + MOVD $1267, R12 + B callbackasm1(SB) + MOVD $1268, R12 + B callbackasm1(SB) + MOVD $1269, R12 + B callbackasm1(SB) + MOVD $1270, R12 + B callbackasm1(SB) + MOVD $1271, R12 + B callbackasm1(SB) + MOVD $1272, R12 + B callbackasm1(SB) + MOVD $1273, R12 + B callbackasm1(SB) + MOVD $1274, R12 + B callbackasm1(SB) + MOVD $1275, R12 + B callbackasm1(SB) + MOVD $1276, R12 + B callbackasm1(SB) + MOVD $1277, R12 + B callbackasm1(SB) + MOVD $1278, R12 + B callbackasm1(SB) + MOVD $1279, R12 + B callbackasm1(SB) + MOVD $1280, R12 + B callbackasm1(SB) + MOVD $1281, R12 + B callbackasm1(SB) + MOVD $1282, R12 + B callbackasm1(SB) + MOVD $1283, R12 + B callbackasm1(SB) + MOVD $1284, R12 + B callbackasm1(SB) + MOVD $1285, R12 + B callbackasm1(SB) + MOVD $1286, R12 + B callbackasm1(SB) + MOVD $1287, R12 + B callbackasm1(SB) + MOVD $1288, R12 + B callbackasm1(SB) + MOVD $1289, R12 + B callbackasm1(SB) + MOVD $1290, R12 + B callbackasm1(SB) + MOVD $1291, R12 + B callbackasm1(SB) + MOVD $1292, R12 + B callbackasm1(SB) + MOVD $1293, R12 + B callbackasm1(SB) + MOVD $1294, R12 + B callbackasm1(SB) + MOVD $1295, R12 + B callbackasm1(SB) + MOVD $1296, R12 + B callbackasm1(SB) + MOVD $1297, R12 + B callbackasm1(SB) + MOVD $1298, R12 + B callbackasm1(SB) + MOVD $1299, R12 + B callbackasm1(SB) + MOVD $1300, R12 + B callbackasm1(SB) + MOVD $1301, R12 + B callbackasm1(SB) + MOVD $1302, R12 + B callbackasm1(SB) + MOVD $1303, R12 + B callbackasm1(SB) + MOVD $1304, R12 + B callbackasm1(SB) + MOVD $1305, R12 + B callbackasm1(SB) + MOVD $1306, R12 + B callbackasm1(SB) + MOVD $1307, R12 + B callbackasm1(SB) + MOVD $1308, R12 + B callbackasm1(SB) + MOVD $1309, R12 + B callbackasm1(SB) + MOVD $1310, R12 + B callbackasm1(SB) + MOVD $1311, R12 + B callbackasm1(SB) + MOVD $1312, R12 + B callbackasm1(SB) + MOVD $1313, R12 + B callbackasm1(SB) + MOVD $1314, R12 + B callbackasm1(SB) + MOVD $1315, R12 + B callbackasm1(SB) + MOVD $1316, R12 + B callbackasm1(SB) + MOVD $1317, R12 + B callbackasm1(SB) + MOVD $1318, R12 + B callbackasm1(SB) + MOVD $1319, R12 + B callbackasm1(SB) + MOVD $1320, R12 + B callbackasm1(SB) + MOVD $1321, R12 + B callbackasm1(SB) + MOVD $1322, R12 + B callbackasm1(SB) + MOVD $1323, R12 + B callbackasm1(SB) + MOVD $1324, R12 + B callbackasm1(SB) + MOVD $1325, R12 + B callbackasm1(SB) + MOVD $1326, R12 + B callbackasm1(SB) + MOVD $1327, R12 + B callbackasm1(SB) + MOVD $1328, R12 + B callbackasm1(SB) + MOVD $1329, R12 + B callbackasm1(SB) + MOVD $1330, R12 + B callbackasm1(SB) + MOVD $1331, R12 + B callbackasm1(SB) + MOVD $1332, R12 + B callbackasm1(SB) + MOVD $1333, R12 + B callbackasm1(SB) + MOVD $1334, R12 + B callbackasm1(SB) + MOVD $1335, R12 + B callbackasm1(SB) + MOVD $1336, R12 + B callbackasm1(SB) + MOVD $1337, R12 + B callbackasm1(SB) + MOVD $1338, R12 + B callbackasm1(SB) + MOVD $1339, R12 + B callbackasm1(SB) + MOVD $1340, R12 + B callbackasm1(SB) + MOVD $1341, R12 + B callbackasm1(SB) + MOVD $1342, R12 + B callbackasm1(SB) + MOVD $1343, R12 + B callbackasm1(SB) + MOVD $1344, R12 + B callbackasm1(SB) + MOVD $1345, R12 + B callbackasm1(SB) + MOVD $1346, R12 + B callbackasm1(SB) + MOVD $1347, R12 + B callbackasm1(SB) + MOVD $1348, R12 + B callbackasm1(SB) + MOVD $1349, R12 + B callbackasm1(SB) + MOVD $1350, R12 + B callbackasm1(SB) + MOVD $1351, R12 + B callbackasm1(SB) + MOVD $1352, R12 + B callbackasm1(SB) + MOVD $1353, R12 + B callbackasm1(SB) + MOVD $1354, R12 + B callbackasm1(SB) + MOVD $1355, R12 + B callbackasm1(SB) + MOVD $1356, R12 + B callbackasm1(SB) + MOVD $1357, R12 + B callbackasm1(SB) + MOVD $1358, R12 + B callbackasm1(SB) + MOVD $1359, R12 + B callbackasm1(SB) + MOVD $1360, R12 + B callbackasm1(SB) + MOVD $1361, R12 + B callbackasm1(SB) + MOVD $1362, R12 + B callbackasm1(SB) + MOVD $1363, R12 + B callbackasm1(SB) + MOVD $1364, R12 + B callbackasm1(SB) + MOVD $1365, R12 + B callbackasm1(SB) + MOVD $1366, R12 + B callbackasm1(SB) + MOVD $1367, R12 + B callbackasm1(SB) + MOVD $1368, R12 + B callbackasm1(SB) + MOVD $1369, R12 + B callbackasm1(SB) + MOVD $1370, R12 + B callbackasm1(SB) + MOVD $1371, R12 + B callbackasm1(SB) + MOVD $1372, R12 + B callbackasm1(SB) + MOVD $1373, R12 + B callbackasm1(SB) + MOVD $1374, R12 + B callbackasm1(SB) + MOVD $1375, R12 + B callbackasm1(SB) + MOVD $1376, R12 + B callbackasm1(SB) + MOVD $1377, R12 + B callbackasm1(SB) + MOVD $1378, R12 + B callbackasm1(SB) + MOVD $1379, R12 + B callbackasm1(SB) + MOVD $1380, R12 + B callbackasm1(SB) + MOVD $1381, R12 + B callbackasm1(SB) + MOVD $1382, R12 + B callbackasm1(SB) + MOVD $1383, R12 + B callbackasm1(SB) + MOVD $1384, R12 + B callbackasm1(SB) + MOVD $1385, R12 + B callbackasm1(SB) + MOVD $1386, R12 + B callbackasm1(SB) + MOVD $1387, R12 + B callbackasm1(SB) + MOVD $1388, R12 + B callbackasm1(SB) + MOVD $1389, R12 + B callbackasm1(SB) + MOVD $1390, R12 + B callbackasm1(SB) + MOVD $1391, R12 + B callbackasm1(SB) + MOVD $1392, R12 + B callbackasm1(SB) + MOVD $1393, R12 + B callbackasm1(SB) + MOVD $1394, R12 + B callbackasm1(SB) + MOVD $1395, R12 + B callbackasm1(SB) + MOVD $1396, R12 + B callbackasm1(SB) + MOVD $1397, R12 + B callbackasm1(SB) + MOVD $1398, R12 + B callbackasm1(SB) + MOVD $1399, R12 + B callbackasm1(SB) + MOVD $1400, R12 + B callbackasm1(SB) + MOVD $1401, R12 + B callbackasm1(SB) + MOVD $1402, R12 + B callbackasm1(SB) + MOVD $1403, R12 + B callbackasm1(SB) + MOVD $1404, R12 + B callbackasm1(SB) + MOVD $1405, R12 + B callbackasm1(SB) + MOVD $1406, R12 + B callbackasm1(SB) + MOVD $1407, R12 + B callbackasm1(SB) + MOVD $1408, R12 + B callbackasm1(SB) + MOVD $1409, R12 + B callbackasm1(SB) + MOVD $1410, R12 + B callbackasm1(SB) + MOVD $1411, R12 + B callbackasm1(SB) + MOVD $1412, R12 + B callbackasm1(SB) + MOVD $1413, R12 + B callbackasm1(SB) + MOVD $1414, R12 + B callbackasm1(SB) + MOVD $1415, R12 + B callbackasm1(SB) + MOVD $1416, R12 + B callbackasm1(SB) + MOVD $1417, R12 + B callbackasm1(SB) + MOVD $1418, R12 + B callbackasm1(SB) + MOVD $1419, R12 + B callbackasm1(SB) + MOVD $1420, R12 + B callbackasm1(SB) + MOVD $1421, R12 + B callbackasm1(SB) + MOVD $1422, R12 + B callbackasm1(SB) + MOVD $1423, R12 + B callbackasm1(SB) + MOVD $1424, R12 + B callbackasm1(SB) + MOVD $1425, R12 + B callbackasm1(SB) + MOVD $1426, R12 + B callbackasm1(SB) + MOVD $1427, R12 + B callbackasm1(SB) + MOVD $1428, R12 + B callbackasm1(SB) + MOVD $1429, R12 + B callbackasm1(SB) + MOVD $1430, R12 + B callbackasm1(SB) + MOVD $1431, R12 + B callbackasm1(SB) + MOVD $1432, R12 + B callbackasm1(SB) + MOVD $1433, R12 + B callbackasm1(SB) + MOVD $1434, R12 + B callbackasm1(SB) + MOVD $1435, R12 + B callbackasm1(SB) + MOVD $1436, R12 + B callbackasm1(SB) + MOVD $1437, R12 + B callbackasm1(SB) + MOVD $1438, R12 + B callbackasm1(SB) + MOVD $1439, R12 + B callbackasm1(SB) + MOVD $1440, R12 + B callbackasm1(SB) + MOVD $1441, R12 + B callbackasm1(SB) + MOVD $1442, R12 + B callbackasm1(SB) + MOVD $1443, R12 + B callbackasm1(SB) + MOVD $1444, R12 + B callbackasm1(SB) + MOVD $1445, R12 + B callbackasm1(SB) + MOVD $1446, R12 + B callbackasm1(SB) + MOVD $1447, R12 + B callbackasm1(SB) + MOVD $1448, R12 + B callbackasm1(SB) + MOVD $1449, R12 + B callbackasm1(SB) + MOVD $1450, R12 + B callbackasm1(SB) + MOVD $1451, R12 + B callbackasm1(SB) + MOVD $1452, R12 + B callbackasm1(SB) + MOVD $1453, R12 + B callbackasm1(SB) + MOVD $1454, R12 + B callbackasm1(SB) + MOVD $1455, R12 + B callbackasm1(SB) + MOVD $1456, R12 + B callbackasm1(SB) + MOVD $1457, R12 + B callbackasm1(SB) + MOVD $1458, R12 + B callbackasm1(SB) + MOVD $1459, R12 + B callbackasm1(SB) + MOVD $1460, R12 + B callbackasm1(SB) + MOVD $1461, R12 + B callbackasm1(SB) + MOVD $1462, R12 + B callbackasm1(SB) + MOVD $1463, R12 + B callbackasm1(SB) + MOVD $1464, R12 + B callbackasm1(SB) + MOVD $1465, R12 + B callbackasm1(SB) + MOVD $1466, R12 + B callbackasm1(SB) + MOVD $1467, R12 + B callbackasm1(SB) + MOVD $1468, R12 + B callbackasm1(SB) + MOVD $1469, R12 + B callbackasm1(SB) + MOVD $1470, R12 + B callbackasm1(SB) + MOVD $1471, R12 + B callbackasm1(SB) + MOVD $1472, R12 + B callbackasm1(SB) + MOVD $1473, R12 + B callbackasm1(SB) + MOVD $1474, R12 + B callbackasm1(SB) + MOVD $1475, R12 + B callbackasm1(SB) + MOVD $1476, R12 + B callbackasm1(SB) + MOVD $1477, R12 + B callbackasm1(SB) + MOVD $1478, R12 + B callbackasm1(SB) + MOVD $1479, R12 + B callbackasm1(SB) + MOVD $1480, R12 + B callbackasm1(SB) + MOVD $1481, R12 + B callbackasm1(SB) + MOVD $1482, R12 + B callbackasm1(SB) + MOVD $1483, R12 + B callbackasm1(SB) + MOVD $1484, R12 + B callbackasm1(SB) + MOVD $1485, R12 + B callbackasm1(SB) + MOVD $1486, R12 + B callbackasm1(SB) + MOVD $1487, R12 + B callbackasm1(SB) + MOVD $1488, R12 + B callbackasm1(SB) + MOVD $1489, R12 + B callbackasm1(SB) + MOVD $1490, R12 + B callbackasm1(SB) + MOVD $1491, R12 + B callbackasm1(SB) + MOVD $1492, R12 + B callbackasm1(SB) + MOVD $1493, R12 + B callbackasm1(SB) + MOVD $1494, R12 + B callbackasm1(SB) + MOVD $1495, R12 + B callbackasm1(SB) + MOVD $1496, R12 + B callbackasm1(SB) + MOVD $1497, R12 + B callbackasm1(SB) + MOVD $1498, R12 + B callbackasm1(SB) + MOVD $1499, R12 + B callbackasm1(SB) + MOVD $1500, R12 + B callbackasm1(SB) + MOVD $1501, R12 + B callbackasm1(SB) + MOVD $1502, R12 + B callbackasm1(SB) + MOVD $1503, R12 + B callbackasm1(SB) + MOVD $1504, R12 + B callbackasm1(SB) + MOVD $1505, R12 + B callbackasm1(SB) + MOVD $1506, R12 + B callbackasm1(SB) + MOVD $1507, R12 + B callbackasm1(SB) + MOVD $1508, R12 + B callbackasm1(SB) + MOVD $1509, R12 + B callbackasm1(SB) + MOVD $1510, R12 + B callbackasm1(SB) + MOVD $1511, R12 + B callbackasm1(SB) + MOVD $1512, R12 + B callbackasm1(SB) + MOVD $1513, R12 + B callbackasm1(SB) + MOVD $1514, R12 + B callbackasm1(SB) + MOVD $1515, R12 + B callbackasm1(SB) + MOVD $1516, R12 + B callbackasm1(SB) + MOVD $1517, R12 + B callbackasm1(SB) + MOVD $1518, R12 + B callbackasm1(SB) + MOVD $1519, R12 + B callbackasm1(SB) + MOVD $1520, R12 + B callbackasm1(SB) + MOVD $1521, R12 + B callbackasm1(SB) + MOVD $1522, R12 + B callbackasm1(SB) + MOVD $1523, R12 + B callbackasm1(SB) + MOVD $1524, R12 + B callbackasm1(SB) + MOVD $1525, R12 + B callbackasm1(SB) + MOVD $1526, R12 + B callbackasm1(SB) + MOVD $1527, R12 + B callbackasm1(SB) + MOVD $1528, R12 + B callbackasm1(SB) + MOVD $1529, R12 + B callbackasm1(SB) + MOVD $1530, R12 + B callbackasm1(SB) + MOVD $1531, R12 + B callbackasm1(SB) + MOVD $1532, R12 + B callbackasm1(SB) + MOVD $1533, R12 + B callbackasm1(SB) + MOVD $1534, R12 + B callbackasm1(SB) + MOVD $1535, R12 + B callbackasm1(SB) + MOVD $1536, R12 + B callbackasm1(SB) + MOVD $1537, R12 + B callbackasm1(SB) + MOVD $1538, R12 + B callbackasm1(SB) + MOVD $1539, R12 + B callbackasm1(SB) + MOVD $1540, R12 + B callbackasm1(SB) + MOVD $1541, R12 + B callbackasm1(SB) + MOVD $1542, R12 + B callbackasm1(SB) + MOVD $1543, R12 + B callbackasm1(SB) + MOVD $1544, R12 + B callbackasm1(SB) + MOVD $1545, R12 + B callbackasm1(SB) + MOVD $1546, R12 + B callbackasm1(SB) + MOVD $1547, R12 + B callbackasm1(SB) + MOVD $1548, R12 + B callbackasm1(SB) + MOVD $1549, R12 + B callbackasm1(SB) + MOVD $1550, R12 + B callbackasm1(SB) + MOVD $1551, R12 + B callbackasm1(SB) + MOVD $1552, R12 + B callbackasm1(SB) + MOVD $1553, R12 + B callbackasm1(SB) + MOVD $1554, R12 + B callbackasm1(SB) + MOVD $1555, R12 + B callbackasm1(SB) + MOVD $1556, R12 + B callbackasm1(SB) + MOVD $1557, R12 + B callbackasm1(SB) + MOVD $1558, R12 + B callbackasm1(SB) + MOVD $1559, R12 + B callbackasm1(SB) + MOVD $1560, R12 + B callbackasm1(SB) + MOVD $1561, R12 + B callbackasm1(SB) + MOVD $1562, R12 + B callbackasm1(SB) + MOVD $1563, R12 + B callbackasm1(SB) + MOVD $1564, R12 + B callbackasm1(SB) + MOVD $1565, R12 + B callbackasm1(SB) + MOVD $1566, R12 + B callbackasm1(SB) + MOVD $1567, R12 + B callbackasm1(SB) + MOVD $1568, R12 + B callbackasm1(SB) + MOVD $1569, R12 + B callbackasm1(SB) + MOVD $1570, R12 + B callbackasm1(SB) + MOVD $1571, R12 + B callbackasm1(SB) + MOVD $1572, R12 + B callbackasm1(SB) + MOVD $1573, R12 + B callbackasm1(SB) + MOVD $1574, R12 + B callbackasm1(SB) + MOVD $1575, R12 + B callbackasm1(SB) + MOVD $1576, R12 + B callbackasm1(SB) + MOVD $1577, R12 + B callbackasm1(SB) + MOVD $1578, R12 + B callbackasm1(SB) + MOVD $1579, R12 + B callbackasm1(SB) + MOVD $1580, R12 + B callbackasm1(SB) + MOVD $1581, R12 + B callbackasm1(SB) + MOVD $1582, R12 + B callbackasm1(SB) + MOVD $1583, R12 + B callbackasm1(SB) + MOVD $1584, R12 + B callbackasm1(SB) + MOVD $1585, R12 + B callbackasm1(SB) + MOVD $1586, R12 + B callbackasm1(SB) + MOVD $1587, R12 + B callbackasm1(SB) + MOVD $1588, R12 + B callbackasm1(SB) + MOVD $1589, R12 + B callbackasm1(SB) + MOVD $1590, R12 + B callbackasm1(SB) + MOVD $1591, R12 + B callbackasm1(SB) + MOVD $1592, R12 + B callbackasm1(SB) + MOVD $1593, R12 + B callbackasm1(SB) + MOVD $1594, R12 + B callbackasm1(SB) + MOVD $1595, R12 + B callbackasm1(SB) + MOVD $1596, R12 + B callbackasm1(SB) + MOVD $1597, R12 + B callbackasm1(SB) + MOVD $1598, R12 + B callbackasm1(SB) + MOVD $1599, R12 + B callbackasm1(SB) + MOVD $1600, R12 + B callbackasm1(SB) + MOVD $1601, R12 + B callbackasm1(SB) + MOVD $1602, R12 + B callbackasm1(SB) + MOVD $1603, R12 + B callbackasm1(SB) + MOVD $1604, R12 + B callbackasm1(SB) + MOVD $1605, R12 + B callbackasm1(SB) + MOVD $1606, R12 + B callbackasm1(SB) + MOVD $1607, R12 + B callbackasm1(SB) + MOVD $1608, R12 + B callbackasm1(SB) + MOVD $1609, R12 + B callbackasm1(SB) + MOVD $1610, R12 + B callbackasm1(SB) + MOVD $1611, R12 + B callbackasm1(SB) + MOVD $1612, R12 + B callbackasm1(SB) + MOVD $1613, R12 + B callbackasm1(SB) + MOVD $1614, R12 + B callbackasm1(SB) + MOVD $1615, R12 + B callbackasm1(SB) + MOVD $1616, R12 + B callbackasm1(SB) + MOVD $1617, R12 + B callbackasm1(SB) + MOVD $1618, R12 + B callbackasm1(SB) + MOVD $1619, R12 + B callbackasm1(SB) + MOVD $1620, R12 + B callbackasm1(SB) + MOVD $1621, R12 + B callbackasm1(SB) + MOVD $1622, R12 + B callbackasm1(SB) + MOVD $1623, R12 + B callbackasm1(SB) + MOVD $1624, R12 + B callbackasm1(SB) + MOVD $1625, R12 + B callbackasm1(SB) + MOVD $1626, R12 + B callbackasm1(SB) + MOVD $1627, R12 + B callbackasm1(SB) + MOVD $1628, R12 + B callbackasm1(SB) + MOVD $1629, R12 + B callbackasm1(SB) + MOVD $1630, R12 + B callbackasm1(SB) + MOVD $1631, R12 + B callbackasm1(SB) + MOVD $1632, R12 + B callbackasm1(SB) + MOVD $1633, R12 + B callbackasm1(SB) + MOVD $1634, R12 + B callbackasm1(SB) + MOVD $1635, R12 + B callbackasm1(SB) + MOVD $1636, R12 + B callbackasm1(SB) + MOVD $1637, R12 + B callbackasm1(SB) + MOVD $1638, R12 + B callbackasm1(SB) + MOVD $1639, R12 + B callbackasm1(SB) + MOVD $1640, R12 + B callbackasm1(SB) + MOVD $1641, R12 + B callbackasm1(SB) + MOVD $1642, R12 + B callbackasm1(SB) + MOVD $1643, R12 + B callbackasm1(SB) + MOVD $1644, R12 + B callbackasm1(SB) + MOVD $1645, R12 + B callbackasm1(SB) + MOVD $1646, R12 + B callbackasm1(SB) + MOVD $1647, R12 + B callbackasm1(SB) + MOVD $1648, R12 + B callbackasm1(SB) + MOVD $1649, R12 + B callbackasm1(SB) + MOVD $1650, R12 + B callbackasm1(SB) + MOVD $1651, R12 + B callbackasm1(SB) + MOVD $1652, R12 + B callbackasm1(SB) + MOVD $1653, R12 + B callbackasm1(SB) + MOVD $1654, R12 + B callbackasm1(SB) + MOVD $1655, R12 + B callbackasm1(SB) + MOVD $1656, R12 + B callbackasm1(SB) + MOVD $1657, R12 + B callbackasm1(SB) + MOVD $1658, R12 + B callbackasm1(SB) + MOVD $1659, R12 + B callbackasm1(SB) + MOVD $1660, R12 + B callbackasm1(SB) + MOVD $1661, R12 + B callbackasm1(SB) + MOVD $1662, R12 + B callbackasm1(SB) + MOVD $1663, R12 + B callbackasm1(SB) + MOVD $1664, R12 + B callbackasm1(SB) + MOVD $1665, R12 + B callbackasm1(SB) + MOVD $1666, R12 + B callbackasm1(SB) + MOVD $1667, R12 + B callbackasm1(SB) + MOVD $1668, R12 + B callbackasm1(SB) + MOVD $1669, R12 + B callbackasm1(SB) + MOVD $1670, R12 + B callbackasm1(SB) + MOVD $1671, R12 + B callbackasm1(SB) + MOVD $1672, R12 + B callbackasm1(SB) + MOVD $1673, R12 + B callbackasm1(SB) + MOVD $1674, R12 + B callbackasm1(SB) + MOVD $1675, R12 + B callbackasm1(SB) + MOVD $1676, R12 + B callbackasm1(SB) + MOVD $1677, R12 + B callbackasm1(SB) + MOVD $1678, R12 + B callbackasm1(SB) + MOVD $1679, R12 + B callbackasm1(SB) + MOVD $1680, R12 + B callbackasm1(SB) + MOVD $1681, R12 + B callbackasm1(SB) + MOVD $1682, R12 + B callbackasm1(SB) + MOVD $1683, R12 + B callbackasm1(SB) + MOVD $1684, R12 + B callbackasm1(SB) + MOVD $1685, R12 + B callbackasm1(SB) + MOVD $1686, R12 + B callbackasm1(SB) + MOVD $1687, R12 + B callbackasm1(SB) + MOVD $1688, R12 + B callbackasm1(SB) + MOVD $1689, R12 + B callbackasm1(SB) + MOVD $1690, R12 + B callbackasm1(SB) + MOVD $1691, R12 + B callbackasm1(SB) + MOVD $1692, R12 + B callbackasm1(SB) + MOVD $1693, R12 + B callbackasm1(SB) + MOVD $1694, R12 + B callbackasm1(SB) + MOVD $1695, R12 + B callbackasm1(SB) + MOVD $1696, R12 + B callbackasm1(SB) + MOVD $1697, R12 + B callbackasm1(SB) + MOVD $1698, R12 + B callbackasm1(SB) + MOVD $1699, R12 + B callbackasm1(SB) + MOVD $1700, R12 + B callbackasm1(SB) + MOVD $1701, R12 + B callbackasm1(SB) + MOVD $1702, R12 + B callbackasm1(SB) + MOVD $1703, R12 + B callbackasm1(SB) + MOVD $1704, R12 + B callbackasm1(SB) + MOVD $1705, R12 + B callbackasm1(SB) + MOVD $1706, R12 + B callbackasm1(SB) + MOVD $1707, R12 + B callbackasm1(SB) + MOVD $1708, R12 + B callbackasm1(SB) + MOVD $1709, R12 + B callbackasm1(SB) + MOVD $1710, R12 + B callbackasm1(SB) + MOVD $1711, R12 + B callbackasm1(SB) + MOVD $1712, R12 + B callbackasm1(SB) + MOVD $1713, R12 + B callbackasm1(SB) + MOVD $1714, R12 + B callbackasm1(SB) + MOVD $1715, R12 + B callbackasm1(SB) + MOVD $1716, R12 + B callbackasm1(SB) + MOVD $1717, R12 + B callbackasm1(SB) + MOVD $1718, R12 + B callbackasm1(SB) + MOVD $1719, R12 + B callbackasm1(SB) + MOVD $1720, R12 + B callbackasm1(SB) + MOVD $1721, R12 + B callbackasm1(SB) + MOVD $1722, R12 + B callbackasm1(SB) + MOVD $1723, R12 + B callbackasm1(SB) + MOVD $1724, R12 + B callbackasm1(SB) + MOVD $1725, R12 + B callbackasm1(SB) + MOVD $1726, R12 + B callbackasm1(SB) + MOVD $1727, R12 + B callbackasm1(SB) + MOVD $1728, R12 + B callbackasm1(SB) + MOVD $1729, R12 + B callbackasm1(SB) + MOVD $1730, R12 + B callbackasm1(SB) + MOVD $1731, R12 + B callbackasm1(SB) + MOVD $1732, R12 + B callbackasm1(SB) + MOVD $1733, R12 + B callbackasm1(SB) + MOVD $1734, R12 + B callbackasm1(SB) + MOVD $1735, R12 + B callbackasm1(SB) + MOVD $1736, R12 + B callbackasm1(SB) + MOVD $1737, R12 + B callbackasm1(SB) + MOVD $1738, R12 + B callbackasm1(SB) + MOVD $1739, R12 + B callbackasm1(SB) + MOVD $1740, R12 + B callbackasm1(SB) + MOVD $1741, R12 + B callbackasm1(SB) + MOVD $1742, R12 + B callbackasm1(SB) + MOVD $1743, R12 + B callbackasm1(SB) + MOVD $1744, R12 + B callbackasm1(SB) + MOVD $1745, R12 + B callbackasm1(SB) + MOVD $1746, R12 + B callbackasm1(SB) + MOVD $1747, R12 + B callbackasm1(SB) + MOVD $1748, R12 + B callbackasm1(SB) + MOVD $1749, R12 + B callbackasm1(SB) + MOVD $1750, R12 + B callbackasm1(SB) + MOVD $1751, R12 + B callbackasm1(SB) + MOVD $1752, R12 + B callbackasm1(SB) + MOVD $1753, R12 + B callbackasm1(SB) + MOVD $1754, R12 + B callbackasm1(SB) + MOVD $1755, R12 + B callbackasm1(SB) + MOVD $1756, R12 + B callbackasm1(SB) + MOVD $1757, R12 + B callbackasm1(SB) + MOVD $1758, R12 + B callbackasm1(SB) + MOVD $1759, R12 + B callbackasm1(SB) + MOVD $1760, R12 + B callbackasm1(SB) + MOVD $1761, R12 + B callbackasm1(SB) + MOVD $1762, R12 + B callbackasm1(SB) + MOVD $1763, R12 + B callbackasm1(SB) + MOVD $1764, R12 + B callbackasm1(SB) + MOVD $1765, R12 + B callbackasm1(SB) + MOVD $1766, R12 + B callbackasm1(SB) + MOVD $1767, R12 + B callbackasm1(SB) + MOVD $1768, R12 + B callbackasm1(SB) + MOVD $1769, R12 + B callbackasm1(SB) + MOVD $1770, R12 + B callbackasm1(SB) + MOVD $1771, R12 + B callbackasm1(SB) + MOVD $1772, R12 + B callbackasm1(SB) + MOVD $1773, R12 + B callbackasm1(SB) + MOVD $1774, R12 + B callbackasm1(SB) + MOVD $1775, R12 + B callbackasm1(SB) + MOVD $1776, R12 + B callbackasm1(SB) + MOVD $1777, R12 + B callbackasm1(SB) + MOVD $1778, R12 + B callbackasm1(SB) + MOVD $1779, R12 + B callbackasm1(SB) + MOVD $1780, R12 + B callbackasm1(SB) + MOVD $1781, R12 + B callbackasm1(SB) + MOVD $1782, R12 + B callbackasm1(SB) + MOVD $1783, R12 + B callbackasm1(SB) + MOVD $1784, R12 + B callbackasm1(SB) + MOVD $1785, R12 + B callbackasm1(SB) + MOVD $1786, R12 + B callbackasm1(SB) + MOVD $1787, R12 + B callbackasm1(SB) + MOVD $1788, R12 + B callbackasm1(SB) + MOVD $1789, R12 + B callbackasm1(SB) + MOVD $1790, R12 + B callbackasm1(SB) + MOVD $1791, R12 + B callbackasm1(SB) + MOVD $1792, R12 + B callbackasm1(SB) + MOVD $1793, R12 + B callbackasm1(SB) + MOVD $1794, R12 + B callbackasm1(SB) + MOVD $1795, R12 + B callbackasm1(SB) + MOVD $1796, R12 + B callbackasm1(SB) + MOVD $1797, R12 + B callbackasm1(SB) + MOVD $1798, R12 + B callbackasm1(SB) + MOVD $1799, R12 + B callbackasm1(SB) + MOVD $1800, R12 + B callbackasm1(SB) + MOVD $1801, R12 + B callbackasm1(SB) + MOVD $1802, R12 + B callbackasm1(SB) + MOVD $1803, R12 + B callbackasm1(SB) + MOVD $1804, R12 + B callbackasm1(SB) + MOVD $1805, R12 + B callbackasm1(SB) + MOVD $1806, R12 + B callbackasm1(SB) + MOVD $1807, R12 + B callbackasm1(SB) + MOVD $1808, R12 + B callbackasm1(SB) + MOVD $1809, R12 + B callbackasm1(SB) + MOVD $1810, R12 + B callbackasm1(SB) + MOVD $1811, R12 + B callbackasm1(SB) + MOVD $1812, R12 + B callbackasm1(SB) + MOVD $1813, R12 + B callbackasm1(SB) + MOVD $1814, R12 + B callbackasm1(SB) + MOVD $1815, R12 + B callbackasm1(SB) + MOVD $1816, R12 + B callbackasm1(SB) + MOVD $1817, R12 + B callbackasm1(SB) + MOVD $1818, R12 + B callbackasm1(SB) + MOVD $1819, R12 + B callbackasm1(SB) + MOVD $1820, R12 + B callbackasm1(SB) + MOVD $1821, R12 + B callbackasm1(SB) + MOVD $1822, R12 + B callbackasm1(SB) + MOVD $1823, R12 + B callbackasm1(SB) + MOVD $1824, R12 + B callbackasm1(SB) + MOVD $1825, R12 + B callbackasm1(SB) + MOVD $1826, R12 + B callbackasm1(SB) + MOVD $1827, R12 + B callbackasm1(SB) + MOVD $1828, R12 + B callbackasm1(SB) + MOVD $1829, R12 + B callbackasm1(SB) + MOVD $1830, R12 + B callbackasm1(SB) + MOVD $1831, R12 + B callbackasm1(SB) + MOVD $1832, R12 + B callbackasm1(SB) + MOVD $1833, R12 + B callbackasm1(SB) + MOVD $1834, R12 + B callbackasm1(SB) + MOVD $1835, R12 + B callbackasm1(SB) + MOVD $1836, R12 + B callbackasm1(SB) + MOVD $1837, R12 + B callbackasm1(SB) + MOVD $1838, R12 + B callbackasm1(SB) + MOVD $1839, R12 + B callbackasm1(SB) + MOVD $1840, R12 + B callbackasm1(SB) + MOVD $1841, R12 + B callbackasm1(SB) + MOVD $1842, R12 + B callbackasm1(SB) + MOVD $1843, R12 + B callbackasm1(SB) + MOVD $1844, R12 + B callbackasm1(SB) + MOVD $1845, R12 + B callbackasm1(SB) + MOVD $1846, R12 + B callbackasm1(SB) + MOVD $1847, R12 + B callbackasm1(SB) + MOVD $1848, R12 + B callbackasm1(SB) + MOVD $1849, R12 + B callbackasm1(SB) + MOVD $1850, R12 + B callbackasm1(SB) + MOVD $1851, R12 + B callbackasm1(SB) + MOVD $1852, R12 + B callbackasm1(SB) + MOVD $1853, R12 + B callbackasm1(SB) + MOVD $1854, R12 + B callbackasm1(SB) + MOVD $1855, R12 + B callbackasm1(SB) + MOVD $1856, R12 + B callbackasm1(SB) + MOVD $1857, R12 + B callbackasm1(SB) + MOVD $1858, R12 + B callbackasm1(SB) + MOVD $1859, R12 + B callbackasm1(SB) + MOVD $1860, R12 + B callbackasm1(SB) + MOVD $1861, R12 + B callbackasm1(SB) + MOVD $1862, R12 + B callbackasm1(SB) + MOVD $1863, R12 + B callbackasm1(SB) + MOVD $1864, R12 + B callbackasm1(SB) + MOVD $1865, R12 + B callbackasm1(SB) + MOVD $1866, R12 + B callbackasm1(SB) + MOVD $1867, R12 + B callbackasm1(SB) + MOVD $1868, R12 + B callbackasm1(SB) + MOVD $1869, R12 + B callbackasm1(SB) + MOVD $1870, R12 + B callbackasm1(SB) + MOVD $1871, R12 + B callbackasm1(SB) + MOVD $1872, R12 + B callbackasm1(SB) + MOVD $1873, R12 + B callbackasm1(SB) + MOVD $1874, R12 + B callbackasm1(SB) + MOVD $1875, R12 + B callbackasm1(SB) + MOVD $1876, R12 + B callbackasm1(SB) + MOVD $1877, R12 + B callbackasm1(SB) + MOVD $1878, R12 + B callbackasm1(SB) + MOVD $1879, R12 + B callbackasm1(SB) + MOVD $1880, R12 + B callbackasm1(SB) + MOVD $1881, R12 + B callbackasm1(SB) + MOVD $1882, R12 + B callbackasm1(SB) + MOVD $1883, R12 + B callbackasm1(SB) + MOVD $1884, R12 + B callbackasm1(SB) + MOVD $1885, R12 + B callbackasm1(SB) + MOVD $1886, R12 + B callbackasm1(SB) + MOVD $1887, R12 + B callbackasm1(SB) + MOVD $1888, R12 + B callbackasm1(SB) + MOVD $1889, R12 + B callbackasm1(SB) + MOVD $1890, R12 + B callbackasm1(SB) + MOVD $1891, R12 + B callbackasm1(SB) + MOVD $1892, R12 + B callbackasm1(SB) + MOVD $1893, R12 + B callbackasm1(SB) + MOVD $1894, R12 + B callbackasm1(SB) + MOVD $1895, R12 + B callbackasm1(SB) + MOVD $1896, R12 + B callbackasm1(SB) + MOVD $1897, R12 + B callbackasm1(SB) + MOVD $1898, R12 + B callbackasm1(SB) + MOVD $1899, R12 + B callbackasm1(SB) + MOVD $1900, R12 + B callbackasm1(SB) + MOVD $1901, R12 + B callbackasm1(SB) + MOVD $1902, R12 + B callbackasm1(SB) + MOVD $1903, R12 + B callbackasm1(SB) + MOVD $1904, R12 + B callbackasm1(SB) + MOVD $1905, R12 + B callbackasm1(SB) + MOVD $1906, R12 + B callbackasm1(SB) + MOVD $1907, R12 + B callbackasm1(SB) + MOVD $1908, R12 + B callbackasm1(SB) + MOVD $1909, R12 + B callbackasm1(SB) + MOVD $1910, R12 + B callbackasm1(SB) + MOVD $1911, R12 + B callbackasm1(SB) + MOVD $1912, R12 + B callbackasm1(SB) + MOVD $1913, R12 + B callbackasm1(SB) + MOVD $1914, R12 + B callbackasm1(SB) + MOVD $1915, R12 + B callbackasm1(SB) + MOVD $1916, R12 + B callbackasm1(SB) + MOVD $1917, R12 + B callbackasm1(SB) + MOVD $1918, R12 + B callbackasm1(SB) + MOVD $1919, R12 + B callbackasm1(SB) + MOVD $1920, R12 + B callbackasm1(SB) + MOVD $1921, R12 + B callbackasm1(SB) + MOVD $1922, R12 + B callbackasm1(SB) + MOVD $1923, R12 + B callbackasm1(SB) + MOVD $1924, R12 + B callbackasm1(SB) + MOVD $1925, R12 + B callbackasm1(SB) + MOVD $1926, R12 + B callbackasm1(SB) + MOVD $1927, R12 + B callbackasm1(SB) + MOVD $1928, R12 + B callbackasm1(SB) + MOVD $1929, R12 + B callbackasm1(SB) + MOVD $1930, R12 + B callbackasm1(SB) + MOVD $1931, R12 + B callbackasm1(SB) + MOVD $1932, R12 + B callbackasm1(SB) + MOVD $1933, R12 + B callbackasm1(SB) + MOVD $1934, R12 + B callbackasm1(SB) + MOVD $1935, R12 + B callbackasm1(SB) + MOVD $1936, R12 + B callbackasm1(SB) + MOVD $1937, R12 + B callbackasm1(SB) + MOVD $1938, R12 + B callbackasm1(SB) + MOVD $1939, R12 + B callbackasm1(SB) + MOVD $1940, R12 + B callbackasm1(SB) + MOVD $1941, R12 + B callbackasm1(SB) + MOVD $1942, R12 + B callbackasm1(SB) + MOVD $1943, R12 + B callbackasm1(SB) + MOVD $1944, R12 + B callbackasm1(SB) + MOVD $1945, R12 + B callbackasm1(SB) + MOVD $1946, R12 + B callbackasm1(SB) + MOVD $1947, R12 + B callbackasm1(SB) + MOVD $1948, R12 + B callbackasm1(SB) + MOVD $1949, R12 + B callbackasm1(SB) + MOVD $1950, R12 + B callbackasm1(SB) + MOVD $1951, R12 + B callbackasm1(SB) + MOVD $1952, R12 + B callbackasm1(SB) + MOVD $1953, R12 + B callbackasm1(SB) + MOVD $1954, R12 + B callbackasm1(SB) + MOVD $1955, R12 + B callbackasm1(SB) + MOVD $1956, R12 + B callbackasm1(SB) + MOVD $1957, R12 + B callbackasm1(SB) + MOVD $1958, R12 + B callbackasm1(SB) + MOVD $1959, R12 + B callbackasm1(SB) + MOVD $1960, R12 + B callbackasm1(SB) + MOVD $1961, R12 + B callbackasm1(SB) + MOVD $1962, R12 + B callbackasm1(SB) + MOVD $1963, R12 + B callbackasm1(SB) + MOVD $1964, R12 + B callbackasm1(SB) + MOVD $1965, R12 + B callbackasm1(SB) + MOVD $1966, R12 + B callbackasm1(SB) + MOVD $1967, R12 + B callbackasm1(SB) + MOVD $1968, R12 + B callbackasm1(SB) + MOVD $1969, R12 + B callbackasm1(SB) + MOVD $1970, R12 + B callbackasm1(SB) + MOVD $1971, R12 + B callbackasm1(SB) + MOVD $1972, R12 + B callbackasm1(SB) + MOVD $1973, R12 + B callbackasm1(SB) + MOVD $1974, R12 + B callbackasm1(SB) + MOVD $1975, R12 + B callbackasm1(SB) + MOVD $1976, R12 + B callbackasm1(SB) + MOVD $1977, R12 + B callbackasm1(SB) + MOVD $1978, R12 + B callbackasm1(SB) + MOVD $1979, R12 + B callbackasm1(SB) + MOVD $1980, R12 + B callbackasm1(SB) + MOVD $1981, R12 + B callbackasm1(SB) + MOVD $1982, R12 + B callbackasm1(SB) + MOVD $1983, R12 + B callbackasm1(SB) + MOVD $1984, R12 + B callbackasm1(SB) + MOVD $1985, R12 + B callbackasm1(SB) + MOVD $1986, R12 + B callbackasm1(SB) + MOVD $1987, R12 + B callbackasm1(SB) + MOVD $1988, R12 + B callbackasm1(SB) + MOVD $1989, R12 + B callbackasm1(SB) + MOVD $1990, R12 + B callbackasm1(SB) + MOVD $1991, R12 + B callbackasm1(SB) + MOVD $1992, R12 + B callbackasm1(SB) + MOVD $1993, R12 + B callbackasm1(SB) + MOVD $1994, R12 + B callbackasm1(SB) + MOVD $1995, R12 + B callbackasm1(SB) + MOVD $1996, R12 + B callbackasm1(SB) + MOVD $1997, R12 + B callbackasm1(SB) + MOVD $1998, R12 + B callbackasm1(SB) + MOVD $1999, R12 + B callbackasm1(SB) diff --git a/vendor/github.com/flopp/go-findfont/LICENSE b/vendor/github.com/flopp/go-findfont/LICENSE new file mode 100644 index 0000000..7417b3d --- /dev/null +++ b/vendor/github.com/flopp/go-findfont/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Florian Pigorsch + +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. diff --git a/vendor/github.com/flopp/go-findfont/README.md b/vendor/github.com/flopp/go-findfont/README.md new file mode 100644 index 0000000..23e8450 --- /dev/null +++ b/vendor/github.com/flopp/go-findfont/README.md @@ -0,0 +1,57 @@ +[![PkgGoDev](https://pkg.go.dev/badge/github.com/flopp/go-findfont)](https://pkg.go.dev/github.com/flopp/go-findfont) +[![Go Report Card](https://goreportcard.com/badge/github.com/flopp/go-findfont)](https://goreportcard.com/report/github.com/flopp/go-findfont) +[![License MIT](https://img.shields.io/badge/license-MIT-lightgrey.svg?style=flat)](https://github.com/flopp/go-findfont/) + +# go-findfont +A platform-agnostic go (golang) library to easily locate truetype font files in your system's user and system font directories. + +## What? +`go-findfont` is a golang library that allows you to locate font file on your system. The library is currently aware of the default font directories on Linux/Unix, Windows, and MacOS. + +## How? + +### Installation + +Installing `go-findfont` is as easy as + +```bash +go get -u github.com/flopp/go-findfont +``` + +### Library Usage + +```go + +import ( + "fmt" + "io/ioutil" + + "github.com/flopp/go-findfont" + "github.com/golang/freetype/truetype" +) + +func main() { + fontPath, err := findfont.Find("arial.ttf") + if err != nil { + panic(err) + } + fmt.Printf("Found 'arial.ttf' in '%s'\n", fontPath) + + // load the font with the freetype library + fontData, err := ioutil.ReadFile(fontPath) + if err != nil { + panic(err) + } + font, err := truetype.Parse(fontData) + if err != nil { + panic(err) + } + + // use the font... +} +``` + +## License +Copyright 2016 Florian Pigorsch. All rights reserved. + +Use of this source code is governed by a MIT-style license that can be found in the LICENSE file. diff --git a/vendor/github.com/flopp/go-findfont/findfont.go b/vendor/github.com/flopp/go-findfont/findfont.go new file mode 100644 index 0000000..1601bb4 --- /dev/null +++ b/vendor/github.com/flopp/go-findfont/findfont.go @@ -0,0 +1,114 @@ +// Copyright 2016 Florian Pigorsch. All rights reserved. +// +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package findfont + +import ( + "fmt" + "os" + "os/user" + "path/filepath" + "strings" +) + +// Find tries to locate the specified font file in the current directory as +// well as in platform specific user and system font directories; if there is +// no exact match, Find tries substring matching. +func Find(fileName string) (filePath string, err error) { + // check if fileName already points to a readable file + if _, err := os.Stat(fileName); err == nil { + return fileName, nil + } + + // search in user and system directories + return find(filepath.Base(fileName)) +} + +// List returns a list of all font files found on the system. +func List() (filePaths []string) { + pathList := []string{} + + walkF := func(path string, info os.FileInfo, err error) error { + if err == nil { + if info.IsDir() == false && isFontFile(path) { + pathList = append(pathList, path) + } + } + return nil + } + for _, dir := range getFontDirectories() { + filepath.Walk(dir, walkF) + } + + return pathList +} + +func isFontFile(fileName string) bool { + lower := strings.ToLower(fileName) + return strings.HasSuffix(lower, ".ttf") || strings.HasSuffix(lower, ".ttc") || strings.HasSuffix(lower, ".otf") +} + +func stripExtension(fileName string) string { + return strings.TrimSuffix(fileName, filepath.Ext(fileName)) +} + +func expandUser(path string) (expandedPath string) { + if strings.HasPrefix(path, "~") { + if u, err := user.Current(); err == nil { + return strings.Replace(path, "~", u.HomeDir, -1) + } + } + return path +} + +func find(needle string) (filePath string, err error) { + lowerNeedle := strings.ToLower(needle) + lowerNeedleBase := stripExtension(lowerNeedle) + + match := "" + partial := "" + partialScore := -1 + + walkF := func(path string, info os.FileInfo, err error) error { + // we have already found a match -> nothing to do + if match != "" { + return nil + } + if err != nil { + return nil + } + + lowerPath := strings.ToLower(info.Name()) + + if info.IsDir() == false && isFontFile(lowerPath) { + lowerBase := stripExtension(lowerPath) + if lowerPath == lowerNeedle { + // exact match + match = path + } else if strings.Contains(lowerBase, lowerNeedleBase) { + // partial match + score := len(lowerBase) - len(lowerNeedle) + if partialScore < 0 || score < partialScore { + partialScore = score + partial = path + } + } + } + return nil + } + + for _, dir := range getFontDirectories() { + filepath.Walk(dir, walkF) + if match != "" { + return match, nil + } + } + + if partial != "" { + return partial, nil + } + + return "", fmt.Errorf("cannot find font '%s' in user or system directories", needle) +} diff --git a/vendor/github.com/flopp/go-findfont/fontdirs_darwin.go b/vendor/github.com/flopp/go-findfont/fontdirs_darwin.go new file mode 100644 index 0000000..0e0aacd --- /dev/null +++ b/vendor/github.com/flopp/go-findfont/fontdirs_darwin.go @@ -0,0 +1,14 @@ +// Copyright 2016 Florian Pigorsch. All rights reserved. +// +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package findfont + +func getFontDirectories() (paths []string) { + return []string{ + expandUser("~/Library/Fonts/"), + "/Library/Fonts/", + "/System/Library/Fonts/", + } +} diff --git a/vendor/github.com/flopp/go-findfont/fontdirs_unix.go b/vendor/github.com/flopp/go-findfont/fontdirs_unix.go new file mode 100644 index 0000000..c30abfd --- /dev/null +++ b/vendor/github.com/flopp/go-findfont/fontdirs_unix.go @@ -0,0 +1,36 @@ +// +build dragonfly freebsd linux nacl netbsd openbsd solaris + +// Copyright 2016 Florian Pigorsch. All rights reserved. +// +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package findfont + +import ( + "os" + "path/filepath" +) + +func getFontDirectories() (paths []string) { + directories := getUserFontDirs() + directories = append(directories, getSystemFontDirs()...) + return directories +} + +func getUserFontDirs() (paths []string) { + if dataPath := os.Getenv("XDG_DATA_HOME"); dataPath != "" { + return []string{expandUser("~/.fonts/"), filepath.Join(expandUser(dataPath), "fonts")} + } + return []string{expandUser("~/.fonts/"), expandUser("~/.local/share/fonts/")} +} + +func getSystemFontDirs() (paths []string) { + if dataPaths := os.Getenv("XDG_DATA_DIRS"); dataPaths != "" { + for _, dataPath := range filepath.SplitList(dataPaths) { + paths = append(paths, filepath.Join(expandUser(dataPath), "fonts")) + } + return paths + } + return []string{"/usr/local/share/fonts/", "/usr/share/fonts/"} +} diff --git a/vendor/github.com/flopp/go-findfont/fontdirs_windows.go b/vendor/github.com/flopp/go-findfont/fontdirs_windows.go new file mode 100644 index 0000000..dbe70e7 --- /dev/null +++ b/vendor/github.com/flopp/go-findfont/fontdirs_windows.go @@ -0,0 +1,18 @@ +// Copyright 2016 Florian Pigorsch. All rights reserved. +// +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package findfont + +import ( + "os" + "path/filepath" +) + +func getFontDirectories() (paths []string) { + return []string{ + filepath.Join(os.Getenv("windir"), "Fonts"), + filepath.Join(os.Getenv("localappdata"), "Microsoft", "Windows", "Fonts"), + } +} diff --git a/vendor/github.com/fsnotify/fsnotify/.cirrus.yml b/vendor/github.com/fsnotify/fsnotify/.cirrus.yml new file mode 100644 index 0000000..f4e7dbf --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/.cirrus.yml @@ -0,0 +1,14 @@ +freebsd_task: + name: 'FreeBSD' + freebsd_instance: + image_family: freebsd-14-1 + install_script: + - pkg update -f + - pkg install -y go + test_script: + # run tests as user "cirrus" instead of root + - pw useradd cirrus -m + - chown -R cirrus:cirrus . + - FSNOTIFY_BUFFER=4096 sudo --preserve-env=FSNOTIFY_BUFFER -u cirrus go test -parallel 1 -race ./... + - sudo --preserve-env=FSNOTIFY_BUFFER -u cirrus go test -parallel 1 -race ./... + - FSNOTIFY_DEBUG=1 sudo --preserve-env=FSNOTIFY_BUFFER -u cirrus go test -parallel 1 -race -v ./... diff --git a/vendor/github.com/fsnotify/fsnotify/.gitignore b/vendor/github.com/fsnotify/fsnotify/.gitignore new file mode 100644 index 0000000..daea9dd --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/.gitignore @@ -0,0 +1,10 @@ +# go test -c output +*.test +*.test.exe + +# Output of go build ./cmd/fsnotify +/fsnotify +/fsnotify.exe + +/test/kqueue +/test/a.out diff --git a/vendor/github.com/fsnotify/fsnotify/.mailmap b/vendor/github.com/fsnotify/fsnotify/.mailmap new file mode 100644 index 0000000..a04f290 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/.mailmap @@ -0,0 +1,2 @@ +Chris Howey +Nathan Youngman <4566+nathany@users.noreply.github.com> diff --git a/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md b/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md new file mode 100644 index 0000000..fa85478 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md @@ -0,0 +1,569 @@ +# Changelog + +1.8.0 2023-10-31 +---------------- + +### Additions + +- all: add `FSNOTIFY_DEBUG` to print debug logs to stderr ([#619]) + +### Changes and fixes + +- windows: fix behaviour of `WatchList()` to be consistent with other platforms ([#610]) + +- kqueue: ignore events with Ident=0 ([#590]) + +- kqueue: set O_CLOEXEC to prevent passing file descriptors to children ([#617]) + +- kqueue: emit events as "/path/dir/file" instead of "path/link/file" when watching a symlink ([#625]) + +- inotify: don't send event for IN_DELETE_SELF when also watching the parent ([#620]) + +- inotify: fix panic when calling Remove() in a goroutine ([#650]) + +- fen: allow watching subdirectories of watched directories ([#621]) + +[#590]: https://github.com/fsnotify/fsnotify/pull/590 +[#610]: https://github.com/fsnotify/fsnotify/pull/610 +[#617]: https://github.com/fsnotify/fsnotify/pull/617 +[#619]: https://github.com/fsnotify/fsnotify/pull/619 +[#620]: https://github.com/fsnotify/fsnotify/pull/620 +[#621]: https://github.com/fsnotify/fsnotify/pull/621 +[#625]: https://github.com/fsnotify/fsnotify/pull/625 +[#650]: https://github.com/fsnotify/fsnotify/pull/650 + +1.7.0 - 2023-10-22 +------------------ +This version of fsnotify needs Go 1.17. + +### Additions + +- illumos: add FEN backend to support illumos and Solaris. ([#371]) + +- all: add `NewBufferedWatcher()` to use a buffered channel, which can be useful + in cases where you can't control the kernel buffer and receive a large number + of events in bursts. ([#550], [#572]) + +- all: add `AddWith()`, which is identical to `Add()` but allows passing + options. ([#521]) + +- windows: allow setting the ReadDirectoryChangesW() buffer size with + `fsnotify.WithBufferSize()`; the default of 64K is the highest value that + works on all platforms and is enough for most purposes, but in some cases a + highest buffer is needed. ([#521]) + +### Changes and fixes + +- inotify: remove watcher if a watched path is renamed ([#518]) + + After a rename the reported name wasn't updated, or even an empty string. + Inotify doesn't provide any good facilities to update it, so just remove the + watcher. This is already how it worked on kqueue and FEN. + + On Windows this does work, and remains working. + +- windows: don't listen for file attribute changes ([#520]) + + File attribute changes are sent as `FILE_ACTION_MODIFIED` by the Windows API, + with no way to see if they're a file write or attribute change, so would show + up as a fsnotify.Write event. This is never useful, and could result in many + spurious Write events. + +- windows: return `ErrEventOverflow` if the buffer is full ([#525]) + + Before it would merely return "short read", making it hard to detect this + error. + +- kqueue: make sure events for all files are delivered properly when removing a + watched directory ([#526]) + + Previously they would get sent with `""` (empty string) or `"."` as the path + name. + +- kqueue: don't emit spurious Create events for symbolic links ([#524]) + + The link would get resolved but kqueue would "forget" it already saw the link + itself, resulting on a Create for every Write event for the directory. + +- all: return `ErrClosed` on `Add()` when the watcher is closed ([#516]) + +- other: add `Watcher.Errors` and `Watcher.Events` to the no-op `Watcher` in + `backend_other.go`, making it easier to use on unsupported platforms such as + WASM, AIX, etc. ([#528]) + +- other: use the `backend_other.go` no-op if the `appengine` build tag is set; + Google AppEngine forbids usage of the unsafe package so the inotify backend + won't compile there. + +[#371]: https://github.com/fsnotify/fsnotify/pull/371 +[#516]: https://github.com/fsnotify/fsnotify/pull/516 +[#518]: https://github.com/fsnotify/fsnotify/pull/518 +[#520]: https://github.com/fsnotify/fsnotify/pull/520 +[#521]: https://github.com/fsnotify/fsnotify/pull/521 +[#524]: https://github.com/fsnotify/fsnotify/pull/524 +[#525]: https://github.com/fsnotify/fsnotify/pull/525 +[#526]: https://github.com/fsnotify/fsnotify/pull/526 +[#528]: https://github.com/fsnotify/fsnotify/pull/528 +[#537]: https://github.com/fsnotify/fsnotify/pull/537 +[#550]: https://github.com/fsnotify/fsnotify/pull/550 +[#572]: https://github.com/fsnotify/fsnotify/pull/572 + +1.6.0 - 2022-10-13 +------------------ +This version of fsnotify needs Go 1.16 (this was already the case since 1.5.1, +but not documented). It also increases the minimum Linux version to 2.6.32. + +### Additions + +- all: add `Event.Has()` and `Op.Has()` ([#477]) + + This makes checking events a lot easier; for example: + + if event.Op&Write == Write && !(event.Op&Remove == Remove) { + } + + Becomes: + + if event.Has(Write) && !event.Has(Remove) { + } + +- all: add cmd/fsnotify ([#463]) + + A command-line utility for testing and some examples. + +### Changes and fixes + +- inotify: don't ignore events for files that don't exist ([#260], [#470]) + + Previously the inotify watcher would call `os.Lstat()` to check if a file + still exists before emitting events. + + This was inconsistent with other platforms and resulted in inconsistent event + reporting (e.g. when a file is quickly removed and re-created), and generally + a source of confusion. It was added in 2013 to fix a memory leak that no + longer exists. + +- all: return `ErrNonExistentWatch` when `Remove()` is called on a path that's + not watched ([#460]) + +- inotify: replace epoll() with non-blocking inotify ([#434]) + + Non-blocking inotify was not generally available at the time this library was + written in 2014, but now it is. As a result, the minimum Linux version is + bumped from 2.6.27 to 2.6.32. This hugely simplifies the code and is faster. + +- kqueue: don't check for events every 100ms ([#480]) + + The watcher would wake up every 100ms, even when there was nothing to do. Now + it waits until there is something to do. + +- macos: retry opening files on EINTR ([#475]) + +- kqueue: skip unreadable files ([#479]) + + kqueue requires a file descriptor for every file in a directory; this would + fail if a file was unreadable by the current user. Now these files are simply + skipped. + +- windows: fix renaming a watched directory if the parent is also watched ([#370]) + +- windows: increase buffer size from 4K to 64K ([#485]) + +- windows: close file handle on Remove() ([#288]) + +- kqueue: put pathname in the error if watching a file fails ([#471]) + +- inotify, windows: calling Close() more than once could race ([#465]) + +- kqueue: improve Close() performance ([#233]) + +- all: various documentation additions and clarifications. + +[#233]: https://github.com/fsnotify/fsnotify/pull/233 +[#260]: https://github.com/fsnotify/fsnotify/pull/260 +[#288]: https://github.com/fsnotify/fsnotify/pull/288 +[#370]: https://github.com/fsnotify/fsnotify/pull/370 +[#434]: https://github.com/fsnotify/fsnotify/pull/434 +[#460]: https://github.com/fsnotify/fsnotify/pull/460 +[#463]: https://github.com/fsnotify/fsnotify/pull/463 +[#465]: https://github.com/fsnotify/fsnotify/pull/465 +[#470]: https://github.com/fsnotify/fsnotify/pull/470 +[#471]: https://github.com/fsnotify/fsnotify/pull/471 +[#475]: https://github.com/fsnotify/fsnotify/pull/475 +[#477]: https://github.com/fsnotify/fsnotify/pull/477 +[#479]: https://github.com/fsnotify/fsnotify/pull/479 +[#480]: https://github.com/fsnotify/fsnotify/pull/480 +[#485]: https://github.com/fsnotify/fsnotify/pull/485 + +## [1.5.4] - 2022-04-25 + +* Windows: add missing defer to `Watcher.WatchList` [#447](https://github.com/fsnotify/fsnotify/pull/447) +* go.mod: use latest x/sys [#444](https://github.com/fsnotify/fsnotify/pull/444) +* Fix compilation for OpenBSD [#443](https://github.com/fsnotify/fsnotify/pull/443) + +## [1.5.3] - 2022-04-22 + +* This version is retracted. An incorrect branch is published accidentally [#445](https://github.com/fsnotify/fsnotify/issues/445) + +## [1.5.2] - 2022-04-21 + +* Add a feature to return the directories and files that are being monitored [#374](https://github.com/fsnotify/fsnotify/pull/374) +* Fix potential crash on windows if `raw.FileNameLength` exceeds `syscall.MAX_PATH` [#361](https://github.com/fsnotify/fsnotify/pull/361) +* Allow build on unsupported GOOS [#424](https://github.com/fsnotify/fsnotify/pull/424) +* Don't set `poller.fd` twice in `newFdPoller` [#406](https://github.com/fsnotify/fsnotify/pull/406) +* fix go vet warnings: call to `(*T).Fatalf` from a non-test goroutine [#416](https://github.com/fsnotify/fsnotify/pull/416) + +## [1.5.1] - 2021-08-24 + +* Revert Add AddRaw to not follow symlinks [#394](https://github.com/fsnotify/fsnotify/pull/394) + +## [1.5.0] - 2021-08-20 + +* Go: Increase minimum required version to Go 1.12 [#381](https://github.com/fsnotify/fsnotify/pull/381) +* Feature: Add AddRaw method which does not follow symlinks when adding a watch [#289](https://github.com/fsnotify/fsnotify/pull/298) +* Windows: Follow symlinks by default like on all other systems [#289](https://github.com/fsnotify/fsnotify/pull/289) +* CI: Use GitHub Actions for CI and cover go 1.12-1.17 + [#378](https://github.com/fsnotify/fsnotify/pull/378) + [#381](https://github.com/fsnotify/fsnotify/pull/381) + [#385](https://github.com/fsnotify/fsnotify/pull/385) +* Go 1.14+: Fix unsafe pointer conversion [#325](https://github.com/fsnotify/fsnotify/pull/325) + +## [1.4.9] - 2020-03-11 + +* Move example usage to the readme #329. This may resolve #328. + +## [1.4.8] - 2020-03-10 + +* CI: test more go versions (@nathany 1d13583d846ea9d66dcabbfefbfb9d8e6fb05216) +* Tests: Queued inotify events could have been read by the test before max_queued_events was hit (@matthias-stone #265) +* Tests: t.Fatalf -> t.Errorf in go routines (@gdey #266) +* CI: Less verbosity (@nathany #267) +* Tests: Darwin: Exchangedata is deprecated on 10.13 (@nathany #267) +* Tests: Check if channels are closed in the example (@alexeykazakov #244) +* CI: Only run golint on latest version of go and fix issues (@cpuguy83 #284) +* CI: Add windows to travis matrix (@cpuguy83 #284) +* Docs: Remover appveyor badge (@nathany 11844c0959f6fff69ba325d097fce35bd85a8e93) +* Linux: create epoll and pipe fds with close-on-exec (@JohannesEbke #219) +* Linux: open files with close-on-exec (@linxiulei #273) +* Docs: Plan to support fanotify (@nathany ab058b44498e8b7566a799372a39d150d9ea0119 ) +* Project: Add go.mod (@nathany #309) +* Project: Revise editor config (@nathany #309) +* Project: Update copyright for 2019 (@nathany #309) +* CI: Drop go1.8 from CI matrix (@nathany #309) +* Docs: Updating the FAQ section for supportability with NFS & FUSE filesystems (@Pratik32 4bf2d1fec78374803a39307bfb8d340688f4f28e ) + +## [1.4.7] - 2018-01-09 + +* BSD/macOS: Fix possible deadlock on closing the watcher on kqueue (thanks @nhooyr and @glycerine) +* Tests: Fix missing verb on format string (thanks @rchiossi) +* Linux: Fix deadlock in Remove (thanks @aarondl) +* Linux: Watch.Add improvements (avoid race, fix consistency, reduce garbage) (thanks @twpayne) +* Docs: Moved FAQ into the README (thanks @vahe) +* Linux: Properly handle inotify's IN_Q_OVERFLOW event (thanks @zeldovich) +* Docs: replace references to OS X with macOS + +## [1.4.2] - 2016-10-10 + +* Linux: use InotifyInit1 with IN_CLOEXEC to stop leaking a file descriptor to a child process when using fork/exec [#178](https://github.com/fsnotify/fsnotify/pull/178) (thanks @pattyshack) + +## [1.4.1] - 2016-10-04 + +* Fix flaky inotify stress test on Linux [#177](https://github.com/fsnotify/fsnotify/pull/177) (thanks @pattyshack) + +## [1.4.0] - 2016-10-01 + +* add a String() method to Event.Op [#165](https://github.com/fsnotify/fsnotify/pull/165) (thanks @oozie) + +## [1.3.1] - 2016-06-28 + +* Windows: fix for double backslash when watching the root of a drive [#151](https://github.com/fsnotify/fsnotify/issues/151) (thanks @brunoqc) + +## [1.3.0] - 2016-04-19 + +* Support linux/arm64 by [patching](https://go-review.googlesource.com/#/c/21971/) x/sys/unix and switching to to it from syscall (thanks @suihkulokki) [#135](https://github.com/fsnotify/fsnotify/pull/135) + +## [1.2.10] - 2016-03-02 + +* Fix golint errors in windows.go [#121](https://github.com/fsnotify/fsnotify/pull/121) (thanks @tiffanyfj) + +## [1.2.9] - 2016-01-13 + +kqueue: Fix logic for CREATE after REMOVE [#111](https://github.com/fsnotify/fsnotify/pull/111) (thanks @bep) + +## [1.2.8] - 2015-12-17 + +* kqueue: fix race condition in Close [#105](https://github.com/fsnotify/fsnotify/pull/105) (thanks @djui for reporting the issue and @ppknap for writing a failing test) +* inotify: fix race in test +* enable race detection for continuous integration (Linux, Mac, Windows) + +## [1.2.5] - 2015-10-17 + +* inotify: use epoll_create1 for arm64 support (requires Linux 2.6.27 or later) [#100](https://github.com/fsnotify/fsnotify/pull/100) (thanks @suihkulokki) +* inotify: fix path leaks [#73](https://github.com/fsnotify/fsnotify/pull/73) (thanks @chamaken) +* kqueue: watch for rename events on subdirectories [#83](https://github.com/fsnotify/fsnotify/pull/83) (thanks @guotie) +* kqueue: avoid infinite loops from symlinks cycles [#101](https://github.com/fsnotify/fsnotify/pull/101) (thanks @illicitonion) + +## [1.2.1] - 2015-10-14 + +* kqueue: don't watch named pipes [#98](https://github.com/fsnotify/fsnotify/pull/98) (thanks @evanphx) + +## [1.2.0] - 2015-02-08 + +* inotify: use epoll to wake up readEvents [#66](https://github.com/fsnotify/fsnotify/pull/66) (thanks @PieterD) +* inotify: closing watcher should now always shut down goroutine [#63](https://github.com/fsnotify/fsnotify/pull/63) (thanks @PieterD) +* kqueue: close kqueue after removing watches, fixes [#59](https://github.com/fsnotify/fsnotify/issues/59) + +## [1.1.1] - 2015-02-05 + +* inotify: Retry read on EINTR [#61](https://github.com/fsnotify/fsnotify/issues/61) (thanks @PieterD) + +## [1.1.0] - 2014-12-12 + +* kqueue: rework internals [#43](https://github.com/fsnotify/fsnotify/pull/43) + * add low-level functions + * only need to store flags on directories + * less mutexes [#13](https://github.com/fsnotify/fsnotify/issues/13) + * done can be an unbuffered channel + * remove calls to os.NewSyscallError +* More efficient string concatenation for Event.String() [#52](https://github.com/fsnotify/fsnotify/pull/52) (thanks @mdlayher) +* kqueue: fix regression in rework causing subdirectories to be watched [#48](https://github.com/fsnotify/fsnotify/issues/48) +* kqueue: cleanup internal watch before sending remove event [#51](https://github.com/fsnotify/fsnotify/issues/51) + +## [1.0.4] - 2014-09-07 + +* kqueue: add dragonfly to the build tags. +* Rename source code files, rearrange code so exported APIs are at the top. +* Add done channel to example code. [#37](https://github.com/fsnotify/fsnotify/pull/37) (thanks @chenyukang) + +## [1.0.3] - 2014-08-19 + +* [Fix] Windows MOVED_TO now translates to Create like on BSD and Linux. [#36](https://github.com/fsnotify/fsnotify/issues/36) + +## [1.0.2] - 2014-08-17 + +* [Fix] Missing create events on macOS. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso) +* [Fix] Make ./path and path equivalent. (thanks @zhsso) + +## [1.0.0] - 2014-08-15 + +* [API] Remove AddWatch on Windows, use Add. +* Improve documentation for exported identifiers. [#30](https://github.com/fsnotify/fsnotify/issues/30) +* Minor updates based on feedback from golint. + +## dev / 2014-07-09 + +* Moved to [github.com/fsnotify/fsnotify](https://github.com/fsnotify/fsnotify). +* Use os.NewSyscallError instead of returning errno (thanks @hariharan-uno) + +## dev / 2014-07-04 + +* kqueue: fix incorrect mutex used in Close() +* Update example to demonstrate usage of Op. + +## dev / 2014-06-28 + +* [API] Don't set the Write Op for attribute notifications [#4](https://github.com/fsnotify/fsnotify/issues/4) +* Fix for String() method on Event (thanks Alex Brainman) +* Don't build on Plan 9 or Solaris (thanks @4ad) + +## dev / 2014-06-21 + +* Events channel of type Event rather than *Event. +* [internal] use syscall constants directly for inotify and kqueue. +* [internal] kqueue: rename events to kevents and fileEvent to event. + +## dev / 2014-06-19 + +* Go 1.3+ required on Windows (uses syscall.ERROR_MORE_DATA internally). +* [internal] remove cookie from Event struct (unused). +* [internal] Event struct has the same definition across every OS. +* [internal] remove internal watch and removeWatch methods. + +## dev / 2014-06-12 + +* [API] Renamed Watch() to Add() and RemoveWatch() to Remove(). +* [API] Pluralized channel names: Events and Errors. +* [API] Renamed FileEvent struct to Event. +* [API] Op constants replace methods like IsCreate(). + +## dev / 2014-06-12 + +* Fix data race on kevent buffer (thanks @tilaks) [#98](https://github.com/howeyc/fsnotify/pull/98) + +## dev / 2014-05-23 + +* [API] Remove current implementation of WatchFlags. + * current implementation doesn't take advantage of OS for efficiency + * provides little benefit over filtering events as they are received, but has extra bookkeeping and mutexes + * no tests for the current implementation + * not fully implemented on Windows [#93](https://github.com/howeyc/fsnotify/issues/93#issuecomment-39285195) + +## [0.9.3] - 2014-12-31 + +* kqueue: cleanup internal watch before sending remove event [#51](https://github.com/fsnotify/fsnotify/issues/51) + +## [0.9.2] - 2014-08-17 + +* [Backport] Fix missing create events on macOS. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso) + +## [0.9.1] - 2014-06-12 + +* Fix data race on kevent buffer (thanks @tilaks) [#98](https://github.com/howeyc/fsnotify/pull/98) + +## [0.9.0] - 2014-01-17 + +* IsAttrib() for events that only concern a file's metadata [#79][] (thanks @abustany) +* [Fix] kqueue: fix deadlock [#77][] (thanks @cespare) +* [NOTICE] Development has moved to `code.google.com/p/go.exp/fsnotify` in preparation for inclusion in the Go standard library. + +## [0.8.12] - 2013-11-13 + +* [API] Remove FD_SET and friends from Linux adapter + +## [0.8.11] - 2013-11-02 + +* [Doc] Add Changelog [#72][] (thanks @nathany) +* [Doc] Spotlight and double modify events on macOS [#62][] (reported by @paulhammond) + +## [0.8.10] - 2013-10-19 + +* [Fix] kqueue: remove file watches when parent directory is removed [#71][] (reported by @mdwhatcott) +* [Fix] kqueue: race between Close and readEvents [#70][] (reported by @bernerdschaefer) +* [Doc] specify OS-specific limits in README (thanks @debrando) + +## [0.8.9] - 2013-09-08 + +* [Doc] Contributing (thanks @nathany) +* [Doc] update package path in example code [#63][] (thanks @paulhammond) +* [Doc] GoCI badge in README (Linux only) [#60][] +* [Doc] Cross-platform testing with Vagrant [#59][] (thanks @nathany) + +## [0.8.8] - 2013-06-17 + +* [Fix] Windows: handle `ERROR_MORE_DATA` on Windows [#49][] (thanks @jbowtie) + +## [0.8.7] - 2013-06-03 + +* [API] Make syscall flags internal +* [Fix] inotify: ignore event changes +* [Fix] race in symlink test [#45][] (reported by @srid) +* [Fix] tests on Windows +* lower case error messages + +## [0.8.6] - 2013-05-23 + +* kqueue: Use EVT_ONLY flag on Darwin +* [Doc] Update README with full example + +## [0.8.5] - 2013-05-09 + +* [Fix] inotify: allow monitoring of "broken" symlinks (thanks @tsg) + +## [0.8.4] - 2013-04-07 + +* [Fix] kqueue: watch all file events [#40][] (thanks @ChrisBuchholz) + +## [0.8.3] - 2013-03-13 + +* [Fix] inoitfy/kqueue memory leak [#36][] (reported by @nbkolchin) +* [Fix] kqueue: use fsnFlags for watching a directory [#33][] (reported by @nbkolchin) + +## [0.8.2] - 2013-02-07 + +* [Doc] add Authors +* [Fix] fix data races for map access [#29][] (thanks @fsouza) + +## [0.8.1] - 2013-01-09 + +* [Fix] Windows path separators +* [Doc] BSD License + +## [0.8.0] - 2012-11-09 + +* kqueue: directory watching improvements (thanks @vmirage) +* inotify: add `IN_MOVED_TO` [#25][] (requested by @cpisto) +* [Fix] kqueue: deleting watched directory [#24][] (reported by @jakerr) + +## [0.7.4] - 2012-10-09 + +* [Fix] inotify: fixes from https://codereview.appspot.com/5418045/ (ugorji) +* [Fix] kqueue: preserve watch flags when watching for delete [#21][] (reported by @robfig) +* [Fix] kqueue: watch the directory even if it isn't a new watch (thanks @robfig) +* [Fix] kqueue: modify after recreation of file + +## [0.7.3] - 2012-09-27 + +* [Fix] kqueue: watch with an existing folder inside the watched folder (thanks @vmirage) +* [Fix] kqueue: no longer get duplicate CREATE events + +## [0.7.2] - 2012-09-01 + +* kqueue: events for created directories + +## [0.7.1] - 2012-07-14 + +* [Fix] for renaming files + +## [0.7.0] - 2012-07-02 + +* [Feature] FSNotify flags +* [Fix] inotify: Added file name back to event path + +## [0.6.0] - 2012-06-06 + +* kqueue: watch files after directory created (thanks @tmc) + +## [0.5.1] - 2012-05-22 + +* [Fix] inotify: remove all watches before Close() + +## [0.5.0] - 2012-05-03 + +* [API] kqueue: return errors during watch instead of sending over channel +* kqueue: match symlink behavior on Linux +* inotify: add `DELETE_SELF` (requested by @taralx) +* [Fix] kqueue: handle EINTR (reported by @robfig) +* [Doc] Godoc example [#1][] (thanks @davecheney) + +## [0.4.0] - 2012-03-30 + +* Go 1 released: build with go tool +* [Feature] Windows support using winfsnotify +* Windows does not have attribute change notifications +* Roll attribute notifications into IsModify + +## [0.3.0] - 2012-02-19 + +* kqueue: add files when watch directory + +## [0.2.0] - 2011-12-30 + +* update to latest Go weekly code + +## [0.1.0] - 2011-10-19 + +* kqueue: add watch on file creation to match inotify +* kqueue: create file event +* inotify: ignore `IN_IGNORED` events +* event String() +* linux: common FileEvent functions +* initial commit + +[#79]: https://github.com/howeyc/fsnotify/pull/79 +[#77]: https://github.com/howeyc/fsnotify/pull/77 +[#72]: https://github.com/howeyc/fsnotify/issues/72 +[#71]: https://github.com/howeyc/fsnotify/issues/71 +[#70]: https://github.com/howeyc/fsnotify/issues/70 +[#63]: https://github.com/howeyc/fsnotify/issues/63 +[#62]: https://github.com/howeyc/fsnotify/issues/62 +[#60]: https://github.com/howeyc/fsnotify/issues/60 +[#59]: https://github.com/howeyc/fsnotify/issues/59 +[#49]: https://github.com/howeyc/fsnotify/issues/49 +[#45]: https://github.com/howeyc/fsnotify/issues/45 +[#40]: https://github.com/howeyc/fsnotify/issues/40 +[#36]: https://github.com/howeyc/fsnotify/issues/36 +[#33]: https://github.com/howeyc/fsnotify/issues/33 +[#29]: https://github.com/howeyc/fsnotify/issues/29 +[#25]: https://github.com/howeyc/fsnotify/issues/25 +[#24]: https://github.com/howeyc/fsnotify/issues/24 +[#21]: https://github.com/howeyc/fsnotify/issues/21 diff --git a/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md b/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md new file mode 100644 index 0000000..e4ac2a2 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md @@ -0,0 +1,144 @@ +Thank you for your interest in contributing to fsnotify! We try to review and +merge PRs in a reasonable timeframe, but please be aware that: + +- To avoid "wasted" work, please discuss changes on the issue tracker first. You + can just send PRs, but they may end up being rejected for one reason or the + other. + +- fsnotify is a cross-platform library, and changes must work reasonably well on + all supported platforms. + +- Changes will need to be compatible; old code should still compile, and the + runtime behaviour can't change in ways that are likely to lead to problems for + users. + +Testing +------- +Just `go test ./...` runs all the tests; the CI runs this on all supported +platforms. Testing different platforms locally can be done with something like +[goon] or [Vagrant], but this isn't super-easy to set up at the moment. + +Use the `-short` flag to make the "stress test" run faster. + +Writing new tests +----------------- +Scripts in the testdata directory allow creating test cases in a "shell-like" +syntax. The basic format is: + + script + + Output: + desired output + +For example: + + # Create a new empty file with some data. + watch / + echo data >/file + + Output: + create /file + write /file + +Just create a new file to add a new test; select which tests to run with +`-run TestScript/[path]`. + +script +------ +The script is a "shell-like" script: + + cmd arg arg + +Comments are supported with `#`: + + # Comment + cmd arg arg # Comment + +All operations are done in a temp directory; a path like "/foo" is rewritten to +"/tmp/TestFoo/foo". + +Arguments can be quoted with `"` or `'`; there are no escapes and they're +functionally identical right now, but this may change in the future, so best to +assume shell-like rules. + + touch "/file with spaces" + +End-of-line escapes with `\` are not supported. + +### Supported commands + + watch path [ops] # Watch the path, reporting events for it. Nothing is + # watched by default. Optionally a list of ops can be + # given, as with AddWith(path, WithOps(...)). + unwatch path # Stop watching the path. + watchlist n # Assert watchlist length. + + stop # Stop running the script; for debugging. + debug [yes/no] # Enable/disable FSNOTIFY_DEBUG (tests are run in + parallel by default, so -parallel=1 is probably a good + idea). + + touch path + mkdir [-p] dir + ln -s target link # Only ln -s supported. + mkfifo path + mknod dev path + mv src dst + rm [-r] path + chmod mode path # Octal only + sleep time-in-ms + + cat path # Read path (does nothing with the data; just reads it). + echo str >>path # Append "str" to "path". + echo str >path # Truncate "path" and write "str". + + require reason # Skip the test if "reason" is true; "skip" and + skip reason # "require" behave identical; it supports both for + # readability. Possible reasons are: + # + # always Always skip this test. + # symlink Symlinks are supported (requires admin + # permissions on Windows). + # mkfifo Platform doesn't support FIFO named sockets. + # mknod Platform doesn't support device nodes. + + +output +------ +After `Output:` the desired output is given; this is indented by convention, but +that's not required. + +The format of that is: + + # Comment + event path # Comment + + system: + event path + system2: + event path + +Every event is one line, and any whitespace between the event and path are +ignored. The path can optionally be surrounded in ". Anything after a "#" is +ignored. + +Platform-specific tests can be added after GOOS; for example: + + watch / + touch /file + + Output: + # Tested if nothing else matches + create /file + + # Windows-specific test. + windows: + write /file + +You can specify multiple platforms with a comma (e.g. "windows, linux:"). +"kqueue" is a shortcut for all kqueue systems (BSD, macOS). + + +[goon]: https://github.com/arp242/goon +[Vagrant]: https://www.vagrantup.com/ +[integration_test.go]: /integration_test.go diff --git a/vendor/github.com/fsnotify/fsnotify/LICENSE b/vendor/github.com/fsnotify/fsnotify/LICENSE new file mode 100644 index 0000000..fb03ade --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/LICENSE @@ -0,0 +1,25 @@ +Copyright © 2012 The Go Authors. All rights reserved. +Copyright © fsnotify Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. +* Neither the name of Google Inc. nor the names of its contributors may be used + to endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/fsnotify/fsnotify/README.md b/vendor/github.com/fsnotify/fsnotify/README.md new file mode 100644 index 0000000..e480733 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/README.md @@ -0,0 +1,184 @@ +fsnotify is a Go library to provide cross-platform filesystem notifications on +Windows, Linux, macOS, BSD, and illumos. + +Go 1.17 or newer is required; the full documentation is at +https://pkg.go.dev/github.com/fsnotify/fsnotify + +--- + +Platform support: + +| Backend | OS | Status | +| :-------------------- | :--------- | :------------------------------------------------------------------------ | +| inotify | Linux | Supported | +| kqueue | BSD, macOS | Supported | +| ReadDirectoryChangesW | Windows | Supported | +| FEN | illumos | Supported | +| fanotify | Linux 5.9+ | [Not yet](https://github.com/fsnotify/fsnotify/issues/114) | +| AHAFS | AIX | [aix branch]; experimental due to lack of maintainer and test environment | +| FSEvents | macOS | [Needs support in x/sys/unix][fsevents] | +| USN Journals | Windows | [Needs support in x/sys/windows][usn] | +| Polling | *All* | [Not yet](https://github.com/fsnotify/fsnotify/issues/9) | + +Linux and illumos should include Android and Solaris, but these are currently +untested. + +[fsevents]: https://github.com/fsnotify/fsnotify/issues/11#issuecomment-1279133120 +[usn]: https://github.com/fsnotify/fsnotify/issues/53#issuecomment-1279829847 +[aix branch]: https://github.com/fsnotify/fsnotify/issues/353#issuecomment-1284590129 + +Usage +----- +A basic example: + +```go +package main + +import ( + "log" + + "github.com/fsnotify/fsnotify" +) + +func main() { + // Create new watcher. + watcher, err := fsnotify.NewWatcher() + if err != nil { + log.Fatal(err) + } + defer watcher.Close() + + // Start listening for events. + go func() { + for { + select { + case event, ok := <-watcher.Events: + if !ok { + return + } + log.Println("event:", event) + if event.Has(fsnotify.Write) { + log.Println("modified file:", event.Name) + } + case err, ok := <-watcher.Errors: + if !ok { + return + } + log.Println("error:", err) + } + } + }() + + // Add a path. + err = watcher.Add("/tmp") + if err != nil { + log.Fatal(err) + } + + // Block main goroutine forever. + <-make(chan struct{}) +} +``` + +Some more examples can be found in [cmd/fsnotify](cmd/fsnotify), which can be +run with: + + % go run ./cmd/fsnotify + +Further detailed documentation can be found in godoc: +https://pkg.go.dev/github.com/fsnotify/fsnotify + +FAQ +--- +### Will a file still be watched when it's moved to another directory? +No, not unless you are watching the location it was moved to. + +### Are subdirectories watched? +No, you must add watches for any directory you want to watch (a recursive +watcher is on the roadmap: [#18]). + +[#18]: https://github.com/fsnotify/fsnotify/issues/18 + +### Do I have to watch the Error and Event channels in a goroutine? +Yes. You can read both channels in the same goroutine using `select` (you don't +need a separate goroutine for both channels; see the example). + +### Why don't notifications work with NFS, SMB, FUSE, /proc, or /sys? +fsnotify requires support from underlying OS to work. The current NFS and SMB +protocols does not provide network level support for file notifications, and +neither do the /proc and /sys virtual filesystems. + +This could be fixed with a polling watcher ([#9]), but it's not yet implemented. + +[#9]: https://github.com/fsnotify/fsnotify/issues/9 + +### Why do I get many Chmod events? +Some programs may generate a lot of attribute changes; for example Spotlight on +macOS, anti-virus programs, backup applications, and some others are known to do +this. As a rule, it's typically best to ignore Chmod events. They're often not +useful, and tend to cause problems. + +Spotlight indexing on macOS can result in multiple events (see [#15]). A +temporary workaround is to add your folder(s) to the *Spotlight Privacy +settings* until we have a native FSEvents implementation (see [#11]). + +[#11]: https://github.com/fsnotify/fsnotify/issues/11 +[#15]: https://github.com/fsnotify/fsnotify/issues/15 + +### Watching a file doesn't work well +Watching individual files (rather than directories) is generally not recommended +as many programs (especially editors) update files atomically: it will write to +a temporary file which is then moved to to destination, overwriting the original +(or some variant thereof). The watcher on the original file is now lost, as that +no longer exists. + +The upshot of this is that a power failure or crash won't leave a half-written +file. + +Watch the parent directory and use `Event.Name` to filter out files you're not +interested in. There is an example of this in `cmd/fsnotify/file.go`. + +Platform-specific notes +----------------------- +### Linux +When a file is removed a REMOVE event won't be emitted until all file +descriptors are closed; it will emit a CHMOD instead: + + fp := os.Open("file") + os.Remove("file") // CHMOD + fp.Close() // REMOVE + +This is the event that inotify sends, so not much can be changed about this. + +The `fs.inotify.max_user_watches` sysctl variable specifies the upper limit for +the number of watches per user, and `fs.inotify.max_user_instances` specifies +the maximum number of inotify instances per user. Every Watcher you create is an +"instance", and every path you add is a "watch". + +These are also exposed in `/proc` as `/proc/sys/fs/inotify/max_user_watches` and +`/proc/sys/fs/inotify/max_user_instances` + +To increase them you can use `sysctl` or write the value to proc file: + + # The default values on Linux 5.18 + sysctl fs.inotify.max_user_watches=124983 + sysctl fs.inotify.max_user_instances=128 + +To make the changes persist on reboot edit `/etc/sysctl.conf` or +`/usr/lib/sysctl.d/50-default.conf` (details differ per Linux distro; check your +distro's documentation): + + fs.inotify.max_user_watches=124983 + fs.inotify.max_user_instances=128 + +Reaching the limit will result in a "no space left on device" or "too many open +files" error. + +### kqueue (macOS, all BSD systems) +kqueue requires opening a file descriptor for every file that's being watched; +so if you're watching a directory with five files then that's six file +descriptors. You will run in to your system's "max open files" limit faster on +these platforms. + +The sysctl variables `kern.maxfiles` and `kern.maxfilesperproc` can be used to +control the maximum number of open files. diff --git a/vendor/github.com/fsnotify/fsnotify/backend_fen.go b/vendor/github.com/fsnotify/fsnotify/backend_fen.go new file mode 100644 index 0000000..c349c32 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/backend_fen.go @@ -0,0 +1,484 @@ +//go:build solaris + +// FEN backend for illumos (supported) and Solaris (untested, but should work). +// +// See port_create(3c) etc. for docs. https://www.illumos.org/man/3C/port_create + +package fsnotify + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "sync" + "time" + + "github.com/fsnotify/fsnotify/internal" + "golang.org/x/sys/unix" +) + +type fen struct { + Events chan Event + Errors chan error + + mu sync.Mutex + port *unix.EventPort + done chan struct{} // Channel for sending a "quit message" to the reader goroutine + dirs map[string]Op // Explicitly watched directories + watches map[string]Op // Explicitly watched non-directories +} + +func newBackend(ev chan Event, errs chan error) (backend, error) { + return newBufferedBackend(0, ev, errs) +} + +func newBufferedBackend(sz uint, ev chan Event, errs chan error) (backend, error) { + w := &fen{ + Events: ev, + Errors: errs, + dirs: make(map[string]Op), + watches: make(map[string]Op), + done: make(chan struct{}), + } + + var err error + w.port, err = unix.NewEventPort() + if err != nil { + return nil, fmt.Errorf("fsnotify.NewWatcher: %w", err) + } + + go w.readEvents() + return w, nil +} + +// sendEvent attempts to send an event to the user, returning true if the event +// was put in the channel successfully and false if the watcher has been closed. +func (w *fen) sendEvent(name string, op Op) (sent bool) { + select { + case <-w.done: + return false + case w.Events <- Event{Name: name, Op: op}: + return true + } +} + +// sendError attempts to send an error to the user, returning true if the error +// was put in the channel successfully and false if the watcher has been closed. +func (w *fen) sendError(err error) (sent bool) { + if err == nil { + return true + } + select { + case <-w.done: + return false + case w.Errors <- err: + return true + } +} + +func (w *fen) isClosed() bool { + select { + case <-w.done: + return true + default: + return false + } +} + +func (w *fen) Close() error { + // Take the lock used by associateFile to prevent lingering events from + // being processed after the close + w.mu.Lock() + defer w.mu.Unlock() + if w.isClosed() { + return nil + } + close(w.done) + return w.port.Close() +} + +func (w *fen) Add(name string) error { return w.AddWith(name) } + +func (w *fen) AddWith(name string, opts ...addOpt) error { + if w.isClosed() { + return ErrClosed + } + if debug { + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s AddWith(%q)\n", + time.Now().Format("15:04:05.000000000"), name) + } + + with := getOptions(opts...) + if !w.xSupports(with.op) { + return fmt.Errorf("%w: %s", xErrUnsupported, with.op) + } + + // Currently we resolve symlinks that were explicitly requested to be + // watched. Otherwise we would use LStat here. + stat, err := os.Stat(name) + if err != nil { + return err + } + + // Associate all files in the directory. + if stat.IsDir() { + err := w.handleDirectory(name, stat, true, w.associateFile) + if err != nil { + return err + } + + w.mu.Lock() + w.dirs[name] = with.op + w.mu.Unlock() + return nil + } + + err = w.associateFile(name, stat, true) + if err != nil { + return err + } + + w.mu.Lock() + w.watches[name] = with.op + w.mu.Unlock() + return nil +} + +func (w *fen) Remove(name string) error { + if w.isClosed() { + return nil + } + if !w.port.PathIsWatched(name) { + return fmt.Errorf("%w: %s", ErrNonExistentWatch, name) + } + if debug { + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s Remove(%q)\n", + time.Now().Format("15:04:05.000000000"), name) + } + + // The user has expressed an intent. Immediately remove this name from + // whichever watch list it might be in. If it's not in there the delete + // doesn't cause harm. + w.mu.Lock() + delete(w.watches, name) + delete(w.dirs, name) + w.mu.Unlock() + + stat, err := os.Stat(name) + if err != nil { + return err + } + + // Remove associations for every file in the directory. + if stat.IsDir() { + err := w.handleDirectory(name, stat, false, w.dissociateFile) + if err != nil { + return err + } + return nil + } + + err = w.port.DissociatePath(name) + if err != nil { + return err + } + + return nil +} + +// readEvents contains the main loop that runs in a goroutine watching for events. +func (w *fen) readEvents() { + // If this function returns, the watcher has been closed and we can close + // these channels + defer func() { + close(w.Errors) + close(w.Events) + }() + + pevents := make([]unix.PortEvent, 8) + for { + count, err := w.port.Get(pevents, 1, nil) + if err != nil && err != unix.ETIME { + // Interrupted system call (count should be 0) ignore and continue + if errors.Is(err, unix.EINTR) && count == 0 { + continue + } + // Get failed because we called w.Close() + if errors.Is(err, unix.EBADF) && w.isClosed() { + return + } + // There was an error not caused by calling w.Close() + if !w.sendError(err) { + return + } + } + + p := pevents[:count] + for _, pevent := range p { + if pevent.Source != unix.PORT_SOURCE_FILE { + // Event from unexpected source received; should never happen. + if !w.sendError(errors.New("Event from unexpected source received")) { + return + } + continue + } + + if debug { + internal.Debug(pevent.Path, pevent.Events) + } + + err = w.handleEvent(&pevent) + if !w.sendError(err) { + return + } + } + } +} + +func (w *fen) handleDirectory(path string, stat os.FileInfo, follow bool, handler func(string, os.FileInfo, bool) error) error { + files, err := os.ReadDir(path) + if err != nil { + return err + } + + // Handle all children of the directory. + for _, entry := range files { + finfo, err := entry.Info() + if err != nil { + return err + } + err = handler(filepath.Join(path, finfo.Name()), finfo, false) + if err != nil { + return err + } + } + + // And finally handle the directory itself. + return handler(path, stat, follow) +} + +// handleEvent might need to emit more than one fsnotify event if the events +// bitmap matches more than one event type (e.g. the file was both modified and +// had the attributes changed between when the association was created and the +// when event was returned) +func (w *fen) handleEvent(event *unix.PortEvent) error { + var ( + events = event.Events + path = event.Path + fmode = event.Cookie.(os.FileMode) + reRegister = true + ) + + w.mu.Lock() + _, watchedDir := w.dirs[path] + _, watchedPath := w.watches[path] + w.mu.Unlock() + isWatched := watchedDir || watchedPath + + if events&unix.FILE_DELETE != 0 { + if !w.sendEvent(path, Remove) { + return nil + } + reRegister = false + } + if events&unix.FILE_RENAME_FROM != 0 { + if !w.sendEvent(path, Rename) { + return nil + } + // Don't keep watching the new file name + reRegister = false + } + if events&unix.FILE_RENAME_TO != 0 { + // We don't report a Rename event for this case, because Rename events + // are interpreted as referring to the _old_ name of the file, and in + // this case the event would refer to the new name of the file. This + // type of rename event is not supported by fsnotify. + + // inotify reports a Remove event in this case, so we simulate this + // here. + if !w.sendEvent(path, Remove) { + return nil + } + // Don't keep watching the file that was removed + reRegister = false + } + + // The file is gone, nothing left to do. + if !reRegister { + if watchedDir { + w.mu.Lock() + delete(w.dirs, path) + w.mu.Unlock() + } + if watchedPath { + w.mu.Lock() + delete(w.watches, path) + w.mu.Unlock() + } + return nil + } + + // If we didn't get a deletion the file still exists and we're going to have + // to watch it again. Let's Stat it now so that we can compare permissions + // and have what we need to continue watching the file + + stat, err := os.Lstat(path) + if err != nil { + // This is unexpected, but we should still emit an event. This happens + // most often on "rm -r" of a subdirectory inside a watched directory We + // get a modify event of something happening inside, but by the time we + // get here, the sudirectory is already gone. Clearly we were watching + // this path but now it is gone. Let's tell the user that it was + // removed. + if !w.sendEvent(path, Remove) { + return nil + } + // Suppress extra write events on removed directories; they are not + // informative and can be confusing. + return nil + } + + // resolve symlinks that were explicitly watched as we would have at Add() + // time. this helps suppress spurious Chmod events on watched symlinks + if isWatched { + stat, err = os.Stat(path) + if err != nil { + // The symlink still exists, but the target is gone. Report the + // Remove similar to above. + if !w.sendEvent(path, Remove) { + return nil + } + // Don't return the error + } + } + + if events&unix.FILE_MODIFIED != 0 { + if fmode.IsDir() && watchedDir { + if err := w.updateDirectory(path); err != nil { + return err + } + } else { + if !w.sendEvent(path, Write) { + return nil + } + } + } + if events&unix.FILE_ATTRIB != 0 && stat != nil { + // Only send Chmod if perms changed + if stat.Mode().Perm() != fmode.Perm() { + if !w.sendEvent(path, Chmod) { + return nil + } + } + } + + if stat != nil { + // If we get here, it means we've hit an event above that requires us to + // continue watching the file or directory + return w.associateFile(path, stat, isWatched) + } + return nil +} + +func (w *fen) updateDirectory(path string) error { + // The directory was modified, so we must find unwatched entities and watch + // them. If something was removed from the directory, nothing will happen, + // as everything else should still be watched. + files, err := os.ReadDir(path) + if err != nil { + return err + } + + for _, entry := range files { + path := filepath.Join(path, entry.Name()) + if w.port.PathIsWatched(path) { + continue + } + + finfo, err := entry.Info() + if err != nil { + return err + } + err = w.associateFile(path, finfo, false) + if !w.sendError(err) { + return nil + } + if !w.sendEvent(path, Create) { + return nil + } + } + return nil +} + +func (w *fen) associateFile(path string, stat os.FileInfo, follow bool) error { + if w.isClosed() { + return ErrClosed + } + // This is primarily protecting the call to AssociatePath but it is + // important and intentional that the call to PathIsWatched is also + // protected by this mutex. Without this mutex, AssociatePath has been seen + // to error out that the path is already associated. + w.mu.Lock() + defer w.mu.Unlock() + + if w.port.PathIsWatched(path) { + // Remove the old association in favor of this one If we get ENOENT, + // then while the x/sys/unix wrapper still thought that this path was + // associated, the underlying event port did not. This call will have + // cleared up that discrepancy. The most likely cause is that the event + // has fired but we haven't processed it yet. + err := w.port.DissociatePath(path) + if err != nil && !errors.Is(err, unix.ENOENT) { + return err + } + } + + var events int + if !follow { + // Watch symlinks themselves rather than their targets unless this entry + // is explicitly watched. + events |= unix.FILE_NOFOLLOW + } + if true { // TODO: implement withOps() + events |= unix.FILE_MODIFIED + } + if true { + events |= unix.FILE_ATTRIB + } + return w.port.AssociatePath(path, stat, events, stat.Mode()) +} + +func (w *fen) dissociateFile(path string, stat os.FileInfo, unused bool) error { + if !w.port.PathIsWatched(path) { + return nil + } + return w.port.DissociatePath(path) +} + +func (w *fen) WatchList() []string { + if w.isClosed() { + return nil + } + + w.mu.Lock() + defer w.mu.Unlock() + + entries := make([]string, 0, len(w.watches)+len(w.dirs)) + for pathname := range w.dirs { + entries = append(entries, pathname) + } + for pathname := range w.watches { + entries = append(entries, pathname) + } + + return entries +} + +func (w *fen) xSupports(op Op) bool { + if op.Has(xUnportableOpen) || op.Has(xUnportableRead) || + op.Has(xUnportableCloseWrite) || op.Has(xUnportableCloseRead) { + return false + } + return true +} diff --git a/vendor/github.com/fsnotify/fsnotify/backend_inotify.go b/vendor/github.com/fsnotify/fsnotify/backend_inotify.go new file mode 100644 index 0000000..36c3116 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/backend_inotify.go @@ -0,0 +1,658 @@ +//go:build linux && !appengine + +package fsnotify + +import ( + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "strings" + "sync" + "time" + "unsafe" + + "github.com/fsnotify/fsnotify/internal" + "golang.org/x/sys/unix" +) + +type inotify struct { + Events chan Event + Errors chan error + + // Store fd here as os.File.Read() will no longer return on close after + // calling Fd(). See: https://github.com/golang/go/issues/26439 + fd int + inotifyFile *os.File + watches *watches + done chan struct{} // Channel for sending a "quit message" to the reader goroutine + doneMu sync.Mutex + doneResp chan struct{} // Channel to respond to Close + + // Store rename cookies in an array, with the index wrapping to 0. Almost + // all of the time what we get is a MOVED_FROM to set the cookie and the + // next event inotify sends will be MOVED_TO to read it. However, this is + // not guaranteed – as described in inotify(7) – and we may get other events + // between the two MOVED_* events (including other MOVED_* ones). + // + // A second issue is that moving a file outside the watched directory will + // trigger a MOVED_FROM to set the cookie, but we never see the MOVED_TO to + // read and delete it. So just storing it in a map would slowly leak memory. + // + // Doing it like this gives us a simple fast LRU-cache that won't allocate. + // Ten items should be more than enough for our purpose, and a loop over + // such a short array is faster than a map access anyway (not that it hugely + // matters since we're talking about hundreds of ns at the most, but still). + cookies [10]koekje + cookieIndex uint8 + cookiesMu sync.Mutex +} + +type ( + watches struct { + mu sync.RWMutex + wd map[uint32]*watch // wd → watch + path map[string]uint32 // pathname → wd + } + watch struct { + wd uint32 // Watch descriptor (as returned by the inotify_add_watch() syscall) + flags uint32 // inotify flags of this watch (see inotify(7) for the list of valid flags) + path string // Watch path. + recurse bool // Recursion with ./...? + } + koekje struct { + cookie uint32 + path string + } +) + +func newWatches() *watches { + return &watches{ + wd: make(map[uint32]*watch), + path: make(map[string]uint32), + } +} + +func (w *watches) len() int { + w.mu.RLock() + defer w.mu.RUnlock() + return len(w.wd) +} + +func (w *watches) add(ww *watch) { + w.mu.Lock() + defer w.mu.Unlock() + w.wd[ww.wd] = ww + w.path[ww.path] = ww.wd +} + +func (w *watches) remove(wd uint32) { + w.mu.Lock() + defer w.mu.Unlock() + watch := w.wd[wd] // Could have had Remove() called. See #616. + if watch == nil { + return + } + delete(w.path, watch.path) + delete(w.wd, wd) +} + +func (w *watches) removePath(path string) ([]uint32, error) { + w.mu.Lock() + defer w.mu.Unlock() + + path, recurse := recursivePath(path) + wd, ok := w.path[path] + if !ok { + return nil, fmt.Errorf("%w: %s", ErrNonExistentWatch, path) + } + + watch := w.wd[wd] + if recurse && !watch.recurse { + return nil, fmt.Errorf("can't use /... with non-recursive watch %q", path) + } + + delete(w.path, path) + delete(w.wd, wd) + if !watch.recurse { + return []uint32{wd}, nil + } + + wds := make([]uint32, 0, 8) + wds = append(wds, wd) + for p, rwd := range w.path { + if filepath.HasPrefix(p, path) { + delete(w.path, p) + delete(w.wd, rwd) + wds = append(wds, rwd) + } + } + return wds, nil +} + +func (w *watches) byPath(path string) *watch { + w.mu.RLock() + defer w.mu.RUnlock() + return w.wd[w.path[path]] +} + +func (w *watches) byWd(wd uint32) *watch { + w.mu.RLock() + defer w.mu.RUnlock() + return w.wd[wd] +} + +func (w *watches) updatePath(path string, f func(*watch) (*watch, error)) error { + w.mu.Lock() + defer w.mu.Unlock() + + var existing *watch + wd, ok := w.path[path] + if ok { + existing = w.wd[wd] + } + + upd, err := f(existing) + if err != nil { + return err + } + if upd != nil { + w.wd[upd.wd] = upd + w.path[upd.path] = upd.wd + + if upd.wd != wd { + delete(w.wd, wd) + } + } + + return nil +} + +func newBackend(ev chan Event, errs chan error) (backend, error) { + return newBufferedBackend(0, ev, errs) +} + +func newBufferedBackend(sz uint, ev chan Event, errs chan error) (backend, error) { + // Need to set nonblocking mode for SetDeadline to work, otherwise blocking + // I/O operations won't terminate on close. + fd, errno := unix.InotifyInit1(unix.IN_CLOEXEC | unix.IN_NONBLOCK) + if fd == -1 { + return nil, errno + } + + w := &inotify{ + Events: ev, + Errors: errs, + fd: fd, + inotifyFile: os.NewFile(uintptr(fd), ""), + watches: newWatches(), + done: make(chan struct{}), + doneResp: make(chan struct{}), + } + + go w.readEvents() + return w, nil +} + +// Returns true if the event was sent, or false if watcher is closed. +func (w *inotify) sendEvent(e Event) bool { + select { + case <-w.done: + return false + case w.Events <- e: + return true + } +} + +// Returns true if the error was sent, or false if watcher is closed. +func (w *inotify) sendError(err error) bool { + if err == nil { + return true + } + select { + case <-w.done: + return false + case w.Errors <- err: + return true + } +} + +func (w *inotify) isClosed() bool { + select { + case <-w.done: + return true + default: + return false + } +} + +func (w *inotify) Close() error { + w.doneMu.Lock() + if w.isClosed() { + w.doneMu.Unlock() + return nil + } + close(w.done) + w.doneMu.Unlock() + + // Causes any blocking reads to return with an error, provided the file + // still supports deadline operations. + err := w.inotifyFile.Close() + if err != nil { + return err + } + + // Wait for goroutine to close + <-w.doneResp + + return nil +} + +func (w *inotify) Add(name string) error { return w.AddWith(name) } + +func (w *inotify) AddWith(path string, opts ...addOpt) error { + if w.isClosed() { + return ErrClosed + } + if debug { + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s AddWith(%q)\n", + time.Now().Format("15:04:05.000000000"), path) + } + + with := getOptions(opts...) + if !w.xSupports(with.op) { + return fmt.Errorf("%w: %s", xErrUnsupported, with.op) + } + + path, recurse := recursivePath(path) + if recurse { + return filepath.WalkDir(path, func(root string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if !d.IsDir() { + if root == path { + return fmt.Errorf("fsnotify: not a directory: %q", path) + } + return nil + } + + // Send a Create event when adding new directory from a recursive + // watch; this is for "mkdir -p one/two/three". Usually all those + // directories will be created before we can set up watchers on the + // subdirectories, so only "one" would be sent as a Create event and + // not "one/two" and "one/two/three" (inotifywait -r has the same + // problem). + if with.sendCreate && root != path { + w.sendEvent(Event{Name: root, Op: Create}) + } + + return w.add(root, with, true) + }) + } + + return w.add(path, with, false) +} + +func (w *inotify) add(path string, with withOpts, recurse bool) error { + var flags uint32 + if with.noFollow { + flags |= unix.IN_DONT_FOLLOW + } + if with.op.Has(Create) { + flags |= unix.IN_CREATE + } + if with.op.Has(Write) { + flags |= unix.IN_MODIFY + } + if with.op.Has(Remove) { + flags |= unix.IN_DELETE | unix.IN_DELETE_SELF + } + if with.op.Has(Rename) { + flags |= unix.IN_MOVED_TO | unix.IN_MOVED_FROM | unix.IN_MOVE_SELF + } + if with.op.Has(Chmod) { + flags |= unix.IN_ATTRIB + } + if with.op.Has(xUnportableOpen) { + flags |= unix.IN_OPEN + } + if with.op.Has(xUnportableRead) { + flags |= unix.IN_ACCESS + } + if with.op.Has(xUnportableCloseWrite) { + flags |= unix.IN_CLOSE_WRITE + } + if with.op.Has(xUnportableCloseRead) { + flags |= unix.IN_CLOSE_NOWRITE + } + return w.register(path, flags, recurse) +} + +func (w *inotify) register(path string, flags uint32, recurse bool) error { + return w.watches.updatePath(path, func(existing *watch) (*watch, error) { + if existing != nil { + flags |= existing.flags | unix.IN_MASK_ADD + } + + wd, err := unix.InotifyAddWatch(w.fd, path, flags) + if wd == -1 { + return nil, err + } + + if existing == nil { + return &watch{ + wd: uint32(wd), + path: path, + flags: flags, + recurse: recurse, + }, nil + } + + existing.wd = uint32(wd) + existing.flags = flags + return existing, nil + }) +} + +func (w *inotify) Remove(name string) error { + if w.isClosed() { + return nil + } + if debug { + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s Remove(%q)\n", + time.Now().Format("15:04:05.000000000"), name) + } + return w.remove(filepath.Clean(name)) +} + +func (w *inotify) remove(name string) error { + wds, err := w.watches.removePath(name) + if err != nil { + return err + } + + for _, wd := range wds { + _, err := unix.InotifyRmWatch(w.fd, wd) + if err != nil { + // TODO: Perhaps it's not helpful to return an error here in every + // case; the only two possible errors are: + // + // EBADF, which happens when w.fd is not a valid file descriptor of + // any kind. + // + // EINVAL, which is when fd is not an inotify descriptor or wd is + // not a valid watch descriptor. Watch descriptors are invalidated + // when they are removed explicitly or implicitly; explicitly by + // inotify_rm_watch, implicitly when the file they are watching is + // deleted. + return err + } + } + return nil +} + +func (w *inotify) WatchList() []string { + if w.isClosed() { + return nil + } + + entries := make([]string, 0, w.watches.len()) + w.watches.mu.RLock() + for pathname := range w.watches.path { + entries = append(entries, pathname) + } + w.watches.mu.RUnlock() + + return entries +} + +// readEvents reads from the inotify file descriptor, converts the +// received events into Event objects and sends them via the Events channel +func (w *inotify) readEvents() { + defer func() { + close(w.doneResp) + close(w.Errors) + close(w.Events) + }() + + var ( + buf [unix.SizeofInotifyEvent * 4096]byte // Buffer for a maximum of 4096 raw events + errno error // Syscall errno + ) + for { + // See if we have been closed. + if w.isClosed() { + return + } + + n, err := w.inotifyFile.Read(buf[:]) + switch { + case errors.Unwrap(err) == os.ErrClosed: + return + case err != nil: + if !w.sendError(err) { + return + } + continue + } + + if n < unix.SizeofInotifyEvent { + var err error + if n == 0 { + err = io.EOF // If EOF is received. This should really never happen. + } else if n < 0 { + err = errno // If an error occurred while reading. + } else { + err = errors.New("notify: short read in readEvents()") // Read was too short. + } + if !w.sendError(err) { + return + } + continue + } + + // We don't know how many events we just read into the buffer + // While the offset points to at least one whole event... + var offset uint32 + for offset <= uint32(n-unix.SizeofInotifyEvent) { + var ( + // Point "raw" to the event in the buffer + raw = (*unix.InotifyEvent)(unsafe.Pointer(&buf[offset])) + mask = uint32(raw.Mask) + nameLen = uint32(raw.Len) + // Move to the next event in the buffer + next = func() { offset += unix.SizeofInotifyEvent + nameLen } + ) + + if mask&unix.IN_Q_OVERFLOW != 0 { + if !w.sendError(ErrEventOverflow) { + return + } + } + + /// If the event happened to the watched directory or the watched + /// file, the kernel doesn't append the filename to the event, but + /// we would like to always fill the the "Name" field with a valid + /// filename. We retrieve the path of the watch from the "paths" + /// map. + watch := w.watches.byWd(uint32(raw.Wd)) + /// Can be nil if Remove() was called in another goroutine for this + /// path inbetween reading the events from the kernel and reading + /// the internal state. Not much we can do about it, so just skip. + /// See #616. + if watch == nil { + next() + continue + } + + name := watch.path + if nameLen > 0 { + /// Point "bytes" at the first byte of the filename + bytes := (*[unix.PathMax]byte)(unsafe.Pointer(&buf[offset+unix.SizeofInotifyEvent]))[:nameLen:nameLen] + /// The filename is padded with NULL bytes. TrimRight() gets rid of those. + name += "/" + strings.TrimRight(string(bytes[0:nameLen]), "\000") + } + + if debug { + internal.Debug(name, raw.Mask, raw.Cookie) + } + + if mask&unix.IN_IGNORED != 0 { //&& event.Op != 0 + next() + continue + } + + // inotify will automatically remove the watch on deletes; just need + // to clean our state here. + if mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF { + w.watches.remove(watch.wd) + } + + // We can't really update the state when a watched path is moved; + // only IN_MOVE_SELF is sent and not IN_MOVED_{FROM,TO}. So remove + // the watch. + if mask&unix.IN_MOVE_SELF == unix.IN_MOVE_SELF { + if watch.recurse { + next() // Do nothing + continue + } + + err := w.remove(watch.path) + if err != nil && !errors.Is(err, ErrNonExistentWatch) { + if !w.sendError(err) { + return + } + } + } + + /// Skip if we're watching both this path and the parent; the parent + /// will already send a delete so no need to do it twice. + if mask&unix.IN_DELETE_SELF != 0 { + if _, ok := w.watches.path[filepath.Dir(watch.path)]; ok { + next() + continue + } + } + + ev := w.newEvent(name, mask, raw.Cookie) + // Need to update watch path for recurse. + if watch.recurse { + isDir := mask&unix.IN_ISDIR == unix.IN_ISDIR + /// New directory created: set up watch on it. + if isDir && ev.Has(Create) { + err := w.register(ev.Name, watch.flags, true) + if !w.sendError(err) { + return + } + + // This was a directory rename, so we need to update all + // the children. + // + // TODO: this is of course pretty slow; we should use a + // better data structure for storing all of this, e.g. store + // children in the watch. I have some code for this in my + // kqueue refactor we can use in the future. For now I'm + // okay with this as it's not publicly available. + // Correctness first, performance second. + if ev.renamedFrom != "" { + w.watches.mu.Lock() + for k, ww := range w.watches.wd { + if k == watch.wd || ww.path == ev.Name { + continue + } + if strings.HasPrefix(ww.path, ev.renamedFrom) { + ww.path = strings.Replace(ww.path, ev.renamedFrom, ev.Name, 1) + w.watches.wd[k] = ww + } + } + w.watches.mu.Unlock() + } + } + } + + /// Send the events that are not ignored on the events channel + if !w.sendEvent(ev) { + return + } + next() + } + } +} + +func (w *inotify) isRecursive(path string) bool { + ww := w.watches.byPath(path) + if ww == nil { // path could be a file, so also check the Dir. + ww = w.watches.byPath(filepath.Dir(path)) + } + return ww != nil && ww.recurse +} + +func (w *inotify) newEvent(name string, mask, cookie uint32) Event { + e := Event{Name: name} + if mask&unix.IN_CREATE == unix.IN_CREATE || mask&unix.IN_MOVED_TO == unix.IN_MOVED_TO { + e.Op |= Create + } + if mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF || mask&unix.IN_DELETE == unix.IN_DELETE { + e.Op |= Remove + } + if mask&unix.IN_MODIFY == unix.IN_MODIFY { + e.Op |= Write + } + if mask&unix.IN_OPEN == unix.IN_OPEN { + e.Op |= xUnportableOpen + } + if mask&unix.IN_ACCESS == unix.IN_ACCESS { + e.Op |= xUnportableRead + } + if mask&unix.IN_CLOSE_WRITE == unix.IN_CLOSE_WRITE { + e.Op |= xUnportableCloseWrite + } + if mask&unix.IN_CLOSE_NOWRITE == unix.IN_CLOSE_NOWRITE { + e.Op |= xUnportableCloseRead + } + if mask&unix.IN_MOVE_SELF == unix.IN_MOVE_SELF || mask&unix.IN_MOVED_FROM == unix.IN_MOVED_FROM { + e.Op |= Rename + } + if mask&unix.IN_ATTRIB == unix.IN_ATTRIB { + e.Op |= Chmod + } + + if cookie != 0 { + if mask&unix.IN_MOVED_FROM == unix.IN_MOVED_FROM { + w.cookiesMu.Lock() + w.cookies[w.cookieIndex] = koekje{cookie: cookie, path: e.Name} + w.cookieIndex++ + if w.cookieIndex > 9 { + w.cookieIndex = 0 + } + w.cookiesMu.Unlock() + } else if mask&unix.IN_MOVED_TO == unix.IN_MOVED_TO { + w.cookiesMu.Lock() + var prev string + for _, c := range w.cookies { + if c.cookie == cookie { + prev = c.path + break + } + } + w.cookiesMu.Unlock() + e.renamedFrom = prev + } + } + return e +} + +func (w *inotify) xSupports(op Op) bool { + return true // Supports everything. +} + +func (w *inotify) state() { + w.watches.mu.Lock() + defer w.watches.mu.Unlock() + for wd, ww := range w.watches.wd { + fmt.Fprintf(os.Stderr, "%4d: recurse=%t %q\n", wd, ww.recurse, ww.path) + } +} diff --git a/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go b/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go new file mode 100644 index 0000000..d8de5ab --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go @@ -0,0 +1,733 @@ +//go:build freebsd || openbsd || netbsd || dragonfly || darwin + +package fsnotify + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "runtime" + "sync" + "time" + + "github.com/fsnotify/fsnotify/internal" + "golang.org/x/sys/unix" +) + +type kqueue struct { + Events chan Event + Errors chan error + + kq int // File descriptor (as returned by the kqueue() syscall). + closepipe [2]int // Pipe used for closing kq. + watches *watches + done chan struct{} + doneMu sync.Mutex +} + +type ( + watches struct { + mu sync.RWMutex + wd map[int]watch // wd → watch + path map[string]int // pathname → wd + byDir map[string]map[int]struct{} // dirname(path) → wd + seen map[string]struct{} // Keep track of if we know this file exists. + byUser map[string]struct{} // Watches added with Watcher.Add() + } + watch struct { + wd int + name string + linkName string // In case of links; name is the target, and this is the link. + isDir bool + dirFlags uint32 + } +) + +func newWatches() *watches { + return &watches{ + wd: make(map[int]watch), + path: make(map[string]int), + byDir: make(map[string]map[int]struct{}), + seen: make(map[string]struct{}), + byUser: make(map[string]struct{}), + } +} + +func (w *watches) listPaths(userOnly bool) []string { + w.mu.RLock() + defer w.mu.RUnlock() + + if userOnly { + l := make([]string, 0, len(w.byUser)) + for p := range w.byUser { + l = append(l, p) + } + return l + } + + l := make([]string, 0, len(w.path)) + for p := range w.path { + l = append(l, p) + } + return l +} + +func (w *watches) watchesInDir(path string) []string { + w.mu.RLock() + defer w.mu.RUnlock() + + l := make([]string, 0, 4) + for fd := range w.byDir[path] { + info := w.wd[fd] + if _, ok := w.byUser[info.name]; !ok { + l = append(l, info.name) + } + } + return l +} + +// Mark path as added by the user. +func (w *watches) addUserWatch(path string) { + w.mu.Lock() + defer w.mu.Unlock() + w.byUser[path] = struct{}{} +} + +func (w *watches) addLink(path string, fd int) { + w.mu.Lock() + defer w.mu.Unlock() + + w.path[path] = fd + w.seen[path] = struct{}{} +} + +func (w *watches) add(path, linkPath string, fd int, isDir bool) { + w.mu.Lock() + defer w.mu.Unlock() + + w.path[path] = fd + w.wd[fd] = watch{wd: fd, name: path, linkName: linkPath, isDir: isDir} + + parent := filepath.Dir(path) + byDir, ok := w.byDir[parent] + if !ok { + byDir = make(map[int]struct{}, 1) + w.byDir[parent] = byDir + } + byDir[fd] = struct{}{} +} + +func (w *watches) byWd(fd int) (watch, bool) { + w.mu.RLock() + defer w.mu.RUnlock() + info, ok := w.wd[fd] + return info, ok +} + +func (w *watches) byPath(path string) (watch, bool) { + w.mu.RLock() + defer w.mu.RUnlock() + info, ok := w.wd[w.path[path]] + return info, ok +} + +func (w *watches) updateDirFlags(path string, flags uint32) { + w.mu.Lock() + defer w.mu.Unlock() + + fd := w.path[path] + info := w.wd[fd] + info.dirFlags = flags + w.wd[fd] = info +} + +func (w *watches) remove(fd int, path string) bool { + w.mu.Lock() + defer w.mu.Unlock() + + isDir := w.wd[fd].isDir + delete(w.path, path) + delete(w.byUser, path) + + parent := filepath.Dir(path) + delete(w.byDir[parent], fd) + + if len(w.byDir[parent]) == 0 { + delete(w.byDir, parent) + } + + delete(w.wd, fd) + delete(w.seen, path) + return isDir +} + +func (w *watches) markSeen(path string, exists bool) { + w.mu.Lock() + defer w.mu.Unlock() + if exists { + w.seen[path] = struct{}{} + } else { + delete(w.seen, path) + } +} + +func (w *watches) seenBefore(path string) bool { + w.mu.RLock() + defer w.mu.RUnlock() + _, ok := w.seen[path] + return ok +} + +func newBackend(ev chan Event, errs chan error) (backend, error) { + return newBufferedBackend(0, ev, errs) +} + +func newBufferedBackend(sz uint, ev chan Event, errs chan error) (backend, error) { + kq, closepipe, err := newKqueue() + if err != nil { + return nil, err + } + + w := &kqueue{ + Events: ev, + Errors: errs, + kq: kq, + closepipe: closepipe, + done: make(chan struct{}), + watches: newWatches(), + } + + go w.readEvents() + return w, nil +} + +// newKqueue creates a new kernel event queue and returns a descriptor. +// +// This registers a new event on closepipe, which will trigger an event when +// it's closed. This way we can use kevent() without timeout/polling; without +// the closepipe, it would block forever and we wouldn't be able to stop it at +// all. +func newKqueue() (kq int, closepipe [2]int, err error) { + kq, err = unix.Kqueue() + if kq == -1 { + return kq, closepipe, err + } + + // Register the close pipe. + err = unix.Pipe(closepipe[:]) + if err != nil { + unix.Close(kq) + return kq, closepipe, err + } + unix.CloseOnExec(closepipe[0]) + unix.CloseOnExec(closepipe[1]) + + // Register changes to listen on the closepipe. + changes := make([]unix.Kevent_t, 1) + // SetKevent converts int to the platform-specific types. + unix.SetKevent(&changes[0], closepipe[0], unix.EVFILT_READ, + unix.EV_ADD|unix.EV_ENABLE|unix.EV_ONESHOT) + + ok, err := unix.Kevent(kq, changes, nil, nil) + if ok == -1 { + unix.Close(kq) + unix.Close(closepipe[0]) + unix.Close(closepipe[1]) + return kq, closepipe, err + } + return kq, closepipe, nil +} + +// Returns true if the event was sent, or false if watcher is closed. +func (w *kqueue) sendEvent(e Event) bool { + select { + case <-w.done: + return false + case w.Events <- e: + return true + } +} + +// Returns true if the error was sent, or false if watcher is closed. +func (w *kqueue) sendError(err error) bool { + if err == nil { + return true + } + select { + case <-w.done: + return false + case w.Errors <- err: + return true + } +} + +func (w *kqueue) isClosed() bool { + select { + case <-w.done: + return true + default: + return false + } +} + +func (w *kqueue) Close() error { + w.doneMu.Lock() + if w.isClosed() { + w.doneMu.Unlock() + return nil + } + close(w.done) + w.doneMu.Unlock() + + pathsToRemove := w.watches.listPaths(false) + for _, name := range pathsToRemove { + w.Remove(name) + } + + // Send "quit" message to the reader goroutine. + unix.Close(w.closepipe[1]) + return nil +} + +func (w *kqueue) Add(name string) error { return w.AddWith(name) } + +func (w *kqueue) AddWith(name string, opts ...addOpt) error { + if debug { + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s AddWith(%q)\n", + time.Now().Format("15:04:05.000000000"), name) + } + + with := getOptions(opts...) + if !w.xSupports(with.op) { + return fmt.Errorf("%w: %s", xErrUnsupported, with.op) + } + + _, err := w.addWatch(name, noteAllEvents) + if err != nil { + return err + } + w.watches.addUserWatch(name) + return nil +} + +func (w *kqueue) Remove(name string) error { + if debug { + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s Remove(%q)\n", + time.Now().Format("15:04:05.000000000"), name) + } + return w.remove(name, true) +} + +func (w *kqueue) remove(name string, unwatchFiles bool) error { + if w.isClosed() { + return nil + } + + name = filepath.Clean(name) + info, ok := w.watches.byPath(name) + if !ok { + return fmt.Errorf("%w: %s", ErrNonExistentWatch, name) + } + + err := w.register([]int{info.wd}, unix.EV_DELETE, 0) + if err != nil { + return err + } + + unix.Close(info.wd) + + isDir := w.watches.remove(info.wd, name) + + // Find all watched paths that are in this directory that are not external. + if unwatchFiles && isDir { + pathsToRemove := w.watches.watchesInDir(name) + for _, name := range pathsToRemove { + // Since these are internal, not much sense in propagating error to + // the user, as that will just confuse them with an error about a + // path they did not explicitly watch themselves. + w.Remove(name) + } + } + return nil +} + +func (w *kqueue) WatchList() []string { + if w.isClosed() { + return nil + } + return w.watches.listPaths(true) +} + +// Watch all events (except NOTE_EXTEND, NOTE_LINK, NOTE_REVOKE) +const noteAllEvents = unix.NOTE_DELETE | unix.NOTE_WRITE | unix.NOTE_ATTRIB | unix.NOTE_RENAME + +// addWatch adds name to the watched file set; the flags are interpreted as +// described in kevent(2). +// +// Returns the real path to the file which was added, with symlinks resolved. +func (w *kqueue) addWatch(name string, flags uint32) (string, error) { + if w.isClosed() { + return "", ErrClosed + } + + name = filepath.Clean(name) + + info, alreadyWatching := w.watches.byPath(name) + if !alreadyWatching { + fi, err := os.Lstat(name) + if err != nil { + return "", err + } + + // Don't watch sockets or named pipes. + if (fi.Mode()&os.ModeSocket == os.ModeSocket) || (fi.Mode()&os.ModeNamedPipe == os.ModeNamedPipe) { + return "", nil + } + + // Follow symlinks. + if fi.Mode()&os.ModeSymlink == os.ModeSymlink { + link, err := os.Readlink(name) + if err != nil { + // Return nil because Linux can add unresolvable symlinks to the + // watch list without problems, so maintain consistency with + // that. There will be no file events for broken symlinks. + // TODO: more specific check; returns os.PathError; ENOENT? + return "", nil + } + + _, alreadyWatching = w.watches.byPath(link) + if alreadyWatching { + // Add to watches so we don't get spurious Create events later + // on when we diff the directories. + w.watches.addLink(name, 0) + return link, nil + } + + info.linkName = name + name = link + fi, err = os.Lstat(name) + if err != nil { + return "", nil + } + } + + // Retry on EINTR; open() can return EINTR in practice on macOS. + // See #354, and Go issues 11180 and 39237. + for { + info.wd, err = unix.Open(name, openMode, 0) + if err == nil { + break + } + if errors.Is(err, unix.EINTR) { + continue + } + + return "", err + } + + info.isDir = fi.IsDir() + } + + err := w.register([]int{info.wd}, unix.EV_ADD|unix.EV_CLEAR|unix.EV_ENABLE, flags) + if err != nil { + unix.Close(info.wd) + return "", err + } + + if !alreadyWatching { + w.watches.add(name, info.linkName, info.wd, info.isDir) + } + + // Watch the directory if it has not been watched before, or if it was + // watched before, but perhaps only a NOTE_DELETE (watchDirectoryFiles) + if info.isDir { + watchDir := (flags&unix.NOTE_WRITE) == unix.NOTE_WRITE && + (!alreadyWatching || (info.dirFlags&unix.NOTE_WRITE) != unix.NOTE_WRITE) + w.watches.updateDirFlags(name, flags) + + if watchDir { + if err := w.watchDirectoryFiles(name); err != nil { + return "", err + } + } + } + return name, nil +} + +// readEvents reads from kqueue and converts the received kevents into +// Event values that it sends down the Events channel. +func (w *kqueue) readEvents() { + defer func() { + close(w.Events) + close(w.Errors) + _ = unix.Close(w.kq) + unix.Close(w.closepipe[0]) + }() + + eventBuffer := make([]unix.Kevent_t, 10) + for { + kevents, err := w.read(eventBuffer) + // EINTR is okay, the syscall was interrupted before timeout expired. + if err != nil && err != unix.EINTR { + if !w.sendError(fmt.Errorf("fsnotify.readEvents: %w", err)) { + return + } + } + + for _, kevent := range kevents { + var ( + wd = int(kevent.Ident) + mask = uint32(kevent.Fflags) + ) + + // Shut down the loop when the pipe is closed, but only after all + // other events have been processed. + if wd == w.closepipe[0] { + return + } + + path, ok := w.watches.byWd(wd) + if debug { + internal.Debug(path.name, &kevent) + } + + // On macOS it seems that sometimes an event with Ident=0 is + // delivered, and no other flags/information beyond that, even + // though we never saw such a file descriptor. For example in + // TestWatchSymlink/277 (usually at the end, but sometimes sooner): + // + // fmt.Printf("READ: %2d %#v\n", kevent.Ident, kevent) + // unix.Kevent_t{Ident:0x2a, Filter:-4, Flags:0x25, Fflags:0x2, Data:0, Udata:(*uint8)(nil)} + // unix.Kevent_t{Ident:0x0, Filter:-4, Flags:0x25, Fflags:0x2, Data:0, Udata:(*uint8)(nil)} + // + // The first is a normal event, the second with Ident 0. No error + // flag, no data, no ... nothing. + // + // I read a bit through bsd/kern_event.c from the xnu source, but I + // don't really see an obvious location where this is triggered – + // this doesn't seem intentional, but idk... + // + // Technically fd 0 is a valid descriptor, so only skip it if + // there's no path, and if we're on macOS. + if !ok && kevent.Ident == 0 && runtime.GOOS == "darwin" { + continue + } + + event := w.newEvent(path.name, path.linkName, mask) + + if event.Has(Rename) || event.Has(Remove) { + w.remove(event.Name, false) + w.watches.markSeen(event.Name, false) + } + + if path.isDir && event.Has(Write) && !event.Has(Remove) { + w.dirChange(event.Name) + } else if !w.sendEvent(event) { + return + } + + if event.Has(Remove) { + // Look for a file that may have overwritten this; for example, + // mv f1 f2 will delete f2, then create f2. + if path.isDir { + fileDir := filepath.Clean(event.Name) + _, found := w.watches.byPath(fileDir) + if found { + // TODO: this branch is never triggered in any test. + // Added in d6220df (2012). + // isDir check added in 8611c35 (2016): https://github.com/fsnotify/fsnotify/pull/111 + // + // I don't really get how this can be triggered either. + // And it wasn't triggered in the patch that added it, + // either. + // + // Original also had a comment: + // make sure the directory exists before we watch for + // changes. When we do a recursive watch and perform + // rm -rf, the parent directory might have gone + // missing, ignore the missing directory and let the + // upcoming delete event remove the watch from the + // parent directory. + err := w.dirChange(fileDir) + if !w.sendError(err) { + return + } + } + } else { + path := filepath.Clean(event.Name) + if fi, err := os.Lstat(path); err == nil { + err := w.sendCreateIfNew(path, fi) + if !w.sendError(err) { + return + } + } + } + } + } + } +} + +// newEvent returns an platform-independent Event based on kqueue Fflags. +func (w *kqueue) newEvent(name, linkName string, mask uint32) Event { + e := Event{Name: name} + if linkName != "" { + // If the user watched "/path/link" then emit events as "/path/link" + // rather than "/path/target". + e.Name = linkName + } + + if mask&unix.NOTE_DELETE == unix.NOTE_DELETE { + e.Op |= Remove + } + if mask&unix.NOTE_WRITE == unix.NOTE_WRITE { + e.Op |= Write + } + if mask&unix.NOTE_RENAME == unix.NOTE_RENAME { + e.Op |= Rename + } + if mask&unix.NOTE_ATTRIB == unix.NOTE_ATTRIB { + e.Op |= Chmod + } + // No point sending a write and delete event at the same time: if it's gone, + // then it's gone. + if e.Op.Has(Write) && e.Op.Has(Remove) { + e.Op &^= Write + } + return e +} + +// watchDirectoryFiles to mimic inotify when adding a watch on a directory +func (w *kqueue) watchDirectoryFiles(dirPath string) error { + files, err := os.ReadDir(dirPath) + if err != nil { + return err + } + + for _, f := range files { + path := filepath.Join(dirPath, f.Name()) + + fi, err := f.Info() + if err != nil { + return fmt.Errorf("%q: %w", path, err) + } + + cleanPath, err := w.internalWatch(path, fi) + if err != nil { + // No permission to read the file; that's not a problem: just skip. + // But do add it to w.fileExists to prevent it from being picked up + // as a "new" file later (it still shows up in the directory + // listing). + switch { + case errors.Is(err, unix.EACCES) || errors.Is(err, unix.EPERM): + cleanPath = filepath.Clean(path) + default: + return fmt.Errorf("%q: %w", path, err) + } + } + + w.watches.markSeen(cleanPath, true) + } + + return nil +} + +// Search the directory for new files and send an event for them. +// +// This functionality is to have the BSD watcher match the inotify, which sends +// a create event for files created in a watched directory. +func (w *kqueue) dirChange(dir string) error { + files, err := os.ReadDir(dir) + if err != nil { + // Directory no longer exists: we can ignore this safely. kqueue will + // still give us the correct events. + if errors.Is(err, os.ErrNotExist) { + return nil + } + return fmt.Errorf("fsnotify.dirChange: %w", err) + } + + for _, f := range files { + fi, err := f.Info() + if err != nil { + return fmt.Errorf("fsnotify.dirChange: %w", err) + } + + err = w.sendCreateIfNew(filepath.Join(dir, fi.Name()), fi) + if err != nil { + // Don't need to send an error if this file isn't readable. + if errors.Is(err, unix.EACCES) || errors.Is(err, unix.EPERM) { + return nil + } + return fmt.Errorf("fsnotify.dirChange: %w", err) + } + } + return nil +} + +// Send a create event if the file isn't already being tracked, and start +// watching this file. +func (w *kqueue) sendCreateIfNew(path string, fi os.FileInfo) error { + if !w.watches.seenBefore(path) { + if !w.sendEvent(Event{Name: path, Op: Create}) { + return nil + } + } + + // Like watchDirectoryFiles, but without doing another ReadDir. + path, err := w.internalWatch(path, fi) + if err != nil { + return err + } + w.watches.markSeen(path, true) + return nil +} + +func (w *kqueue) internalWatch(name string, fi os.FileInfo) (string, error) { + if fi.IsDir() { + // mimic Linux providing delete events for subdirectories, but preserve + // the flags used if currently watching subdirectory + info, _ := w.watches.byPath(name) + return w.addWatch(name, info.dirFlags|unix.NOTE_DELETE|unix.NOTE_RENAME) + } + + // watch file to mimic Linux inotify + return w.addWatch(name, noteAllEvents) +} + +// Register events with the queue. +func (w *kqueue) register(fds []int, flags int, fflags uint32) error { + changes := make([]unix.Kevent_t, len(fds)) + for i, fd := range fds { + // SetKevent converts int to the platform-specific types. + unix.SetKevent(&changes[i], fd, unix.EVFILT_VNODE, flags) + changes[i].Fflags = fflags + } + + // Register the events. + success, err := unix.Kevent(w.kq, changes, nil, nil) + if success == -1 { + return err + } + return nil +} + +// read retrieves pending events, or waits until an event occurs. +func (w *kqueue) read(events []unix.Kevent_t) ([]unix.Kevent_t, error) { + n, err := unix.Kevent(w.kq, nil, events, nil) + if err != nil { + return nil, err + } + return events[0:n], nil +} + +func (w *kqueue) xSupports(op Op) bool { + if runtime.GOOS == "freebsd" { + //return true // Supports everything. + } + if op.Has(xUnportableOpen) || op.Has(xUnportableRead) || + op.Has(xUnportableCloseWrite) || op.Has(xUnportableCloseRead) { + return false + } + return true +} diff --git a/vendor/github.com/fsnotify/fsnotify/backend_other.go b/vendor/github.com/fsnotify/fsnotify/backend_other.go new file mode 100644 index 0000000..5eb5dbc --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/backend_other.go @@ -0,0 +1,23 @@ +//go:build appengine || (!darwin && !dragonfly && !freebsd && !openbsd && !linux && !netbsd && !solaris && !windows) + +package fsnotify + +import "errors" + +type other struct { + Events chan Event + Errors chan error +} + +func newBackend(ev chan Event, errs chan error) (backend, error) { + return nil, errors.New("fsnotify not supported on the current platform") +} +func newBufferedBackend(sz uint, ev chan Event, errs chan error) (backend, error) { + return newBackend(ev, errs) +} +func (w *other) Close() error { return nil } +func (w *other) WatchList() []string { return nil } +func (w *other) Add(name string) error { return nil } +func (w *other) AddWith(name string, opts ...addOpt) error { return nil } +func (w *other) Remove(name string) error { return nil } +func (w *other) xSupports(op Op) bool { return false } diff --git a/vendor/github.com/fsnotify/fsnotify/backend_windows.go b/vendor/github.com/fsnotify/fsnotify/backend_windows.go new file mode 100644 index 0000000..c54a630 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/backend_windows.go @@ -0,0 +1,682 @@ +//go:build windows + +// Windows backend based on ReadDirectoryChangesW() +// +// https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-readdirectorychangesw + +package fsnotify + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "strings" + "sync" + "time" + "unsafe" + + "github.com/fsnotify/fsnotify/internal" + "golang.org/x/sys/windows" +) + +type readDirChangesW struct { + Events chan Event + Errors chan error + + port windows.Handle // Handle to completion port + input chan *input // Inputs to the reader are sent on this channel + quit chan chan<- error + + mu sync.Mutex // Protects access to watches, closed + watches watchMap // Map of watches (key: i-number) + closed bool // Set to true when Close() is first called +} + +func newBackend(ev chan Event, errs chan error) (backend, error) { + return newBufferedBackend(50, ev, errs) +} + +func newBufferedBackend(sz uint, ev chan Event, errs chan error) (backend, error) { + port, err := windows.CreateIoCompletionPort(windows.InvalidHandle, 0, 0, 0) + if err != nil { + return nil, os.NewSyscallError("CreateIoCompletionPort", err) + } + w := &readDirChangesW{ + Events: ev, + Errors: errs, + port: port, + watches: make(watchMap), + input: make(chan *input, 1), + quit: make(chan chan<- error, 1), + } + go w.readEvents() + return w, nil +} + +func (w *readDirChangesW) isClosed() bool { + w.mu.Lock() + defer w.mu.Unlock() + return w.closed +} + +func (w *readDirChangesW) sendEvent(name, renamedFrom string, mask uint64) bool { + if mask == 0 { + return false + } + + event := w.newEvent(name, uint32(mask)) + event.renamedFrom = renamedFrom + select { + case ch := <-w.quit: + w.quit <- ch + case w.Events <- event: + } + return true +} + +// Returns true if the error was sent, or false if watcher is closed. +func (w *readDirChangesW) sendError(err error) bool { + if err == nil { + return true + } + select { + case w.Errors <- err: + return true + case <-w.quit: + return false + } +} + +func (w *readDirChangesW) Close() error { + if w.isClosed() { + return nil + } + + w.mu.Lock() + w.closed = true + w.mu.Unlock() + + // Send "quit" message to the reader goroutine + ch := make(chan error) + w.quit <- ch + if err := w.wakeupReader(); err != nil { + return err + } + return <-ch +} + +func (w *readDirChangesW) Add(name string) error { return w.AddWith(name) } + +func (w *readDirChangesW) AddWith(name string, opts ...addOpt) error { + if w.isClosed() { + return ErrClosed + } + if debug { + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s AddWith(%q)\n", + time.Now().Format("15:04:05.000000000"), filepath.ToSlash(name)) + } + + with := getOptions(opts...) + if !w.xSupports(with.op) { + return fmt.Errorf("%w: %s", xErrUnsupported, with.op) + } + if with.bufsize < 4096 { + return fmt.Errorf("fsnotify.WithBufferSize: buffer size cannot be smaller than 4096 bytes") + } + + in := &input{ + op: opAddWatch, + path: filepath.Clean(name), + flags: sysFSALLEVENTS, + reply: make(chan error), + bufsize: with.bufsize, + } + w.input <- in + if err := w.wakeupReader(); err != nil { + return err + } + return <-in.reply +} + +func (w *readDirChangesW) Remove(name string) error { + if w.isClosed() { + return nil + } + if debug { + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s Remove(%q)\n", + time.Now().Format("15:04:05.000000000"), filepath.ToSlash(name)) + } + + in := &input{ + op: opRemoveWatch, + path: filepath.Clean(name), + reply: make(chan error), + } + w.input <- in + if err := w.wakeupReader(); err != nil { + return err + } + return <-in.reply +} + +func (w *readDirChangesW) WatchList() []string { + if w.isClosed() { + return nil + } + + w.mu.Lock() + defer w.mu.Unlock() + + entries := make([]string, 0, len(w.watches)) + for _, entry := range w.watches { + for _, watchEntry := range entry { + for name := range watchEntry.names { + entries = append(entries, filepath.Join(watchEntry.path, name)) + } + // the directory itself is being watched + if watchEntry.mask != 0 { + entries = append(entries, watchEntry.path) + } + } + } + + return entries +} + +// These options are from the old golang.org/x/exp/winfsnotify, where you could +// add various options to the watch. This has long since been removed. +// +// The "sys" in the name is misleading as they're not part of any "system". +// +// This should all be removed at some point, and just use windows.FILE_NOTIFY_* +const ( + sysFSALLEVENTS = 0xfff + sysFSCREATE = 0x100 + sysFSDELETE = 0x200 + sysFSDELETESELF = 0x400 + sysFSMODIFY = 0x2 + sysFSMOVE = 0xc0 + sysFSMOVEDFROM = 0x40 + sysFSMOVEDTO = 0x80 + sysFSMOVESELF = 0x800 + sysFSIGNORED = 0x8000 +) + +func (w *readDirChangesW) newEvent(name string, mask uint32) Event { + e := Event{Name: name} + if mask&sysFSCREATE == sysFSCREATE || mask&sysFSMOVEDTO == sysFSMOVEDTO { + e.Op |= Create + } + if mask&sysFSDELETE == sysFSDELETE || mask&sysFSDELETESELF == sysFSDELETESELF { + e.Op |= Remove + } + if mask&sysFSMODIFY == sysFSMODIFY { + e.Op |= Write + } + if mask&sysFSMOVE == sysFSMOVE || mask&sysFSMOVESELF == sysFSMOVESELF || mask&sysFSMOVEDFROM == sysFSMOVEDFROM { + e.Op |= Rename + } + return e +} + +const ( + opAddWatch = iota + opRemoveWatch +) + +const ( + provisional uint64 = 1 << (32 + iota) +) + +type input struct { + op int + path string + flags uint32 + bufsize int + reply chan error +} + +type inode struct { + handle windows.Handle + volume uint32 + index uint64 +} + +type watch struct { + ov windows.Overlapped + ino *inode // i-number + recurse bool // Recursive watch? + path string // Directory path + mask uint64 // Directory itself is being watched with these notify flags + names map[string]uint64 // Map of names being watched and their notify flags + rename string // Remembers the old name while renaming a file + buf []byte // buffer, allocated later +} + +type ( + indexMap map[uint64]*watch + watchMap map[uint32]indexMap +) + +func (w *readDirChangesW) wakeupReader() error { + err := windows.PostQueuedCompletionStatus(w.port, 0, 0, nil) + if err != nil { + return os.NewSyscallError("PostQueuedCompletionStatus", err) + } + return nil +} + +func (w *readDirChangesW) getDir(pathname string) (dir string, err error) { + attr, err := windows.GetFileAttributes(windows.StringToUTF16Ptr(pathname)) + if err != nil { + return "", os.NewSyscallError("GetFileAttributes", err) + } + if attr&windows.FILE_ATTRIBUTE_DIRECTORY != 0 { + dir = pathname + } else { + dir, _ = filepath.Split(pathname) + dir = filepath.Clean(dir) + } + return +} + +func (w *readDirChangesW) getIno(path string) (ino *inode, err error) { + h, err := windows.CreateFile(windows.StringToUTF16Ptr(path), + windows.FILE_LIST_DIRECTORY, + windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, + nil, windows.OPEN_EXISTING, + windows.FILE_FLAG_BACKUP_SEMANTICS|windows.FILE_FLAG_OVERLAPPED, 0) + if err != nil { + return nil, os.NewSyscallError("CreateFile", err) + } + + var fi windows.ByHandleFileInformation + err = windows.GetFileInformationByHandle(h, &fi) + if err != nil { + windows.CloseHandle(h) + return nil, os.NewSyscallError("GetFileInformationByHandle", err) + } + ino = &inode{ + handle: h, + volume: fi.VolumeSerialNumber, + index: uint64(fi.FileIndexHigh)<<32 | uint64(fi.FileIndexLow), + } + return ino, nil +} + +// Must run within the I/O thread. +func (m watchMap) get(ino *inode) *watch { + if i := m[ino.volume]; i != nil { + return i[ino.index] + } + return nil +} + +// Must run within the I/O thread. +func (m watchMap) set(ino *inode, watch *watch) { + i := m[ino.volume] + if i == nil { + i = make(indexMap) + m[ino.volume] = i + } + i[ino.index] = watch +} + +// Must run within the I/O thread. +func (w *readDirChangesW) addWatch(pathname string, flags uint64, bufsize int) error { + pathname, recurse := recursivePath(pathname) + + dir, err := w.getDir(pathname) + if err != nil { + return err + } + + ino, err := w.getIno(dir) + if err != nil { + return err + } + w.mu.Lock() + watchEntry := w.watches.get(ino) + w.mu.Unlock() + if watchEntry == nil { + _, err := windows.CreateIoCompletionPort(ino.handle, w.port, 0, 0) + if err != nil { + windows.CloseHandle(ino.handle) + return os.NewSyscallError("CreateIoCompletionPort", err) + } + watchEntry = &watch{ + ino: ino, + path: dir, + names: make(map[string]uint64), + recurse: recurse, + buf: make([]byte, bufsize), + } + w.mu.Lock() + w.watches.set(ino, watchEntry) + w.mu.Unlock() + flags |= provisional + } else { + windows.CloseHandle(ino.handle) + } + if pathname == dir { + watchEntry.mask |= flags + } else { + watchEntry.names[filepath.Base(pathname)] |= flags + } + + err = w.startRead(watchEntry) + if err != nil { + return err + } + + if pathname == dir { + watchEntry.mask &= ^provisional + } else { + watchEntry.names[filepath.Base(pathname)] &= ^provisional + } + return nil +} + +// Must run within the I/O thread. +func (w *readDirChangesW) remWatch(pathname string) error { + pathname, recurse := recursivePath(pathname) + + dir, err := w.getDir(pathname) + if err != nil { + return err + } + ino, err := w.getIno(dir) + if err != nil { + return err + } + + w.mu.Lock() + watch := w.watches.get(ino) + w.mu.Unlock() + + if recurse && !watch.recurse { + return fmt.Errorf("can't use \\... with non-recursive watch %q", pathname) + } + + err = windows.CloseHandle(ino.handle) + if err != nil { + w.sendError(os.NewSyscallError("CloseHandle", err)) + } + if watch == nil { + return fmt.Errorf("%w: %s", ErrNonExistentWatch, pathname) + } + if pathname == dir { + w.sendEvent(watch.path, "", watch.mask&sysFSIGNORED) + watch.mask = 0 + } else { + name := filepath.Base(pathname) + w.sendEvent(filepath.Join(watch.path, name), "", watch.names[name]&sysFSIGNORED) + delete(watch.names, name) + } + + return w.startRead(watch) +} + +// Must run within the I/O thread. +func (w *readDirChangesW) deleteWatch(watch *watch) { + for name, mask := range watch.names { + if mask&provisional == 0 { + w.sendEvent(filepath.Join(watch.path, name), "", mask&sysFSIGNORED) + } + delete(watch.names, name) + } + if watch.mask != 0 { + if watch.mask&provisional == 0 { + w.sendEvent(watch.path, "", watch.mask&sysFSIGNORED) + } + watch.mask = 0 + } +} + +// Must run within the I/O thread. +func (w *readDirChangesW) startRead(watch *watch) error { + err := windows.CancelIo(watch.ino.handle) + if err != nil { + w.sendError(os.NewSyscallError("CancelIo", err)) + w.deleteWatch(watch) + } + mask := w.toWindowsFlags(watch.mask) + for _, m := range watch.names { + mask |= w.toWindowsFlags(m) + } + if mask == 0 { + err := windows.CloseHandle(watch.ino.handle) + if err != nil { + w.sendError(os.NewSyscallError("CloseHandle", err)) + } + w.mu.Lock() + delete(w.watches[watch.ino.volume], watch.ino.index) + w.mu.Unlock() + return nil + } + + // We need to pass the array, rather than the slice. + hdr := (*reflect.SliceHeader)(unsafe.Pointer(&watch.buf)) + rdErr := windows.ReadDirectoryChanges(watch.ino.handle, + (*byte)(unsafe.Pointer(hdr.Data)), uint32(hdr.Len), + watch.recurse, mask, nil, &watch.ov, 0) + if rdErr != nil { + err := os.NewSyscallError("ReadDirectoryChanges", rdErr) + if rdErr == windows.ERROR_ACCESS_DENIED && watch.mask&provisional == 0 { + // Watched directory was probably removed + w.sendEvent(watch.path, "", watch.mask&sysFSDELETESELF) + err = nil + } + w.deleteWatch(watch) + w.startRead(watch) + return err + } + return nil +} + +// readEvents reads from the I/O completion port, converts the +// received events into Event objects and sends them via the Events channel. +// Entry point to the I/O thread. +func (w *readDirChangesW) readEvents() { + var ( + n uint32 + key uintptr + ov *windows.Overlapped + ) + runtime.LockOSThread() + + for { + // This error is handled after the watch == nil check below. + qErr := windows.GetQueuedCompletionStatus(w.port, &n, &key, &ov, windows.INFINITE) + + watch := (*watch)(unsafe.Pointer(ov)) + if watch == nil { + select { + case ch := <-w.quit: + w.mu.Lock() + var indexes []indexMap + for _, index := range w.watches { + indexes = append(indexes, index) + } + w.mu.Unlock() + for _, index := range indexes { + for _, watch := range index { + w.deleteWatch(watch) + w.startRead(watch) + } + } + + err := windows.CloseHandle(w.port) + if err != nil { + err = os.NewSyscallError("CloseHandle", err) + } + close(w.Events) + close(w.Errors) + ch <- err + return + case in := <-w.input: + switch in.op { + case opAddWatch: + in.reply <- w.addWatch(in.path, uint64(in.flags), in.bufsize) + case opRemoveWatch: + in.reply <- w.remWatch(in.path) + } + default: + } + continue + } + + switch qErr { + case nil: + // No error + case windows.ERROR_MORE_DATA: + if watch == nil { + w.sendError(errors.New("ERROR_MORE_DATA has unexpectedly null lpOverlapped buffer")) + } else { + // The i/o succeeded but the buffer is full. + // In theory we should be building up a full packet. + // In practice we can get away with just carrying on. + n = uint32(unsafe.Sizeof(watch.buf)) + } + case windows.ERROR_ACCESS_DENIED: + // Watched directory was probably removed + w.sendEvent(watch.path, "", watch.mask&sysFSDELETESELF) + w.deleteWatch(watch) + w.startRead(watch) + continue + case windows.ERROR_OPERATION_ABORTED: + // CancelIo was called on this handle + continue + default: + w.sendError(os.NewSyscallError("GetQueuedCompletionPort", qErr)) + continue + } + + var offset uint32 + for { + if n == 0 { + w.sendError(ErrEventOverflow) + break + } + + // Point "raw" to the event in the buffer + raw := (*windows.FileNotifyInformation)(unsafe.Pointer(&watch.buf[offset])) + + // Create a buf that is the size of the path name + size := int(raw.FileNameLength / 2) + var buf []uint16 + // TODO: Use unsafe.Slice in Go 1.17; https://stackoverflow.com/questions/51187973 + sh := (*reflect.SliceHeader)(unsafe.Pointer(&buf)) + sh.Data = uintptr(unsafe.Pointer(&raw.FileName)) + sh.Len = size + sh.Cap = size + name := windows.UTF16ToString(buf) + fullname := filepath.Join(watch.path, name) + + if debug { + internal.Debug(fullname, raw.Action) + } + + var mask uint64 + switch raw.Action { + case windows.FILE_ACTION_REMOVED: + mask = sysFSDELETESELF + case windows.FILE_ACTION_MODIFIED: + mask = sysFSMODIFY + case windows.FILE_ACTION_RENAMED_OLD_NAME: + watch.rename = name + case windows.FILE_ACTION_RENAMED_NEW_NAME: + // Update saved path of all sub-watches. + old := filepath.Join(watch.path, watch.rename) + w.mu.Lock() + for _, watchMap := range w.watches { + for _, ww := range watchMap { + if strings.HasPrefix(ww.path, old) { + ww.path = filepath.Join(fullname, strings.TrimPrefix(ww.path, old)) + } + } + } + w.mu.Unlock() + + if watch.names[watch.rename] != 0 { + watch.names[name] |= watch.names[watch.rename] + delete(watch.names, watch.rename) + mask = sysFSMOVESELF + } + } + + if raw.Action != windows.FILE_ACTION_RENAMED_NEW_NAME { + w.sendEvent(fullname, "", watch.names[name]&mask) + } + if raw.Action == windows.FILE_ACTION_REMOVED { + w.sendEvent(fullname, "", watch.names[name]&sysFSIGNORED) + delete(watch.names, name) + } + + if watch.rename != "" && raw.Action == windows.FILE_ACTION_RENAMED_NEW_NAME { + w.sendEvent(fullname, filepath.Join(watch.path, watch.rename), watch.mask&w.toFSnotifyFlags(raw.Action)) + } else { + w.sendEvent(fullname, "", watch.mask&w.toFSnotifyFlags(raw.Action)) + } + + if raw.Action == windows.FILE_ACTION_RENAMED_NEW_NAME { + w.sendEvent(filepath.Join(watch.path, watch.rename), "", watch.names[name]&mask) + } + + // Move to the next event in the buffer + if raw.NextEntryOffset == 0 { + break + } + offset += raw.NextEntryOffset + + // Error! + if offset >= n { + //lint:ignore ST1005 Windows should be capitalized + w.sendError(errors.New("Windows system assumed buffer larger than it is, events have likely been missed")) + break + } + } + + if err := w.startRead(watch); err != nil { + w.sendError(err) + } + } +} + +func (w *readDirChangesW) toWindowsFlags(mask uint64) uint32 { + var m uint32 + if mask&sysFSMODIFY != 0 { + m |= windows.FILE_NOTIFY_CHANGE_LAST_WRITE + } + if mask&(sysFSMOVE|sysFSCREATE|sysFSDELETE) != 0 { + m |= windows.FILE_NOTIFY_CHANGE_FILE_NAME | windows.FILE_NOTIFY_CHANGE_DIR_NAME + } + return m +} + +func (w *readDirChangesW) toFSnotifyFlags(action uint32) uint64 { + switch action { + case windows.FILE_ACTION_ADDED: + return sysFSCREATE + case windows.FILE_ACTION_REMOVED: + return sysFSDELETE + case windows.FILE_ACTION_MODIFIED: + return sysFSMODIFY + case windows.FILE_ACTION_RENAMED_OLD_NAME: + return sysFSMOVEDFROM + case windows.FILE_ACTION_RENAMED_NEW_NAME: + return sysFSMOVEDTO + } + return 0 +} + +func (w *readDirChangesW) xSupports(op Op) bool { + if op.Has(xUnportableOpen) || op.Has(xUnportableRead) || + op.Has(xUnportableCloseWrite) || op.Has(xUnportableCloseRead) { + return false + } + return true +} diff --git a/vendor/github.com/fsnotify/fsnotify/fsnotify.go b/vendor/github.com/fsnotify/fsnotify/fsnotify.go new file mode 100644 index 0000000..0760efe --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/fsnotify.go @@ -0,0 +1,494 @@ +// Package fsnotify provides a cross-platform interface for file system +// notifications. +// +// Currently supported systems: +// +// - Linux via inotify +// - BSD, macOS via kqueue +// - Windows via ReadDirectoryChangesW +// - illumos via FEN +// +// # FSNOTIFY_DEBUG +// +// Set the FSNOTIFY_DEBUG environment variable to "1" to print debug messages to +// stderr. This can be useful to track down some problems, especially in cases +// where fsnotify is used as an indirect dependency. +// +// Every event will be printed as soon as there's something useful to print, +// with as little processing from fsnotify. +// +// Example output: +// +// FSNOTIFY_DEBUG: 11:34:23.633087586 256:IN_CREATE → "/tmp/file-1" +// FSNOTIFY_DEBUG: 11:34:23.633202319 4:IN_ATTRIB → "/tmp/file-1" +// FSNOTIFY_DEBUG: 11:34:28.989728764 512:IN_DELETE → "/tmp/file-1" +package fsnotify + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" +) + +// Watcher watches a set of paths, delivering events on a channel. +// +// A watcher should not be copied (e.g. pass it by pointer, rather than by +// value). +// +// # Linux notes +// +// When a file is removed a Remove event won't be emitted until all file +// descriptors are closed, and deletes will always emit a Chmod. For example: +// +// fp := os.Open("file") +// os.Remove("file") // Triggers Chmod +// fp.Close() // Triggers Remove +// +// This is the event that inotify sends, so not much can be changed about this. +// +// The fs.inotify.max_user_watches sysctl variable specifies the upper limit +// for the number of watches per user, and fs.inotify.max_user_instances +// specifies the maximum number of inotify instances per user. Every Watcher you +// create is an "instance", and every path you add is a "watch". +// +// These are also exposed in /proc as /proc/sys/fs/inotify/max_user_watches and +// /proc/sys/fs/inotify/max_user_instances +// +// To increase them you can use sysctl or write the value to the /proc file: +// +// # Default values on Linux 5.18 +// sysctl fs.inotify.max_user_watches=124983 +// sysctl fs.inotify.max_user_instances=128 +// +// To make the changes persist on reboot edit /etc/sysctl.conf or +// /usr/lib/sysctl.d/50-default.conf (details differ per Linux distro; check +// your distro's documentation): +// +// fs.inotify.max_user_watches=124983 +// fs.inotify.max_user_instances=128 +// +// Reaching the limit will result in a "no space left on device" or "too many open +// files" error. +// +// # kqueue notes (macOS, BSD) +// +// kqueue requires opening a file descriptor for every file that's being watched; +// so if you're watching a directory with five files then that's six file +// descriptors. You will run in to your system's "max open files" limit faster on +// these platforms. +// +// The sysctl variables kern.maxfiles and kern.maxfilesperproc can be used to +// control the maximum number of open files, as well as /etc/login.conf on BSD +// systems. +// +// # Windows notes +// +// Paths can be added as "C:\\path\\to\\dir", but forward slashes +// ("C:/path/to/dir") will also work. +// +// When a watched directory is removed it will always send an event for the +// directory itself, but may not send events for all files in that directory. +// Sometimes it will send events for all files, sometimes it will send no +// events, and often only for some files. +// +// The default ReadDirectoryChangesW() buffer size is 64K, which is the largest +// value that is guaranteed to work with SMB filesystems. If you have many +// events in quick succession this may not be enough, and you will have to use +// [WithBufferSize] to increase the value. +type Watcher struct { + b backend + + // Events sends the filesystem change events. + // + // fsnotify can send the following events; a "path" here can refer to a + // file, directory, symbolic link, or special file like a FIFO. + // + // fsnotify.Create A new path was created; this may be followed by one + // or more Write events if data also gets written to a + // file. + // + // fsnotify.Remove A path was removed. + // + // fsnotify.Rename A path was renamed. A rename is always sent with the + // old path as Event.Name, and a Create event will be + // sent with the new name. Renames are only sent for + // paths that are currently watched; e.g. moving an + // unmonitored file into a monitored directory will + // show up as just a Create. Similarly, renaming a file + // to outside a monitored directory will show up as + // only a Rename. + // + // fsnotify.Write A file or named pipe was written to. A Truncate will + // also trigger a Write. A single "write action" + // initiated by the user may show up as one or multiple + // writes, depending on when the system syncs things to + // disk. For example when compiling a large Go program + // you may get hundreds of Write events, and you may + // want to wait until you've stopped receiving them + // (see the dedup example in cmd/fsnotify). + // + // Some systems may send Write event for directories + // when the directory content changes. + // + // fsnotify.Chmod Attributes were changed. On Linux this is also sent + // when a file is removed (or more accurately, when a + // link to an inode is removed). On kqueue it's sent + // when a file is truncated. On Windows it's never + // sent. + Events chan Event + + // Errors sends any errors. + Errors chan error +} + +// Event represents a file system notification. +type Event struct { + // Path to the file or directory. + // + // Paths are relative to the input; for example with Add("dir") the Name + // will be set to "dir/file" if you create that file, but if you use + // Add("/path/to/dir") it will be "/path/to/dir/file". + Name string + + // File operation that triggered the event. + // + // This is a bitmask and some systems may send multiple operations at once. + // Use the Event.Has() method instead of comparing with ==. + Op Op + + // Create events will have this set to the old path if it's a rename. This + // only works when both the source and destination are watched. It's not + // reliable when watching individual files, only directories. + // + // For example "mv /tmp/file /tmp/rename" will emit: + // + // Event{Op: Rename, Name: "/tmp/file"} + // Event{Op: Create, Name: "/tmp/rename", RenamedFrom: "/tmp/file"} + renamedFrom string +} + +// Op describes a set of file operations. +type Op uint32 + +// The operations fsnotify can trigger; see the documentation on [Watcher] for a +// full description, and check them with [Event.Has]. +const ( + // A new pathname was created. + Create Op = 1 << iota + + // The pathname was written to; this does *not* mean the write has finished, + // and a write can be followed by more writes. + Write + + // The path was removed; any watches on it will be removed. Some "remove" + // operations may trigger a Rename if the file is actually moved (for + // example "remove to trash" is often a rename). + Remove + + // The path was renamed to something else; any watches on it will be + // removed. + Rename + + // File attributes were changed. + // + // It's generally not recommended to take action on this event, as it may + // get triggered very frequently by some software. For example, Spotlight + // indexing on macOS, anti-virus software, backup software, etc. + Chmod + + // File descriptor was opened. + // + // Only works on Linux and FreeBSD. + xUnportableOpen + + // File was read from. + // + // Only works on Linux and FreeBSD. + xUnportableRead + + // File opened for writing was closed. + // + // Only works on Linux and FreeBSD. + // + // The advantage of using this over Write is that it's more reliable than + // waiting for Write events to stop. It's also faster (if you're not + // listening to Write events): copying a file of a few GB can easily + // generate tens of thousands of Write events in a short span of time. + xUnportableCloseWrite + + // File opened for reading was closed. + // + // Only works on Linux and FreeBSD. + xUnportableCloseRead +) + +var ( + // ErrNonExistentWatch is used when Remove() is called on a path that's not + // added. + ErrNonExistentWatch = errors.New("fsnotify: can't remove non-existent watch") + + // ErrClosed is used when trying to operate on a closed Watcher. + ErrClosed = errors.New("fsnotify: watcher already closed") + + // ErrEventOverflow is reported from the Errors channel when there are too + // many events: + // + // - inotify: inotify returns IN_Q_OVERFLOW – because there are too + // many queued events (the fs.inotify.max_queued_events + // sysctl can be used to increase this). + // - windows: The buffer size is too small; WithBufferSize() can be used to increase it. + // - kqueue, fen: Not used. + ErrEventOverflow = errors.New("fsnotify: queue or buffer overflow") + + // ErrUnsupported is returned by AddWith() when WithOps() specified an + // Unportable event that's not supported on this platform. + xErrUnsupported = errors.New("fsnotify: not supported with this backend") +) + +// NewWatcher creates a new Watcher. +func NewWatcher() (*Watcher, error) { + ev, errs := make(chan Event), make(chan error) + b, err := newBackend(ev, errs) + if err != nil { + return nil, err + } + return &Watcher{b: b, Events: ev, Errors: errs}, nil +} + +// NewBufferedWatcher creates a new Watcher with a buffered Watcher.Events +// channel. +// +// The main use case for this is situations with a very large number of events +// where the kernel buffer size can't be increased (e.g. due to lack of +// permissions). An unbuffered Watcher will perform better for almost all use +// cases, and whenever possible you will be better off increasing the kernel +// buffers instead of adding a large userspace buffer. +func NewBufferedWatcher(sz uint) (*Watcher, error) { + ev, errs := make(chan Event), make(chan error) + b, err := newBufferedBackend(sz, ev, errs) + if err != nil { + return nil, err + } + return &Watcher{b: b, Events: ev, Errors: errs}, nil +} + +// Add starts monitoring the path for changes. +// +// A path can only be watched once; watching it more than once is a no-op and will +// not return an error. Paths that do not yet exist on the filesystem cannot be +// watched. +// +// A watch will be automatically removed if the watched path is deleted or +// renamed. The exception is the Windows backend, which doesn't remove the +// watcher on renames. +// +// Notifications on network filesystems (NFS, SMB, FUSE, etc.) or special +// filesystems (/proc, /sys, etc.) generally don't work. +// +// Returns [ErrClosed] if [Watcher.Close] was called. +// +// See [Watcher.AddWith] for a version that allows adding options. +// +// # Watching directories +// +// All files in a directory are monitored, including new files that are created +// after the watcher is started. Subdirectories are not watched (i.e. it's +// non-recursive). +// +// # Watching files +// +// Watching individual files (rather than directories) is generally not +// recommended as many programs (especially editors) update files atomically: it +// will write to a temporary file which is then moved to destination, +// overwriting the original (or some variant thereof). The watcher on the +// original file is now lost, as that no longer exists. +// +// The upshot of this is that a power failure or crash won't leave a +// half-written file. +// +// Watch the parent directory and use Event.Name to filter out files you're not +// interested in. There is an example of this in cmd/fsnotify/file.go. +func (w *Watcher) Add(path string) error { return w.b.Add(path) } + +// AddWith is like [Watcher.Add], but allows adding options. When using Add() +// the defaults described below are used. +// +// Possible options are: +// +// - [WithBufferSize] sets the buffer size for the Windows backend; no-op on +// other platforms. The default is 64K (65536 bytes). +func (w *Watcher) AddWith(path string, opts ...addOpt) error { return w.b.AddWith(path, opts...) } + +// Remove stops monitoring the path for changes. +// +// Directories are always removed non-recursively. For example, if you added +// /tmp/dir and /tmp/dir/subdir then you will need to remove both. +// +// Removing a path that has not yet been added returns [ErrNonExistentWatch]. +// +// Returns nil if [Watcher.Close] was called. +func (w *Watcher) Remove(path string) error { return w.b.Remove(path) } + +// Close removes all watches and closes the Events channel. +func (w *Watcher) Close() error { return w.b.Close() } + +// WatchList returns all paths explicitly added with [Watcher.Add] (and are not +// yet removed). +// +// Returns nil if [Watcher.Close] was called. +func (w *Watcher) WatchList() []string { return w.b.WatchList() } + +// Supports reports if all the listed operations are supported by this platform. +// +// Create, Write, Remove, Rename, and Chmod are always supported. It can only +// return false for an Op starting with Unportable. +func (w *Watcher) xSupports(op Op) bool { return w.b.xSupports(op) } + +func (o Op) String() string { + var b strings.Builder + if o.Has(Create) { + b.WriteString("|CREATE") + } + if o.Has(Remove) { + b.WriteString("|REMOVE") + } + if o.Has(Write) { + b.WriteString("|WRITE") + } + if o.Has(xUnportableOpen) { + b.WriteString("|OPEN") + } + if o.Has(xUnportableRead) { + b.WriteString("|READ") + } + if o.Has(xUnportableCloseWrite) { + b.WriteString("|CLOSE_WRITE") + } + if o.Has(xUnportableCloseRead) { + b.WriteString("|CLOSE_READ") + } + if o.Has(Rename) { + b.WriteString("|RENAME") + } + if o.Has(Chmod) { + b.WriteString("|CHMOD") + } + if b.Len() == 0 { + return "[no events]" + } + return b.String()[1:] +} + +// Has reports if this operation has the given operation. +func (o Op) Has(h Op) bool { return o&h != 0 } + +// Has reports if this event has the given operation. +func (e Event) Has(op Op) bool { return e.Op.Has(op) } + +// String returns a string representation of the event with their path. +func (e Event) String() string { + if e.renamedFrom != "" { + return fmt.Sprintf("%-13s %q ← %q", e.Op.String(), e.Name, e.renamedFrom) + } + return fmt.Sprintf("%-13s %q", e.Op.String(), e.Name) +} + +type ( + backend interface { + Add(string) error + AddWith(string, ...addOpt) error + Remove(string) error + WatchList() []string + Close() error + xSupports(Op) bool + } + addOpt func(opt *withOpts) + withOpts struct { + bufsize int + op Op + noFollow bool + sendCreate bool + } +) + +var debug = func() bool { + // Check for exactly "1" (rather than mere existence) so we can add + // options/flags in the future. I don't know if we ever want that, but it's + // nice to leave the option open. + return os.Getenv("FSNOTIFY_DEBUG") == "1" +}() + +var defaultOpts = withOpts{ + bufsize: 65536, // 64K + op: Create | Write | Remove | Rename | Chmod, +} + +func getOptions(opts ...addOpt) withOpts { + with := defaultOpts + for _, o := range opts { + if o != nil { + o(&with) + } + } + return with +} + +// WithBufferSize sets the [ReadDirectoryChangesW] buffer size. +// +// This only has effect on Windows systems, and is a no-op for other backends. +// +// The default value is 64K (65536 bytes) which is the highest value that works +// on all filesystems and should be enough for most applications, but if you +// have a large burst of events it may not be enough. You can increase it if +// you're hitting "queue or buffer overflow" errors ([ErrEventOverflow]). +// +// [ReadDirectoryChangesW]: https://learn.microsoft.com/en-gb/windows/win32/api/winbase/nf-winbase-readdirectorychangesw +func WithBufferSize(bytes int) addOpt { + return func(opt *withOpts) { opt.bufsize = bytes } +} + +// WithOps sets which operations to listen for. The default is [Create], +// [Write], [Remove], [Rename], and [Chmod]. +// +// Excluding operations you're not interested in can save quite a bit of CPU +// time; in some use cases there may be hundreds of thousands of useless Write +// or Chmod operations per second. +// +// This can also be used to add unportable operations not supported by all +// platforms; unportable operations all start with "Unportable": +// [UnportableOpen], [UnportableRead], [UnportableCloseWrite], and +// [UnportableCloseRead]. +// +// AddWith returns an error when using an unportable operation that's not +// supported. Use [Watcher.Support] to check for support. +func withOps(op Op) addOpt { + return func(opt *withOpts) { opt.op = op } +} + +// WithNoFollow disables following symlinks, so the symlinks themselves are +// watched. +func withNoFollow() addOpt { + return func(opt *withOpts) { opt.noFollow = true } +} + +// "Internal" option for recursive watches on inotify. +func withCreate() addOpt { + return func(opt *withOpts) { opt.sendCreate = true } +} + +var enableRecurse = false + +// Check if this path is recursive (ends with "/..." or "\..."), and return the +// path with the /... stripped. +func recursivePath(path string) (string, bool) { + path = filepath.Clean(path) + if !enableRecurse { // Only enabled in tests for now. + return path, false + } + if filepath.Base(path) == "..." { + return filepath.Dir(path), true + } + return path, false +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/darwin.go b/vendor/github.com/fsnotify/fsnotify/internal/darwin.go new file mode 100644 index 0000000..b0eab10 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/darwin.go @@ -0,0 +1,39 @@ +//go:build darwin + +package internal + +import ( + "syscall" + + "golang.org/x/sys/unix" +) + +var ( + SyscallEACCES = syscall.EACCES + UnixEACCES = unix.EACCES +) + +var maxfiles uint64 + +// Go 1.19 will do this automatically: https://go-review.googlesource.com/c/go/+/393354/ +func SetRlimit() { + var l syscall.Rlimit + err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &l) + if err == nil && l.Cur != l.Max { + l.Cur = l.Max + syscall.Setrlimit(syscall.RLIMIT_NOFILE, &l) + } + maxfiles = l.Cur + + if n, err := syscall.SysctlUint32("kern.maxfiles"); err == nil && uint64(n) < maxfiles { + maxfiles = uint64(n) + } + + if n, err := syscall.SysctlUint32("kern.maxfilesperproc"); err == nil && uint64(n) < maxfiles { + maxfiles = uint64(n) + } +} + +func Maxfiles() uint64 { return maxfiles } +func Mkfifo(path string, mode uint32) error { return unix.Mkfifo(path, mode) } +func Mknod(path string, mode uint32, dev int) error { return unix.Mknod(path, mode, dev) } diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_darwin.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_darwin.go new file mode 100644 index 0000000..928319f --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/debug_darwin.go @@ -0,0 +1,57 @@ +package internal + +import "golang.org/x/sys/unix" + +var names = []struct { + n string + m uint32 +}{ + {"NOTE_ABSOLUTE", unix.NOTE_ABSOLUTE}, + {"NOTE_ATTRIB", unix.NOTE_ATTRIB}, + {"NOTE_BACKGROUND", unix.NOTE_BACKGROUND}, + {"NOTE_CHILD", unix.NOTE_CHILD}, + {"NOTE_CRITICAL", unix.NOTE_CRITICAL}, + {"NOTE_DELETE", unix.NOTE_DELETE}, + {"NOTE_EXEC", unix.NOTE_EXEC}, + {"NOTE_EXIT", unix.NOTE_EXIT}, + {"NOTE_EXITSTATUS", unix.NOTE_EXITSTATUS}, + {"NOTE_EXIT_CSERROR", unix.NOTE_EXIT_CSERROR}, + {"NOTE_EXIT_DECRYPTFAIL", unix.NOTE_EXIT_DECRYPTFAIL}, + {"NOTE_EXIT_DETAIL", unix.NOTE_EXIT_DETAIL}, + {"NOTE_EXIT_DETAIL_MASK", unix.NOTE_EXIT_DETAIL_MASK}, + {"NOTE_EXIT_MEMORY", unix.NOTE_EXIT_MEMORY}, + {"NOTE_EXIT_REPARENTED", unix.NOTE_EXIT_REPARENTED}, + {"NOTE_EXTEND", unix.NOTE_EXTEND}, + {"NOTE_FFAND", unix.NOTE_FFAND}, + {"NOTE_FFCOPY", unix.NOTE_FFCOPY}, + {"NOTE_FFCTRLMASK", unix.NOTE_FFCTRLMASK}, + {"NOTE_FFLAGSMASK", unix.NOTE_FFLAGSMASK}, + {"NOTE_FFNOP", unix.NOTE_FFNOP}, + {"NOTE_FFOR", unix.NOTE_FFOR}, + {"NOTE_FORK", unix.NOTE_FORK}, + {"NOTE_FUNLOCK", unix.NOTE_FUNLOCK}, + {"NOTE_LEEWAY", unix.NOTE_LEEWAY}, + {"NOTE_LINK", unix.NOTE_LINK}, + {"NOTE_LOWAT", unix.NOTE_LOWAT}, + {"NOTE_MACHTIME", unix.NOTE_MACHTIME}, + {"NOTE_MACH_CONTINUOUS_TIME", unix.NOTE_MACH_CONTINUOUS_TIME}, + {"NOTE_NONE", unix.NOTE_NONE}, + {"NOTE_NSECONDS", unix.NOTE_NSECONDS}, + {"NOTE_OOB", unix.NOTE_OOB}, + //{"NOTE_PCTRLMASK", unix.NOTE_PCTRLMASK}, -0x100000 (?!) + {"NOTE_PDATAMASK", unix.NOTE_PDATAMASK}, + {"NOTE_REAP", unix.NOTE_REAP}, + {"NOTE_RENAME", unix.NOTE_RENAME}, + {"NOTE_REVOKE", unix.NOTE_REVOKE}, + {"NOTE_SECONDS", unix.NOTE_SECONDS}, + {"NOTE_SIGNAL", unix.NOTE_SIGNAL}, + {"NOTE_TRACK", unix.NOTE_TRACK}, + {"NOTE_TRACKERR", unix.NOTE_TRACKERR}, + {"NOTE_TRIGGER", unix.NOTE_TRIGGER}, + {"NOTE_USECONDS", unix.NOTE_USECONDS}, + {"NOTE_VM_ERROR", unix.NOTE_VM_ERROR}, + {"NOTE_VM_PRESSURE", unix.NOTE_VM_PRESSURE}, + {"NOTE_VM_PRESSURE_SUDDEN_TERMINATE", unix.NOTE_VM_PRESSURE_SUDDEN_TERMINATE}, + {"NOTE_VM_PRESSURE_TERMINATE", unix.NOTE_VM_PRESSURE_TERMINATE}, + {"NOTE_WRITE", unix.NOTE_WRITE}, +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_dragonfly.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_dragonfly.go new file mode 100644 index 0000000..3186b0c --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/debug_dragonfly.go @@ -0,0 +1,33 @@ +package internal + +import "golang.org/x/sys/unix" + +var names = []struct { + n string + m uint32 +}{ + {"NOTE_ATTRIB", unix.NOTE_ATTRIB}, + {"NOTE_CHILD", unix.NOTE_CHILD}, + {"NOTE_DELETE", unix.NOTE_DELETE}, + {"NOTE_EXEC", unix.NOTE_EXEC}, + {"NOTE_EXIT", unix.NOTE_EXIT}, + {"NOTE_EXTEND", unix.NOTE_EXTEND}, + {"NOTE_FFAND", unix.NOTE_FFAND}, + {"NOTE_FFCOPY", unix.NOTE_FFCOPY}, + {"NOTE_FFCTRLMASK", unix.NOTE_FFCTRLMASK}, + {"NOTE_FFLAGSMASK", unix.NOTE_FFLAGSMASK}, + {"NOTE_FFNOP", unix.NOTE_FFNOP}, + {"NOTE_FFOR", unix.NOTE_FFOR}, + {"NOTE_FORK", unix.NOTE_FORK}, + {"NOTE_LINK", unix.NOTE_LINK}, + {"NOTE_LOWAT", unix.NOTE_LOWAT}, + {"NOTE_OOB", unix.NOTE_OOB}, + {"NOTE_PCTRLMASK", unix.NOTE_PCTRLMASK}, + {"NOTE_PDATAMASK", unix.NOTE_PDATAMASK}, + {"NOTE_RENAME", unix.NOTE_RENAME}, + {"NOTE_REVOKE", unix.NOTE_REVOKE}, + {"NOTE_TRACK", unix.NOTE_TRACK}, + {"NOTE_TRACKERR", unix.NOTE_TRACKERR}, + {"NOTE_TRIGGER", unix.NOTE_TRIGGER}, + {"NOTE_WRITE", unix.NOTE_WRITE}, +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_freebsd.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_freebsd.go new file mode 100644 index 0000000..f69fdb9 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/debug_freebsd.go @@ -0,0 +1,42 @@ +package internal + +import "golang.org/x/sys/unix" + +var names = []struct { + n string + m uint32 +}{ + {"NOTE_ABSTIME", unix.NOTE_ABSTIME}, + {"NOTE_ATTRIB", unix.NOTE_ATTRIB}, + {"NOTE_CHILD", unix.NOTE_CHILD}, + {"NOTE_CLOSE", unix.NOTE_CLOSE}, + {"NOTE_CLOSE_WRITE", unix.NOTE_CLOSE_WRITE}, + {"NOTE_DELETE", unix.NOTE_DELETE}, + {"NOTE_EXEC", unix.NOTE_EXEC}, + {"NOTE_EXIT", unix.NOTE_EXIT}, + {"NOTE_EXTEND", unix.NOTE_EXTEND}, + {"NOTE_FFAND", unix.NOTE_FFAND}, + {"NOTE_FFCOPY", unix.NOTE_FFCOPY}, + {"NOTE_FFCTRLMASK", unix.NOTE_FFCTRLMASK}, + {"NOTE_FFLAGSMASK", unix.NOTE_FFLAGSMASK}, + {"NOTE_FFNOP", unix.NOTE_FFNOP}, + {"NOTE_FFOR", unix.NOTE_FFOR}, + {"NOTE_FILE_POLL", unix.NOTE_FILE_POLL}, + {"NOTE_FORK", unix.NOTE_FORK}, + {"NOTE_LINK", unix.NOTE_LINK}, + {"NOTE_LOWAT", unix.NOTE_LOWAT}, + {"NOTE_MSECONDS", unix.NOTE_MSECONDS}, + {"NOTE_NSECONDS", unix.NOTE_NSECONDS}, + {"NOTE_OPEN", unix.NOTE_OPEN}, + {"NOTE_PCTRLMASK", unix.NOTE_PCTRLMASK}, + {"NOTE_PDATAMASK", unix.NOTE_PDATAMASK}, + {"NOTE_READ", unix.NOTE_READ}, + {"NOTE_RENAME", unix.NOTE_RENAME}, + {"NOTE_REVOKE", unix.NOTE_REVOKE}, + {"NOTE_SECONDS", unix.NOTE_SECONDS}, + {"NOTE_TRACK", unix.NOTE_TRACK}, + {"NOTE_TRACKERR", unix.NOTE_TRACKERR}, + {"NOTE_TRIGGER", unix.NOTE_TRIGGER}, + {"NOTE_USECONDS", unix.NOTE_USECONDS}, + {"NOTE_WRITE", unix.NOTE_WRITE}, +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_kqueue.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_kqueue.go new file mode 100644 index 0000000..607e683 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/debug_kqueue.go @@ -0,0 +1,32 @@ +//go:build freebsd || openbsd || netbsd || dragonfly || darwin + +package internal + +import ( + "fmt" + "os" + "strings" + "time" + + "golang.org/x/sys/unix" +) + +func Debug(name string, kevent *unix.Kevent_t) { + mask := uint32(kevent.Fflags) + + var ( + l []string + unknown = mask + ) + for _, n := range names { + if mask&n.m == n.m { + l = append(l, n.n) + unknown ^= n.m + } + } + if unknown > 0 { + l = append(l, fmt.Sprintf("0x%x", unknown)) + } + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s %10d:%-60s → %q\n", + time.Now().Format("15:04:05.000000000"), mask, strings.Join(l, " | "), name) +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_linux.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_linux.go new file mode 100644 index 0000000..35c734b --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/debug_linux.go @@ -0,0 +1,56 @@ +package internal + +import ( + "fmt" + "os" + "strings" + "time" + + "golang.org/x/sys/unix" +) + +func Debug(name string, mask, cookie uint32) { + names := []struct { + n string + m uint32 + }{ + {"IN_ACCESS", unix.IN_ACCESS}, + {"IN_ATTRIB", unix.IN_ATTRIB}, + {"IN_CLOSE", unix.IN_CLOSE}, + {"IN_CLOSE_NOWRITE", unix.IN_CLOSE_NOWRITE}, + {"IN_CLOSE_WRITE", unix.IN_CLOSE_WRITE}, + {"IN_CREATE", unix.IN_CREATE}, + {"IN_DELETE", unix.IN_DELETE}, + {"IN_DELETE_SELF", unix.IN_DELETE_SELF}, + {"IN_IGNORED", unix.IN_IGNORED}, + {"IN_ISDIR", unix.IN_ISDIR}, + {"IN_MODIFY", unix.IN_MODIFY}, + {"IN_MOVE", unix.IN_MOVE}, + {"IN_MOVED_FROM", unix.IN_MOVED_FROM}, + {"IN_MOVED_TO", unix.IN_MOVED_TO}, + {"IN_MOVE_SELF", unix.IN_MOVE_SELF}, + {"IN_OPEN", unix.IN_OPEN}, + {"IN_Q_OVERFLOW", unix.IN_Q_OVERFLOW}, + {"IN_UNMOUNT", unix.IN_UNMOUNT}, + } + + var ( + l []string + unknown = mask + ) + for _, n := range names { + if mask&n.m == n.m { + l = append(l, n.n) + unknown ^= n.m + } + } + if unknown > 0 { + l = append(l, fmt.Sprintf("0x%x", unknown)) + } + var c string + if cookie > 0 { + c = fmt.Sprintf("(cookie: %d) ", cookie) + } + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s %-30s → %s%q\n", + time.Now().Format("15:04:05.000000000"), strings.Join(l, "|"), c, name) +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_netbsd.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_netbsd.go new file mode 100644 index 0000000..e5b3b6f --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/debug_netbsd.go @@ -0,0 +1,25 @@ +package internal + +import "golang.org/x/sys/unix" + +var names = []struct { + n string + m uint32 +}{ + {"NOTE_ATTRIB", unix.NOTE_ATTRIB}, + {"NOTE_CHILD", unix.NOTE_CHILD}, + {"NOTE_DELETE", unix.NOTE_DELETE}, + {"NOTE_EXEC", unix.NOTE_EXEC}, + {"NOTE_EXIT", unix.NOTE_EXIT}, + {"NOTE_EXTEND", unix.NOTE_EXTEND}, + {"NOTE_FORK", unix.NOTE_FORK}, + {"NOTE_LINK", unix.NOTE_LINK}, + {"NOTE_LOWAT", unix.NOTE_LOWAT}, + {"NOTE_PCTRLMASK", unix.NOTE_PCTRLMASK}, + {"NOTE_PDATAMASK", unix.NOTE_PDATAMASK}, + {"NOTE_RENAME", unix.NOTE_RENAME}, + {"NOTE_REVOKE", unix.NOTE_REVOKE}, + {"NOTE_TRACK", unix.NOTE_TRACK}, + {"NOTE_TRACKERR", unix.NOTE_TRACKERR}, + {"NOTE_WRITE", unix.NOTE_WRITE}, +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_openbsd.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_openbsd.go new file mode 100644 index 0000000..1dd455b --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/debug_openbsd.go @@ -0,0 +1,28 @@ +package internal + +import "golang.org/x/sys/unix" + +var names = []struct { + n string + m uint32 +}{ + {"NOTE_ATTRIB", unix.NOTE_ATTRIB}, + // {"NOTE_CHANGE", unix.NOTE_CHANGE}, // Not on 386? + {"NOTE_CHILD", unix.NOTE_CHILD}, + {"NOTE_DELETE", unix.NOTE_DELETE}, + {"NOTE_EOF", unix.NOTE_EOF}, + {"NOTE_EXEC", unix.NOTE_EXEC}, + {"NOTE_EXIT", unix.NOTE_EXIT}, + {"NOTE_EXTEND", unix.NOTE_EXTEND}, + {"NOTE_FORK", unix.NOTE_FORK}, + {"NOTE_LINK", unix.NOTE_LINK}, + {"NOTE_LOWAT", unix.NOTE_LOWAT}, + {"NOTE_PCTRLMASK", unix.NOTE_PCTRLMASK}, + {"NOTE_PDATAMASK", unix.NOTE_PDATAMASK}, + {"NOTE_RENAME", unix.NOTE_RENAME}, + {"NOTE_REVOKE", unix.NOTE_REVOKE}, + {"NOTE_TRACK", unix.NOTE_TRACK}, + {"NOTE_TRACKERR", unix.NOTE_TRACKERR}, + {"NOTE_TRUNCATE", unix.NOTE_TRUNCATE}, + {"NOTE_WRITE", unix.NOTE_WRITE}, +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_solaris.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_solaris.go new file mode 100644 index 0000000..f1b2e73 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/debug_solaris.go @@ -0,0 +1,45 @@ +package internal + +import ( + "fmt" + "os" + "strings" + "time" + + "golang.org/x/sys/unix" +) + +func Debug(name string, mask int32) { + names := []struct { + n string + m int32 + }{ + {"FILE_ACCESS", unix.FILE_ACCESS}, + {"FILE_MODIFIED", unix.FILE_MODIFIED}, + {"FILE_ATTRIB", unix.FILE_ATTRIB}, + {"FILE_TRUNC", unix.FILE_TRUNC}, + {"FILE_NOFOLLOW", unix.FILE_NOFOLLOW}, + {"FILE_DELETE", unix.FILE_DELETE}, + {"FILE_RENAME_TO", unix.FILE_RENAME_TO}, + {"FILE_RENAME_FROM", unix.FILE_RENAME_FROM}, + {"UNMOUNTED", unix.UNMOUNTED}, + {"MOUNTEDOVER", unix.MOUNTEDOVER}, + {"FILE_EXCEPTION", unix.FILE_EXCEPTION}, + } + + var ( + l []string + unknown = mask + ) + for _, n := range names { + if mask&n.m == n.m { + l = append(l, n.n) + unknown ^= n.m + } + } + if unknown > 0 { + l = append(l, fmt.Sprintf("0x%x", unknown)) + } + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s %10d:%-30s → %q\n", + time.Now().Format("15:04:05.000000000"), mask, strings.Join(l, " | "), name) +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_windows.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_windows.go new file mode 100644 index 0000000..52bf4ce --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/debug_windows.go @@ -0,0 +1,40 @@ +package internal + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "golang.org/x/sys/windows" +) + +func Debug(name string, mask uint32) { + names := []struct { + n string + m uint32 + }{ + {"FILE_ACTION_ADDED", windows.FILE_ACTION_ADDED}, + {"FILE_ACTION_REMOVED", windows.FILE_ACTION_REMOVED}, + {"FILE_ACTION_MODIFIED", windows.FILE_ACTION_MODIFIED}, + {"FILE_ACTION_RENAMED_OLD_NAME", windows.FILE_ACTION_RENAMED_OLD_NAME}, + {"FILE_ACTION_RENAMED_NEW_NAME", windows.FILE_ACTION_RENAMED_NEW_NAME}, + } + + var ( + l []string + unknown = mask + ) + for _, n := range names { + if mask&n.m == n.m { + l = append(l, n.n) + unknown ^= n.m + } + } + if unknown > 0 { + l = append(l, fmt.Sprintf("0x%x", unknown)) + } + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s %-65s → %q\n", + time.Now().Format("15:04:05.000000000"), strings.Join(l, " | "), filepath.ToSlash(name)) +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/freebsd.go b/vendor/github.com/fsnotify/fsnotify/internal/freebsd.go new file mode 100644 index 0000000..547df1d --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/freebsd.go @@ -0,0 +1,31 @@ +//go:build freebsd + +package internal + +import ( + "syscall" + + "golang.org/x/sys/unix" +) + +var ( + SyscallEACCES = syscall.EACCES + UnixEACCES = unix.EACCES +) + +var maxfiles uint64 + +func SetRlimit() { + // Go 1.19 will do this automatically: https://go-review.googlesource.com/c/go/+/393354/ + var l syscall.Rlimit + err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &l) + if err == nil && l.Cur != l.Max { + l.Cur = l.Max + syscall.Setrlimit(syscall.RLIMIT_NOFILE, &l) + } + maxfiles = uint64(l.Cur) +} + +func Maxfiles() uint64 { return maxfiles } +func Mkfifo(path string, mode uint32) error { return unix.Mkfifo(path, mode) } +func Mknod(path string, mode uint32, dev int) error { return unix.Mknod(path, mode, uint64(dev)) } diff --git a/vendor/github.com/fsnotify/fsnotify/internal/internal.go b/vendor/github.com/fsnotify/fsnotify/internal/internal.go new file mode 100644 index 0000000..7daa45e --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/internal.go @@ -0,0 +1,2 @@ +// Package internal contains some helpers. +package internal diff --git a/vendor/github.com/fsnotify/fsnotify/internal/unix.go b/vendor/github.com/fsnotify/fsnotify/internal/unix.go new file mode 100644 index 0000000..30976ce --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/unix.go @@ -0,0 +1,31 @@ +//go:build !windows && !darwin && !freebsd + +package internal + +import ( + "syscall" + + "golang.org/x/sys/unix" +) + +var ( + SyscallEACCES = syscall.EACCES + UnixEACCES = unix.EACCES +) + +var maxfiles uint64 + +func SetRlimit() { + // Go 1.19 will do this automatically: https://go-review.googlesource.com/c/go/+/393354/ + var l syscall.Rlimit + err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &l) + if err == nil && l.Cur != l.Max { + l.Cur = l.Max + syscall.Setrlimit(syscall.RLIMIT_NOFILE, &l) + } + maxfiles = uint64(l.Cur) +} + +func Maxfiles() uint64 { return maxfiles } +func Mkfifo(path string, mode uint32) error { return unix.Mkfifo(path, mode) } +func Mknod(path string, mode uint32, dev int) error { return unix.Mknod(path, mode, dev) } diff --git a/vendor/github.com/fsnotify/fsnotify/internal/unix2.go b/vendor/github.com/fsnotify/fsnotify/internal/unix2.go new file mode 100644 index 0000000..37dfedd --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/unix2.go @@ -0,0 +1,7 @@ +//go:build !windows + +package internal + +func HasPrivilegesForSymlink() bool { + return true +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/windows.go b/vendor/github.com/fsnotify/fsnotify/internal/windows.go new file mode 100644 index 0000000..a72c649 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/windows.go @@ -0,0 +1,41 @@ +//go:build windows + +package internal + +import ( + "errors" + + "golang.org/x/sys/windows" +) + +// Just a dummy. +var ( + SyscallEACCES = errors.New("dummy") + UnixEACCES = errors.New("dummy") +) + +func SetRlimit() {} +func Maxfiles() uint64 { return 1<<64 - 1 } +func Mkfifo(path string, mode uint32) error { return errors.New("no FIFOs on Windows") } +func Mknod(path string, mode uint32, dev int) error { return errors.New("no device nodes on Windows") } + +func HasPrivilegesForSymlink() bool { + var sid *windows.SID + err := windows.AllocateAndInitializeSid( + &windows.SECURITY_NT_AUTHORITY, + 2, + windows.SECURITY_BUILTIN_DOMAIN_RID, + windows.DOMAIN_ALIAS_RID_ADMINS, + 0, 0, 0, 0, 0, 0, + &sid) + if err != nil { + return false + } + defer windows.FreeSid(sid) + token := windows.Token(0) + member, err := token.IsMember(sid) + if err != nil { + return false + } + return member || token.IsElevated() +} diff --git a/vendor/github.com/fsnotify/fsnotify/system_bsd.go b/vendor/github.com/fsnotify/fsnotify/system_bsd.go new file mode 100644 index 0000000..f65e8fe --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/system_bsd.go @@ -0,0 +1,7 @@ +//go:build freebsd || openbsd || netbsd || dragonfly + +package fsnotify + +import "golang.org/x/sys/unix" + +const openMode = unix.O_NONBLOCK | unix.O_RDONLY | unix.O_CLOEXEC diff --git a/vendor/github.com/fsnotify/fsnotify/system_darwin.go b/vendor/github.com/fsnotify/fsnotify/system_darwin.go new file mode 100644 index 0000000..a29fc7a --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/system_darwin.go @@ -0,0 +1,8 @@ +//go:build darwin + +package fsnotify + +import "golang.org/x/sys/unix" + +// note: this constant is not defined on BSD +const openMode = unix.O_EVTONLY | unix.O_CLOEXEC diff --git a/vendor/github.com/gen2brain/malgo/.gitignore b/vendor/github.com/gen2brain/malgo/.gitignore new file mode 100644 index 0000000..9f11b75 --- /dev/null +++ b/vendor/github.com/gen2brain/malgo/.gitignore @@ -0,0 +1 @@ +.idea/ diff --git a/vendor/github.com/gen2brain/malgo/LICENSE b/vendor/github.com/gen2brain/malgo/LICENSE new file mode 100644 index 0000000..69843e4 --- /dev/null +++ b/vendor/github.com/gen2brain/malgo/LICENSE @@ -0,0 +1,24 @@ +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 [http://unlicense.org] diff --git a/vendor/github.com/gen2brain/malgo/README.md b/vendor/github.com/gen2brain/malgo/README.md new file mode 100644 index 0000000..cbe316b --- /dev/null +++ b/vendor/github.com/gen2brain/malgo/README.md @@ -0,0 +1,25 @@ +## malgo +[![Build Status](https://github.com/gen2brain/malgo/actions/workflows/build.yml/badge.svg)](https://github.com/gen2brain/malgo/actions) +[![GoDoc](https://godoc.org/github.com/gen2brain/malgo?status.svg)](https://godoc.org/github.com/gen2brain/malgo) +[![Go Report Card](https://goreportcard.com/badge/github.com/gen2brain/malgo?branch=master)](https://goreportcard.com/report/github.com/gen2brain/malgo) + + +Go bindings for [miniaudio](https://github.com/dr-soft/miniaudio) library. + +Requires `cgo` but does not require linking to anything on the Windows/macOS and it links only `-ldl` on Linux/BSDs. + +### Installation + + go get -u github.com/gen2brain/malgo + +### Documentation + +Documentation on [GoDoc](https://godoc.org/github.com/gen2brain/malgo). Also check [examples](https://github.com/gen2brain/malgo/tree/master/_examples). + +### Platforms + +* Windows (WASAPI, DirectSound, WinMM) +* Linux (PulseAudio, ALSA, JACK) +* FreeBSD/NetBSD/OpenBSD (OSS/audio(4)/sndio) +* macOS/iOS (CoreAudio) +* Android (OpenSL|ES, AAudio) diff --git a/vendor/github.com/gen2brain/malgo/constants.go b/vendor/github.com/gen2brain/malgo/constants.go new file mode 100644 index 0000000..e3282a5 --- /dev/null +++ b/vendor/github.com/gen2brain/malgo/constants.go @@ -0,0 +1,5 @@ +package malgo + +const ( + simdAlignment = 64 +) diff --git a/vendor/github.com/gen2brain/malgo/context.go b/vendor/github.com/gen2brain/malgo/context.go new file mode 100644 index 0000000..01c5fc5 --- /dev/null +++ b/vendor/github.com/gen2brain/malgo/context.go @@ -0,0 +1,222 @@ +package malgo + +// #include "malgo.h" +import "C" +import ( + "reflect" + "sync" + "unsafe" +) + +// LogProc type. +type LogProc func(message string) + +// AlsaContextConfig type. +type AlsaContextConfig struct { + UseVerboseDeviceEnumeration uint32 +} + +// PulseContextConfig type. +type PulseContextConfig struct { + PApplicationName *byte + PServerName *byte + // Enables autospawning of the PulseAudio daemon if necessary. + TryAutoSpawn uint32 +} + +// CoreAudioConfig type. +type CoreAudioConfig struct { + SessionCategory IOSSessionCategory + SessionCategoryOptions IOSSessionCategoryOptions +} + +// JackContextConfig type. +type JackContextConfig struct { + PClientName *byte + TryStartServer uint32 +} + +// ContextConfig type. +type ContextConfig struct { + LogCallback *[0]byte + ThreadPriority ThreadPriority + PUserData *byte + AllocationCallbacks AllocationCallbacks + Alsa AlsaContextConfig + Pulse PulseContextConfig + CoreAudio CoreAudioConfig + Jack JackContextConfig +} + +func (d *ContextConfig) toC() (C.ma_context_config, error) { + ctxConfig := C.ma_context_config_init() + ctxConfig.threadPriority = C.ma_thread_priority(d.ThreadPriority) + ctxConfig.pUserData = unsafe.Pointer(d.PUserData) + ctxConfig.allocationCallbacks.pUserData = unsafe.Pointer(d.AllocationCallbacks.PUserData) + ctxConfig.allocationCallbacks.onMalloc = d.AllocationCallbacks.OnMalloc + ctxConfig.allocationCallbacks.onRealloc = d.AllocationCallbacks.OnRealloc + ctxConfig.allocationCallbacks.onFree = d.AllocationCallbacks.OnFree + ctxConfig.alsa.useVerboseDeviceEnumeration = C.uint(d.Alsa.UseVerboseDeviceEnumeration) + ctxConfig.pulse.pApplicationName = (*C.char)(unsafe.Pointer((d.Pulse.PApplicationName))) + ctxConfig.pulse.pServerName = (*C.char)(unsafe.Pointer((d.Pulse.PServerName))) + ctxConfig.pulse.tryAutoSpawn = C.uint(d.Pulse.TryAutoSpawn) + ctxConfig.coreaudio.sessionCategory = C.ma_ios_session_category(d.CoreAudio.SessionCategory) + ctxConfig.coreaudio.sessionCategoryOptions = C.uint(d.CoreAudio.SessionCategoryOptions) + ctxConfig.jack.pClientName = (*C.char)(unsafe.Pointer((d.Jack.PClientName))) + ctxConfig.jack.tryStartServer = C.uint(d.Jack.TryStartServer) + + return ctxConfig, nil +} + +// AllocationCallbacks types. +type AllocationCallbacks struct { + PUserData *byte + OnMalloc *[0]byte + OnRealloc *[0]byte + OnFree *[0]byte +} + +// Context is used for selecting and initializing the relevant backends. +type Context struct { + ptr *unsafe.Pointer +} + +// DefaultContext is an unspecified context. It can be used to initialize a streaming +// function with implicit context defaults. +var DefaultContext Context = Context{} + +func (ctx Context) cptr() *C.ma_context { + return (*C.ma_context)(*ctx.ptr) +} + +// Uninit uninitializes a context. +// Results are undefined if you call this while any device created by this context is still active. +func (ctx Context) Uninit() error { + result := C.ma_context_uninit(ctx.cptr()) + return errorFromResult(result) +} + +// Devices retrieves basic information about every active playback or capture device. +func (ctx Context) Devices(kind DeviceType) ([]DeviceInfo, error) { + contextMutex.Lock() + defer contextMutex.Unlock() + + var playbackDevices *C.ma_device_info + var playbackDeviceCount C.ma_uint32 + var captureDevices *C.ma_device_info + var captureDeviceCount C.ma_uint32 + + result := C.ma_context_get_devices(ctx.cptr(), + &playbackDevices, &playbackDeviceCount, + &captureDevices, &captureDeviceCount) + err := errorFromResult(result) + if err != nil { + return nil, err + } + devices := playbackDevices + deviceCount := int(playbackDeviceCount) + if kind == Capture { + devices = captureDevices + deviceCount = int(captureDeviceCount) + } + info := make([]DeviceInfo, deviceCount) + deviceInfoAddr := unsafe.Pointer(devices) + for i := 0; i < deviceCount; i++ { + info[i] = deviceInfoFromPointer(deviceInfoAddr) + deviceInfoAddr = unsafe.Add(deviceInfoAddr, rawDeviceInfoSize) + } + + return info, nil +} + +// DeviceInfo retrieves information about a device of the given type, with the specified ID and share mode. +func (ctx Context) DeviceInfo(kind DeviceType, id DeviceID, mode ShareMode) (DeviceInfo, error) { + var info C.ma_device_info + + result := C.ma_context_get_device_info(ctx.cptr(), C.ma_device_type(kind), id.cptr(), &info) + err := errorFromResult(result) + if err != nil { + return DeviceInfo{}, err + } + + return deviceInfoFromPointer(unsafe.Pointer(&info)), nil +} + +var contextMutex sync.Mutex +var logProcMap = make(map[*C.ma_context]LogProc) + +// SetLogProc sets the logging callback for the context. +func (ctx Context) SetLogProc(proc LogProc) { + contextMutex.Lock() + defer contextMutex.Unlock() + ptr := ctx.cptr() + if proc != nil { + logProcMap[ptr] = proc + } else { + delete(logProcMap, ptr) + } +} + +//export goLogCallback +func goLogCallback(pContext *C.ma_context, message *C.char) { + contextMutex.Lock() + callback := logProcMap[pContext] + contextMutex.Unlock() + + if callback != nil { + callback(C.GoString(message)) + } +} + +// AllocatedContext is a Context that has been created by the application. +// It must be freed after use in order to release resources. +type AllocatedContext struct { + Context + config *C.ma_context_config +} + +// InitContext creates and initializes a context. +// When the application no longer needs the context instance, it needs to call Free() . +func InitContext(backends []Backend, config ContextConfig, logProc LogProc) (*AllocatedContext, error) { + configC, err := config.toC() + if err != nil { + return nil, err + } + + ptr := C.ma_malloc(C.sizeof_ma_context, nil) + ctx := AllocatedContext{ + Context: Context{ptr: &ptr}, + } + if uintptr(*ctx.Context.ptr) == 0 { + ctx.Free() + return nil, ErrOutOfMemory + } + + C.goSetContextConfigCallbacks(&configC, ctx.cptr()) + ctx.SetLogProc(logProc) + + var backendsArg *C.ma_backend + backendCountArg := (C.ma_uint32)(len(backends)) + if backendCountArg > 0 { + backendsArg = (*C.ma_backend)(unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&backends)).Data)) + } + + result := C.ma_context_init(backendsArg, backendCountArg, &configC, ctx.cptr()) + if err := errorFromResult(result); err != nil { + ctx.SetLogProc(nil) + ctx.Free() + return nil, err + } + return &ctx, nil +} + +// Free must be called when the allocated data is no longer used. +// This function must only be called for an uninitialized context. +func (ctx *AllocatedContext) Free() { + if ctx.Context.ptr == nil || uintptr(*ctx.Context.ptr) == 0 { + return + } + ctx.SetLogProc(nil) + C.ma_free(unsafe.Pointer(ctx.cptr()), nil) + ctx.Context.ptr = nil +} diff --git a/vendor/github.com/gen2brain/malgo/device.go b/vendor/github.com/gen2brain/malgo/device.go new file mode 100644 index 0000000..4a70f80 --- /dev/null +++ b/vendor/github.com/gen2brain/malgo/device.go @@ -0,0 +1,188 @@ +package malgo + +// #include "malgo.h" +import "C" +import ( + "sync" + "unsafe" +) + +// DataProc type. +type DataProc func(pOutputSample, pInputSamples []byte, framecount uint32) + +// StopProc type. +type StopProc func() + +// DeviceCallbacks contains callbacks for one initialized device. +type DeviceCallbacks struct { + // Data is called for the full duplex IO. + Data DataProc + // Stop is called when the device stopped. + Stop StopProc +} + +// Device represents a streaming instance. +type Device struct { + ptr *unsafe.Pointer +} + +// InitDevice initializes a device. +// +// The device ID can be nil, in which case the default device is used. Otherwise, you +// can retrieve the ID by calling Context.Devices() and use the ID from the returned data. +// +// Set device ID to nil to use the default device. Do _not_ rely on the first device ID returned +// by Context.Devices() to be the default device. +// +// The returned instance has to be cleaned up using Uninit(). +func InitDevice(context Context, deviceConfig DeviceConfig, deviceCallbacks DeviceCallbacks) (*Device, error) { + ptr := C.ma_malloc(C.sizeof_ma_device, nil) + dev := Device{ + ptr: &ptr, + } + if uintptr(*dev.ptr) == 0 { + return nil, ErrOutOfMemory + } + devConfigC, release := deviceConfig.toC() + defer release() + + rawDevice := dev.cptr() + C.goSetDeviceConfigCallbacks(&devConfigC) + result := C.ma_device_init(context.cptr(), &devConfigC, rawDevice) + if result != 0 { + dev.free() + return nil, errorFromResult(result) + } + deviceMutex.Lock() + dataCallbacks[rawDevice] = deviceCallbacks.Data + stopCallbacks[rawDevice] = deviceCallbacks.Stop + deviceMutex.Unlock() + + return &dev, nil +} + +func (dev Device) cptr() *C.ma_device { + return (*C.ma_device)(*dev.ptr) +} + +func (dev Device) free() { + if dev.ptr != nil { + C.ma_free(*dev.ptr, nil) + } +} + +// Type returns device type. +func (dev *Device) Type() DeviceType { + return DeviceType(dev.cptr()._type) +} + +// PlaybackFormat returns device playback format. +func (dev *Device) PlaybackFormat() FormatType { + return FormatType(dev.cptr().playback.format) +} + +// CaptureFormat returns device capture format. +func (dev *Device) CaptureFormat() FormatType { + return FormatType(dev.cptr().capture.format) +} + +// PlaybackChannels returns number of playback channels. +func (dev *Device) PlaybackChannels() uint32 { + return uint32(dev.cptr().playback.channels) +} + +// CaptureChannels returns number of playback channels. +func (dev *Device) CaptureChannels() uint32 { + return uint32(dev.cptr().capture.channels) +} + +// SampleRate returns sample rate. +func (dev *Device) SampleRate() uint32 { + return uint32(dev.cptr().sampleRate) +} + +// Start 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. +func (dev *Device) Start() error { + result := C.ma_device_start(dev.cptr()) + return errorFromResult(result) +} + +// IsStarted determines whether or not the device is started. +func (dev *Device) IsStarted() bool { + result := C.ma_device_is_started(dev.cptr()) + return result != 0 +} + +// Stop puts the device to sleep, but does not uninitialize it. Use 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). +func (dev *Device) Stop() error { + result := C.ma_device_stop(dev.cptr()) + return errorFromResult(result) +} + +// Uninit uninitializes a device. +// +// This will explicitly stop the device. You do not need to call Stop() beforehand, but it's +// harmless if you do. +func (dev *Device) Uninit() { + rawDevice := dev.cptr() + deviceMutex.Lock() + delete(dataCallbacks, rawDevice) + delete(stopCallbacks, rawDevice) + deviceMutex.Unlock() + + C.ma_device_uninit(rawDevice) + dev.free() +} + +var deviceMutex sync.Mutex +var dataCallbacks = make(map[*C.ma_device]DataProc) +var stopCallbacks = make(map[*C.ma_device]StopProc) + +//export goDataCallback +func goDataCallback(pDevice *C.ma_device, pOutput, pInput unsafe.Pointer, frameCount C.ma_uint32) { + deviceMutex.Lock() + callback := dataCallbacks[pDevice] + deviceMutex.Unlock() + + if callback != nil { + var inputSamples, outputSamples []byte + + if pOutput != nil { + sampleCount := uint32(frameCount) * uint32(pDevice.playback.channels) + sizeInBytes := uint32(C.ma_get_bytes_per_sample(pDevice.playback.format)) + outputSamples = unsafe.Slice((*byte)(pOutput), sampleCount*sizeInBytes) + } + + if pInput != nil { + sampleCount := uint32(frameCount) * uint32(pDevice.capture.channels) + sizeInBytes := uint32(C.ma_get_bytes_per_sample(pDevice.capture.format)) + inputSamples = unsafe.Slice((*byte)(pInput), sampleCount*sizeInBytes) + } + + callback(outputSamples, inputSamples, uint32(frameCount)) + } +} + +//export goStopCallback +func goStopCallback(pDevice *C.ma_device) { + deviceMutex.Lock() + callback := stopCallbacks[pDevice] + deviceMutex.Unlock() + + if callback != nil { + callback() + } +} diff --git a/vendor/github.com/gen2brain/malgo/device_config.go b/vendor/github.com/gen2brain/malgo/device_config.go new file mode 100644 index 0000000..80a8152 --- /dev/null +++ b/vendor/github.com/gen2brain/malgo/device_config.go @@ -0,0 +1,205 @@ +package malgo + +// #include "malgo.h" +import "C" +import ( + "unsafe" +) + +// DeviceConfig type. +type DeviceConfig struct { + DeviceType DeviceType + SampleRate uint32 + PeriodSizeInFrames uint32 + PeriodSizeInMilliseconds uint32 + Periods uint32 + PerformanceProfile PerformanceProfile + NoPreSilencedOutputBuffer uint32 + NoClip uint32 + NoDisableDenormals uint32 + NoFixedSizedCallback uint32 + DataCallback *[0]byte + NotificationCallback *[0]byte + StopCallback *[0]byte + PUserData *byte + Resampling ResampleConfig + Playback SubConfig + Capture SubConfig + Wasapi WasapiDeviceConfig + Alsa AlsaDeviceConfig + Pulse PulseDeviceConfig + // TODO: Add support for coreaudio, opensl, aaudio +} + +// DefaultDeviceConfig returns a default device config. +func DefaultDeviceConfig(deviceType DeviceType) DeviceConfig { + config := C.ma_device_config_init(C.ma_device_type(deviceType)) + + var deviceConfig DeviceConfig + + deviceConfig.DeviceType = DeviceType(config.deviceType) + deviceConfig.SampleRate = uint32(config.sampleRate) + deviceConfig.PeriodSizeInFrames = uint32(config.periodSizeInFrames) + deviceConfig.PeriodSizeInMilliseconds = uint32(config.periodSizeInMilliseconds) + deviceConfig.Periods = uint32(config.periods) + deviceConfig.PerformanceProfile = PerformanceProfile(config.performanceProfile) + deviceConfig.NoPreSilencedOutputBuffer = uint32(config.noPreSilencedOutputBuffer) + deviceConfig.NoClip = uint32(config.noClip) + deviceConfig.NoDisableDenormals = uint32(config.noDisableDenormals) + deviceConfig.NoFixedSizedCallback = uint32(config.noFixedSizedCallback) + deviceConfig.DataCallback = config.dataCallback + deviceConfig.NotificationCallback = config.notificationCallback + deviceConfig.StopCallback = config.stopCallback + deviceConfig.PUserData = (*byte)(config.pUserData) + + deviceConfig.Resampling.Algorithm = ResampleAlgorithm(config.resampling.algorithm) + deviceConfig.Resampling.Linear.LpfOrder = uint32(config.resampling.linear.lpfOrder) + + deviceConfig.Playback.DeviceID = unsafe.Pointer(config.playback.pDeviceID) + deviceConfig.Playback.Format = FormatType(config.playback.format) + deviceConfig.Playback.Channels = uint32(config.playback.channels) + deviceConfig.Playback.ChannelMap = unsafe.Pointer(config.playback.pChannelMap) + deviceConfig.Playback.ShareMode = ShareMode(config.playback.shareMode) + + deviceConfig.Capture.DeviceID = unsafe.Pointer(config.capture.pDeviceID) + deviceConfig.Capture.Format = FormatType(config.capture.format) + deviceConfig.Capture.Channels = uint32(config.capture.channels) + deviceConfig.Capture.ChannelMap = unsafe.Pointer(config.capture.pChannelMap) + deviceConfig.Capture.ShareMode = ShareMode(config.capture.shareMode) + + deviceConfig.Wasapi.NoAutoConvertSRC = uint32(config.wasapi.noAutoConvertSRC) + deviceConfig.Wasapi.NoDefaultQualitySRC = uint32(config.wasapi.noDefaultQualitySRC) + deviceConfig.Wasapi.NoAutoStreamRouting = uint32(config.wasapi.noAutoStreamRouting) + deviceConfig.Wasapi.NoHardwareOffloading = uint32(config.wasapi.noHardwareOffloading) + + deviceConfig.Alsa.NoMMap = uint32(config.alsa.noMMap) + deviceConfig.Alsa.NoAutoFormat = uint32(config.alsa.noAutoFormat) + deviceConfig.Alsa.NoAutoChannels = uint32(config.alsa.noAutoChannels) + deviceConfig.Alsa.NoAutoResample = uint32(config.alsa.noAutoResample) + + if config.pulse.pStreamNameCapture != nil { + deviceConfig.Pulse.StreamNameCapture = C.GoString(config.pulse.pStreamNameCapture) + } + if config.pulse.pStreamNamePlayback != nil { + deviceConfig.Pulse.StreamNamePlayback = C.GoString(config.pulse.pStreamNamePlayback) + } + + return deviceConfig +} + +func (d *DeviceConfig) toC() (C.ma_device_config, func()) { + deviceConfig := C.ma_device_config_init(C.ma_device_type(d.DeviceType)) + + deviceConfig.sampleRate = C.uint(d.SampleRate) + deviceConfig.periodSizeInFrames = C.uint(d.PeriodSizeInFrames) + deviceConfig.periodSizeInMilliseconds = C.uint(d.PeriodSizeInMilliseconds) + deviceConfig.periods = C.uint(d.Periods) + deviceConfig.performanceProfile = C.ma_performance_profile(d.PerformanceProfile) + deviceConfig.noPreSilencedOutputBuffer = C.uchar(d.NoPreSilencedOutputBuffer) + deviceConfig.noClip = C.uchar(d.NoClip) + deviceConfig.noDisableDenormals = C.uchar(d.NoDisableDenormals) + deviceConfig.noFixedSizedCallback = C.uchar(d.NoFixedSizedCallback) + + deviceConfig.dataCallback = d.DataCallback + deviceConfig.notificationCallback = d.NotificationCallback + deviceConfig.stopCallback = d.StopCallback + deviceConfig.pUserData = unsafe.Pointer(d.PUserData) + + deviceConfig.resampling.algorithm = C.ma_resample_algorithm(d.Resampling.Algorithm) + deviceConfig.resampling.linear.lpfOrder = C.uint(d.Resampling.Linear.LpfOrder) + + deviceConfig.playback.pDeviceID = (*C.ma_device_id)(d.Playback.DeviceID) + deviceConfig.playback.format = C.ma_format(d.Playback.Format) + deviceConfig.playback.channels = C.uint(d.Playback.Channels) + deviceConfig.playback.pChannelMap = (*C.ma_channel)(d.Playback.ChannelMap) + deviceConfig.playback.shareMode = C.ma_share_mode(d.Playback.ShareMode) + + deviceConfig.capture.pDeviceID = (*C.ma_device_id)(d.Capture.DeviceID) + deviceConfig.capture.format = C.ma_format(d.Capture.Format) + deviceConfig.capture.channels = C.uint(d.Capture.Channels) + deviceConfig.capture.pChannelMap = (*C.ma_channel)(d.Capture.ChannelMap) + deviceConfig.capture.shareMode = C.ma_share_mode(d.Capture.ShareMode) + + deviceConfig.wasapi.noAutoConvertSRC = C.uchar(d.Wasapi.NoAutoConvertSRC) + deviceConfig.wasapi.noDefaultQualitySRC = C.uchar(d.Wasapi.NoDefaultQualitySRC) + deviceConfig.wasapi.noAutoStreamRouting = C.uchar(d.Wasapi.NoAutoStreamRouting) + deviceConfig.wasapi.noHardwareOffloading = C.uchar(d.Wasapi.NoHardwareOffloading) + + deviceConfig.alsa.noMMap = C.uint(d.Alsa.NoMMap) + deviceConfig.alsa.noAutoFormat = C.uint(d.Alsa.NoAutoFormat) + deviceConfig.alsa.noAutoChannels = C.uint(d.Alsa.NoAutoChannels) + deviceConfig.alsa.noAutoResample = C.uint(d.Alsa.NoAutoResample) + + var releasers []func() + if d.Pulse.StreamNameCapture != "" { + streamNameCapturePtr := C.CString(d.Pulse.StreamNameCapture) + deviceConfig.pulse.pStreamNameCapture = streamNameCapturePtr + releasers = append(releasers, func() { + C.ma_free(unsafe.Pointer(streamNameCapturePtr), nil) + }) + } + if d.Pulse.StreamNamePlayback != "" { + streamNamePlaybackPtr := C.CString(d.Pulse.StreamNamePlayback) + deviceConfig.pulse.pStreamNamePlayback = streamNamePlaybackPtr + releasers = append(releasers, func() { + C.ma_free(unsafe.Pointer(streamNamePlaybackPtr), nil) + }) + } + + return deviceConfig, func() { + for _, release := range releasers { + defer release() + } + } +} + +// SubConfig type. +type SubConfig struct { + DeviceID unsafe.Pointer + Format FormatType + Channels uint32 + ChannelMap unsafe.Pointer + ShareMode ShareMode + + // Unexposed: channelMixMode, calculateLFEFromSpatialChannels +} + +// WasapiDeviceConfig type. +type WasapiDeviceConfig struct { + NoAutoConvertSRC uint32 + NoDefaultQualitySRC uint32 + NoAutoStreamRouting uint32 + NoHardwareOffloading uint32 +} + +// AlsaDeviceConfig type. +type AlsaDeviceConfig struct { + NoMMap uint32 + NoAutoFormat uint32 + NoAutoChannels uint32 + NoAutoResample uint32 +} + +// PulseDeviceConfig type. +type PulseDeviceConfig struct { + StreamNamePlayback string + StreamNameCapture string +} + +// ResampleConfig type. +type ResampleConfig struct { + Algorithm ResampleAlgorithm + Linear ResampleLinearConfig + + // Unexposed: format, channels, sampleRateIn, sampleRateOut, pBackendVTable, pBackendUserData +} + +// ResampleLinearConfig type. +type ResampleLinearConfig struct { + LpfOrder uint32 +} + +// ResampleSpeexConfig type. +type ResampleSpeexConfig struct { + Quality int +} diff --git a/vendor/github.com/gen2brain/malgo/device_info.go b/vendor/github.com/gen2brain/malgo/device_info.go new file mode 100644 index 0000000..e42940d --- /dev/null +++ b/vendor/github.com/gen2brain/malgo/device_info.go @@ -0,0 +1,81 @@ +package malgo + +// #include "malgo.h" +import "C" +import ( + "encoding/hex" + "fmt" + "unsafe" +) + +// DeviceID type. +type DeviceID [C.sizeof_ma_device_id]byte + +// String returns the string representation of the identifier. +// It is the hexadecimal form of the underlying bytes of a minimum length of 2 digits, with trailing zeroes removed. +func (d DeviceID) String() string { + displayLen := len(d) + for (displayLen > 1) && (d[displayLen-1] == 0) { + displayLen-- + } + return hex.EncodeToString(d[:displayLen]) +} + +func (d *DeviceID) Pointer() unsafe.Pointer { + return C.CBytes(d[:]) +} + +func (d *DeviceID) cptr() *C.ma_device_id { + return (*C.ma_device_id)(unsafe.Pointer(d)) +} + +// DeviceInfo type. +type DeviceInfo struct { + ID DeviceID + name [256]byte + IsDefault uint32 + FormatCount uint32 + Formats []DataFormat +} + +// Name returns the name of the device. +func (d *DeviceInfo) Name() string { + // find the first null byte in d.name + var end int + for end = 0; end < len(d.name) && d.name[end] != 0; end++ { + } + return string(d.name[:end]) +} + +// String returns string. +func (d *DeviceInfo) String() string { + return fmt.Sprintf("{ID: [%v], Name: %s}", d.ID, d.Name()) +} + +func deviceInfoFromPointer(ptr unsafe.Pointer) DeviceInfo { + device := (*C.ma_device_info)(ptr) + var newDevice DeviceInfo + newDevice.ID = DeviceID(device.id) + for i := 0; i < len(device.name); i++ { + newDevice.name[i] = (byte)(device.name[i]) + } + newDevice.IsDefault = uint32(device.isDefault) + newDevice.FormatCount = uint32(device.nativeDataFormatCount) + newDevice.Formats = make([]DataFormat, newDevice.FormatCount) + for i := 0; i < int(newDevice.FormatCount); i++ { + newDevice.Formats[i] = DataFormat{ + Format: FormatType(device.nativeDataFormats[i].format), + Channels: uint32(device.nativeDataFormats[i].channels), + SampleRate: uint32(device.nativeDataFormats[i].sampleRate), + Flags: uint32(device.nativeDataFormats[i].flags), + } + } + return newDevice +} + +type DataFormat struct { + Format FormatType + Channels uint32 + SampleRate uint32 + Flags uint32 +} diff --git a/vendor/github.com/gen2brain/malgo/enumerations.go b/vendor/github.com/gen2brain/malgo/enumerations.go new file mode 100644 index 0000000..332336c --- /dev/null +++ b/vendor/github.com/gen2brain/malgo/enumerations.go @@ -0,0 +1,118 @@ +package malgo + +// Backend type. +type Backend uint32 + +// Backend enumeration. +const ( + BackendWasapi = iota + BackendDsound + BackendWinmm + BackendCoreaudio + BackendSndio + BackendAudio4 + BackendOss + BackendPulseaudio + BackendAlsa + BackendJack + BackendAaudio + BackendOpensl + BackendWebaudio + BackendNull +) + +// DeviceType type. +type DeviceType uint32 + +// DeviceType enumeration. +const ( + Playback DeviceType = iota + 1 + Capture + Duplex + Loopback +) + +// ShareMode type. +type ShareMode uint32 + +// ShareMode enumeration. +const ( + Shared ShareMode = iota + Exclusive +) + +// PerformanceProfile type. +type PerformanceProfile uint32 + +// PerformanceProfile enumeration. +const ( + LowLatency PerformanceProfile = iota + Conservative +) + +// FormatType type. +type FormatType uint32 + +// Format enumeration. +const ( + FormatUnknown FormatType = iota + FormatU8 + FormatS16 + FormatS24 + FormatS32 + FormatF32 +) + +// ThreadPriority type. +type ThreadPriority int32 + +// ThreadPriority enumeration. +const ( + ThreadPriorityIdle ThreadPriority = -5 + ThreadPriorityLowest ThreadPriority = -4 + ThreadPriorityLow ThreadPriority = -3 + ThreadPriorityNormal ThreadPriority = -2 + ThreadPriorityHigh ThreadPriority = -1 + ThreadPriorityHighest ThreadPriority = 0 + ThreadPriorityRealtime ThreadPriority = 1 + + ThreadPriorityDefault ThreadPriority = 0 +) + +// ResampleAlgorithm type. +type ResampleAlgorithm uint32 + +// ResampleAlgorithm enumeration. +const ( + ResampleAlgorithmLinear ResampleAlgorithm = 0 + ResampleAlgorithmSpeex ResampleAlgorithm = 1 +) + +// IOSSessionCategory type. +type IOSSessionCategory uint32 + +// IOSSessionCategory enumeration. +const ( + IOSSessionCategoryDefault IOSSessionCategory = iota // AVAudioSessionCategoryPlayAndRecord with AVAudioSessionCategoryOptionDefaultToSpeaker. + IOSSessionCategoryNone // Leave the session category unchanged. + IOSSessionCategoryAmbient // AVAudioSessionCategoryAmbient + IOSSessionCategorySoloAmbient // AVAudioSessionCategorySoloAmbient + IOSSessionCategoryPlayback // AVAudioSessionCategoryPlayback + IOSSessionCategoryRecord // AVAudioSessionCategoryRecord + IOSSessionCategoryPlayAndRecord // AVAudioSessionCategoryPlayAndRecord + IOSSessionCategoryMultiRoute // AVAudioSessionCategoryMultiRoute +) + +// IOSSessionCategoryOptions type. +type IOSSessionCategoryOptions uint32 + +// IOSSessionCategoryOptions enumeration. +const ( + IOSSessionCategoryOptionMixWithOthers = 0x01 // AVAudioSessionCategoryOptionMixWithOthers + IOSSessionCategoryOptionDuckOthers = 0x02 // AVAudioSessionCategoryOptionDuckOthers + IOSSessionCategoryOptionAllowBluetooth = 0x04 // AVAudioSessionCategoryOptionAllowBluetooth + IOSSessionCategoryOptionDefaultToSpeaker = 0x08 // AVAudioSessionCategoryOptionDefaultToSpeaker + IOSSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers = 0x11 // AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers + IOSSessionCategoryOptionAllowBluetoothA2dp = 0x20 // AVAudioSessionCategoryOptionAllowBluetoothA2DP + IOSSessionCategoryOptionAllowAirPlay = 0x40 // AVAudioSessionCategoryOptionAllowAirPlay +) diff --git a/vendor/github.com/gen2brain/malgo/errors.go b/vendor/github.com/gen2brain/malgo/errors.go new file mode 100644 index 0000000..9376672 --- /dev/null +++ b/vendor/github.com/gen2brain/malgo/errors.go @@ -0,0 +1,108 @@ +package malgo + +/* +#include "malgo.h" +*/ +import "C" + +// Result type. +type Result int32 + +func (self Result) Error() string { + return errTag + C.GoString(C.ma_result_description(C.ma_result(self))) +} + +// Errors. +const ( + errTag = "miniaudio: " +) + +var ( + // General errors. + ErrGeneric = Result(C.MA_ERROR) + ErrInvalidArgs = Result(C.MA_INVALID_ARGS) + ErrInvalidOperation = Result(C.MA_INVALID_OPERATION) + ErrOutOfMemory = Result(C.MA_OUT_OF_MEMORY) + ErrOutOfRange = Result(C.MA_OUT_OF_RANGE) + ErrAccessDenied = Result(C.MA_ACCESS_DENIED) + ErrDoesNotExist = Result(C.MA_DOES_NOT_EXIST) + ErrAlreadyExists = Result(C.MA_ALREADY_EXISTS) + ErrTooManyOpenFiles = Result(C.MA_TOO_MANY_OPEN_FILES) + ErrInvalidFile = Result(C.MA_INVALID_FILE) + ErrTooBig = Result(C.MA_TOO_BIG) + ErrPathTooLong = Result(C.MA_PATH_TOO_LONG) + ErrNameTooLong = Result(C.MA_NAME_TOO_LONG) + ErrNotDirectory = Result(C.MA_NOT_DIRECTORY) + ErrIsDirectory = Result(C.MA_IS_DIRECTORY) + ErrDirectoryNotEmpty = Result(C.MA_DIRECTORY_NOT_EMPTY) + ErrAtEnd = Result(C.MA_AT_END) + ErrNoSpace = Result(C.MA_NO_SPACE) + ErrBusy = Result(C.MA_BUSY) + ErrIO = Result(C.MA_IO_ERROR) + ErrInterrupt = Result(C.MA_INTERRUPT) + ErrUnavailable = Result(C.MA_UNAVAILABLE) + ErrAlreadyInUse = Result(C.MA_ALREADY_IN_USE) + ErrBadAddress = Result(C.MA_BAD_ADDRESS) + ErrBadSeek = Result(C.MA_BAD_SEEK) + ErrBadPipe = Result(C.MA_BAD_PIPE) + ErrDeadlock = Result(C.MA_DEADLOCK) + ErrTooManyLinks = Result(C.MA_TOO_MANY_LINKS) + ErrNotImplemented = Result(C.MA_NOT_IMPLEMENTED) + ErrNoMessage = Result(C.MA_NO_MESSAGE) + ErrBadMessage = Result(C.MA_BAD_MESSAGE) + ErrNoDataAvailable = Result(C.MA_NO_DATA_AVAILABLE) + ErrInvalidData = Result(C.MA_INVALID_DATA) + ErrTimeout = Result(C.MA_TIMEOUT) + ErrNetwork = Result(C.MA_NO_NETWORK) + ErrNotUnique = Result(C.MA_NOT_UNIQUE) + ErrNotSocket = Result(C.MA_NOT_SOCKET) + ErrNoAddress = Result(C.MA_NO_ADDRESS) + ErrBadProtocol = Result(C.MA_BAD_PROTOCOL) + ErrProtocolUnavailable = Result(C.MA_PROTOCOL_UNAVAILABLE) + ErrProtocolNotSupported = Result(C.MA_PROTOCOL_NOT_SUPPORTED) + ErrProtocolFamilyNotSupported = Result(C.MA_PROTOCOL_FAMILY_NOT_SUPPORTED) + ErrAddressFamilyNotSupported = Result(C.MA_ADDRESS_FAMILY_NOT_SUPPORTED) + ErrSocketNotSupported = Result(C.MA_SOCKET_NOT_SUPPORTED) + ErrConnectionReset = Result(C.MA_CONNECTION_RESET) + ErrAlreadyConnected = Result(C.MA_ALREADY_CONNECTED) + ErrNotConnected = Result(C.MA_NOT_CONNECTED) + ErrConnectionRefused = Result(C.MA_CONNECTION_REFUSED) + ErrNoHost = Result(C.MA_NO_HOST) + ErrInProgress = Result(C.MA_IN_PROGRESS) + ErrCancelled = Result(C.MA_CANCELLED) + ErrMemoryAlreadyMapped = Result(C.MA_MEMORY_ALREADY_MAPPED) + + // General miniaudio-specific errors. + ErrFormatNotSupported = Result(C.MA_FORMAT_NOT_SUPPORTED) + ErrDeviceTypeNotSupported = Result(C.MA_DEVICE_TYPE_NOT_SUPPORTED) + ErrShareModeNotSupported = Result(C.MA_SHARE_MODE_NOT_SUPPORTED) + ErrNoBackend = Result(C.MA_NO_BACKEND) + ErrNoDevice = Result(C.MA_NO_DEVICE) + ErrAPINotFound = Result(C.MA_API_NOT_FOUND) + ErrInvalidDeviceConfig = Result(C.MA_INVALID_DEVICE_CONFIG) + ErrLoop = Result(C.MA_LOOP) + + // State errors. + + ErrDeviceNotInitialized = Result(C.MA_DEVICE_NOT_INITIALIZED) + ErrDeviceAlreadyInitialized = Result(C.MA_DEVICE_ALREADY_INITIALIZED) + ErrDeviceNotStarted = Result(C.MA_DEVICE_NOT_STARTED) + ErrDeviceNotStopped = Result(C.MA_DEVICE_NOT_STOPPED) + + // Operation errors. + + ErrFailedToInitBackend = Result(C.MA_FAILED_TO_INIT_BACKEND) + ErrFailedToOpenBackendDevice = Result(C.MA_FAILED_TO_OPEN_BACKEND_DEVICE) + ErrFailedToStartBackendDevice = Result(C.MA_FAILED_TO_START_BACKEND_DEVICE) + ErrFailedToStopBackendDevice = Result(C.MA_FAILED_TO_STOP_BACKEND_DEVICE) +) + +// errorFromResult returns error for result code. +func errorFromResult(r C.ma_result) error { + switch r { + case C.MA_SUCCESS: + return nil + default: + return Result(r) + } +} diff --git a/vendor/github.com/gen2brain/malgo/malgo.h b/vendor/github.com/gen2brain/malgo/malgo.h new file mode 100644 index 0000000..5c0682e --- /dev/null +++ b/vendor/github.com/gen2brain/malgo/malgo.h @@ -0,0 +1,21 @@ +#ifndef H_MALGO +#define H_MALGO + +#include "miniaudio.h" + +#ifdef __cplusplus +extern "C" { +#endif + +extern void goLogCallback(ma_context* pContext, char* message); +void goSetContextConfigCallbacks(ma_context_config* pConfig, ma_context* pContext); + +extern void goDataCallback(ma_device *pDevice, void *pOutput, void *pInput, ma_uint32 frameCount); +extern void goStopCallback(ma_device* pDevice); +void goSetDeviceConfigCallbacks(ma_device_config* pConfig); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/vendor/github.com/gen2brain/malgo/miniaudio.c b/vendor/github.com/gen2brain/malgo/miniaudio.c new file mode 100644 index 0000000..32b808f --- /dev/null +++ b/vendor/github.com/gen2brain/malgo/miniaudio.c @@ -0,0 +1,29 @@ +#include "_cgo_export.h" + +#define MINIAUDIO_IMPLEMENTATION +#include "miniaudio.h" + +static void goLogCallbackWrapper(void* pUserData, ma_uint32 logLevel, const char *message) { + goLogCallback((ma_context*) pUserData, (char *)message); +} + +// Note that the context in the argument has not been initialized here. We will only use the pointer as pUserData +// so that we could easily identify which context a log callback belongs to. +void goSetContextConfigCallbacks(ma_context_config* pConfig, ma_context* pContext) { + ma_log* log = malloc(sizeof(ma_log)); + ma_log_init(NULL, log); // TODO: Set allocation callback? + ma_log_register_callback(log, ma_log_callback_init(goLogCallbackWrapper, (void*)pContext)); + pConfig->pLog = log; +} + +static void goDataCallbackWrapper(ma_device *pDevice, + void *pOutput, const void *pInput, + ma_uint32 frames) +{ + goDataCallback(pDevice, pOutput, (void *)pInput, frames); +} + +void goSetDeviceConfigCallbacks(ma_device_config* pConfig) { + pConfig->dataCallback = goDataCallbackWrapper; + pConfig->stopCallback = goStopCallback; +} diff --git a/vendor/github.com/gen2brain/malgo/miniaudio.go b/vendor/github.com/gen2brain/malgo/miniaudio.go new file mode 100644 index 0000000..766b68b --- /dev/null +++ b/vendor/github.com/gen2brain/malgo/miniaudio.go @@ -0,0 +1,34 @@ +// Package malgo - Mini audio library (miniaudio cgo bindings). +package malgo + +/* +#cgo CFLAGS: -std=gnu99 -Wno-unused-result +#cgo ma_debug CFLAGS: -DMA_DEBUG_OUTPUT=1 + +#cgo linux,!android LDFLAGS: -ldl -lpthread -lm +#cgo linux,arm LDFLAGS: -latomic +#cgo openbsd LDFLAGS: -ldl -lpthread -lm +#cgo netbsd LDFLAGS: -ldl -lpthread -lm +#cgo freebsd LDFLAGS: -ldl -lpthread -lm +#cgo android LDFLAGS: -lm +#cgo ios CFLAGS: -x objective-c +#cgo ios LDFLAGS: -framework CoreFoundation -framework AVFAudio -framework CoreAudio -framework AudioToolbox + +#cgo !noasm,!arm,!arm64 CFLAGS: -msse2 +#cgo !noasm,arm,arm64 CFLAGS: -mfpu=neon -mfloat-abi=hard +#cgo noasm CFLAGS: -DMA_NO_SSE2 -DMA_NO_AVX2 -DMA_NO_AVX512 -DMA_NO_NEON + +#include "malgo.h" +*/ +import "C" + +// SampleSizeInBytes retrieves the size of a sample in bytes for the given format. +func SampleSizeInBytes(format FormatType) int { + cformat := (C.ma_format)(format) + ret := C.ma_get_bytes_per_sample(cformat) + return int(ret) +} + +const ( + rawDeviceInfoSize = C.sizeof_ma_device_info +) diff --git a/vendor/github.com/gen2brain/malgo/miniaudio.h b/vendor/github.com/gen2brain/malgo/miniaudio.h new file mode 100644 index 0000000..47332e1 --- /dev/null +++ b/vendor/github.com/gen2brain/malgo/miniaudio.h @@ -0,0 +1,92621 @@ +/* +Audio playback and capture library. Choice of public domain or MIT-0. See license statements at the end of this file. +miniaudio - v0.11.21 - 2023-11-15 + +David Reid - mackron@gmail.com + +Website: https://miniaud.io +Documentation: https://miniaud.io/docs +GitHub: https://github.com/mackron/miniaudio +*/ + +/* +1. Introduction +=============== +miniaudio is a single file library for audio playback and capture. To use it, do the following in +one .c file: + + ```c + #define MINIAUDIO_IMPLEMENTATION + #include "miniaudio.h" + ``` + +You can do `#include "miniaudio.h"` in other parts of the program just like any other header. + +miniaudio includes both low level and high level APIs. The low level API is good for those who want +to do all of their mixing themselves and only require a light weight interface to the underlying +audio device. The high level API is good for those who have complex mixing and effect requirements. + +In miniaudio, objects are transparent structures. Unlike many other libraries, there are no handles +to opaque objects which means you need to allocate memory for objects yourself. In the examples +presented in this documentation you will often see objects declared on the stack. You need to be +careful when translating these examples to your own code so that you don't accidentally declare +your objects on the stack and then cause them to become invalid once the function returns. In +addition, you must ensure the memory address of your objects remain the same throughout their +lifetime. You therefore cannot be making copies of your objects. + +A config/init pattern is used throughout the entire library. The idea is that you set up a config +object and pass that into the initialization routine. The advantage to this system is that the +config object can be initialized with logical defaults and new properties added to it without +breaking the API. The config object can be allocated on the stack and does not need to be +maintained after initialization of the corresponding object. + + +1.1. Low Level API +------------------ +The low level API gives you access to the raw audio data of an audio device. It supports playback, +capture, full-duplex and loopback (WASAPI only). You can enumerate over devices to determine which +physical device(s) you want to connect to. + +The low level API uses the concept of a "device" as the abstraction for physical devices. The idea +is that you choose a physical device to emit or capture audio from, and then move data to/from the +device when miniaudio tells you to. Data is delivered to and from devices asynchronously via a +callback which you specify when initializing the device. + +When initializing the device you first need to configure it. The device configuration allows you to +specify things like the format of the data delivered via the callback, the size of the internal +buffer and the ID of the device you want to emit or capture audio from. + +Once you have the device configuration set up you can initialize the device. When initializing a +device you need to allocate memory for the device object beforehand. This gives the application +complete control over how the memory is allocated. In the example below we initialize a playback +device on the stack, but you could allocate it on the heap if that suits your situation better. + + ```c + void data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount) + { + // In playback mode copy data to pOutput. In capture mode read data from pInput. In full-duplex mode, both + // pOutput and pInput will be valid and you can move data from pInput into pOutput. Never process more than + // frameCount frames. + } + + int main() + { + ma_device_config config = ma_device_config_init(ma_device_type_playback); + config.playback.format = ma_format_f32; // Set to ma_format_unknown to use the device's native format. + config.playback.channels = 2; // Set to 0 to use the device's native channel count. + config.sampleRate = 48000; // Set to 0 to use the device's native sample rate. + config.dataCallback = data_callback; // This function will be called when miniaudio needs more data. + config.pUserData = pMyCustomData; // Can be accessed from the device object (device.pUserData). + + ma_device device; + if (ma_device_init(NULL, &config, &device) != MA_SUCCESS) { + return -1; // Failed to initialize the device. + } + + ma_device_start(&device); // The device is sleeping by default so you'll need to start it manually. + + // Do something here. Probably your program's main loop. + + ma_device_uninit(&device); + return 0; + } + ``` + +In the example above, `data_callback()` is where audio data is written and read from the device. +The idea is in playback mode you cause sound to be emitted from the speakers by writing audio data +to the output buffer (`pOutput` in the example). In capture mode you read data from the input +buffer (`pInput`) to extract sound captured by the microphone. The `frameCount` parameter tells you +how many frames can be written to the output buffer and read from the input buffer. A "frame" is +one sample for each channel. For example, in a stereo stream (2 channels), one frame is 2 +samples: one for the left, one for the right. The channel count is defined by the device config. +The size in bytes of an individual sample is defined by the sample format which is also specified +in the device config. Multi-channel audio data is always interleaved, which means the samples for +each frame are stored next to each other in memory. For example, in a stereo stream the first pair +of samples will be the left and right samples for the first frame, the second pair of samples will +be the left and right samples for the second frame, etc. + +The configuration of the device is defined by the `ma_device_config` structure. The config object +is always initialized with `ma_device_config_init()`. It's important to always initialize the +config with this function as it initializes it with logical defaults and ensures your program +doesn't break when new members are added to the `ma_device_config` structure. The example above +uses a fairly simple and standard device configuration. The call to `ma_device_config_init()` takes +a single parameter, which is whether or not the device is a playback, capture, duplex or loopback +device (loopback devices are not supported on all backends). The `config.playback.format` member +sets the sample format which can be one of the following (all formats are native-endian): + + +---------------+----------------------------------------+---------------------------+ + | Symbol | Description | Range | + +---------------+----------------------------------------+---------------------------+ + | ma_format_f32 | 32-bit floating point | [-1, 1] | + | ma_format_s16 | 16-bit signed integer | [-32768, 32767] | + | ma_format_s24 | 24-bit signed integer (tightly packed) | [-8388608, 8388607] | + | ma_format_s32 | 32-bit signed integer | [-2147483648, 2147483647] | + | ma_format_u8 | 8-bit unsigned integer | [0, 255] | + +---------------+----------------------------------------+---------------------------+ + +The `config.playback.channels` member sets the number of channels to use with the device. The +channel count cannot exceed MA_MAX_CHANNELS. The `config.sampleRate` member sets the sample rate +(which must be the same for both playback and capture in full-duplex configurations). This is +usually set to 44100 or 48000, but can be set to anything. It's recommended to keep this between +8000 and 384000, however. + +Note that leaving the format, channel count and/or sample rate at their default values will result +in the internal device's native configuration being used which is useful if you want to avoid the +overhead of miniaudio's automatic data conversion. + +In addition to the sample format, channel count and sample rate, the data callback and user data +pointer are also set via the config. The user data pointer is not passed into the callback as a +parameter, but is instead set to the `pUserData` member of `ma_device` which you can access +directly since all miniaudio structures are transparent. + +Initializing the device is done with `ma_device_init()`. This will return a result code telling you +what went wrong, if anything. On success it will return `MA_SUCCESS`. After initialization is +complete the device will be in a stopped state. To start it, use `ma_device_start()`. +Uninitializing the device will stop it, which is what the example above does, but you can also stop +the device with `ma_device_stop()`. To resume the device simply call `ma_device_start()` again. +Note that it's important to never stop or start the device from inside the callback. This will +result in a deadlock. Instead you set a variable or signal an event indicating that the device +needs to stop and handle it in a different thread. The following APIs must never be called inside +the callback: + + ```c + ma_device_init() + ma_device_init_ex() + ma_device_uninit() + ma_device_start() + ma_device_stop() + ``` + +You must never try uninitializing and reinitializing a device inside the callback. You must also +never try to stop and start it from inside the callback. There are a few other things you shouldn't +do in the callback depending on your requirements, however this isn't so much a thread-safety +thing, but rather a real-time processing thing which is beyond the scope of this introduction. + +The example above demonstrates the initialization of a playback device, but it works exactly the +same for capture. All you need to do is change the device type from `ma_device_type_playback` to +`ma_device_type_capture` when setting up the config, like so: + + ```c + ma_device_config config = ma_device_config_init(ma_device_type_capture); + config.capture.format = MY_FORMAT; + config.capture.channels = MY_CHANNEL_COUNT; + ``` + +In the data callback you just read from the input buffer (`pInput` in the example above) and leave +the output buffer alone (it will be set to NULL when the device type is set to +`ma_device_type_capture`). + +These are the available device types and how you should handle the buffers in the callback: + + +-------------------------+--------------------------------------------------------+ + | Device Type | Callback Behavior | + +-------------------------+--------------------------------------------------------+ + | ma_device_type_playback | Write to output buffer, leave input buffer untouched. | + | ma_device_type_capture | Read from input buffer, leave output buffer untouched. | + | ma_device_type_duplex | Read from input buffer, write to output buffer. | + | ma_device_type_loopback | Read from input buffer, leave output buffer untouched. | + +-------------------------+--------------------------------------------------------+ + +You will notice in the example above that the sample format and channel count is specified +separately for playback and capture. This is to support different data formats between the playback +and capture devices in a full-duplex system. An example may be that you want to capture audio data +as a monaural stream (one channel), but output sound to a stereo speaker system. Note that if you +use different formats between playback and capture in a full-duplex configuration you will need to +convert the data yourself. There are functions available to help you do this which will be +explained later. + +The example above did not specify a physical device to connect to which means it will use the +operating system's default device. If you have multiple physical devices connected and you want to +use a specific one you will need to specify the device ID in the configuration, like so: + + ```c + config.playback.pDeviceID = pMyPlaybackDeviceID; // Only if requesting a playback or duplex device. + config.capture.pDeviceID = pMyCaptureDeviceID; // Only if requesting a capture, duplex or loopback device. + ``` + +To retrieve the device ID you will need to perform device enumeration, however this requires the +use of a new concept called the "context". Conceptually speaking the context sits above the device. +There is one context to many devices. The purpose of the context is to represent the backend at a +more global level and to perform operations outside the scope of an individual device. Mainly it is +used for performing run-time linking against backend libraries, initializing backends and +enumerating devices. The example below shows how to enumerate devices. + + ```c + ma_context context; + if (ma_context_init(NULL, 0, NULL, &context) != MA_SUCCESS) { + // Error. + } + + ma_device_info* pPlaybackInfos; + ma_uint32 playbackCount; + ma_device_info* pCaptureInfos; + ma_uint32 captureCount; + if (ma_context_get_devices(&context, &pPlaybackInfos, &playbackCount, &pCaptureInfos, &captureCount) != MA_SUCCESS) { + // Error. + } + + // Loop over each device info and do something with it. Here we just print the name with their index. You may want + // to give the user the opportunity to choose which device they'd prefer. + for (ma_uint32 iDevice = 0; iDevice < playbackCount; iDevice += 1) { + printf("%d - %s\n", iDevice, pPlaybackInfos[iDevice].name); + } + + ma_device_config config = ma_device_config_init(ma_device_type_playback); + config.playback.pDeviceID = &pPlaybackInfos[chosenPlaybackDeviceIndex].id; + config.playback.format = MY_FORMAT; + config.playback.channels = MY_CHANNEL_COUNT; + config.sampleRate = MY_SAMPLE_RATE; + config.dataCallback = data_callback; + config.pUserData = pMyCustomData; + + ma_device device; + if (ma_device_init(&context, &config, &device) != MA_SUCCESS) { + // Error + } + + ... + + ma_device_uninit(&device); + ma_context_uninit(&context); + ``` + +The first thing we do in this example is initialize a `ma_context` object with `ma_context_init()`. +The first parameter is a pointer to a list of `ma_backend` values which are used to override the +default backend priorities. When this is NULL, as in this example, miniaudio's default priorities +are used. The second parameter is the number of backends listed in the array pointed to by the +first parameter. The third parameter is a pointer to a `ma_context_config` object which can be +NULL, in which case defaults are used. The context configuration is used for setting the logging +callback, custom memory allocation callbacks, user-defined data and some backend-specific +configurations. + +Once the context has been initialized you can enumerate devices. In the example above we use the +simpler `ma_context_get_devices()`, however you can also use a callback for handling devices by +using `ma_context_enumerate_devices()`. When using `ma_context_get_devices()` you provide a pointer +to a pointer that will, upon output, be set to a pointer to a buffer containing a list of +`ma_device_info` structures. You also provide a pointer to an unsigned integer that will receive +the number of items in the returned buffer. Do not free the returned buffers as their memory is +managed internally by miniaudio. + +The `ma_device_info` structure contains an `id` member which is the ID you pass to the device +config. It also contains the name of the device which is useful for presenting a list of devices +to the user via the UI. + +When creating your own context you will want to pass it to `ma_device_init()` when initializing the +device. Passing in NULL, like we do in the first example, will result in miniaudio creating the +context for you, which you don't want to do since you've already created a context. Note that +internally the context is only tracked by it's pointer which means you must not change the location +of the `ma_context` object. If this is an issue, consider using `malloc()` to allocate memory for +the context. + + +1.2. High Level API +------------------- +The high level API consists of three main parts: + + * Resource management for loading and streaming sounds. + * A node graph for advanced mixing and effect processing. + * A high level "engine" that wraps around the resource manager and node graph. + +The resource manager (`ma_resource_manager`) is used for loading sounds. It supports loading sounds +fully into memory and also streaming. It will also deal with reference counting for you which +avoids the same sound being loaded multiple times. + +The node graph is used for mixing and effect processing. The idea is that you connect a number of +nodes into the graph by connecting each node's outputs to another node's inputs. Each node can +implement it's own effect. By chaining nodes together, advanced mixing and effect processing can +be achieved. + +The engine encapsulates both the resource manager and the node graph to create a simple, easy to +use high level API. The resource manager and node graph APIs are covered in more later sections of +this manual. + +The code below shows how you can initialize an engine using it's default configuration. + + ```c + ma_result result; + ma_engine engine; + + result = ma_engine_init(NULL, &engine); + if (result != MA_SUCCESS) { + return result; // Failed to initialize the engine. + } + ``` + +This creates an engine instance which will initialize a device internally which you can access with +`ma_engine_get_device()`. It will also initialize a resource manager for you which can be accessed +with `ma_engine_get_resource_manager()`. The engine itself is a node graph (`ma_node_graph`) which +means you can pass a pointer to the engine object into any of the `ma_node_graph` APIs (with a +cast). Alternatively, you can use `ma_engine_get_node_graph()` instead of a cast. + +Note that all objects in miniaudio, including the `ma_engine` object in the example above, are +transparent structures. There are no handles to opaque structures in miniaudio which means you need +to be mindful of how you declare them. In the example above we are declaring it on the stack, but +this will result in the struct being invalidated once the function encapsulating it returns. If +allocating the engine on the heap is more appropriate, you can easily do so with a standard call +to `malloc()` or whatever heap allocation routine you like: + + ```c + ma_engine* pEngine = malloc(sizeof(*pEngine)); + ``` + +The `ma_engine` API uses the same config/init pattern used all throughout miniaudio. To configure +an engine, you can fill out a `ma_engine_config` object and pass it into the first parameter of +`ma_engine_init()`: + + ```c + ma_result result; + ma_engine engine; + ma_engine_config engineConfig; + + engineConfig = ma_engine_config_init(); + engineConfig.pResourceManager = &myCustomResourceManager; // <-- Initialized as some earlier stage. + + result = ma_engine_init(&engineConfig, &engine); + if (result != MA_SUCCESS) { + return result; + } + ``` + +This creates an engine instance using a custom config. In this particular example it's showing how +you can specify a custom resource manager rather than having the engine initialize one internally. +This is particularly useful if you want to have multiple engine's share the same resource manager. + +The engine must be uninitialized with `ma_engine_uninit()` when it's no longer needed. + +By default the engine will be started, but nothing will be playing because no sounds have been +initialized. The easiest but least flexible way of playing a sound is like so: + + ```c + ma_engine_play_sound(&engine, "my_sound.wav", NULL); + ``` + +This plays what miniaudio calls an "inline" sound. It plays the sound once, and then puts the +internal sound up for recycling. The last parameter is used to specify which sound group the sound +should be associated with which will be explained later. This particular way of playing a sound is +simple, but lacks flexibility and features. A more flexible way of playing a sound is to first +initialize a sound: + + ```c + ma_result result; + ma_sound sound; + + result = ma_sound_init_from_file(&engine, "my_sound.wav", 0, NULL, NULL, &sound); + if (result != MA_SUCCESS) { + return result; + } + + ma_sound_start(&sound); + ``` + +This returns a `ma_sound` object which represents a single instance of the specified sound file. If +you want to play the same file multiple times simultaneously, you need to create one sound for each +instance. + +Sounds should be uninitialized with `ma_sound_uninit()`. + +Sounds are not started by default. Start a sound with `ma_sound_start()` and stop it with +`ma_sound_stop()`. When a sound is stopped, it is not rewound to the start. Use +`ma_sound_seek_to_pcm_frame(&sound, 0)` to seek back to the start of a sound. By default, starting +and stopping sounds happens immediately, but sometimes it might be convenient to schedule the sound +the be started and/or stopped at a specific time. This can be done with the following functions: + + ```c + ma_sound_set_start_time_in_pcm_frames() + ma_sound_set_start_time_in_milliseconds() + ma_sound_set_stop_time_in_pcm_frames() + ma_sound_set_stop_time_in_milliseconds() + ``` + +The start/stop time needs to be specified based on the absolute timer which is controlled by the +engine. The current global time time in PCM frames can be retrieved with +`ma_engine_get_time_in_pcm_frames()`. The engine's global time can be changed with +`ma_engine_set_time_in_pcm_frames()` for synchronization purposes if required. Note that scheduling +a start time still requires an explicit call to `ma_sound_start()` before anything will play: + + ```c + ma_sound_set_start_time_in_pcm_frames(&sound, ma_engine_get_time_in_pcm_frames(&engine) + (ma_engine_get_sample_rate(&engine) * 2); + ma_sound_start(&sound); + ``` + +The third parameter of `ma_sound_init_from_file()` is a set of flags that control how the sound be +loaded and a few options on which features should be enabled for that sound. By default, the sound +is synchronously loaded fully into memory straight from the file system without any kind of +decoding. If you want to decode the sound before storing it in memory, you need to specify the +`MA_SOUND_FLAG_DECODE` flag. This is useful if you want to incur the cost of decoding at an earlier +stage, such as a loading stage. Without this option, decoding will happen dynamically at mixing +time which might be too expensive on the audio thread. + +If you want to load the sound asynchronously, you can specify the `MA_SOUND_FLAG_ASYNC` flag. This +will result in `ma_sound_init_from_file()` returning quickly, but the sound will not start playing +until the sound has had some audio decoded. + +The fourth parameter is a pointer to sound group. A sound group is used as a mechanism to organise +sounds into groups which have their own effect processing and volume control. An example is a game +which might have separate groups for sfx, voice and music. Each of these groups have their own +independent volume control. Use `ma_sound_group_init()` or `ma_sound_group_init_ex()` to initialize +a sound group. + +Sounds and sound groups are nodes in the engine's node graph and can be plugged into any `ma_node` +API. This makes it possible to connect sounds and sound groups to effect nodes to produce complex +effect chains. + +A sound can have it's volume changed with `ma_sound_set_volume()`. If you prefer decibel volume +control you can use `ma_volume_db_to_linear()` to convert from decibel representation to linear. + +Panning and pitching is supported with `ma_sound_set_pan()` and `ma_sound_set_pitch()`. If you know +a sound will never have it's pitch changed with `ma_sound_set_pitch()` or via the doppler effect, +you can specify the `MA_SOUND_FLAG_NO_PITCH` flag when initializing the sound for an optimization. + +By default, sounds and sound groups have spatialization enabled. If you don't ever want to +spatialize your sounds, initialize the sound with the `MA_SOUND_FLAG_NO_SPATIALIZATION` flag. The +spatialization model is fairly simple and is roughly on feature parity with OpenAL. HRTF and +environmental occlusion are not currently supported, but planned for the future. The supported +features include: + + * Sound and listener positioning and orientation with cones + * Attenuation models: none, inverse, linear and exponential + * Doppler effect + +Sounds can be faded in and out with `ma_sound_set_fade_in_pcm_frames()`. + +To check if a sound is currently playing, you can use `ma_sound_is_playing()`. To check if a sound +is at the end, use `ma_sound_at_end()`. Looping of a sound can be controlled with +`ma_sound_set_looping()`. Use `ma_sound_is_looping()` to check whether or not the sound is looping. + + + +2. Building +=========== +miniaudio should work cleanly out of the box without the need to download or install any +dependencies. See below for platform-specific details. + +Note that GCC and Clang require `-msse2`, `-mavx2`, etc. for SIMD optimizations. + +If you get errors about undefined references to `__sync_val_compare_and_swap_8`, `__atomic_load_8`, +etc. you need to link with `-latomic`. + + +2.1. Windows +------------ +The Windows build should compile cleanly on all popular compilers without the need to configure any +include paths nor link to any libraries. + +The UWP build may require linking to mmdevapi.lib if you get errors about an unresolved external +symbol for `ActivateAudioInterfaceAsync()`. + + +2.2. macOS and iOS +------------------ +The macOS build should compile cleanly without the need to download any dependencies nor link to +any libraries or frameworks. The iOS build needs to be compiled as Objective-C and will need to +link the relevant frameworks but should compile cleanly out of the box with Xcode. Compiling +through the command line requires linking to `-lpthread` and `-lm`. + +Due to the way miniaudio links to frameworks at runtime, your application may not pass Apple's +notarization process. To fix this there are two options. The first is to use the +`MA_NO_RUNTIME_LINKING` option, like so: + + ```c + #ifdef __APPLE__ + #define MA_NO_RUNTIME_LINKING + #endif + #define MINIAUDIO_IMPLEMENTATION + #include "miniaudio.h" + ``` + +This will require linking with `-framework CoreFoundation -framework CoreAudio -framework AudioToolbox`. +If you get errors about AudioToolbox, try with `-framework AudioUnit` instead. You may get this when +using older versions of iOS. Alternatively, if you would rather keep using runtime linking you can +add the following to your entitlements.xcent file: + + ``` + com.apple.security.cs.allow-dyld-environment-variables + + com.apple.security.cs.allow-unsigned-executable-memory + + ``` + +See this discussion for more info: https://github.com/mackron/miniaudio/issues/203. + + +2.3. Linux +---------- +The Linux build only requires linking to `-ldl`, `-lpthread` and `-lm`. You do not need any +development packages. You may need to link with `-latomic` if you're compiling for 32-bit ARM. + + +2.4. BSD +-------- +The BSD build only requires linking to `-lpthread` and `-lm`. NetBSD uses audio(4), OpenBSD uses +sndio and FreeBSD uses OSS. You may need to link with `-latomic` if you're compiling for 32-bit +ARM. + + +2.5. Android +------------ +AAudio is the highest priority backend on Android. This should work 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+. + +There have been reports that the OpenSL|ES backend fails to initialize on some Android based +devices due to `dlopen()` failing to open "libOpenSLES.so". If this happens on your platform +you'll need to disable run-time linking with `MA_NO_RUNTIME_LINKING` and link with -lOpenSLES. + + +2.6. Emscripten +--------------- +The Emscripten build emits Web Audio JavaScript directly and should compile cleanly out of the box. +You cannot use `-std=c*` compiler flags, nor `-ansi`. + +You can enable the use of AudioWorkets by defining `MA_ENABLE_AUDIO_WORKLETS` and then compiling +with the following options: + + -sAUDIO_WORKLET=1 -sWASM_WORKERS=1 -sASYNCIFY + +An example for compiling with AudioWorklet support might look like this: + + emcc program.c -o bin/program.html -DMA_ENABLE_AUDIO_WORKLETS -sAUDIO_WORKLET=1 -sWASM_WORKERS=1 -sASYNCIFY + +To run locally, you'll need to use emrun: + + emrun bin/program.html + + + +2.7. Build Options +------------------ +`#define` these options before including miniaudio.h. + + +----------------------------------+--------------------------------------------------------------------+ + | Option | Description | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_WASAPI | Disables the WASAPI backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_DSOUND | Disables the DirectSound backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_WINMM | Disables the WinMM backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_ALSA | Disables the ALSA backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_PULSEAUDIO | Disables the PulseAudio backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_JACK | Disables the JACK backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_COREAUDIO | Disables the Core Audio backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_SNDIO | Disables the sndio backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_AUDIO4 | Disables the audio(4) backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_OSS | Disables the OSS backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_AAUDIO | Disables the AAudio backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_OPENSL | Disables the OpenSL|ES backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_WEBAUDIO | Disables the Web Audio backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_NULL | Disables the null backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_ENABLE_ONLY_SPECIFIC_BACKENDS | Disables all backends by default and requires `MA_ENABLE_*` to | + | | enable specific backends. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_ENABLE_WASAPI | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to | + | | enable the WASAPI backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_ENABLE_DSOUND | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to | + | | enable the DirectSound backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_ENABLE_WINMM | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to | + | | enable the WinMM backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_ENABLE_ALSA | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to | + | | enable the ALSA backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_ENABLE_PULSEAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to | + | | enable the PulseAudio backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_ENABLE_JACK | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to | + | | enable the JACK backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_ENABLE_COREAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to | + | | enable the Core Audio backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_ENABLE_SNDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to | + | | enable the sndio backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_ENABLE_AUDIO4 | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to | + | | enable the audio(4) backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_ENABLE_OSS | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to | + | | enable the OSS backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_ENABLE_AAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to | + | | enable the AAudio backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_ENABLE_OPENSL | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to | + | | enable the OpenSL|ES backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_ENABLE_WEBAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to | + | | enable the Web Audio backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_ENABLE_NULL | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to | + | | enable the null backend. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_DECODING | Disables decoding APIs. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_ENCODING | Disables encoding APIs. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_WAV | Disables the built-in WAV decoder and encoder. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_FLAC | Disables the built-in FLAC decoder. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_MP3 | Disables the built-in MP3 decoder. | + +----------------------------------+--------------------------------------------------------------------+ + | 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. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_RESOURCE_MANAGER | Disables the resource manager. When using the engine this will | + | | also disable the following functions: | + | | | + | | ``` | + | | ma_sound_init_from_file() | + | | ma_sound_init_from_file_w() | + | | ma_sound_init_copy() | + | | ma_engine_play_sound_ex() | + | | ma_engine_play_sound() | + | | ``` | + | | | + | | The only way to initialize a `ma_sound` object is to initialize it | + | | from a data source. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_NODE_GRAPH | Disables the node graph API. This will also disable the engine API | + | | because it depends on the node graph. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_ENGINE | Disables the engine API. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_THREADING | Disables the `ma_thread`, `ma_mutex`, `ma_semaphore` and | + | | `ma_event` APIs. This option is useful if you only need to use | + | | miniaudio for data conversion, decoding and/or encoding. Some | + | | families of APIs require threading which means the following | + | | options must also be set: | + | | | + | | ``` | + | | MA_NO_DEVICE_IO | + | | ``` | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_GENERATION | Disables generation APIs such a `ma_waveform` and `ma_noise`. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_SSE2 | Disables SSE2 optimizations. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_AVX2 | Disables AVX2 optimizations. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_NEON | Disables NEON optimizations. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_NO_RUNTIME_LINKING | Disables runtime linking. This is useful for passing Apple's | + | | notarization process. When enabling this, you may need to avoid | + | | using `-std=c89` or `-std=c99` on Linux builds or else you may end | + | | up with compilation errors due to conflicts with `timespec` and | + | | `timeval` data types. | + | | | + | | You may need to enable this if your target platform does not allow | + | | runtime linking via `dlopen()`. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_DEBUG_OUTPUT | Enable `printf()` output of debug logs (`MA_LOG_LEVEL_DEBUG`). | + +----------------------------------+--------------------------------------------------------------------+ + | MA_COINIT_VALUE | Windows only. The value to pass to internal calls to | + | | `CoInitializeEx()`. Defaults to `COINIT_MULTITHREADED`. | + +----------------------------------+--------------------------------------------------------------------+ + | MA_API | Controls how public APIs should be decorated. Default is `extern`. | + +----------------------------------+--------------------------------------------------------------------+ + + +3. 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. + +3.1. 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. + +3.2. Frame / PCM Frame +---------------------- +A frame is a group 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". + +3.3. 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. + +3.4. 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. + +3.5. Formats +------------ +Throughout miniaudio you will see references to different sample formats: + + +---------------+----------------------------------------+---------------------------+ + | Symbol | Description | Range | + +---------------+----------------------------------------+---------------------------+ + | ma_format_f32 | 32-bit floating point | [-1, 1] | + | ma_format_s16 | 16-bit signed integer | [-32768, 32767] | + | ma_format_s24 | 24-bit signed integer (tightly packed) | [-8388608, 8388607] | + | ma_format_s32 | 32-bit signed integer | [-2147483648, 2147483647] | + | ma_format_u8 | 8-bit unsigned integer | [0, 255] | + +---------------+----------------------------------------+---------------------------+ + +All formats are native-endian. + + + +4. Data Sources +=============== +The data source abstraction in miniaudio is used for retrieving audio data from some source. A few +examples include `ma_decoder`, `ma_noise` and `ma_waveform`. You will need to be familiar with data +sources in order to make sense of some of the higher level concepts in miniaudio. + +The `ma_data_source` API is a generic interface for reading from a data source. Any object that +implements the data source interface can be plugged into any `ma_data_source` function. + +To read data from a data source: + + ```c + ma_result result; + ma_uint64 framesRead; + + result = ma_data_source_read_pcm_frames(pDataSource, pFramesOut, frameCount, &framesRead); + if (result != MA_SUCCESS) { + return result; // Failed to read data from the data source. + } + ``` + +If you don't need the number of frames that were successfully read you can pass in `NULL` to the +`pFramesRead` parameter. If this returns a value less than the number of frames requested it means +the end of the file has been reached. `MA_AT_END` will be returned only when the number of frames +read is 0. + +When calling any data source function, with the exception of `ma_data_source_init()` and +`ma_data_source_uninit()`, you can pass in any object that implements a data source. For example, +you could plug in a decoder like so: + + ```c + ma_result result; + ma_uint64 framesRead; + ma_decoder decoder; // <-- This would be initialized with `ma_decoder_init_*()`. + + result = ma_data_source_read_pcm_frames(&decoder, pFramesOut, frameCount, &framesRead); + if (result != MA_SUCCESS) { + return result; // Failed to read data from the decoder. + } + ``` + +If you want to seek forward you can pass in `NULL` to the `pFramesOut` parameter. Alternatively you +can use `ma_data_source_seek_pcm_frames()`. + +To seek to a specific PCM frame: + + ```c + result = ma_data_source_seek_to_pcm_frame(pDataSource, frameIndex); + if (result != MA_SUCCESS) { + return result; // Failed to seek to PCM frame. + } + ``` + +You can retrieve the total length of a data source in PCM frames, but note that some data sources +may not have the notion of a length, such as noise and waveforms, and others may just not have a +way of determining the length such as some decoders. To retrieve the length: + + ```c + ma_uint64 length; + + result = ma_data_source_get_length_in_pcm_frames(pDataSource, &length); + if (result != MA_SUCCESS) { + return result; // Failed to retrieve the length. + } + ``` + +Care should be taken when retrieving the length of a data source where the underlying decoder is +pulling data from a data stream with an undefined length, such as internet radio or some kind of +broadcast. If you do this, `ma_data_source_get_length_in_pcm_frames()` may never return. + +The current position of the cursor in PCM frames can also be retrieved: + + ```c + ma_uint64 cursor; + + result = ma_data_source_get_cursor_in_pcm_frames(pDataSource, &cursor); + if (result != MA_SUCCESS) { + return result; // Failed to retrieve the cursor. + } + ``` + +You will often need to know the data format that will be returned after reading. This can be +retrieved like so: + + ```c + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + ma_channel channelMap[MA_MAX_CHANNELS]; + + result = ma_data_source_get_data_format(pDataSource, &format, &channels, &sampleRate, channelMap, MA_MAX_CHANNELS); + if (result != MA_SUCCESS) { + return result; // Failed to retrieve data format. + } + ``` + +If you do not need a specific data format property, just pass in NULL to the respective parameter. + +There may be cases where you want to implement something like a sound bank where you only want to +read data within a certain range of the underlying data. To do this you can use a range: + + ```c + result = ma_data_source_set_range_in_pcm_frames(pDataSource, rangeBegInFrames, rangeEndInFrames); + if (result != MA_SUCCESS) { + return result; // Failed to set the range. + } + ``` + +This is useful if you have a sound bank where many sounds are stored in the same file and you want +the data source to only play one of those sub-sounds. Note that once the range is set, everything +that takes a position, such as cursors and loop points, should always be relatvie to the start of +the range. When the range is set, any previously defined loop point will be reset. + +Custom loop points can also be used with data sources. By default, data sources will loop after +they reach the end of the data source, but if you need to loop at a specific location, you can do +the following: + + ```c + result = ma_data_set_loop_point_in_pcm_frames(pDataSource, loopBegInFrames, loopEndInFrames); + if (result != MA_SUCCESS) { + return result; // Failed to set the loop point. + } + ``` + +The loop point is relative to the current range. + +It's sometimes useful to chain data sources together so that a seamless transition can be achieved. +To do this, you can use chaining: + + ```c + ma_decoder decoder1; + ma_decoder decoder2; + + // ... initialize decoders with ma_decoder_init_*() ... + + result = ma_data_source_set_next(&decoder1, &decoder2); + if (result != MA_SUCCESS) { + return result; // Failed to set the next data source. + } + + result = ma_data_source_read_pcm_frames(&decoder1, pFramesOut, frameCount, pFramesRead); + if (result != MA_SUCCESS) { + return result; // Failed to read from the decoder. + } + ``` + +In the example above we're using decoders. When reading from a chain, you always want to read from +the top level data source in the chain. In the example above, `decoder1` is the top level data +source in the chain. When `decoder1` reaches the end, `decoder2` will start seamlessly without any +gaps. + +Note that when looping is enabled, only the current data source will be looped. You can loop the +entire chain by linking in a loop like so: + + ```c + ma_data_source_set_next(&decoder1, &decoder2); // decoder1 -> decoder2 + ma_data_source_set_next(&decoder2, &decoder1); // decoder2 -> decoder1 (loop back to the start). + ``` + +Note that setting up chaining is not thread safe, so care needs to be taken if you're dynamically +changing links while the audio thread is in the middle of reading. + +Do not use `ma_decoder_seek_to_pcm_frame()` as a means to reuse a data source to play multiple +instances of the same sound simultaneously. This can be extremely inefficient depending on the type +of data source and can result in glitching due to subtle changes to the state of internal filters. +Instead, initialize multiple data sources for each instance. + + +4.1. Custom Data Sources +------------------------ +You can implement a custom data source by implementing the functions in `ma_data_source_vtable`. +Your custom object must have `ma_data_source_base` as it's first member: + + ```c + struct my_data_source + { + ma_data_source_base base; + ... + }; + ``` + +In your initialization routine, you need to call `ma_data_source_init()` in order to set up the +base object (`ma_data_source_base`): + + ```c + static ma_result my_data_source_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) + { + // Read data here. Output in the same format returned by my_data_source_get_data_format(). + } + + static ma_result my_data_source_seek(ma_data_source* pDataSource, ma_uint64 frameIndex) + { + // Seek to a specific PCM frame here. Return MA_NOT_IMPLEMENTED if seeking is not supported. + } + + static ma_result my_data_source_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) + { + // Return the format of the data here. + } + + static ma_result my_data_source_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor) + { + // Retrieve the current position of the cursor here. Return MA_NOT_IMPLEMENTED and set *pCursor to 0 if there is no notion of a cursor. + } + + static ma_result my_data_source_get_length(ma_data_source* pDataSource, ma_uint64* pLength) + { + // Retrieve the length in PCM frames here. Return MA_NOT_IMPLEMENTED and set *pLength to 0 if there is no notion of a length or if the length is unknown. + } + + static ma_data_source_vtable g_my_data_source_vtable = + { + my_data_source_read, + my_data_source_seek, + my_data_source_get_data_format, + my_data_source_get_cursor, + my_data_source_get_length + }; + + ma_result my_data_source_init(my_data_source* pMyDataSource) + { + ma_result result; + ma_data_source_config baseConfig; + + baseConfig = ma_data_source_config_init(); + baseConfig.vtable = &g_my_data_source_vtable; + + result = ma_data_source_init(&baseConfig, &pMyDataSource->base); + if (result != MA_SUCCESS) { + return result; + } + + // ... do the initialization of your custom data source here ... + + return MA_SUCCESS; + } + + void my_data_source_uninit(my_data_source* pMyDataSource) + { + // ... do the uninitialization of your custom data source here ... + + // You must uninitialize the base data source. + ma_data_source_uninit(&pMyDataSource->base); + } + ``` + +Note that `ma_data_source_init()` and `ma_data_source_uninit()` are never called directly outside +of the custom data source. It's up to the custom data source itself to call these within their own +init/uninit functions. + + + +5. Engine +========= +The `ma_engine` API is a high level API for managing and mixing sounds and effect processing. The +`ma_engine` object encapsulates a resource manager and a node graph, both of which will be +explained in more detail later. + +Sounds are called `ma_sound` and are created from an engine. Sounds can be associated with a mixing +group called `ma_sound_group` which are also created from the engine. Both `ma_sound` and +`ma_sound_group` objects are nodes within the engine's node graph. + +When the engine is initialized, it will normally create a device internally. If you would rather +manage the device yourself, you can do so and just pass a pointer to it via the engine config when +you initialize the engine. You can also just use the engine without a device, which again can be +configured via the engine config. + +The most basic way to initialize the engine is with a default config, like so: + + ```c + ma_result result; + ma_engine engine; + + result = ma_engine_init(NULL, &engine); + if (result != MA_SUCCESS) { + return result; // Failed to initialize the engine. + } + ``` + +This will result in the engine initializing a playback device using the operating system's default +device. This will be sufficient for many use cases, but if you need more flexibility you'll want to +configure the engine with an engine config: + + ```c + ma_result result; + ma_engine engine; + ma_engine_config engineConfig; + + engineConfig = ma_engine_config_init(); + engineConfig.pDevice = &myDevice; + + result = ma_engine_init(&engineConfig, &engine); + if (result != MA_SUCCESS) { + return result; // Failed to initialize the engine. + } + ``` + +In the example above we're passing in a pre-initialized device. Since the caller is the one in +control of the device's data callback, it's their responsibility to manually call +`ma_engine_read_pcm_frames()` from inside their data callback: + + ```c + void playback_data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount) + { + ma_engine_read_pcm_frames(&g_Engine, pOutput, frameCount, NULL); + } + ``` + +You can also use the engine independent of a device entirely: + + ```c + ma_result result; + ma_engine engine; + ma_engine_config engineConfig; + + engineConfig = ma_engine_config_init(); + engineConfig.noDevice = MA_TRUE; + engineConfig.channels = 2; // Must be set when not using a device. + engineConfig.sampleRate = 48000; // Must be set when not using a device. + + result = ma_engine_init(&engineConfig, &engine); + if (result != MA_SUCCESS) { + return result; // Failed to initialize the engine. + } + ``` + +Note that when you're not using a device, you must set the channel count and sample rate in the +config or else miniaudio won't know what to use (miniaudio will use the device to determine this +normally). When not using a device, you need to use `ma_engine_read_pcm_frames()` to process audio +data from the engine. This kind of setup is useful if you want to do something like offline +processing or want to use a different audio system for playback such as SDL. + +When a sound is loaded it goes through a resource manager. By default the engine will initialize a +resource manager internally, but you can also specify a pre-initialized resource manager: + + ```c + ma_result result; + ma_engine engine1; + ma_engine engine2; + ma_engine_config engineConfig; + + engineConfig = ma_engine_config_init(); + engineConfig.pResourceManager = &myResourceManager; + + ma_engine_init(&engineConfig, &engine1); + ma_engine_init(&engineConfig, &engine2); + ``` + +In this example we are initializing two engines, both of which are sharing the same resource +manager. This is especially useful for saving memory when loading the same file across multiple +engines. If you were not to use a shared resource manager, each engine instance would use their own +which would result in any sounds that are used between both engine's being loaded twice. By using +a shared resource manager, it would only be loaded once. Using multiple engine's is useful when you +need to output to multiple playback devices, such as in a local multiplayer game where each player +is using their own set of headphones. + +By default an engine will be in a started state. To make it so the engine is not automatically +started you can configure it as such: + + ```c + engineConfig.noAutoStart = MA_TRUE; + + // The engine will need to be started manually. + ma_engine_start(&engine); + + // Later on the engine can be stopped with ma_engine_stop(). + ma_engine_stop(&engine); + ``` + +The concept of starting or stopping an engine is only relevant when using the engine with a +device. Attempting to start or stop an engine that is not associated with a device will result in +`MA_INVALID_OPERATION`. + +The master volume of the engine can be controlled with `ma_engine_set_volume()` which takes a +linear scale, with 0 resulting in silence and anything above 1 resulting in amplification. If you +prefer decibel based volume control, use `ma_volume_db_to_linear()` to convert from dB to linear. + +When a sound is spatialized, it is done so relative to a listener. An engine can be configured to +have multiple listeners which can be configured via the config: + + ```c + engineConfig.listenerCount = 2; + ``` + +The maximum number of listeners is restricted to `MA_ENGINE_MAX_LISTENERS`. By default, when a +sound is spatialized, it will be done so relative to the closest listener. You can also pin a sound +to a specific listener which will be explained later. Listener's have a position, direction, cone, +and velocity (for doppler effect). A listener is referenced by an index, the meaning of which is up +to the caller (the index is 0 based and cannot go beyond the listener count, minus 1). The +position, direction and velocity are all specified in absolute terms: + + ```c + ma_engine_listener_set_position(&engine, listenerIndex, worldPosX, worldPosY, worldPosZ); + ``` + +The direction of the listener represents it's forward vector. The listener's up vector can also be +specified and defaults to +1 on the Y axis. + + ```c + ma_engine_listener_set_direction(&engine, listenerIndex, forwardX, forwardY, forwardZ); + ma_engine_listener_set_world_up(&engine, listenerIndex, 0, 1, 0); + ``` + +The engine supports directional attenuation. The listener can have a cone the controls how sound is +attenuated based on the listener's direction. When a sound is between the inner and outer cones, it +will be attenuated between 1 and the cone's outer gain: + + ```c + ma_engine_listener_set_cone(&engine, listenerIndex, innerAngleInRadians, outerAngleInRadians, outerGain); + ``` + +When a sound is inside the inner code, no directional attenuation is applied. When the sound is +outside of the outer cone, the attenuation will be set to `outerGain` in the example above. When +the sound is in between the inner and outer cones, the attenuation will be interpolated between 1 +and the outer gain. + +The engine's coordinate system follows the OpenGL coordinate system where positive X points right, +positive Y points up and negative Z points forward. + +The simplest and least flexible way to play a sound is like so: + + ```c + ma_engine_play_sound(&engine, "my_sound.wav", pGroup); + ``` + +This is a "fire and forget" style of function. The engine will manage the `ma_sound` object +internally. When the sound finishes playing, it'll be put up for recycling. For more flexibility +you'll want to initialize a sound object: + + ```c + ma_sound sound; + + result = ma_sound_init_from_file(&engine, "my_sound.wav", flags, pGroup, NULL, &sound); + if (result != MA_SUCCESS) { + return result; // Failed to load sound. + } + ``` + +Sounds need to be uninitialized with `ma_sound_uninit()`. + +The example above loads a sound from a file. If the resource manager has been disabled you will not +be able to use this function and instead you'll need to initialize a sound directly from a data +source: + + ```c + ma_sound sound; + + result = ma_sound_init_from_data_source(&engine, &dataSource, flags, pGroup, &sound); + if (result != MA_SUCCESS) { + return result; + } + ``` + +Each `ma_sound` object represents a single instance of the sound. If you want to play the same +sound multiple times at the same time, you need to initialize a separate `ma_sound` object. + +For the most flexibility when initializing sounds, use `ma_sound_init_ex()`. This uses miniaudio's +standard config/init pattern: + + ```c + ma_sound sound; + ma_sound_config soundConfig; + + soundConfig = ma_sound_config_init(); + soundConfig.pFilePath = NULL; // Set this to load from a file path. + soundConfig.pDataSource = NULL; // Set this to initialize from an existing data source. + soundConfig.pInitialAttachment = &someNodeInTheNodeGraph; + soundConfig.initialAttachmentInputBusIndex = 0; + soundConfig.channelsIn = 1; + soundConfig.channelsOut = 0; // Set to 0 to use the engine's native channel count. + + result = ma_sound_init_ex(&soundConfig, &sound); + if (result != MA_SUCCESS) { + return result; + } + ``` + +In the example above, the sound is being initialized without a file nor a data source. This is +valid, in which case the sound acts as a node in the middle of the node graph. This means you can +connect other sounds to this sound and allow it to act like a sound group. Indeed, this is exactly +what a `ma_sound_group` is. + +When loading a sound, you specify a set of flags that control how the sound is loaded and what +features are enabled for that sound. When no flags are set, the sound will be fully loaded into +memory in exactly the same format as how it's stored on the file system. The resource manager will +allocate a block of memory and then load the file directly into it. When reading audio data, it +will be decoded dynamically on the fly. In order to save processing time on the audio thread, it +might be beneficial to pre-decode the sound. You can do this with the `MA_SOUND_FLAG_DECODE` flag: + + ```c + ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_DECODE, pGroup, NULL, &sound); + ``` + +By default, sounds will be loaded synchronously, meaning `ma_sound_init_*()` will not return until +the sound has been fully loaded. If this is prohibitive you can instead load sounds asynchronously +by specifying the `MA_SOUND_FLAG_ASYNC` flag: + + ```c + ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_DECODE | MA_SOUND_FLAG_ASYNC, pGroup, NULL, &sound); + ``` + +This will result in `ma_sound_init_*()` returning quickly, but the sound won't yet have been fully +loaded. When you start the sound, it won't output anything until some sound is available. The sound +will start outputting audio before the sound has been fully decoded when the `MA_SOUND_FLAG_DECODE` +is specified. + +If you need to wait for an asynchronously loaded sound to be fully loaded, you can use a fence. A +fence in miniaudio is a simple synchronization mechanism which simply blocks until it's internal +counter hit's zero. You can specify a fence like so: + + ```c + ma_result result; + ma_fence fence; + ma_sound sounds[4]; + + result = ma_fence_init(&fence); + if (result != MA_SUCCESS) { + return result; + } + + // Load some sounds asynchronously. + for (int iSound = 0; iSound < 4; iSound += 1) { + ma_sound_init_from_file(&engine, mySoundFilesPaths[iSound], MA_SOUND_FLAG_DECODE | MA_SOUND_FLAG_ASYNC, pGroup, &fence, &sounds[iSound]); + } + + // ... do some other stuff here in the mean time ... + + // Wait for all sounds to finish loading. + ma_fence_wait(&fence); + ``` + +If loading the entire sound into memory is prohibitive, you can also configure the engine to stream +the audio data: + + ```c + ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_STREAM, pGroup, NULL, &sound); + ``` + +When streaming sounds, 2 seconds worth of audio data is stored in memory. Although it should work +fine, it's inefficient to use streaming for short sounds. Streaming is useful for things like music +tracks in games. + +When loading a sound from a file path, the engine will reference count the file to prevent it from +being loaded if it's already in memory. When you uninitialize a sound, the reference count will be +decremented, and if it hits zero, the sound will be unloaded from memory. This reference counting +system is not used for streams. The engine will use a 64-bit hash of the file name when comparing +file paths which means there's a small chance you might encounter a name collision. If this is an +issue, you'll need to use a different name for one of the colliding file paths, or just not load +from files and instead load from a data source. + +You can use `ma_sound_init_copy()` to initialize a copy of another sound. Note, however, that this +only works for sounds that were initialized with `ma_sound_init_from_file()` and without the +`MA_SOUND_FLAG_STREAM` flag. + +When you initialize a sound, if you specify a sound group the sound will be attached to that group +automatically. If you set it to NULL, it will be automatically attached to the engine's endpoint. +If you would instead rather leave the sound unattached by default, you can can specify the +`MA_SOUND_FLAG_NO_DEFAULT_ATTACHMENT` flag. This is useful if you want to set up a complex node +graph. + +Sounds are not started by default. To start a sound, use `ma_sound_start()`. Stop a sound with +`ma_sound_stop()`. + +Sounds can have their volume controlled with `ma_sound_set_volume()` in the same way as the +engine's master volume. + +Sounds support stereo panning and pitching. Set the pan with `ma_sound_set_pan()`. Setting the pan +to 0 will result in an unpanned sound. Setting it to -1 will shift everything to the left, whereas ++1 will shift it to the right. The pitch can be controlled with `ma_sound_set_pitch()`. A larger +value will result in a higher pitch. The pitch must be greater than 0. + +The engine supports 3D spatialization of sounds. By default sounds will have spatialization +enabled, but if a sound does not need to be spatialized it's best to disable it. There are two ways +to disable spatialization of a sound: + + ```c + // Disable spatialization at initialization time via a flag: + ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_NO_SPATIALIZATION, NULL, NULL, &sound); + + // Dynamically disable or enable spatialization post-initialization: + ma_sound_set_spatialization_enabled(&sound, isSpatializationEnabled); + ``` + +By default sounds will be spatialized based on the closest listener. If a sound should always be +spatialized relative to a specific listener it can be pinned to one: + + ```c + ma_sound_set_pinned_listener_index(&sound, listenerIndex); + ``` + +Like listeners, sounds have a position. By default, the position of a sound is in absolute space, +but it can be changed to be relative to a listener: + + ```c + ma_sound_set_positioning(&sound, ma_positioning_relative); + ``` + +Note that relative positioning of a sound only makes sense if there is either only one listener, or +the sound is pinned to a specific listener. To set the position of a sound: + + ```c + ma_sound_set_position(&sound, posX, posY, posZ); + ``` + +The direction works the same way as a listener and represents the sound's forward direction: + + ```c + ma_sound_set_direction(&sound, forwardX, forwardY, forwardZ); + ``` + +Sound's also have a cone for controlling directional attenuation. This works exactly the same as +listeners: + + ```c + ma_sound_set_cone(&sound, innerAngleInRadians, outerAngleInRadians, outerGain); + ``` + +The velocity of a sound is used for doppler effect and can be set as such: + + ```c + ma_sound_set_velocity(&sound, velocityX, velocityY, velocityZ); + ``` + +The engine supports different attenuation models which can be configured on a per-sound basis. By +default the attenuation model is set to `ma_attenuation_model_inverse` which is the equivalent to +OpenAL's `AL_INVERSE_DISTANCE_CLAMPED`. Configure the attenuation model like so: + + ```c + ma_sound_set_attenuation_model(&sound, ma_attenuation_model_inverse); + ``` + +The supported attenuation models include the following: + + +----------------------------------+----------------------------------------------+ + | ma_attenuation_model_none | No distance attenuation. | + +----------------------------------+----------------------------------------------+ + | ma_attenuation_model_inverse | Equivalent to `AL_INVERSE_DISTANCE_CLAMPED`. | + +----------------------------------+----------------------------------------------+ + | ma_attenuation_model_linear | Linear attenuation. | + +----------------------------------+----------------------------------------------+ + | ma_attenuation_model_exponential | Exponential attenuation. | + +----------------------------------+----------------------------------------------+ + +To control how quickly a sound rolls off as it moves away from the listener, you need to configure +the rolloff: + + ```c + ma_sound_set_rolloff(&sound, rolloff); + ``` + +You can control the minimum and maximum gain to apply from spatialization: + + ```c + ma_sound_set_min_gain(&sound, minGain); + ma_sound_set_max_gain(&sound, maxGain); + ``` + +Likewise, in the calculation of attenuation, you can control the minimum and maximum distances for +the attenuation calculation. This is useful if you want to ensure sounds don't drop below a certain +volume after the listener moves further away and to have sounds play a maximum volume when the +listener is within a certain distance: + + ```c + ma_sound_set_min_distance(&sound, minDistance); + ma_sound_set_max_distance(&sound, maxDistance); + ``` + +The engine's spatialization system supports doppler effect. The doppler factor can be configure on +a per-sound basis like so: + + ```c + ma_sound_set_doppler_factor(&sound, dopplerFactor); + ``` + +You can fade sounds in and out with `ma_sound_set_fade_in_pcm_frames()` and +`ma_sound_set_fade_in_milliseconds()`. Set the volume to -1 to use the current volume as the +starting volume: + + ```c + // Fade in over 1 second. + ma_sound_set_fade_in_milliseconds(&sound, 0, 1, 1000); + + // ... sometime later ... + + // Fade out over 1 second, starting from the current volume. + ma_sound_set_fade_in_milliseconds(&sound, -1, 0, 1000); + ``` + +By default sounds will start immediately, but sometimes for timing and synchronization purposes it +can be useful to schedule a sound to start or stop: + + ```c + // Start the sound in 1 second from now. + ma_sound_set_start_time_in_pcm_frames(&sound, ma_engine_get_time_in_pcm_frames(&engine) + (ma_engine_get_sample_rate(&engine) * 1)); + + // Stop the sound in 2 seconds from now. + ma_sound_set_stop_time_in_pcm_frames(&sound, ma_engine_get_time_in_pcm_frames(&engine) + (ma_engine_get_sample_rate(&engine) * 2)); + ``` + +Note that scheduling a start time still requires an explicit call to `ma_sound_start()` before +anything will play. + +The time is specified in global time which is controlled by the engine. You can get the engine's +current time with `ma_engine_get_time_in_pcm_frames()`. The engine's global time is incremented +automatically as audio data is read, but it can be reset with `ma_engine_set_time_in_pcm_frames()` +in case it needs to be resynchronized for some reason. + +To determine whether or not a sound is currently playing, use `ma_sound_is_playing()`. This will +take the scheduled start and stop times into account. + +Whether or not a sound should loop can be controlled with `ma_sound_set_looping()`. Sounds will not +be looping by default. Use `ma_sound_is_looping()` to determine whether or not a sound is looping. + +Use `ma_sound_at_end()` to determine whether or not a sound is currently at the end. For a looping +sound this should never return true. Alternatively, you can configure a callback that will be fired +when the sound reaches the end. Note that the callback is fired from the audio thread which means +you cannot be uninitializing sound from the callback. To set the callback you can use +`ma_sound_set_end_callback()`. Alternatively, if you're using `ma_sound_init_ex()`, you can pass it +into the config like so: + + ```c + soundConfig.endCallback = my_end_callback; + soundConfig.pEndCallbackUserData = pMyEndCallbackUserData; + ``` + +The end callback is declared like so: + + ```c + void my_end_callback(void* pUserData, ma_sound* pSound) + { + ... + } + ``` + +Internally a sound wraps around a data source. Some APIs exist to control the underlying data +source, mainly for convenience: + + ```c + ma_sound_seek_to_pcm_frame(&sound, frameIndex); + ma_sound_get_data_format(&sound, &format, &channels, &sampleRate, pChannelMap, channelMapCapacity); + ma_sound_get_cursor_in_pcm_frames(&sound, &cursor); + ma_sound_get_length_in_pcm_frames(&sound, &length); + ``` + +Sound groups have the same API as sounds, only they are called `ma_sound_group`, and since they do +not have any notion of a data source, anything relating to a data source is unavailable. + +Internally, sound data is loaded via the `ma_decoder` API which means by default it only supports +file formats that have built-in support in miniaudio. You can extend this to support any kind of +file format through the use of custom decoders. To do this you'll need to use a self-managed +resource manager and configure it appropriately. See the "Resource Management" section below for +details on how to set this up. + + +6. Resource Management +====================== +Many programs will want to manage sound resources for things such as reference counting and +streaming. This is supported by miniaudio via the `ma_resource_manager` API. + +The resource manager is mainly responsible for the following: + + * Loading of sound files into memory with reference counting. + * Streaming of sound data. + +When loading a sound file, the resource manager will give you back a `ma_data_source` compatible +object called `ma_resource_manager_data_source`. This object can be passed into any +`ma_data_source` API which is how you can read and seek audio data. When loading a sound file, you +specify whether or not you want the sound to be fully loaded into memory (and optionally +pre-decoded) or streamed. When loading into memory, you can also specify whether or not you want +the data to be loaded asynchronously. + +The example below is how you can initialize a resource manager using it's default configuration: + + ```c + ma_resource_manager_config config; + ma_resource_manager resourceManager; + + config = ma_resource_manager_config_init(); + result = ma_resource_manager_init(&config, &resourceManager); + if (result != MA_SUCCESS) { + ma_device_uninit(&device); + printf("Failed to initialize the resource manager."); + return -1; + } + ``` + +You can configure the format, channels and sample rate of the decoded audio data. By default it +will use the file's native data format, but you can configure it to use a consistent format. This +is useful for offloading the cost of data conversion to load time rather than dynamically +converting at mixing time. To do this, you configure the decoded format, channels and sample rate +like the code below: + + ```c + config = ma_resource_manager_config_init(); + config.decodedFormat = device.playback.format; + config.decodedChannels = device.playback.channels; + config.decodedSampleRate = device.sampleRate; + ``` + +In the code above, the resource manager will be configured so that any decoded audio data will be +pre-converted at load time to the device's native data format. If instead you used defaults and +the data format of the file did not match the device's data format, you would need to convert the +data at mixing time which may be prohibitive in high-performance and large scale scenarios like +games. + +Internally the resource manager uses the `ma_decoder` API to load sounds. This means by default it +only supports decoders that are built into miniaudio. It's possible to support additional encoding +formats through the use of custom decoders. To do so, pass in your `ma_decoding_backend_vtable` +vtables into the resource manager config: + + ```c + ma_decoding_backend_vtable* pCustomBackendVTables[] = + { + &g_ma_decoding_backend_vtable_libvorbis, + &g_ma_decoding_backend_vtable_libopus + }; + + ... + + resourceManagerConfig.ppCustomDecodingBackendVTables = pCustomBackendVTables; + resourceManagerConfig.customDecodingBackendCount = sizeof(pCustomBackendVTables) / sizeof(pCustomBackendVTables[0]); + resourceManagerConfig.pCustomDecodingBackendUserData = NULL; + ``` + +This system can allow you to support any kind of file format. See the "Decoding" section for +details on how to implement custom decoders. The miniaudio repository includes examples for Opus +via libopus and libopusfile and Vorbis via libvorbis and libvorbisfile. + +Asynchronicity is achieved via a job system. When an operation needs to be performed, such as the +decoding of a page, a job will be posted to a queue which will then be processed by a job thread. +By default there will be only one job thread running, but this can be configured, like so: + + ```c + config = ma_resource_manager_config_init(); + config.jobThreadCount = MY_JOB_THREAD_COUNT; + ``` + +By default job threads are managed internally by the resource manager, however you can also self +manage your job threads if, for example, you want to integrate the job processing into your +existing job infrastructure, or if you simply don't like the way the resource manager does it. To +do this, just set the job thread count to 0 and process jobs manually. To process jobs, you first +need to retrieve a job using `ma_resource_manager_next_job()` and then process it using +`ma_job_process()`: + + ```c + config = ma_resource_manager_config_init(); + config.jobThreadCount = 0; // Don't manage any job threads internally. + config.flags = MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING; // Optional. Makes `ma_resource_manager_next_job()` non-blocking. + + // ... Initialize your custom job threads ... + + void my_custom_job_thread(...) + { + for (;;) { + ma_job job; + ma_result result = ma_resource_manager_next_job(pMyResourceManager, &job); + if (result != MA_SUCCESS) { + if (result == MA_NO_DATA_AVAILABLE) { + // No jobs are available. Keep going. Will only get this if the resource manager was initialized + // with MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING. + continue; + } else if (result == MA_CANCELLED) { + // MA_JOB_TYPE_QUIT was posted. Exit. + break; + } else { + // Some other error occurred. + break; + } + } + + ma_job_process(&job); + } + } + ``` + +In the example above, the `MA_JOB_TYPE_QUIT` event is the used as the termination +indicator, but you can use whatever you would like to terminate the thread. The call to +`ma_resource_manager_next_job()` is blocking by default, but can be configured to be non-blocking +by initializing the resource manager with the `MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING` configuration +flag. Note that the `MA_JOB_TYPE_QUIT` will never be removed from the job queue. This +is to give every thread the opportunity to catch the event and terminate naturally. + +When loading a file, it's sometimes convenient to be able to customize how files are opened and +read instead of using standard `fopen()`, `fclose()`, etc. which is what miniaudio will use by +default. This can be done by setting `pVFS` member of the resource manager's config: + + ```c + // Initialize your custom VFS object. See documentation for VFS for information on how to do this. + my_custom_vfs vfs = my_custom_vfs_init(); + + config = ma_resource_manager_config_init(); + config.pVFS = &vfs; + ``` + +This is particularly useful in programs like games where you want to read straight from an archive +rather than the normal file system. If you do not specify a custom VFS, the resource manager will +use the operating system's normal file operations. + +To load a sound file and create a data source, call `ma_resource_manager_data_source_init()`. When +loading a sound you need to specify the file path and options for how the sounds should be loaded. +By default a sound will be loaded synchronously. The returned data source is owned by the caller +which means the caller is responsible for the allocation and freeing of the data source. Below is +an example for initializing a data source: + + ```c + ma_resource_manager_data_source dataSource; + ma_result result = ma_resource_manager_data_source_init(pResourceManager, pFilePath, flags, &dataSource); + if (result != MA_SUCCESS) { + // Error. + } + + // ... + + // A ma_resource_manager_data_source object is compatible with the `ma_data_source` API. To read data, just call + // the `ma_data_source_read_pcm_frames()` like you would with any normal data source. + result = ma_data_source_read_pcm_frames(&dataSource, pDecodedData, frameCount, &framesRead); + if (result != MA_SUCCESS) { + // Failed to read PCM frames. + } + + // ... + + ma_resource_manager_data_source_uninit(&dataSource); + ``` + +The `flags` parameter specifies how you want to perform loading of the sound file. It can be a +combination of the following flags: + + ``` + MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM + MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE + MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC + MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT + ``` + +When no flags are specified (set to 0), the sound will be fully loaded into memory, but not +decoded, meaning the raw file data will be stored in memory, and then dynamically decoded when +`ma_data_source_read_pcm_frames()` is called. To instead decode the audio data before storing it in +memory, use the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE` flag. By default, the sound file will +be loaded synchronously, meaning `ma_resource_manager_data_source_init()` will only return after +the entire file has been loaded. This is good for simplicity, but can be prohibitively slow. You +can instead load the sound asynchronously using the `MA_RESOURCE_MANAGER_DATA_SOURCE_ASYNC` flag. +This will result in `ma_resource_manager_data_source_init()` returning quickly, but no data will be +returned by `ma_data_source_read_pcm_frames()` until some data is available. When no data is +available because the asynchronous decoding hasn't caught up, `MA_BUSY` will be returned by +`ma_data_source_read_pcm_frames()`. + +For large sounds, it's often prohibitive to store the entire file in memory. To mitigate this, you +can instead stream audio data which you can do by specifying the +`MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag. When streaming, data will be decoded in 1 +second pages. When a new page needs to be decoded, a job will be posted to the job queue and then +subsequently processed in a job thread. + +For in-memory sounds, reference counting is used to ensure the data is loaded only once. This means +multiple calls to `ma_resource_manager_data_source_init()` with the same file path will result in +the file data only being loaded once. Each call to `ma_resource_manager_data_source_init()` must be +matched up with a call to `ma_resource_manager_data_source_uninit()`. Sometimes it can be useful +for a program to register self-managed raw audio data and associate it with a file path. Use the +`ma_resource_manager_register_*()` and `ma_resource_manager_unregister_*()` APIs to do this. +`ma_resource_manager_register_decoded_data()` is used to associate a pointer to raw, self-managed +decoded audio data in the specified data format with the specified name. Likewise, +`ma_resource_manager_register_encoded_data()` is used to associate a pointer to raw self-managed +encoded audio data (the raw file data) with the specified name. Note that these names need not be +actual file paths. When `ma_resource_manager_data_source_init()` is called (without the +`MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag), the resource manager will look for these +explicitly registered data buffers and, if found, will use it as the backing data for the data +source. Note that the resource manager does *not* make a copy of this data so it is up to the +caller to ensure the pointer stays valid for it's lifetime. Use +`ma_resource_manager_unregister_data()` to unregister the self-managed data. You can also use +`ma_resource_manager_register_file()` and `ma_resource_manager_unregister_file()` to register and +unregister a file. It does not make sense to use the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` +flag with a self-managed data pointer. + + +6.1. Asynchronous Loading and Synchronization +--------------------------------------------- +When loading asynchronously, it can be useful to poll whether or not loading has finished. Use +`ma_resource_manager_data_source_result()` to determine this. For in-memory sounds, this will +return `MA_SUCCESS` when the file has been *entirely* decoded. If the sound is still being decoded, +`MA_BUSY` will be returned. Otherwise, some other error code will be returned if the sound failed +to load. For streaming data sources, `MA_SUCCESS` will be returned when the first page has been +decoded and the sound is ready to be played. If the first page is still being decoded, `MA_BUSY` +will be returned. Otherwise, some other error code will be returned if the sound failed to load. + +In addition to polling, you can also use a simple synchronization object called a "fence" to wait +for asynchronously loaded sounds to finish. This is called `ma_fence`. The advantage to using a +fence is that it can be used to wait for a group of sounds to finish loading rather than waiting +for sounds on an individual basis. There are two stages to loading a sound: + + * Initialization of the internal decoder; and + * Completion of decoding of the file (the file is fully decoded) + +You can specify separate fences for each of the different stages. Waiting for the initialization +of the internal decoder is important for when you need to know the sample format, channels and +sample rate of the file. + +The example below shows how you could use a fence when loading a number of sounds: + + ```c + // This fence will be released when all sounds are finished loading entirely. + ma_fence fence; + ma_fence_init(&fence); + + // This will be passed into the initialization routine for each sound. + ma_resource_manager_pipeline_notifications notifications = ma_resource_manager_pipeline_notifications_init(); + notifications.done.pFence = &fence; + + // Now load a bunch of sounds: + for (iSound = 0; iSound < soundCount; iSound += 1) { + ma_resource_manager_data_source_init(pResourceManager, pSoundFilePaths[iSound], flags, ¬ifications, &pSoundSources[iSound]); + } + + // ... DO SOMETHING ELSE WHILE SOUNDS ARE LOADING ... + + // Wait for loading of sounds to finish. + ma_fence_wait(&fence); + ``` + +In the example above we used a fence for waiting until the entire file has been fully decoded. If +you only need to wait for the initialization of the internal decoder to complete, you can use the +`init` member of the `ma_resource_manager_pipeline_notifications` object: + + ```c + notifications.init.pFence = &fence; + ``` + +If a fence is not appropriate for your situation, you can instead use a callback that is fired on +an individual sound basis. This is done in a very similar way to fences: + + ```c + typedef struct + { + ma_async_notification_callbacks cb; + void* pMyData; + } my_notification; + + void my_notification_callback(ma_async_notification* pNotification) + { + my_notification* pMyNotification = (my_notification*)pNotification; + + // Do something in response to the sound finishing loading. + } + + ... + + my_notification myCallback; + myCallback.cb.onSignal = my_notification_callback; + myCallback.pMyData = pMyData; + + ma_resource_manager_pipeline_notifications notifications = ma_resource_manager_pipeline_notifications_init(); + notifications.done.pNotification = &myCallback; + + ma_resource_manager_data_source_init(pResourceManager, "my_sound.wav", flags, ¬ifications, &mySound); + ``` + +In the example above we just extend the `ma_async_notification_callbacks` object and pass an +instantiation into the `ma_resource_manager_pipeline_notifications` in the same way as we did with +the fence, only we set `pNotification` instead of `pFence`. You can set both of these at the same +time and they should both work as expected. If using the `pNotification` system, you need to ensure +your `ma_async_notification_callbacks` object stays valid. + + + +6.2. Resource Manager Implementation Details +-------------------------------------------- +Resources are managed in two main ways: + + * By storing the entire sound inside an in-memory buffer (referred to as a data buffer) + * By streaming audio data on the fly (referred to as a data stream) + +A resource managed data source (`ma_resource_manager_data_source`) encapsulates a data buffer or +data stream, depending on whether or not the data source was initialized with the +`MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag. If so, it will make use of a +`ma_resource_manager_data_stream` object. Otherwise it will use a `ma_resource_manager_data_buffer` +object. Both of these objects are data sources which means they can be used with any +`ma_data_source_*()` API. + +Another major feature of the resource manager is the ability to asynchronously decode audio files. +This relieves the audio thread of time-consuming decoding which can negatively affect scalability +due to the audio thread needing to complete it's work extremely quickly to avoid glitching. +Asynchronous decoding is achieved through a job system. There is a central multi-producer, +multi-consumer, fixed-capacity job queue. When some asynchronous work needs to be done, a job is +posted to the queue which is then read by a job thread. The number of job threads can be +configured for improved scalability, and job threads can all run in parallel without needing to +worry about the order of execution (how this is achieved is explained below). + +When a sound is being loaded asynchronously, playback can begin before the sound has been fully +decoded. This enables the application to start playback of the sound quickly, while at the same +time allowing to resource manager to keep loading in the background. Since there may be less +threads than the number of sounds being loaded at a given time, a simple scheduling system is used +to keep decoding time balanced and fair. The resource manager solves this by splitting decoding +into chunks called pages. By default, each page is 1 second long. When a page has been decoded, a +new job will be posted to start decoding the next page. By dividing up decoding into pages, an +individual sound shouldn't ever delay every other sound from having their first page decoded. Of +course, when loading many sounds at the same time, there will always be an amount of time required +to process jobs in the queue so in heavy load situations there will still be some delay. To +determine if a data source is ready to have some frames read, use +`ma_resource_manager_data_source_get_available_frames()`. This will return the number of frames +available starting from the current position. + + +6.2.1. Job Queue +---------------- +The resource manager uses a job queue which is multi-producer, multi-consumer, and fixed-capacity. +This job queue is not currently lock-free, and instead uses a spinlock to achieve thread-safety. +Only a fixed number of jobs can be allocated and inserted into the queue which is done through a +lock-free data structure for allocating an index into a fixed sized array, with reference counting +for mitigation of the ABA problem. The reference count is 32-bit. + +For many types of jobs it's important that they execute in a specific order. In these cases, jobs +are executed serially. For the resource manager, serial execution of jobs is only required on a +per-object basis (per data buffer or per data stream). Each of these objects stores an execution +counter. When a job is posted it is associated with an execution counter. When the job is +processed, it checks if the execution counter of the job equals the execution counter of the +owning object and if so, processes the job. If the counters are not equal, the job will be posted +back onto the job queue for later processing. When the job finishes processing the execution order +of the main object is incremented. This system means the no matter how many job threads are +executing, decoding of an individual sound will always get processed serially. The advantage to +having multiple threads comes into play when loading multiple sounds at the same time. + +The resource manager's job queue is not 100% lock-free and will use a spinlock to achieve +thread-safety for a very small section of code. This is only relevant when the resource manager +uses more than one job thread. If only using a single job thread, which is the default, the +lock should never actually wait in practice. The amount of time spent locking should be quite +short, but it's something to be aware of for those who have pedantic lock-free requirements and +need to use more than one job thread. There are plans to remove this lock in a future version. + +In addition, posting a job will release a semaphore, which on Win32 is implemented with +`ReleaseSemaphore` and on POSIX platforms via a condition variable: + + ```c + pthread_mutex_lock(&pSemaphore->lock); + { + pSemaphore->value += 1; + pthread_cond_signal(&pSemaphore->cond); + } + pthread_mutex_unlock(&pSemaphore->lock); + ``` + +Again, this is relevant for those with strict lock-free requirements in the audio thread. To avoid +this, you can use non-blocking mode (via the `MA_JOB_QUEUE_FLAG_NON_BLOCKING` +flag) and implement your own job processing routine (see the "Resource Manager" section above for +details on how to do this). + + + +6.2.2. Data Buffers +------------------- +When the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag is excluded at initialization time, the +resource manager will try to load the data into an in-memory data buffer. Before doing so, however, +it will first check if the specified file is already loaded. If so, it will increment a reference +counter and just use the already loaded data. This saves both time and memory. When the data buffer +is uninitialized, the reference counter will be decremented. If the counter hits zero, the file +will be unloaded. This is a detail to keep in mind because it could result in excessive loading and +unloading of a sound. For example, the following sequence will result in a file be loaded twice, +once after the other: + + ```c + ma_resource_manager_data_source_init(pResourceManager, "my_file", ..., &myDataBuffer0); // Refcount = 1. Initial load. + ma_resource_manager_data_source_uninit(&myDataBuffer0); // Refcount = 0. Unloaded. + + ma_resource_manager_data_source_init(pResourceManager, "my_file", ..., &myDataBuffer1); // Refcount = 1. Reloaded because previous uninit() unloaded it. + ma_resource_manager_data_source_uninit(&myDataBuffer1); // Refcount = 0. Unloaded. + ``` + +A binary search tree (BST) is used for storing data buffers as it has good balance between +efficiency and simplicity. The key of the BST is a 64-bit hash of the file path that was passed +into `ma_resource_manager_data_source_init()`. The advantage of using a hash is that it saves +memory over storing the entire path, has faster comparisons, and results in a mostly balanced BST +due to the random nature of the hash. The disadvantages are that file names are case-sensitive and +there's a small chance of name collisions. If case-sensitivity is an issue, you should normalize +your file names to upper- or lower-case before initializing your data sources. If name collisions +become an issue, you'll need to change the name of one of the colliding names or just not use the +resource manager. + +When a sound file has not already been loaded and the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC` +flag is excluded, the file will be decoded synchronously by the calling thread. There are two +options for controlling how the audio is stored in the data buffer - encoded or decoded. When the +`MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE` option is excluded, the raw file data will be stored +in memory. Otherwise the sound will be decoded before storing it in memory. Synchronous loading is +a very simple and standard process of simply adding an item to the BST, allocating a block of +memory and then decoding (if `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE` is specified). + +When the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC` flag is specified, loading of the data buffer +is done asynchronously. In this case, a job is posted to the queue to start loading and then the +function immediately returns, setting an internal result code to `MA_BUSY`. This result code is +returned when the program calls `ma_resource_manager_data_source_result()`. When decoding has fully +completed `MA_SUCCESS` will be returned. This can be used to know if loading has fully completed. + +When loading asynchronously, a single job is posted to the queue of the type +`MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER_NODE`. This involves making a copy of the file path and +associating it with job. When the job is processed by the job thread, it will first load the file +using the VFS associated with the resource manager. When using a custom VFS, it's important that it +be completely thread-safe because it will be used from one or more job threads at the same time. +Individual files should only ever be accessed by one thread at a time, however. After opening the +file via the VFS, the job will determine whether or not the file is being decoded. If not, it +simply allocates a block of memory and loads the raw file contents into it and returns. On the +other hand, when the file is being decoded, it will first allocate a decoder on the heap and +initialize it. Then it will check if the length of the file is known. If so it will allocate a +block of memory to store the decoded output and initialize it to silence. If the size is unknown, +it will allocate room for one page. After memory has been allocated, the first page will be +decoded. If the sound is shorter than a page, the result code will be set to `MA_SUCCESS` and the +completion event will be signalled and loading is now complete. If, however, there is more to +decode, a job with the code `MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE` is posted. This job +will decode the next page and perform the same process if it reaches the end. If there is more to +decode, the job will post another `MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE` job which will +keep on happening until the sound has been fully decoded. For sounds of an unknown length, each +page will be linked together as a linked list. Internally this is implemented via the +`ma_paged_audio_buffer` object. + + +6.2.3. Data Streams +------------------- +Data streams only ever store two pages worth of data for each instance. They are most useful for +large sounds like music tracks in games that would consume too much memory if fully decoded in +memory. After every frame from a page has been read, a job will be posted to load the next page +which is done from the VFS. + +For data streams, the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC` flag will determine whether or +not initialization of the data source waits until the two pages have been decoded. When unset, +`ma_resource_manager_data_source_init()` will wait until the two pages have been loaded, otherwise +it will return immediately. + +When frames are read from a data stream using `ma_resource_manager_data_source_read_pcm_frames()`, +`MA_BUSY` will be returned if there are no frames available. If there are some frames available, +but less than the number requested, `MA_SUCCESS` will be returned, but the actual number of frames +read will be less than the number requested. Due to the asynchronous nature of data streams, +seeking is also asynchronous. If the data stream is in the middle of a seek, `MA_BUSY` will be +returned when trying to read frames. + +When `ma_resource_manager_data_source_read_pcm_frames()` results in a page getting fully consumed +a job is posted to load the next page. This will be posted from the same thread that called +`ma_resource_manager_data_source_read_pcm_frames()`. + +Data streams are uninitialized by posting a job to the queue, but the function won't return until +that job has been processed. The reason for this is that the caller owns the data stream object and +therefore miniaudio needs to ensure everything completes before handing back control to the caller. +Also, if the data stream is uninitialized while pages are in the middle of decoding, they must +complete before destroying any underlying object and the job system handles this cleanly. + +Note that when a new page needs to be loaded, a job will be posted to the resource manager's job +thread from the audio thread. You must keep in mind the details mentioned in the "Job Queue" +section above regarding locking when posting an event if you require a strictly lock-free audio +thread. + + + +7. Node Graph +============= +miniaudio's routing infrastructure follows a node graph paradigm. The idea is that you create a +node whose outputs are attached to inputs of another node, thereby creating a graph. There are +different types of nodes, with each node in the graph processing input data to produce output, +which is then fed through the chain. Each node in the graph can apply their own custom effects. At +the start of the graph will usually be one or more data source nodes which have no inputs and +instead pull their data from a data source. At the end of the graph is an endpoint which represents +the end of the chain and is where the final output is ultimately extracted from. + +Each node has a number of input buses and a number of output buses. An output bus from a node is +attached to an input bus of another. Multiple nodes can connect their output buses to another +node's input bus, in which case their outputs will be mixed before processing by the node. Below is +a diagram that illustrates a hypothetical node graph setup: + + ``` + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Data flows left to right >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + + +---------------+ +-----------------+ + | Data Source 1 =----+ +----------+ +----= Low Pass Filter =----+ + +---------------+ | | =----+ +-----------------+ | +----------+ + +----= Splitter | +----= ENDPOINT | + +---------------+ | | =----+ +-----------------+ | +----------+ + | Data Source 2 =----+ +----------+ +----= Echo / Delay =----+ + +---------------+ +-----------------+ + ``` + +In the above graph, it starts with two data sources whose outputs are attached to the input of a +splitter node. It's at this point that the two data sources are mixed. After mixing, the splitter +performs it's processing routine and produces two outputs which is simply a duplication of the +input stream. One output is attached to a low pass filter, whereas the other output is attached to +a echo/delay. The outputs of the the low pass filter and the echo are attached to the endpoint, and +since they're both connected to the same input bus, they'll be mixed. + +Each input bus must be configured to accept the same number of channels, but the number of channels +used by input buses can be different to the number of channels for output buses in which case +miniaudio will automatically convert the input data to the output channel count before processing. +The number of channels of an output bus of one node must match the channel count of the input bus +it's attached to. The channel counts cannot be changed after the node has been initialized. If you +attempt to attach an output bus to an input bus with a different channel count, attachment will +fail. + +To use a node graph, you first need to initialize a `ma_node_graph` object. This is essentially a +container around the entire graph. The `ma_node_graph` object is required for some thread-safety +issues which will be explained later. A `ma_node_graph` object is initialized using miniaudio's +standard config/init system: + + ```c + ma_node_graph_config nodeGraphConfig = ma_node_graph_config_init(myChannelCount); + + result = ma_node_graph_init(&nodeGraphConfig, NULL, &nodeGraph); // Second parameter is a pointer to allocation callbacks. + if (result != MA_SUCCESS) { + // Failed to initialize node graph. + } + ``` + +When you initialize the node graph, you're specifying the channel count of the endpoint. The +endpoint is a special node which has one input bus and one output bus, both of which have the +same channel count, which is specified in the config. Any nodes that connect directly to the +endpoint must be configured such that their output buses have the same channel count. When you read +audio data from the node graph, it'll have the channel count you specified in the config. To read +data from the graph: + + ```c + ma_uint32 framesRead; + result = ma_node_graph_read_pcm_frames(&nodeGraph, pFramesOut, frameCount, &framesRead); + if (result != MA_SUCCESS) { + // Failed to read data from the node graph. + } + ``` + +When you read audio data, miniaudio starts at the node graph's endpoint node which then pulls in +data from it's input attachments, which in turn recursively pull in data from their inputs, and so +on. At the start of the graph there will be some kind of data source node which will have zero +inputs and will instead read directly from a data source. The base nodes don't literally need to +read from a `ma_data_source` object, but they will always have some kind of underlying object that +sources some kind of audio. The `ma_data_source_node` node can be used to read from a +`ma_data_source`. Data is always in floating-point format and in the number of channels you +specified when the graph was initialized. The sample rate is defined by the underlying data sources. +It's up to you to ensure they use a consistent and appropriate sample rate. + +The `ma_node` API is designed to allow custom nodes to be implemented with relative ease, but +miniaudio includes a few stock nodes for common functionality. This is how you would initialize a +node which reads directly from a data source (`ma_data_source_node`) which is an example of one +of the stock nodes that comes with miniaudio: + + ```c + ma_data_source_node_config config = ma_data_source_node_config_init(pMyDataSource); + + ma_data_source_node dataSourceNode; + result = ma_data_source_node_init(&nodeGraph, &config, NULL, &dataSourceNode); + if (result != MA_SUCCESS) { + // Failed to create data source node. + } + ``` + +The data source node will use the output channel count to determine the channel count of the output +bus. There will be 1 output bus and 0 input buses (data will be drawn directly from the data +source). The data source must output to floating-point (`ma_format_f32`) or else an error will be +returned from `ma_data_source_node_init()`. + +By default the node will not be attached to the graph. To do so, use `ma_node_attach_output_bus()`: + + ```c + result = ma_node_attach_output_bus(&dataSourceNode, 0, ma_node_graph_get_endpoint(&nodeGraph), 0); + if (result != MA_SUCCESS) { + // Failed to attach node. + } + ``` + +The code above connects the data source node directly to the endpoint. Since the data source node +has only a single output bus, the index will always be 0. Likewise, the endpoint only has a single +input bus which means the input bus index will also always be 0. + +To detach a specific output bus, use `ma_node_detach_output_bus()`. To detach all output buses, use +`ma_node_detach_all_output_buses()`. If you want to just move the output bus from one attachment to +another, you do not need to detach first. You can just call `ma_node_attach_output_bus()` and it'll +deal with it for you. + +Less frequently you may want to create a specialized node. This will be a node where you implement +your own processing callback to apply a custom effect of some kind. This is similar to initializing +one of the stock node types, only this time you need to specify a pointer to a vtable containing a +pointer to the processing function and the number of input and output buses. Example: + + ```c + static void my_custom_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut) + { + // Do some processing of ppFramesIn (one stream of audio data per input bus) + const float* pFramesIn_0 = ppFramesIn[0]; // Input bus @ index 0. + const float* pFramesIn_1 = ppFramesIn[1]; // Input bus @ index 1. + float* pFramesOut_0 = ppFramesOut[0]; // Output bus @ index 0. + + // Do some processing. On input, `pFrameCountIn` will be the number of input frames in each + // buffer in `ppFramesIn` and `pFrameCountOut` will be the capacity of each of the buffers + // in `ppFramesOut`. On output, `pFrameCountIn` should be set to the number of input frames + // your node consumed and `pFrameCountOut` should be set the number of output frames that + // were produced. + // + // You should process as many frames as you can. If your effect consumes input frames at the + // same rate as output frames (always the case, unless you're doing resampling), you need + // only look at `ppFramesOut` and process that exact number of frames. If you're doing + // resampling, you'll need to be sure to set both `pFrameCountIn` and `pFrameCountOut` + // properly. + } + + static ma_node_vtable my_custom_node_vtable = + { + my_custom_node_process_pcm_frames, // The function that will be called to process your custom node. This is where you'd implement your effect processing. + NULL, // Optional. A callback for calculating the number of input frames that are required to process a specified number of output frames. + 2, // 2 input buses. + 1, // 1 output bus. + 0 // Default flags. + }; + + ... + + // Each bus needs to have a channel count specified. To do this you need to specify the channel + // counts in an array and then pass that into the node config. + ma_uint32 inputChannels[2]; // Equal in size to the number of input channels specified in the vtable. + ma_uint32 outputChannels[1]; // Equal in size to the number of output channels specified in the vtable. + + inputChannels[0] = channelsIn; + inputChannels[1] = channelsIn; + outputChannels[0] = channelsOut; + + ma_node_config nodeConfig = ma_node_config_init(); + nodeConfig.vtable = &my_custom_node_vtable; + nodeConfig.pInputChannels = inputChannels; + nodeConfig.pOutputChannels = outputChannels; + + ma_node_base node; + result = ma_node_init(&nodeGraph, &nodeConfig, NULL, &node); + if (result != MA_SUCCESS) { + // Failed to initialize node. + } + ``` + +When initializing a custom node, as in the code above, you'll normally just place your vtable in +static space. The number of input and output buses are specified as part of the vtable. If you need +a variable number of buses on a per-node bases, the vtable should have the relevant bus count set +to `MA_NODE_BUS_COUNT_UNKNOWN`. In this case, the bus count should be set in the node config: + + ```c + static ma_node_vtable my_custom_node_vtable = + { + my_custom_node_process_pcm_frames, // The function that will be called process your custom node. This is where you'd implement your effect processing. + NULL, // Optional. A callback for calculating the number of input frames that are required to process a specified number of output frames. + MA_NODE_BUS_COUNT_UNKNOWN, // The number of input buses is determined on a per-node basis. + 1, // 1 output bus. + 0 // Default flags. + }; + + ... + + ma_node_config nodeConfig = ma_node_config_init(); + nodeConfig.vtable = &my_custom_node_vtable; + nodeConfig.inputBusCount = myBusCount; // <-- Since the vtable specifies MA_NODE_BUS_COUNT_UNKNOWN, the input bus count should be set here. + nodeConfig.pInputChannels = inputChannels; // <-- Make sure there are nodeConfig.inputBusCount elements in this array. + nodeConfig.pOutputChannels = outputChannels; // <-- The vtable specifies 1 output bus, so there must be 1 element in this array. + ``` + +In the above example it's important to never set the `inputBusCount` and `outputBusCount` members +to anything other than their defaults if the vtable specifies an explicit count. They can only be +set if the vtable specifies MA_NODE_BUS_COUNT_UNKNOWN in the relevant bus count. + +Most often you'll want to create a structure to encapsulate your node with some extra data. You +need to make sure the `ma_node_base` object is your first member of the structure: + + ```c + typedef struct + { + ma_node_base base; // <-- Make sure this is always the first member. + float someCustomData; + } my_custom_node; + ``` + +By doing this, your object will be compatible with all `ma_node` APIs and you can attach it to the +graph just like any other node. + +In the custom processing callback (`my_custom_node_process_pcm_frames()` in the example above), the +number of channels for each bus is what was specified by the config when the node was initialized +with `ma_node_init()`. In addition, all attachments to each of the input buses will have been +pre-mixed by miniaudio. The config allows you to specify different channel counts for each +individual input and output bus. It's up to the effect to handle it appropriate, and if it can't, +return an error in it's initialization routine. + +Custom nodes can be assigned some flags to describe their behaviour. These are set via the vtable +and include the following: + + +-----------------------------------------+---------------------------------------------------+ + | Flag Name | Description | + +-----------------------------------------+---------------------------------------------------+ + | MA_NODE_FLAG_PASSTHROUGH | Useful for nodes that do not do any kind of audio | + | | processing, but are instead used for tracking | + | | time, handling events, etc. Also used by the | + | | internal endpoint node. It reads directly from | + | | the input bus to the output bus. Nodes with this | + | | flag must have exactly 1 input bus and 1 output | + | | bus, and both buses must have the same channel | + | | counts. | + +-----------------------------------------+---------------------------------------------------+ + | MA_NODE_FLAG_CONTINUOUS_PROCESSING | Causes the processing callback to be called even | + | | when no data is available to be read from input | + | | attachments. When a node has at least one input | + | | bus, but there are no inputs attached or the | + | | inputs do not deliver any data, the node's | + | | processing callback will not get fired. This flag | + | | will make it so the callback is always fired | + | | regardless of whether or not any input data is | + | | received. This is useful for effects like | + | | echos where there will be a tail of audio data | + | | that still needs to be processed even when the | + | | original data sources have reached their ends. It | + | | may also be useful for nodes that must always | + | | have their processing callback fired when there | + | | are no inputs attached. | + +-----------------------------------------+---------------------------------------------------+ + | MA_NODE_FLAG_ALLOW_NULL_INPUT | Used in conjunction with | + | | `MA_NODE_FLAG_CONTINUOUS_PROCESSING`. When this | + | | is set, the `ppFramesIn` parameter of the | + | | processing callback will be set to NULL when | + | | there are no input frames are available. When | + | | this is unset, silence will be posted to the | + | | processing callback. | + +-----------------------------------------+---------------------------------------------------+ + | MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES | Used to tell miniaudio that input and output | + | | frames are processed at different rates. You | + | | should set this for any nodes that perform | + | | resampling. | + +-----------------------------------------+---------------------------------------------------+ + | MA_NODE_FLAG_SILENT_OUTPUT | Used to tell miniaudio that a node produces only | + | | silent output. This is useful for nodes where you | + | | don't want the output to contribute to the final | + | | mix. An example might be if you want split your | + | | stream and have one branch be output to a file. | + | | When using this flag, you should avoid writing to | + | | the output buffer of the node's processing | + | | callback because miniaudio will ignore it anyway. | + +-----------------------------------------+---------------------------------------------------+ + + +If you need to make a copy of an audio stream for effect processing you can use a splitter node +called `ma_splitter_node`. This takes has 1 input bus and splits the stream into 2 output buses. +You can use it like this: + + ```c + ma_splitter_node_config splitterNodeConfig = ma_splitter_node_config_init(channels); + + ma_splitter_node splitterNode; + result = ma_splitter_node_init(&nodeGraph, &splitterNodeConfig, NULL, &splitterNode); + if (result != MA_SUCCESS) { + // Failed to create node. + } + + // Attach your output buses to two different input buses (can be on two different nodes). + ma_node_attach_output_bus(&splitterNode, 0, ma_node_graph_get_endpoint(&nodeGraph), 0); // Attach directly to the endpoint. + ma_node_attach_output_bus(&splitterNode, 1, &myEffectNode, 0); // Attach to input bus 0 of some effect node. + ``` + +The volume of an output bus can be configured on a per-bus basis: + + ```c + ma_node_set_output_bus_volume(&splitterNode, 0, 0.5f); + ma_node_set_output_bus_volume(&splitterNode, 1, 0.5f); + ``` + +In the code above we're using the splitter node from before and changing the volume of each of the +copied streams. + +You can start and stop a node with the following: + + ```c + ma_node_set_state(&splitterNode, ma_node_state_started); // The default state. + ma_node_set_state(&splitterNode, ma_node_state_stopped); + ``` + +By default the node is in a started state, but since it won't be connected to anything won't +actually be invoked by the node graph until it's connected. When you stop a node, data will not be +read from any of it's input connections. You can use this property to stop a group of sounds +atomically. + +You can configure the initial state of a node in it's config: + + ```c + nodeConfig.initialState = ma_node_state_stopped; + ``` + +Note that for the stock specialized nodes, all of their configs will have a `nodeConfig` member +which is the config to use with the base node. This is where the initial state can be configured +for specialized nodes: + + ```c + dataSourceNodeConfig.nodeConfig.initialState = ma_node_state_stopped; + ``` + +When using a specialized node like `ma_data_source_node` or `ma_splitter_node`, be sure to not +modify the `vtable` member of the `nodeConfig` object. + + +7.1. Timing +----------- +The node graph supports starting and stopping nodes at scheduled times. This is especially useful +for data source nodes where you want to get the node set up, but only start playback at a specific +time. There are two clocks: local and global. + +A local clock is per-node, whereas the global clock is per graph. Scheduling starts and stops can +only be done based on the global clock because the local clock will not be running while the node +is stopped. The global clocks advances whenever `ma_node_graph_read_pcm_frames()` is called. On the +other hand, the local clock only advances when the node's processing callback is fired, and is +advanced based on the output frame count. + +To retrieve the global time, use `ma_node_graph_get_time()`. The global time can be set with +`ma_node_graph_set_time()` which might be useful if you want to do seeking on a global timeline. +Getting and setting the local time is similar. Use `ma_node_get_time()` to retrieve the local time, +and `ma_node_set_time()` to set the local time. The global and local times will be advanced by the +audio thread, so care should be taken to avoid data races. Ideally you should avoid calling these +outside of the node processing callbacks which are always run on the audio thread. + +There is basic support for scheduling the starting and stopping of nodes. You can only schedule one +start and one stop at a time. This is mainly intended for putting nodes into a started or stopped +state in a frame-exact manner. Without this mechanism, starting and stopping of a node is limited +to the resolution of a call to `ma_node_graph_read_pcm_frames()` which would typically be in blocks +of several milliseconds. The following APIs can be used for scheduling node states: + + ```c + ma_node_set_state_time() + ma_node_get_state_time() + ``` + +The time is absolute and must be based on the global clock. An example is below: + + ```c + ma_node_set_state_time(&myNode, ma_node_state_started, sampleRate*1); // Delay starting to 1 second. + ma_node_set_state_time(&myNode, ma_node_state_stopped, sampleRate*5); // Delay stopping to 5 seconds. + ``` + +An example for changing the state using a relative time. + + ```c + ma_node_set_state_time(&myNode, ma_node_state_started, sampleRate*1 + ma_node_graph_get_time(&myNodeGraph)); + ma_node_set_state_time(&myNode, ma_node_state_stopped, sampleRate*5 + ma_node_graph_get_time(&myNodeGraph)); + ``` + +Note that due to the nature of multi-threading the times may not be 100% exact. If this is an +issue, consider scheduling state changes from within a processing callback. An idea might be to +have some kind of passthrough trigger node that is used specifically for tracking time and handling +events. + + + +7.2. Thread Safety and Locking +------------------------------ +When processing audio, it's ideal not to have any kind of locking in the audio thread. Since it's +expected that `ma_node_graph_read_pcm_frames()` would be run on the audio thread, it does so +without the use of any locks. This section discusses the implementation used by miniaudio and goes +over some of the compromises employed by miniaudio to achieve this goal. Note that the current +implementation may not be ideal - feedback and critiques are most welcome. + +The node graph API is not *entirely* lock-free. Only `ma_node_graph_read_pcm_frames()` is expected +to be lock-free. Attachment, detachment and uninitialization of nodes use locks to simplify the +implementation, but are crafted in a way such that such locking is not required when reading audio +data from the graph. Locking in these areas are achieved by means of spinlocks. + +The main complication with keeping `ma_node_graph_read_pcm_frames()` lock-free stems from the fact +that a node can be uninitialized, and it's memory potentially freed, while in the middle of being +processed on the audio thread. There are times when the audio thread will be referencing a node, +which means the uninitialization process of a node needs to make sure it delays returning until the +audio thread is finished so that control is not handed back to the caller thereby giving them a +chance to free the node's memory. + +When the audio thread is processing a node, it does so by reading from each of the output buses of +the node. In order for a node to process data for one of it's output buses, it needs to read from +each of it's input buses, and so on an so forth. It follows that once all output buses of a node +are detached, the node as a whole will be disconnected and no further processing will occur unless +it's output buses are reattached, which won't be happening when the node is being uninitialized. +By having `ma_node_detach_output_bus()` wait until the audio thread is finished with it, we can +simplify a few things, at the expense of making `ma_node_detach_output_bus()` a bit slower. By +doing this, the implementation of `ma_node_uninit()` becomes trivial - just detach all output +nodes, followed by each of the attachments to each of it's input nodes, and then do any final clean +up. + +With the above design, the worst-case scenario is `ma_node_detach_output_bus()` taking as long as +it takes to process the output bus being detached. This will happen if it's called at just the +wrong moment where the audio thread has just iterated it and has just started processing. The +caller of `ma_node_detach_output_bus()` will stall until the audio thread is finished, which +includes the cost of recursively processing it's inputs. This is the biggest compromise made with +the approach taken by miniaudio for it's lock-free processing system. The cost of detaching nodes +earlier in the pipeline (data sources, for example) will be cheaper than the cost of detaching +higher level nodes, such as some kind of final post-processing endpoint. If you need to do mass +detachments, detach starting from the lowest level nodes and work your way towards the final +endpoint node (but don't try detaching the node graph's endpoint). If the audio thread is not +running, detachment will be fast and detachment in any order will be the same. The reason nodes +need to wait for their input attachments to complete is due to the potential for desyncs between +data sources. If the node was to terminate processing mid way through processing it's inputs, +there's a chance that some of the underlying data sources will have been read, but then others not. +That will then result in a potential desynchronization when detaching and reattaching higher-level +nodes. A possible solution to this is to have an option when detaching to terminate processing +before processing all input attachments which should be fairly simple. + +Another compromise, albeit less significant, is locking when attaching and detaching nodes. This +locking is achieved by means of a spinlock in order to reduce memory overhead. A lock is present +for each input bus and output bus. When an output bus is connected to an input bus, both the output +bus and input bus is locked. This locking is specifically for attaching and detaching across +different threads and does not affect `ma_node_graph_read_pcm_frames()` in any way. The locking and +unlocking is mostly self-explanatory, but a slightly less intuitive aspect comes into it when +considering that iterating over attachments must not break as a result of attaching or detaching a +node while iteration is occurring. + +Attaching and detaching are both quite simple. When an output bus of a node is attached to an input +bus of another node, it's added to a linked list. Basically, an input bus is a linked list, where +each item in the list is and output bus. We have some intentional (and convenient) restrictions on +what can done with the linked list in order to simplify the implementation. First of all, whenever +something needs to iterate over the list, it must do so in a forward direction. Backwards iteration +is not supported. Also, items can only be added to the start of the list. + +The linked list is a doubly-linked list where each item in the list (an output bus) holds a pointer +to the next item in the list, and another to the previous item. A pointer to the previous item is +only required for fast detachment of the node - it is never used in iteration. This is an +important property because it means from the perspective of iteration, attaching and detaching of +an item can be done with a single atomic assignment. This is exploited by both the attachment and +detachment process. When attaching the node, the first thing that is done is the setting of the +local "next" and "previous" pointers of the node. After that, the item is "attached" to the list +by simply performing an atomic exchange with the head pointer. After that, the node is "attached" +to the list from the perspective of iteration. Even though the "previous" pointer of the next item +hasn't yet been set, from the perspective of iteration it's been attached because iteration will +only be happening in a forward direction which means the "previous" pointer won't actually ever get +used. The same general process applies to detachment. See `ma_node_attach_output_bus()` and +`ma_node_detach_output_bus()` for the implementation of this mechanism. + + + +8. Decoding +=========== +The `ma_decoder` API is used for reading audio files. Decoders are completely decoupled from +devices and can be used independently. Built-in support is included for the following formats: + + +---------+ + | Format | + +---------+ + | WAV | + | MP3 | + | FLAC | + +---------+ + +You can disable the built-in decoders by specifying one or more of the following options before the +miniaudio implementation: + + ```c + #define MA_NO_WAV + #define MA_NO_MP3 + #define MA_NO_FLAC + ``` + +miniaudio supports the ability to plug in custom decoders. See the section below for details on how +to use custom decoders. + +A decoder can be initialized from a file with `ma_decoder_init_file()`, a block of memory with +`ma_decoder_init_memory()`, or from data delivered via callbacks with `ma_decoder_init()`. Here is +an example for loading a decoder from a file: + + ```c + ma_decoder decoder; + ma_result result = ma_decoder_init_file("MySong.mp3", NULL, &decoder); + if (result != MA_SUCCESS) { + return false; // An error occurred. + } + + ... + + ma_decoder_uninit(&decoder); + ``` + +When initializing a decoder, you can optionally pass in a pointer to a `ma_decoder_config` object +(the `NULL` argument in the example above) which allows you to configure the output format, channel +count, sample rate and channel map: + + ```c + ma_decoder_config config = ma_decoder_config_init(ma_format_f32, 2, 48000); + ``` + +When passing in `NULL` for decoder config in `ma_decoder_init*()`, the output format will be the +same as that defined by the decoding backend. + +Data is read from the decoder as PCM frames. This will output the number of PCM frames actually +read. If this is less than the requested number of PCM frames it means you've reached the end. The +return value will be `MA_AT_END` if no samples have been read and the end has been reached. + + ```c + ma_result result = ma_decoder_read_pcm_frames(pDecoder, pFrames, framesToRead, &framesRead); + if (framesRead < framesToRead) { + // Reached the end. + } + ``` + +You can also seek to a specific frame like so: + + ```c + ma_result result = ma_decoder_seek_to_pcm_frame(pDecoder, targetFrame); + if (result != MA_SUCCESS) { + return false; // An error occurred. + } + ``` + +If you want to loop back to the start, you can simply seek back to the first PCM frame: + + ```c + ma_decoder_seek_to_pcm_frame(pDecoder, 0); + ``` + +When loading a decoder, miniaudio uses a trial and error technique to find the appropriate decoding +backend. This can be unnecessarily inefficient if the type is already known. In this case you can +use `encodingFormat` variable in the device config to specify a specific encoding format you want +to decode: + + ```c + decoderConfig.encodingFormat = ma_encoding_format_wav; + ``` + +See the `ma_encoding_format` enum for possible encoding formats. + +The `ma_decoder_init_file()` API will try using the file extension to determine which decoding +backend to prefer. + + +8.1. Custom Decoders +-------------------- +It's possible to implement a custom decoder and plug it into miniaudio. This is extremely useful +when you want to use the `ma_decoder` API, but need to support an encoding format that's not one of +the stock formats supported by miniaudio. This can be put to particularly good use when using the +`ma_engine` and/or `ma_resource_manager` APIs because they use `ma_decoder` internally. If, for +example, you wanted to support Opus, you can do so with a custom decoder (there if a reference +Opus decoder in the "extras" folder of the miniaudio repository which uses libopus + libopusfile). + +A custom decoder must implement a data source. A vtable called `ma_decoding_backend_vtable` needs +to be implemented which is then passed into the decoder config: + + ```c + ma_decoding_backend_vtable* pCustomBackendVTables[] = + { + &g_ma_decoding_backend_vtable_libvorbis, + &g_ma_decoding_backend_vtable_libopus + }; + + ... + + decoderConfig = ma_decoder_config_init_default(); + decoderConfig.pCustomBackendUserData = NULL; + decoderConfig.ppCustomBackendVTables = pCustomBackendVTables; + decoderConfig.customBackendCount = sizeof(pCustomBackendVTables) / sizeof(pCustomBackendVTables[0]); + ``` + +The `ma_decoding_backend_vtable` vtable has the following functions: + + ``` + onInit + onInitFile + onInitFileW + onInitMemory + onUninit + ``` + +There are only two functions that must be implemented - `onInit` and `onUninit`. The other +functions can be implemented for a small optimization for loading from a file path or memory. If +these are not specified, miniaudio will deal with it for you via a generic implementation. + +When you initialize a custom data source (by implementing the `onInit` function in the vtable) you +will need to output a pointer to a `ma_data_source` which implements your custom decoder. See the +section about data sources for details on how to implement this. Alternatively, see the +"custom_decoders" example in the miniaudio repository. + +The `onInit` function takes a pointer to some callbacks for the purpose of reading raw audio data +from some arbitrary source. You'll use these functions to read from the raw data and perform the +decoding. When you call them, you will pass in the `pReadSeekTellUserData` pointer to the relevant +parameter. + +The `pConfig` parameter in `onInit` can be used to configure the backend if appropriate. It's only +used as a hint and can be ignored. However, if any of the properties are relevant to your decoder, +an optimal implementation will handle the relevant properties appropriately. + +If memory allocation is required, it should be done so via the specified allocation callbacks if +possible (the `pAllocationCallbacks` parameter). + +If an error occurs when initializing the decoder, you should leave `ppBackend` unset, or set to +NULL, and make sure everything is cleaned up appropriately and an appropriate result code returned. +When multiple custom backends are specified, miniaudio will cycle through the vtables in the order +they're listed in the array that's passed into the decoder config so it's important that your +initialization routine is clean. + +When a decoder is uninitialized, the `onUninit` callback will be fired which will give you an +opportunity to clean up and internal data. + + + +9. Encoding +=========== +The `ma_encoding` API is used for writing audio files. The only supported output format is WAV. +This can be disabled by specifying the following option before the implementation of miniaudio: + + ```c + #define MA_NO_WAV + ``` + +An encoder can be initialized to write to a file with `ma_encoder_init_file()` or from data +delivered via callbacks with `ma_encoder_init()`. Below is an example for initializing an encoder +to output to a file. + + ```c + ma_encoder_config config = ma_encoder_config_init(ma_encoding_format_wav, FORMAT, CHANNELS, SAMPLE_RATE); + ma_encoder encoder; + ma_result result = ma_encoder_init_file("my_file.wav", &config, &encoder); + if (result != MA_SUCCESS) { + // Error + } + + ... + + ma_encoder_uninit(&encoder); + ``` + +When initializing an encoder you must specify a config which is initialized with +`ma_encoder_config_init()`. Here you must specify the file type, the output sample format, output +channel count and output sample rate. The following file types are supported: + + +------------------------+-------------+ + | Enum | Description | + +------------------------+-------------+ + | ma_encoding_format_wav | WAV | + +------------------------+-------------+ + +If the format, channel count or sample rate is not supported by the output file type an error will +be returned. The encoder will not perform data conversion so you will need to convert it before +outputting any audio data. To output audio data, use `ma_encoder_write_pcm_frames()`, like in the +example below: + + ```c + ma_uint64 framesWritten; + result = ma_encoder_write_pcm_frames(&encoder, pPCMFramesToWrite, framesToWrite, &framesWritten); + if (result != MA_SUCCESS) { + ... handle error ... + } + ``` + +The `framesWritten` variable will contain the number of PCM frames that were actually written. This +is optionally and you can pass in `NULL` if you need this. + +Encoders must be uninitialized with `ma_encoder_uninit()`. + + + +10. Data Conversion +=================== +A data conversion API is included with miniaudio which supports the majority of data conversion +requirements. This supports conversion between sample formats, channel counts (with channel +mapping) and sample rates. + + +10.1. Sample Format Conversion +------------------------------ +Conversion between sample formats is achieved with the `ma_pcm_*_to_*()`, `ma_pcm_convert()` and +`ma_convert_pcm_frames_format()` APIs. Use `ma_pcm_*_to_*()` to convert between two specific +formats. Use `ma_pcm_convert()` to convert based on a `ma_format` variable. Use +`ma_convert_pcm_frames_format()` to convert PCM frames where you want to specify the frame count +and channel count as a variable instead of the total sample count. + + +10.1.1. Dithering +----------------- +Dithering can be set using the ditherMode parameter. + +The different dithering modes include the following, in order of efficiency: + + +-----------+--------------------------+ + | Type | Enum Token | + +-----------+--------------------------+ + | 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. + + + +10.2. Channel Conversion +------------------------ +Channel conversion is used for channel rearrangement and conversion from one channel count to +another. The `ma_channel_converter` API is used for channel conversion. Below is an example of +initializing a simple channel converter which converts from mono to stereo. + + ```c + ma_channel_converter_config config = ma_channel_converter_config_init( + ma_format, // Sample format + 1, // Input channels + NULL, // Input channel map + 2, // Output channels + NULL, // Output channel map + ma_channel_mix_mode_default); // The mixing algorithm to use when combining channels. + + result = ma_channel_converter_init(&config, NULL, &converter); + if (result != MA_SUCCESS) { + // Error. + } + ``` + +To perform the conversion simply call `ma_channel_converter_process_pcm_frames()` like so: + + ```c + ma_result result = ma_channel_converter_process_pcm_frames(&converter, pFramesOut, pFramesIn, frameCount); + if (result != MA_SUCCESS) { + // Error. + } + ``` + +It is up to the caller to ensure the output buffer is large enough to accommodate the new PCM +frames. + +Input and output PCM frames are always interleaved. Deinterleaved layouts are not supported. + + +10.2.1. Channel Mapping +----------------------- +In addition to converting from one channel count to another, like the example above, the channel +converter can also be used to rearrange channels. When initializing the channel converter, you can +optionally pass in channel maps for both the input and output frames. If the channel counts are the +same, and each channel map contains the same channel positions with the exception that they're in +a different order, a simple shuffling of the channels will be performed. If, however, there is not +a 1:1 mapping of channel positions, or the channel counts differ, the input channels will be mixed +based on a mixing mode which is specified when initializing the `ma_channel_converter_config` +object. + +When converting from mono to multi-channel, the mono channel is simply copied to each output +channel. When going the other way around, the audio of each output channel is simply averaged and +copied to the mono channel. + +In more complicated cases blending is used. The `ma_channel_mix_mode_simple` mode will drop excess +channels and silence extra channels. For example, converting from 4 to 2 channels, the 3rd and 4th +channels will be dropped, whereas converting from 2 to 4 channels will put silence into the 3rd and +4th channels. + +The `ma_channel_mix_mode_rectangle` mode uses spacial locality based on a rectangle to compute a +simple distribution between input and output. Imagine sitting in the middle of a room, with +speakers on the walls representing channel positions. The `MA_CHANNEL_FRONT_LEFT` position can be +thought of as being in the corner of the front and left walls. + +Finally, the `ma_channel_mix_mode_custom_weights` mode can be used to use custom user-defined +weights. Custom weights can be passed in as the last parameter of +`ma_channel_converter_config_init()`. + +Predefined channel maps can be retrieved with `ma_channel_map_init_standard()`. This takes a +`ma_standard_channel_map` enum as it's first parameter, which can be one of the following: + + +-----------------------------------+-----------------------------------------------------------+ + | Name | Description | + +-----------------------------------+-----------------------------------------------------------+ + | ma_standard_channel_map_default | Default channel map used by miniaudio. See below. | + | ma_standard_channel_map_microsoft | Channel map used by Microsoft's bitfield channel maps. | + | ma_standard_channel_map_alsa | Default ALSA channel map. | + | ma_standard_channel_map_rfc3551 | RFC 3551. Based on AIFF. | + | ma_standard_channel_map_flac | FLAC channel map. | + | ma_standard_channel_map_vorbis | Vorbis channel map. | + | ma_standard_channel_map_sound4 | FreeBSD's sound(4). | + | ma_standard_channel_map_sndio | sndio channel map. http://www.sndio.org/tips.html. | + | ma_standard_channel_map_webaudio | https://webaudio.github.io/web-audio-api/#ChannelOrdering | + +-----------------------------------+-----------------------------------------------------------+ + +Below are the channel maps used by default in miniaudio (`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. | + +---------------+---------------------------------+ + + + +10.3. Resampling +---------------- +Resampling is achieved with the `ma_resampler` object. To create a resampler object, do something +like the following: + + ```c + ma_resampler_config config = ma_resampler_config_init( + ma_format_s16, + channels, + sampleRateIn, + sampleRateOut, + ma_resample_algorithm_linear); + + ma_resampler resampler; + ma_result result = ma_resampler_init(&config, &resampler); + if (result != MA_SUCCESS) { + // An error occurred... + } + ``` + +Do the following to uninitialize the resampler: + + ```c + ma_resampler_uninit(&resampler); + ``` + +The following example shows how data can be processed + + ```c + ma_uint64 frameCountIn = 1000; + ma_uint64 frameCountOut = 2000; + ma_result result = ma_resampler_process_pcm_frames(&resampler, pFramesIn, &frameCountIn, pFramesOut, &frameCountOut); + if (result != MA_SUCCESS) { + // An error occurred... + } + + // At this point, frameCountIn contains the number of input frames that were consumed and frameCountOut contains the + // number of output frames written. + ``` + +To initialize the resampler you first need to set up a config (`ma_resampler_config`) with +`ma_resampler_config_init()`. You need to specify the sample format you want to use, the number of +channels, the input and output sample rate, and the algorithm. + +The sample format can be either `ma_format_s16` or `ma_format_f32`. If you need a different format +you will need to perform pre- and post-conversions yourself where necessary. Note that the format +is the same for both input and output. The format cannot be changed after initialization. + +The resampler supports multiple channels and is always interleaved (both input and output). The +channel count cannot be changed after initialization. + +The sample rates can be anything other than zero, and are always specified in hertz. They should be +set to something like 44100, etc. The sample rate is the only configuration property that can be +changed after initialization. + +The miniaudio resampler has built-in support for the following algorithms: + + +-----------+------------------------------+ + | Algorithm | Enum Token | + +-----------+------------------------------+ + | Linear | ma_resample_algorithm_linear | + | Custom | ma_resample_algorithm_custom | + +-----------+------------------------------+ + +The algorithm cannot be changed after initialization. + +Processing always happens on a per PCM frame basis and always assumes interleaved input and output. +De-interleaved processing is not supported. To process frames, use +`ma_resampler_process_pcm_frames()`. On input, this function takes the number of output frames you +can fit in the output buffer and the number of input frames contained in the input buffer. On +output these variables contain the number of output frames that were written to the output buffer +and the number of input frames that were consumed in the process. You can pass in NULL for the +input buffer in which case it will be treated as an infinitely large buffer of zeros. The output +buffer can also be NULL, in which case the processing will be treated as seek. + +The sample rate can be changed dynamically on the fly. You can change this with explicit sample +rates with `ma_resampler_set_rate()` and also with a decimal ratio with +`ma_resampler_set_rate_ratio()`. The ratio is in/out. + +Sometimes it's useful to know exactly how many input frames will be required to output a specific +number of frames. You can calculate this with `ma_resampler_get_required_input_frame_count()`. +Likewise, it's sometimes useful to know exactly how many frames would be output given a certain +number of input frames. You can do this with `ma_resampler_get_expected_output_frame_count()`. + +Due to the nature of how resampling works, the resampler introduces some latency. This can be +retrieved in terms of both the input rate and the output rate with +`ma_resampler_get_input_latency()` and `ma_resampler_get_output_latency()`. + + +10.3.1. Resampling Algorithms +----------------------------- +The choice of resampling algorithm depends on your situation and requirements. + + +10.3.1.1. Linear Resampling +--------------------------- +The linear resampler is the fastest, but comes at the expense of poorer quality. There is, however, +some control over the quality of the linear resampler which may make it a suitable option depending +on your requirements. + +The linear resampler performs low-pass filtering before or after downsampling or upsampling, +depending on the sample rates you're converting between. When decreasing the sample rate, the +low-pass filter will be applied before downsampling. When increasing the rate it will be performed +after upsampling. By default a fourth order low-pass filter will be applied. This can be configured +via the `lpfOrder` configuration variable. Setting this to 0 will disable filtering. + +The low-pass filter has a cutoff frequency which defaults to half the sample rate of the lowest of +the input and output sample rates (Nyquist Frequency). + +The API for the linear resampler is the same as the main resampler API, only it's called +`ma_linear_resampler`. + + +10.3.2. Custom Resamplers +------------------------- +You can implement a custom resampler by using the `ma_resample_algorithm_custom` resampling +algorithm and setting a vtable in the resampler config: + + ```c + ma_resampler_config config = ma_resampler_config_init(..., ma_resample_algorithm_custom); + config.pBackendVTable = &g_customResamplerVTable; + ``` + +Custom resamplers are useful if the stock algorithms are not appropriate for your use case. You +need to implement the required functions in `ma_resampling_backend_vtable`. Note that not all +functions in the vtable need to be implemented, but if it's possible to implement, they should be. + +You can use the `ma_linear_resampler` object for an example on how to implement the vtable. The +`onGetHeapSize` callback is used to calculate the size of any internal heap allocation the custom +resampler will need to make given the supplied config. When you initialize the resampler via the +`onInit` callback, you'll be given a pointer to a heap allocation which is where you should store +the heap allocated data. You should not free this data in `onUninit` because miniaudio will manage +it for you. + +The `onProcess` callback is where the actual resampling takes place. On input, `pFrameCountIn` +points to a variable containing the number of frames in the `pFramesIn` buffer and +`pFrameCountOut` points to a variable containing the capacity in frames of the `pFramesOut` buffer. +On output, `pFrameCountIn` should be set to the number of input frames that were fully consumed, +whereas `pFrameCountOut` should be set to the number of frames that were written to `pFramesOut`. + +The `onSetRate` callback is optional and is used for dynamically changing the sample rate. If +dynamic rate changes are not supported, you can set this callback to NULL. + +The `onGetInputLatency` and `onGetOutputLatency` functions are used for retrieving the latency in +input and output rates respectively. These can be NULL in which case latency calculations will be +assumed to be NULL. + +The `onGetRequiredInputFrameCount` callback is used to give miniaudio a hint as to how many input +frames are required to be available to produce the given number of output frames. Likewise, the +`onGetExpectedOutputFrameCount` callback is used to determine how many output frames will be +produced given the specified number of input frames. miniaudio will use these as a hint, but they +are optional and can be set to NULL if you're unable to implement them. + + + +10.4. General Data Conversion +----------------------------- +The `ma_data_converter` API can be used to wrap sample format conversion, channel conversion and +resampling into one operation. This is what miniaudio uses internally to convert between the format +requested when the device was initialized and the format of the backend's native device. The API +for general data conversion is very similar to the resampling API. Create a `ma_data_converter` +object like this: + + ```c + ma_data_converter_config config = ma_data_converter_config_init( + inputFormat, + outputFormat, + inputChannels, + outputChannels, + inputSampleRate, + outputSampleRate + ); + + ma_data_converter converter; + ma_result result = ma_data_converter_init(&config, NULL, &converter); + if (result != MA_SUCCESS) { + // An error occurred... + } + ``` + +In the example above we use `ma_data_converter_config_init()` to initialize the config, however +there's many more properties that can be configured, such as channel maps and resampling quality. +Something like the following may be more suitable depending on your requirements: + + ```c + ma_data_converter_config config = ma_data_converter_config_init_default(); + config.formatIn = inputFormat; + config.formatOut = outputFormat; + config.channelsIn = inputChannels; + config.channelsOut = outputChannels; + config.sampleRateIn = inputSampleRate; + config.sampleRateOut = outputSampleRate; + ma_channel_map_init_standard(ma_standard_channel_map_flac, config.channelMapIn, sizeof(config.channelMapIn)/sizeof(config.channelMapIn[0]), config.channelCountIn); + config.resampling.linear.lpfOrder = MA_MAX_FILTER_ORDER; + ``` + +Do the following to uninitialize the data converter: + + ```c + ma_data_converter_uninit(&converter, NULL); + ``` + +The following example shows how data can be processed + + ```c + ma_uint64 frameCountIn = 1000; + ma_uint64 frameCountOut = 2000; + ma_result result = ma_data_converter_process_pcm_frames(&converter, pFramesIn, &frameCountIn, pFramesOut, &frameCountOut); + if (result != MA_SUCCESS) { + // An error occurred... + } + + // At this point, frameCountIn contains the number of input frames that were consumed and frameCountOut contains the number + // of output frames written. + ``` + +The data converter supports multiple channels and is always interleaved (both input and output). +The channel count cannot be changed after initialization. + +Sample rates can be anything other than zero, and are always specified in hertz. They should be set +to something like 44100, etc. The sample rate is the only configuration property that can be +changed after initialization, but only if the `resampling.allowDynamicSampleRate` member of +`ma_data_converter_config` is set to `MA_TRUE`. To change the sample rate, use +`ma_data_converter_set_rate()` or `ma_data_converter_set_rate_ratio()`. The ratio must be in/out. +The resampling algorithm cannot be changed after initialization. + +Processing always happens on a per PCM frame basis and always assumes interleaved input and output. +De-interleaved processing is not supported. To process frames, use +`ma_data_converter_process_pcm_frames()`. On input, this function takes the number of output frames +you can fit in the output buffer and the number of input frames contained in the input buffer. On +output these variables contain the number of output frames that were written to the output buffer +and the number of input frames that were consumed in the process. You can pass in NULL for the +input buffer in which case it will be treated as an infinitely large +buffer of zeros. The output buffer can also be NULL, in which case the processing will be treated +as seek. + +Sometimes it's useful to know exactly how many input frames will be required to output a specific +number of frames. You can calculate this with `ma_data_converter_get_required_input_frame_count()`. +Likewise, it's sometimes useful to know exactly how many frames would be output given a certain +number of input frames. You can do this with `ma_data_converter_get_expected_output_frame_count()`. + +Due to the nature of how resampling works, the data converter introduces some latency if resampling +is required. This can be retrieved in terms of both the input rate and the output rate with +`ma_data_converter_get_input_latency()` and `ma_data_converter_get_output_latency()`. + + + +11. Filtering +============= + +11.1. Biquad Filtering +---------------------- +Biquad filtering is achieved with the `ma_biquad` API. Example: + + ```c + ma_biquad_config config = ma_biquad_config_init(ma_format_f32, channels, b0, b1, b2, a0, a1, a2); + ma_result result = ma_biquad_init(&config, &biquad); + if (result != MA_SUCCESS) { + // Error. + } + + ... + + ma_biquad_process_pcm_frames(&biquad, pFramesOut, pFramesIn, frameCount); + ``` + +Biquad filtering is implemented using transposed direct form 2. The numerator coefficients are b0, +b1 and b2, and the denominator coefficients are a0, a1 and a2. The a0 coefficient is required and +coefficients must not be pre-normalized. + +Supported formats are `ma_format_s16` and `ma_format_f32`. If you need to use a different format +you need to convert it yourself beforehand. When using `ma_format_s16` the biquad filter will use +fixed point arithmetic. When using `ma_format_f32`, floating point arithmetic will be used. + +Input and output frames are always interleaved. + +Filtering can be applied in-place by passing in the same pointer for both the input and output +buffers, like so: + + ```c + ma_biquad_process_pcm_frames(&biquad, pMyData, pMyData, frameCount); + ``` + +If you need to change the values of the coefficients, but maintain the values in the registers you +can do so with `ma_biquad_reinit()`. This is useful if you need to change the properties of the +filter while keeping the values of registers valid to avoid glitching. Do not use +`ma_biquad_init()` for this as it will do a full initialization which involves clearing the +registers to 0. Note that changing the format or channel count after initialization is invalid and +will result in an error. + + +11.2. Low-Pass Filtering +------------------------ +Low-pass filtering is achieved with the following APIs: + + +---------+------------------------------------------+ + | API | Description | + +---------+------------------------------------------+ + | ma_lpf1 | First order low-pass filter | + | ma_lpf2 | Second order low-pass filter | + | ma_lpf | High order low-pass filter (Butterworth) | + +---------+------------------------------------------+ + +Low-pass filter example: + + ```c + ma_lpf_config config = ma_lpf_config_init(ma_format_f32, channels, sampleRate, cutoffFrequency, order); + ma_result result = ma_lpf_init(&config, &lpf); + if (result != MA_SUCCESS) { + // Error. + } + + ... + + ma_lpf_process_pcm_frames(&lpf, pFramesOut, pFramesIn, frameCount); + ``` + +Supported formats are `ma_format_s16` and` ma_format_f32`. If you need to use a different format +you need to convert it yourself beforehand. Input and output frames are always interleaved. + +Filtering can be applied in-place by passing in the same pointer for both the input and output +buffers, like so: + + ```c + ma_lpf_process_pcm_frames(&lpf, pMyData, pMyData, frameCount); + ``` + +The maximum filter order is limited to `MA_MAX_FILTER_ORDER` which is set to 8. If you need more, +you can chain first and second order filters together. + + ```c + for (iFilter = 0; iFilter < filterCount; iFilter += 1) { + ma_lpf2_process_pcm_frames(&lpf2[iFilter], pMyData, pMyData, frameCount); + } + ``` + +If you need to change the configuration of the filter, but need to maintain the state of internal +registers you can do so with `ma_lpf_reinit()`. This may be useful if you need to change the sample +rate and/or cutoff frequency dynamically while maintaining smooth transitions. Note that changing the +format or channel count after initialization is invalid and will result in an error. + +The `ma_lpf` object supports a configurable order, but if you only need a first order filter you +may want to consider using `ma_lpf1`. Likewise, if you only need a second order filter you can use +`ma_lpf2`. The advantage of this is that they're lighter weight and a bit more efficient. + +If an even filter order is specified, a series of second order filters will be processed in a +chain. If an odd filter order is specified, a first order filter will be applied, followed by a +series of second order filters in a chain. + + +11.3. High-Pass Filtering +------------------------- +High-pass filtering is achieved with the following APIs: + + +---------+-------------------------------------------+ + | API | Description | + +---------+-------------------------------------------+ + | ma_hpf1 | First order high-pass filter | + | ma_hpf2 | Second order high-pass filter | + | ma_hpf | High order high-pass filter (Butterworth) | + +---------+-------------------------------------------+ + +High-pass filters work exactly the same as low-pass filters, only the APIs are called `ma_hpf1`, +`ma_hpf2` and `ma_hpf`. See example code for low-pass filters for example usage. + + +11.4. Band-Pass Filtering +------------------------- +Band-pass filtering is achieved with the following APIs: + + +---------+-------------------------------+ + | API | Description | + +---------+-------------------------------+ + | ma_bpf2 | Second order band-pass filter | + | ma_bpf | High order band-pass filter | + +---------+-------------------------------+ + +Band-pass filters work exactly the same as low-pass filters, only the APIs are called `ma_bpf2` and +`ma_hpf`. See example code for low-pass filters for example usage. Note that the order for +band-pass filters must be an even number which means there is no first order band-pass filter, +unlike low-pass and high-pass filters. + + +11.5. Notch Filtering +--------------------- +Notch filtering is achieved with the following APIs: + + +-----------+------------------------------------------+ + | API | Description | + +-----------+------------------------------------------+ + | ma_notch2 | Second order notching filter | + +-----------+------------------------------------------+ + + +11.6. Peaking EQ Filtering +------------------------- +Peaking filtering is achieved with the following APIs: + + +----------+------------------------------------------+ + | API | Description | + +----------+------------------------------------------+ + | ma_peak2 | Second order peaking filter | + +----------+------------------------------------------+ + + +11.7. Low Shelf Filtering +------------------------- +Low shelf filtering is achieved with the following APIs: + + +-------------+------------------------------------------+ + | API | Description | + +-------------+------------------------------------------+ + | ma_loshelf2 | Second order low shelf filter | + +-------------+------------------------------------------+ + +Where a high-pass filter is used to eliminate lower frequencies, a low shelf filter can be used to +just turn them down rather than eliminate them entirely. + + +11.8. High Shelf Filtering +-------------------------- +High shelf filtering is achieved with the following APIs: + + +-------------+------------------------------------------+ + | API | Description | + +-------------+------------------------------------------+ + | ma_hishelf2 | Second order high shelf filter | + +-------------+------------------------------------------+ + +The high shelf filter has the same API as the low shelf filter, only you would use `ma_hishelf` +instead of `ma_loshelf`. Where a low shelf filter is used to adjust the volume of low frequencies, +the high shelf filter does the same thing for high frequencies. + + + + +12. Waveform and Noise Generation +================================= + +12.1. Waveforms +--------------- +miniaudio supports generation of sine, square, triangle and sawtooth waveforms. This is achieved +with the `ma_waveform` API. Example: + + ```c + ma_waveform_config config = ma_waveform_config_init( + FORMAT, + CHANNELS, + SAMPLE_RATE, + ma_waveform_type_sine, + amplitude, + frequency); + + ma_waveform waveform; + ma_result result = ma_waveform_init(&config, &waveform); + if (result != MA_SUCCESS) { + // Error. + } + + ... + + ma_waveform_read_pcm_frames(&waveform, pOutput, frameCount); + ``` + +The amplitude, frequency, type, and sample rate can be changed dynamically with +`ma_waveform_set_amplitude()`, `ma_waveform_set_frequency()`, `ma_waveform_set_type()`, and +`ma_waveform_set_sample_rate()` respectively. + +You can invert the waveform by setting the amplitude to a negative value. You can use this to +control whether or not a sawtooth has a positive or negative ramp, for example. + +Below are the supported waveform types: + + +---------------------------+ + | Enum Name | + +---------------------------+ + | ma_waveform_type_sine | + | ma_waveform_type_square | + | ma_waveform_type_triangle | + | ma_waveform_type_sawtooth | + +---------------------------+ + + + +12.2. Noise +----------- +miniaudio supports generation of white, pink and Brownian noise via the `ma_noise` API. Example: + + ```c + ma_noise_config config = ma_noise_config_init( + FORMAT, + CHANNELS, + ma_noise_type_white, + SEED, + amplitude); + + ma_noise noise; + ma_result result = ma_noise_init(&config, &noise); + if (result != MA_SUCCESS) { + // Error. + } + + ... + + ma_noise_read_pcm_frames(&noise, pOutput, frameCount); + ``` + +The noise API uses simple LCG random number generation. It supports a custom seed which is useful +for things like automated testing requiring reproducibility. Setting the seed to zero will default +to `MA_DEFAULT_LCG_SEED`. + +The amplitude and seed can be changed dynamically with `ma_noise_set_amplitude()` and +`ma_noise_set_seed()` respectively. + +By default, the noise API will use different values for different channels. So, for example, the +left side in a stereo stream will be different to the right side. To instead have each channel use +the same random value, set the `duplicateChannels` member of the noise config to true, like so: + + ```c + config.duplicateChannels = MA_TRUE; + ``` + +Below are the supported noise types. + + +------------------------+ + | Enum Name | + +------------------------+ + | ma_noise_type_white | + | ma_noise_type_pink | + | ma_noise_type_brownian | + +------------------------+ + + + +13. Audio Buffers +================= +miniaudio supports reading from a buffer of raw audio data via the `ma_audio_buffer` API. This can +read from memory that's managed by the application, but can also handle the memory management for +you internally. Memory management is flexible and should support most use cases. + +Audio buffers are initialized using the standard configuration system used everywhere in miniaudio: + + ```c + ma_audio_buffer_config config = ma_audio_buffer_config_init( + format, + channels, + sizeInFrames, + pExistingData, + &allocationCallbacks); + + ma_audio_buffer buffer; + result = ma_audio_buffer_init(&config, &buffer); + if (result != MA_SUCCESS) { + // Error. + } + + ... + + ma_audio_buffer_uninit(&buffer); + ``` + +In the example above, the memory pointed to by `pExistingData` will *not* be copied and is how an +application can do self-managed memory allocation. If you would rather make a copy of the data, use +`ma_audio_buffer_init_copy()`. To uninitialize the buffer, use `ma_audio_buffer_uninit()`. + +Sometimes it can be convenient to allocate the memory for the `ma_audio_buffer` structure and the +raw audio data in a contiguous block of memory. That is, the raw audio data will be located +immediately after the `ma_audio_buffer` structure. To do this, use +`ma_audio_buffer_alloc_and_init()`: + + ```c + ma_audio_buffer_config config = ma_audio_buffer_config_init( + format, + channels, + sizeInFrames, + pExistingData, + &allocationCallbacks); + + ma_audio_buffer* pBuffer + result = ma_audio_buffer_alloc_and_init(&config, &pBuffer); + if (result != MA_SUCCESS) { + // Error + } + + ... + + ma_audio_buffer_uninit_and_free(&buffer); + ``` + +If you initialize the buffer with `ma_audio_buffer_alloc_and_init()` you should uninitialize it +with `ma_audio_buffer_uninit_and_free()`. In the example above, the memory pointed to by +`pExistingData` will be copied into the buffer, which is contrary to the behavior of +`ma_audio_buffer_init()`. + +An audio buffer has a playback cursor just like a decoder. As you read frames from the buffer, the +cursor moves forward. The last parameter (`loop`) can be used to determine if the buffer should +loop. The return value is the number of frames actually read. If this is less than the number of +frames requested it means the end has been reached. This should never happen if the `loop` +parameter is set to true. If you want to manually loop back to the start, you can do so with with +`ma_audio_buffer_seek_to_pcm_frame(pAudioBuffer, 0)`. Below is an example for reading data from an +audio buffer. + + ```c + ma_uint64 framesRead = ma_audio_buffer_read_pcm_frames(pAudioBuffer, pFramesOut, desiredFrameCount, isLooping); + if (framesRead < desiredFrameCount) { + // If not looping, this means the end has been reached. This should never happen in looping mode with valid input. + } + ``` + +Sometimes you may want to avoid the cost of data movement between the internal buffer and the +output buffer. Instead you can use memory mapping to retrieve a pointer to a segment of data: + + ```c + void* pMappedFrames; + ma_uint64 frameCount = frameCountToTryMapping; + ma_result result = ma_audio_buffer_map(pAudioBuffer, &pMappedFrames, &frameCount); + if (result == MA_SUCCESS) { + // Map was successful. The value in frameCount will be how many frames were _actually_ mapped, which may be + // less due to the end of the buffer being reached. + ma_copy_pcm_frames(pFramesOut, pMappedFrames, frameCount, pAudioBuffer->format, pAudioBuffer->channels); + + // You must unmap the buffer. + ma_audio_buffer_unmap(pAudioBuffer, frameCount); + } + ``` + +When you use memory mapping, the read cursor is increment by the frame count passed in to +`ma_audio_buffer_unmap()`. If you decide not to process every frame you can pass in a value smaller +than the value returned by `ma_audio_buffer_map()`. The disadvantage to using memory mapping is +that it does not handle looping for you. You can determine if the buffer is at the end for the +purpose of looping with `ma_audio_buffer_at_end()` or by inspecting the return value of +`ma_audio_buffer_unmap()` and checking if it equals `MA_AT_END`. You should not treat `MA_AT_END` +as an error when returned by `ma_audio_buffer_unmap()`. + + + +14. Ring Buffers +================ +miniaudio supports lock free (single producer, single consumer) ring buffers which are exposed via +the `ma_rb` and `ma_pcm_rb` APIs. The `ma_rb` API operates on bytes, whereas the `ma_pcm_rb` +operates on PCM frames. They are otherwise identical as `ma_pcm_rb` is just a wrapper around +`ma_rb`. + +Unlike most other APIs in miniaudio, ring buffers support both interleaved and deinterleaved +streams. The caller can also allocate their own backing memory for the ring buffer to use +internally for added flexibility. Otherwise the ring buffer will manage it's internal memory for +you. + +The examples below use the PCM frame variant of the ring buffer since that's most likely the one +you will want to use. To initialize a ring buffer, do something like the following: + + ```c + ma_pcm_rb rb; + ma_result result = ma_pcm_rb_init(FORMAT, CHANNELS, BUFFER_SIZE_IN_FRAMES, NULL, NULL, &rb); + if (result != MA_SUCCESS) { + // Error + } + ``` + +The `ma_pcm_rb_init()` function takes the sample format and channel count as parameters because +it's the PCM variant of the ring buffer API. For the regular ring buffer that operates on bytes you +would call `ma_rb_init()` which leaves these out and just takes the size of the buffer in bytes +instead of frames. The fourth parameter is an optional pre-allocated buffer and the fifth parameter +is a pointer to a `ma_allocation_callbacks` structure for custom memory allocation routines. +Passing in `NULL` for this results in `MA_MALLOC()` and `MA_FREE()` being used. + +Use `ma_pcm_rb_init_ex()` if you need a deinterleaved buffer. The data for each sub-buffer is +offset from each other based on the stride. To manage your sub-buffers you can use +`ma_pcm_rb_get_subbuffer_stride()`, `ma_pcm_rb_get_subbuffer_offset()` and +`ma_pcm_rb_get_subbuffer_ptr()`. + +Use `ma_pcm_rb_acquire_read()` and `ma_pcm_rb_acquire_write()` to retrieve a pointer to a section +of the ring buffer. You specify the number of frames 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 frames +requested will require a loop, it will be clamped to the end of the buffer. Therefore, the number +of frames you're given may be less than the number you requested. + +After calling `ma_pcm_rb_acquire_read()` or `ma_pcm_rb_acquire_write()`, you do your work on the +buffer and then "commit" it with `ma_pcm_rb_commit_read()` or `ma_pcm_rb_commit_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_pcm_rb_acquire_read()` or `ma_pcm_rb_acquire_write()` and is +only used for validation. The number of frames passed to `ma_pcm_rb_commit_read()` and +`ma_pcm_rb_commit_write()` is what's used to increment the pointers, and can be less that what was +originally requested. + +If you want to correct for drift between the write pointer and the read pointer you can use a +combination of `ma_pcm_rb_pointer_distance()`, `ma_pcm_rb_seek_read()` and +`ma_pcm_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. + +You can use a ring buffer at the byte level instead of the PCM frame level by using the `ma_rb` +API. This is exactly the same, only you will use the `ma_rb` functions instead of `ma_pcm_rb` and +instead of frame counts you will pass around byte counts. + +The maximum size of the buffer in bytes is `0x7FFFFFFF-(MA_SIMD_ALIGNMENT-1)` due to the most +significant bit being used to encode a loop flag and the internally managed buffers always being +aligned to `MA_SIMD_ALIGNMENT`. + +Note that the ring buffer is only thread safe when used by a single consumer thread and single +producer thread. + + + +15. Backends +============ +The following backends are supported by miniaudio. These are listed in order of default priority. +When no backend is specified when initializing a context or device, miniaudio will attempt to use +each of these backends in the order listed in the table below. + +Note that backends that are not usable by the build target will not be included in the build. For +example, ALSA, which is specific to Linux, will not be included in the Windows build. + + +-------------+-----------------------+--------------------------------------------------------+ + | Name | Enum Name | Supported Operating Systems | + +-------------+-----------------------+--------------------------------------------------------+ + | WASAPI | ma_backend_wasapi | Windows Vista+ | + | DirectSound | ma_backend_dsound | Windows XP+ | + | WinMM | ma_backend_winmm | Windows 95+ | + | Core Audio | ma_backend_coreaudio | macOS, iOS | + | sndio | ma_backend_sndio | OpenBSD | + | audio(4) | ma_backend_audio4 | NetBSD, OpenBSD | + | OSS | ma_backend_oss | FreeBSD | + | PulseAudio | ma_backend_pulseaudio | Cross Platform (disabled on Windows, BSD and Android) | + | ALSA | ma_backend_alsa | Linux | + | JACK | ma_backend_jack | Cross Platform (disabled on BSD and Android) | + | AAudio | ma_backend_aaudio | Android 8+ | + | OpenSL ES | ma_backend_opensl | Android (API level 16+) | + | Web Audio | ma_backend_webaudio | Web (via Emscripten) | + | Custom | ma_backend_custom | Cross Platform | + | Null | ma_backend_null | Cross Platform (not used on Web) | + +-------------+-----------------------+--------------------------------------------------------+ + +Some backends have some nuance details you may want to be aware of. + +15.1. WASAPI +------------ +- Low-latency shared mode will be disabled when using an application-defined sample rate which is + different to the device's native sample rate. To work around this, set `wasapi.noAutoConvertSRC` + to true in the device config. This is due to IAudioClient3_InitializeSharedAudioStream() failing + when the `AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM` flag is specified. Setting wasapi.noAutoConvertSRC + will result in miniaudio's internal resampler being used instead which will in turn enable the + use of low-latency shared mode. + +15.2. 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. + +15.3. 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. + +BSD +--- +- 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. + +15.4. UWP +--------- +- UWP only supports default playback and capture devices. +- UWP requires the Microphone capability to be enabled in the application's manifest (Package.appxmanifest): + + ``` + + ... + + + + + ``` + +15.5. Web Audio / Emscripten +---------------------------- +- You cannot use `-std=c*` compiler flags, nor `-ansi`. This only applies to the Emscripten build. +- The first time a context is initialized it will create a global object called "miniaudio" 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 has implemented a policy in their browsers that prevent automatic media output without + first receiving some kind of user input. The following web page has additional 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. + + + +16. Optimization Tips +===================== +See below for some tips on improving performance. + +16.1. Low Level API +------------------- +- In the data callback, if your data is already clipped prior to copying it into the output buffer, + set the `noClip` config option in the device config to true. This will disable miniaudio's built + in clipping function. +- By default, miniaudio will pre-silence the data callback's output buffer. If you know that you + will always write valid data to the output buffer you can disable pre-silencing by setting the + `noPreSilence` config option in the device config to true. + +16.2. High Level API +-------------------- +- If a sound does not require doppler or pitch shifting, consider disabling pitching by + initializing the sound with the `MA_SOUND_FLAG_NO_PITCH` flag. +- If a sound does not require spatialization, disable it by initializing the sound with the + `MA_SOUND_FLAG_NO_SPATIALIZATION` flag. It can be re-enabled again post-initialization with + `ma_sound_set_spatialization_enabled()`. +- If you know all of your sounds will always be the same sample rate, set the engine's sample + rate to match that of the sounds. Likewise, if you're using a self-managed resource manager, + consider setting the decoded sample rate to match your sounds. By configuring everything to + use a consistent sample rate, sample rate conversion can be avoided. + + + +17. Miscellaneous Notes +======================= +- 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. +- When compiling with VC6 and earlier, decoding is restricted to files less than 2GB in size. This + is due to 64-bit file APIs not being available. +*/ + +#ifndef miniaudio_h +#define miniaudio_h + +#ifdef __cplusplus +extern "C" { +#endif + +#define MA_STRINGIFY(x) #x +#define MA_XSTRINGIFY(x) MA_STRINGIFY(x) + +#define MA_VERSION_MAJOR 0 +#define MA_VERSION_MINOR 11 +#define MA_VERSION_REVISION 21 +#define MA_VERSION_STRING MA_XSTRINGIFY(MA_VERSION_MAJOR) "." MA_XSTRINGIFY(MA_VERSION_MINOR) "." MA_XSTRINGIFY(MA_VERSION_REVISION) + +#if defined(_MSC_VER) && !defined(__clang__) + #pragma warning(push) + #pragma warning(disable:4201) /* nonstandard extension used: nameless struct/union */ + #pragma warning(disable:4214) /* nonstandard extension used: bit field types other than int */ + #pragma warning(disable:4324) /* structure was padded due to alignment specifier */ +#elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wpedantic" /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */ + #if defined(__clang__) + #pragma GCC diagnostic ignored "-Wc11-extensions" /* anonymous unions are a C11 extension */ + #endif +#endif + + + +#if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || defined(_M_IA64) || defined(__aarch64__) || defined(_M_ARM64) || defined(__powerpc64__) + #define MA_SIZEOF_PTR 8 +#else + #define MA_SIZEOF_PTR 4 +#endif + +#include /* For size_t. */ + +/* Sized types. */ +#if defined(MA_USE_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; +#else + typedef signed char ma_int8; + typedef unsigned char ma_uint8; + typedef signed short ma_int16; + typedef unsigned short ma_uint16; + typedef signed int ma_int32; + typedef unsigned int ma_uint32; + #if defined(_MSC_VER) && !defined(__clang__) + typedef signed __int64 ma_int64; + typedef unsigned __int64 ma_uint64; + #else + #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wlong-long" + #if defined(__clang__) + #pragma GCC diagnostic ignored "-Wc++11-long-long" + #endif + #endif + typedef signed long long ma_int64; + typedef unsigned long long ma_uint64; + #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))) + #pragma GCC diagnostic pop + #endif + #endif +#endif /* MA_USE_STDINT */ + +#if MA_SIZEOF_PTR == 8 + typedef ma_uint64 ma_uintptr; +#else + typedef ma_uint32 ma_uintptr; +#endif + +typedef ma_uint8 ma_bool8; +typedef ma_uint32 ma_bool32; +#define MA_TRUE 1 +#define MA_FALSE 0 + +/* These float types are not used universally by miniaudio. It's to simplify some macro expansion for atomic types. */ +typedef float ma_float; +typedef double ma_double; + +typedef void* ma_handle; +typedef void* ma_ptr; + +/* +ma_proc is annoying because when compiling with GCC we get pendantic warnings about converting +between `void*` and `void (*)()`. We can't use `void (*)()` with MSVC however, because we'll get +warning C4191 about "type cast between incompatible function types". To work around this I'm going +to use a different data type depending on the compiler. +*/ +#if defined(__GNUC__) +typedef void (*ma_proc)(void); +#else +typedef void* ma_proc; +#endif + +#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 + + +/* Platform/backend detection. */ +#if defined(_WIN32) || defined(__COSMOPOLITAN__) + #define MA_WIN32 + #if defined(MA_FORCE_UWP) || (defined(WINAPI_FAMILY) && ((defined(WINAPI_FAMILY_PC_APP) && WINAPI_FAMILY == WINAPI_FAMILY_PC_APP) || (defined(WINAPI_FAMILY_PHONE_APP) && WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP))) + #define MA_WIN32_UWP + #elif defined(WINAPI_FAMILY) && (defined(WINAPI_FAMILY_GAMES) && WINAPI_FAMILY == WINAPI_FAMILY_GAMES) + #define MA_WIN32_GDK + #else + #define MA_WIN32_DESKTOP + #endif +#endif +#if !defined(_WIN32) /* If it's not Win32, assume POSIX. */ + #define MA_POSIX + + /* + Use the MA_NO_PTHREAD_IN_HEADER option at your own risk. This is intentionally undocumented. + You can use this to avoid including pthread.h in the header section. The downside is that it + results in some fixed sized structures being declared for the various types that are used in + miniaudio. The risk here is that these types might be too small for a given platform. This + risk is yours to take and no support will be offered if you enable this option. + */ + #ifndef MA_NO_PTHREAD_IN_HEADER + #include /* Unfortunate #include, but needed for pthread_t, pthread_mutex_t and pthread_cond_t types. */ + typedef pthread_t ma_pthread_t; + typedef pthread_mutex_t ma_pthread_mutex_t; + typedef pthread_cond_t ma_pthread_cond_t; + #else + typedef ma_uintptr ma_pthread_t; + typedef union ma_pthread_mutex_t { char __data[40]; ma_uint64 __alignment; } ma_pthread_mutex_t; + typedef union ma_pthread_cond_t { char __data[48]; ma_uint64 __alignment; } ma_pthread_cond_t; + #endif + + #if defined(__unix__) + #define MA_UNIX + #endif + #if defined(__linux__) + #define MA_LINUX + #endif + #if defined(__APPLE__) + #define MA_APPLE + #endif + #if defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) + #define MA_BSD + #endif + #if defined(__ANDROID__) + #define MA_ANDROID + #endif + #if defined(__EMSCRIPTEN__) + #define MA_EMSCRIPTEN + #endif + #if defined(__ORBIS__) + #define MA_ORBIS + #endif + #if defined(__PROSPERO__) + #define MA_PROSPERO + #endif + #if defined(__NX__) + #define MA_NX + #endif + #if defined(__BEOS__) || defined(__HAIKU__) + #define MA_BEOS + #endif + #if defined(__HAIKU__) + #define MA_HAIKU + #endif +#endif + +#if defined(__has_c_attribute) + #if __has_c_attribute(fallthrough) + #define MA_FALLTHROUGH [[fallthrough]] + #endif +#endif +#if !defined(MA_FALLTHROUGH) && defined(__has_attribute) && (defined(__clang__) || defined(__GNUC__)) + #if __has_attribute(fallthrough) + #define MA_FALLTHROUGH __attribute__((fallthrough)) + #endif +#endif +#if !defined(MA_FALLTHROUGH) + #define MA_FALLTHROUGH ((void)0) +#endif + +#ifdef _MSC_VER + #define MA_INLINE __forceinline + + /* noinline was introduced in Visual Studio 2005. */ + #if _MSC_VER >= 1400 + #define MA_NO_INLINE __declspec(noinline) + #else + #define MA_NO_INLINE + #endif +#elif defined(__GNUC__) + /* + I've had a bug report where GCC is emitting warnings about functions possibly not being inlineable. This warning happens when + the __attribute__((always_inline)) attribute is defined without an "inline" statement. I think therefore there must be some + case where "__inline__" is not always defined, thus the compiler emitting these warnings. When using -std=c89 or -ansi on the + command line, we cannot use the "inline" keyword and instead need to use "__inline__". In an attempt to work around this issue + I am using "__inline__" only when we're compiling in strict ANSI mode. + */ + #if defined(__STRICT_ANSI__) + #define MA_GNUC_INLINE_HINT __inline__ + #else + #define MA_GNUC_INLINE_HINT inline + #endif + + #if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 2)) || defined(__clang__) + #define MA_INLINE MA_GNUC_INLINE_HINT __attribute__((always_inline)) + #define MA_NO_INLINE __attribute__((noinline)) + #else + #define MA_INLINE MA_GNUC_INLINE_HINT + #define MA_NO_INLINE __attribute__((noinline)) + #endif +#elif defined(__WATCOMC__) + #define MA_INLINE __inline + #define MA_NO_INLINE +#else + #define MA_INLINE + #define MA_NO_INLINE +#endif + +/* MA_DLL is not officially supported. You're on your own if you want to use this. */ +#if defined(MA_DLL) + #if defined(_WIN32) + #define MA_DLL_IMPORT __declspec(dllimport) + #define MA_DLL_EXPORT __declspec(dllexport) + #define MA_DLL_PRIVATE static + #else + #if defined(__GNUC__) && __GNUC__ >= 4 + #define MA_DLL_IMPORT __attribute__((visibility("default"))) + #define MA_DLL_EXPORT __attribute__((visibility("default"))) + #define MA_DLL_PRIVATE __attribute__((visibility("hidden"))) + #else + #define MA_DLL_IMPORT + #define MA_DLL_EXPORT + #define MA_DLL_PRIVATE static + #endif + #endif +#endif + +#if !defined(MA_API) + #if defined(MA_DLL) + #if defined(MINIAUDIO_IMPLEMENTATION) || defined(MA_IMPLEMENTATION) + #define MA_API MA_DLL_EXPORT + #else + #define MA_API MA_DLL_IMPORT + #endif + #else + #define MA_API extern + #endif +#endif + +#if !defined(MA_STATIC) + #if defined(MA_DLL) + #define MA_PRIVATE MA_DLL_PRIVATE + #else + #define MA_PRIVATE static + #endif +#endif + + +/* SIMD alignment in bytes. Currently set to 32 bytes in preparation for future AVX optimizations. */ +#define MA_SIMD_ALIGNMENT 32 + +/* +Special wchar_t type to ensure any structures in the public sections that reference it have a +consistent size across all platforms. + +On Windows, wchar_t is 2 bytes, whereas everywhere else it's 4 bytes. Since Windows likes to use +wchar_t for it's IDs, we need a special explicitly sized wchar type that is always 2 bytes on all +platforms. +*/ +#if !defined(MA_POSIX) && defined(MA_WIN32) +typedef wchar_t ma_wchar_win32; +#else +typedef ma_uint16 ma_wchar_win32; +#endif + + + +/* +Logging Levels +============== +Log levels are only used to give logging callbacks some context as to the severity of a log message +so they can do filtering. All log levels will be posted to registered logging callbacks. If you +don't want to output a certain log level you can discriminate against the log level in the callback. + +MA_LOG_LEVEL_DEBUG + Used for debugging. Useful for debug and test builds, but should be disabled in release builds. + +MA_LOG_LEVEL_INFO + Informational logging. Useful for debugging. This will never be called from within the data + callback. + +MA_LOG_LEVEL_WARNING + Warnings. You should enable this in you development builds and action them when encounted. These + logs usually indicate a potential problem or misconfiguration, but still allow you to keep + running. This will never be called from within the data callback. + +MA_LOG_LEVEL_ERROR + Error logging. This will be fired when an operation fails and is subsequently aborted. This can + be fired from within the data callback, in which case the device will be stopped. You should + always have this log level enabled. +*/ +typedef enum +{ + MA_LOG_LEVEL_DEBUG = 4, + MA_LOG_LEVEL_INFO = 3, + MA_LOG_LEVEL_WARNING = 2, + MA_LOG_LEVEL_ERROR = 1 +} ma_log_level; + +/* +Variables needing to be accessed atomically should be declared with this macro for two reasons: + + 1) It allows people who read the code to identify a variable as such; and + 2) It forces alignment on platforms where it's required or optimal. + +Note that for x86/64, alignment is not strictly necessary, but does have some performance +implications. Where supported by the compiler, alignment will be used, but otherwise if the CPU +architecture does not require it, it will simply leave it unaligned. This is the case with old +versions of Visual Studio, which I've confirmed with at least VC6. +*/ +#if !defined(_MSC_VER) && defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) + #include + #define MA_ATOMIC(alignment, type) _Alignas(alignment) type +#else + #if defined(__GNUC__) + /* GCC-style compilers. */ + #define MA_ATOMIC(alignment, type) type __attribute__((aligned(alignment))) + #elif defined(_MSC_VER) && _MSC_VER > 1200 /* 1200 = VC6. Alignment not supported, but not necessary because x86 is the only supported target. */ + /* MSVC. */ + #define MA_ATOMIC(alignment, type) __declspec(align(alignment)) type + #else + /* Other compilers. */ + #define MA_ATOMIC(alignment, type) type + #endif +#endif + +typedef struct ma_context ma_context; +typedef struct ma_device ma_device; + +typedef ma_uint8 ma_channel; +typedef enum +{ + MA_CHANNEL_NONE = 0, + MA_CHANNEL_MONO = 1, + MA_CHANNEL_FRONT_LEFT = 2, + MA_CHANNEL_FRONT_RIGHT = 3, + MA_CHANNEL_FRONT_CENTER = 4, + MA_CHANNEL_LFE = 5, + MA_CHANNEL_BACK_LEFT = 6, + MA_CHANNEL_BACK_RIGHT = 7, + MA_CHANNEL_FRONT_LEFT_CENTER = 8, + MA_CHANNEL_FRONT_RIGHT_CENTER = 9, + MA_CHANNEL_BACK_CENTER = 10, + MA_CHANNEL_SIDE_LEFT = 11, + MA_CHANNEL_SIDE_RIGHT = 12, + MA_CHANNEL_TOP_CENTER = 13, + MA_CHANNEL_TOP_FRONT_LEFT = 14, + MA_CHANNEL_TOP_FRONT_CENTER = 15, + MA_CHANNEL_TOP_FRONT_RIGHT = 16, + MA_CHANNEL_TOP_BACK_LEFT = 17, + MA_CHANNEL_TOP_BACK_CENTER = 18, + MA_CHANNEL_TOP_BACK_RIGHT = 19, + MA_CHANNEL_AUX_0 = 20, + MA_CHANNEL_AUX_1 = 21, + MA_CHANNEL_AUX_2 = 22, + MA_CHANNEL_AUX_3 = 23, + MA_CHANNEL_AUX_4 = 24, + MA_CHANNEL_AUX_5 = 25, + MA_CHANNEL_AUX_6 = 26, + MA_CHANNEL_AUX_7 = 27, + MA_CHANNEL_AUX_8 = 28, + MA_CHANNEL_AUX_9 = 29, + MA_CHANNEL_AUX_10 = 30, + MA_CHANNEL_AUX_11 = 31, + MA_CHANNEL_AUX_12 = 32, + MA_CHANNEL_AUX_13 = 33, + MA_CHANNEL_AUX_14 = 34, + MA_CHANNEL_AUX_15 = 35, + MA_CHANNEL_AUX_16 = 36, + MA_CHANNEL_AUX_17 = 37, + MA_CHANNEL_AUX_18 = 38, + MA_CHANNEL_AUX_19 = 39, + MA_CHANNEL_AUX_20 = 40, + MA_CHANNEL_AUX_21 = 41, + MA_CHANNEL_AUX_22 = 42, + MA_CHANNEL_AUX_23 = 43, + MA_CHANNEL_AUX_24 = 44, + MA_CHANNEL_AUX_25 = 45, + MA_CHANNEL_AUX_26 = 46, + MA_CHANNEL_AUX_27 = 47, + MA_CHANNEL_AUX_28 = 48, + MA_CHANNEL_AUX_29 = 49, + MA_CHANNEL_AUX_30 = 50, + MA_CHANNEL_AUX_31 = 51, + MA_CHANNEL_LEFT = MA_CHANNEL_FRONT_LEFT, + MA_CHANNEL_RIGHT = MA_CHANNEL_FRONT_RIGHT, + MA_CHANNEL_POSITION_COUNT = (MA_CHANNEL_AUX_31 + 1) +} _ma_channel_position; /* Do not use `_ma_channel_position` directly. Use `ma_channel` instead. */ + +typedef enum +{ + MA_SUCCESS = 0, + MA_ERROR = -1, /* A generic error. */ + MA_INVALID_ARGS = -2, + MA_INVALID_OPERATION = -3, + MA_OUT_OF_MEMORY = -4, + MA_OUT_OF_RANGE = -5, + MA_ACCESS_DENIED = -6, + MA_DOES_NOT_EXIST = -7, + MA_ALREADY_EXISTS = -8, + MA_TOO_MANY_OPEN_FILES = -9, + MA_INVALID_FILE = -10, + MA_TOO_BIG = -11, + MA_PATH_TOO_LONG = -12, + MA_NAME_TOO_LONG = -13, + MA_NOT_DIRECTORY = -14, + MA_IS_DIRECTORY = -15, + MA_DIRECTORY_NOT_EMPTY = -16, + MA_AT_END = -17, + MA_NO_SPACE = -18, + MA_BUSY = -19, + MA_IO_ERROR = -20, + MA_INTERRUPT = -21, + MA_UNAVAILABLE = -22, + MA_ALREADY_IN_USE = -23, + MA_BAD_ADDRESS = -24, + MA_BAD_SEEK = -25, + MA_BAD_PIPE = -26, + MA_DEADLOCK = -27, + MA_TOO_MANY_LINKS = -28, + MA_NOT_IMPLEMENTED = -29, + MA_NO_MESSAGE = -30, + MA_BAD_MESSAGE = -31, + MA_NO_DATA_AVAILABLE = -32, + MA_INVALID_DATA = -33, + MA_TIMEOUT = -34, + MA_NO_NETWORK = -35, + MA_NOT_UNIQUE = -36, + MA_NOT_SOCKET = -37, + MA_NO_ADDRESS = -38, + MA_BAD_PROTOCOL = -39, + MA_PROTOCOL_UNAVAILABLE = -40, + MA_PROTOCOL_NOT_SUPPORTED = -41, + MA_PROTOCOL_FAMILY_NOT_SUPPORTED = -42, + MA_ADDRESS_FAMILY_NOT_SUPPORTED = -43, + MA_SOCKET_NOT_SUPPORTED = -44, + MA_CONNECTION_RESET = -45, + MA_ALREADY_CONNECTED = -46, + MA_NOT_CONNECTED = -47, + MA_CONNECTION_REFUSED = -48, + MA_NO_HOST = -49, + MA_IN_PROGRESS = -50, + MA_CANCELLED = -51, + MA_MEMORY_ALREADY_MAPPED = -52, + + /* General non-standard errors. */ + MA_CRC_MISMATCH = -100, + + /* General miniaudio-specific errors. */ + MA_FORMAT_NOT_SUPPORTED = -200, + MA_DEVICE_TYPE_NOT_SUPPORTED = -201, + MA_SHARE_MODE_NOT_SUPPORTED = -202, + MA_NO_BACKEND = -203, + MA_NO_DEVICE = -204, + MA_API_NOT_FOUND = -205, + MA_INVALID_DEVICE_CONFIG = -206, + MA_LOOP = -207, + MA_BACKEND_NOT_ENABLED = -208, + + /* State errors. */ + MA_DEVICE_NOT_INITIALIZED = -300, + MA_DEVICE_ALREADY_INITIALIZED = -301, + MA_DEVICE_NOT_STARTED = -302, + MA_DEVICE_NOT_STOPPED = -303, + + /* Operation errors. */ + MA_FAILED_TO_INIT_BACKEND = -400, + MA_FAILED_TO_OPEN_BACKEND_DEVICE = -401, + MA_FAILED_TO_START_BACKEND_DEVICE = -402, + MA_FAILED_TO_STOP_BACKEND_DEVICE = -403 +} ma_result; + + +#define MA_MIN_CHANNELS 1 +#ifndef MA_MAX_CHANNELS +#define MA_MAX_CHANNELS 254 +#endif + +#ifndef MA_MAX_FILTER_ORDER +#define MA_MAX_FILTER_ORDER 8 +#endif + +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 +{ + /* Standard rates need to be in priority order. */ + ma_standard_sample_rate_48000 = 48000, /* Most common */ + ma_standard_sample_rate_44100 = 44100, + + ma_standard_sample_rate_32000 = 32000, /* Lows */ + ma_standard_sample_rate_24000 = 24000, + ma_standard_sample_rate_22050 = 22050, + + ma_standard_sample_rate_88200 = 88200, /* Highs */ + ma_standard_sample_rate_96000 = 96000, + ma_standard_sample_rate_176400 = 176400, + ma_standard_sample_rate_192000 = 192000, + + ma_standard_sample_rate_16000 = 16000, /* Extreme lows */ + ma_standard_sample_rate_11025 = 11025, + ma_standard_sample_rate_8000 = 8000, + + ma_standard_sample_rate_352800 = 352800, /* Extreme highs */ + ma_standard_sample_rate_384000 = 384000, + + ma_standard_sample_rate_min = ma_standard_sample_rate_8000, + ma_standard_sample_rate_max = ma_standard_sample_rate_384000, + ma_standard_sample_rate_count = 14 /* Need to maintain the count manually. Make sure this is updated if items are added to enum. */ +} ma_standard_sample_rate; + + +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_converter_config. */ + ma_channel_mix_mode_default = ma_channel_mix_mode_rectangular +} 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 +{ + void* pUserData; + void* (* onMalloc)(size_t sz, void* pUserData); + void* (* onRealloc)(void* p, size_t sz, void* pUserData); + void (* onFree)(void* p, void* pUserData); +} ma_allocation_callbacks; + +typedef struct +{ + ma_int32 state; +} ma_lcg; + + +/* +Atomics. + +These are typesafe structures to prevent errors as a result of forgetting to reference variables atomically. It's too +easy to introduce subtle bugs where you accidentally do a regular assignment instead of an atomic load/store, etc. By +using a struct we can enforce the use of atomics at compile time. + +These types are declared in the header section because we need to reference them in structs below, but functions for +using them are only exposed in the implementation section. I do not want these to be part of the public API. + +There's a few downsides to this system. The first is that you need to declare a new struct for each type. Below are +some macros to help with the declarations. They will be named like so: + + ma_atomic_uint32 - atomic ma_uint32 + ma_atomic_int32 - atomic ma_int32 + ma_atomic_uint64 - atomic ma_uint64 + ma_atomic_float - atomic float + ma_atomic_bool32 - atomic ma_bool32 + +The other downside is that atomic pointers are extremely messy. You need to declare a new struct for each specific +type of pointer you need to make atomic. For example, an atomic ma_node* will look like this: + + MA_ATOMIC_SAFE_TYPE_IMPL_PTR(node) + +Which will declare a type struct that's named like so: + + ma_atomic_ptr_node + +Functions to use the atomic types are declared in the implementation section. All atomic functions are prefixed with +the name of the struct. For example: + + ma_atomic_uint32_set() - Atomic store of ma_uint32 + ma_atomic_uint32_get() - Atomic load of ma_uint32 + etc. + +For pointer types it's the same, which makes them a bit messy to use due to the length of each function name, but in +return you get type safety and enforcement of atomic operations. +*/ +#define MA_ATOMIC_SAFE_TYPE_DECL(c89TypeExtension, typeSize, type) \ + typedef struct \ + { \ + MA_ATOMIC(typeSize, ma_##type) value; \ + } ma_atomic_##type; \ + +#define MA_ATOMIC_SAFE_TYPE_DECL_PTR(type) \ + typedef struct \ + { \ + MA_ATOMIC(MA_SIZEOF_PTR, ma_##type*) value; \ + } ma_atomic_ptr_##type; \ + +MA_ATOMIC_SAFE_TYPE_DECL(32, 4, uint32) +MA_ATOMIC_SAFE_TYPE_DECL(i32, 4, int32) +MA_ATOMIC_SAFE_TYPE_DECL(64, 8, uint64) +MA_ATOMIC_SAFE_TYPE_DECL(f32, 4, float) +MA_ATOMIC_SAFE_TYPE_DECL(32, 4, bool32) + + +/* Spinlocks are 32-bit for compatibility reasons. */ +typedef ma_uint32 ma_spinlock; + +#ifndef MA_NO_THREADING + /* Thread priorities 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; + + #if defined(MA_POSIX) + typedef ma_pthread_t ma_thread; + #elif defined(MA_WIN32) + typedef ma_handle ma_thread; + #endif + + #if defined(MA_POSIX) + typedef ma_pthread_mutex_t ma_mutex; + #elif defined(MA_WIN32) + typedef ma_handle ma_mutex; + #endif + + #if defined(MA_POSIX) + typedef struct + { + ma_uint32 value; + ma_pthread_mutex_t lock; + ma_pthread_cond_t cond; + } ma_event; + #elif defined(MA_WIN32) + typedef ma_handle ma_event; + #endif + + #if defined(MA_POSIX) + typedef struct + { + int value; + ma_pthread_mutex_t lock; + ma_pthread_cond_t cond; + } ma_semaphore; + #elif defined(MA_WIN32) + typedef ma_handle ma_semaphore; + #endif +#else + /* MA_NO_THREADING is set which means threading is disabled. Threading is required by some API families. If any of these are enabled we need to throw an error. */ + #ifndef MA_NO_DEVICE_IO + #error "MA_NO_THREADING cannot be used without MA_NO_DEVICE_IO"; + #endif +#endif /* MA_NO_THREADING */ + + +/* +Retrieves the version of miniaudio as separated integers. Each component can be NULL if it's not required. +*/ +MA_API void ma_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision); + +/* +Retrieves the version of miniaudio as a string which can be useful for logging purposes. +*/ +MA_API const char* ma_version_string(void); + + +/************************************************************************************************************************************************************** + +Logging + +**************************************************************************************************************************************************************/ +#include /* For va_list. */ + +#if defined(__has_attribute) + #if __has_attribute(format) + #define MA_ATTRIBUTE_FORMAT(fmt, va) __attribute__((format(printf, fmt, va))) + #endif +#endif +#ifndef MA_ATTRIBUTE_FORMAT +#define MA_ATTRIBUTE_FORMAT(fmt, va) +#endif + +#ifndef MA_MAX_LOG_CALLBACKS +#define MA_MAX_LOG_CALLBACKS 4 +#endif + + +/* +The callback for handling log messages. + + +Parameters +---------- +pUserData (in) + The user data pointer that was passed into ma_log_register_callback(). + +logLevel (in) + The log level. This can be one of the following: + + +----------------------+ + | Log Level | + +----------------------+ + | MA_LOG_LEVEL_DEBUG | + | MA_LOG_LEVEL_INFO | + | MA_LOG_LEVEL_WARNING | + | MA_LOG_LEVEL_ERROR | + +----------------------+ + +pMessage (in) + The log message. +*/ +typedef void (* ma_log_callback_proc)(void* pUserData, ma_uint32 level, const char* pMessage); + +typedef struct +{ + ma_log_callback_proc onLog; + void* pUserData; +} ma_log_callback; + +MA_API ma_log_callback ma_log_callback_init(ma_log_callback_proc onLog, void* pUserData); + + +typedef struct +{ + ma_log_callback callbacks[MA_MAX_LOG_CALLBACKS]; + ma_uint32 callbackCount; + ma_allocation_callbacks allocationCallbacks; /* Need to store these persistently because ma_log_postv() might need to allocate a buffer on the heap. */ +#ifndef MA_NO_THREADING + ma_mutex lock; /* For thread safety just to make it easier and safer for the logging implementation. */ +#endif +} ma_log; + +MA_API ma_result ma_log_init(const ma_allocation_callbacks* pAllocationCallbacks, ma_log* pLog); +MA_API void ma_log_uninit(ma_log* pLog); +MA_API ma_result ma_log_register_callback(ma_log* pLog, ma_log_callback callback); +MA_API ma_result ma_log_unregister_callback(ma_log* pLog, ma_log_callback callback); +MA_API ma_result ma_log_post(ma_log* pLog, ma_uint32 level, const char* pMessage); +MA_API ma_result ma_log_postv(ma_log* pLog, ma_uint32 level, const char* pFormat, va_list args); +MA_API ma_result ma_log_postf(ma_log* pLog, ma_uint32 level, const char* pFormat, ...) MA_ATTRIBUTE_FORMAT(3, 4); + + +/************************************************************************************************************************************************************** + +Biquad Filtering + +**************************************************************************************************************************************************************/ +typedef union +{ + float f32; + ma_int32 s32; +} ma_biquad_coefficient; + +typedef struct +{ + ma_format format; + ma_uint32 channels; + double b0; + double b1; + double b2; + double a0; + double a1; + double a2; +} ma_biquad_config; + +MA_API ma_biquad_config ma_biquad_config_init(ma_format format, ma_uint32 channels, double b0, double b1, double b2, double a0, double a1, double a2); + +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_biquad_coefficient b0; + ma_biquad_coefficient b1; + ma_biquad_coefficient b2; + ma_biquad_coefficient a1; + ma_biquad_coefficient a2; + ma_biquad_coefficient* pR1; + ma_biquad_coefficient* pR2; + + /* Memory management. */ + void* _pHeap; + ma_bool32 _ownsHeap; +} ma_biquad; + +MA_API ma_result ma_biquad_get_heap_size(const ma_biquad_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_biquad_init_preallocated(const ma_biquad_config* pConfig, void* pHeap, ma_biquad* pBQ); +MA_API ma_result ma_biquad_init(const ma_biquad_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_biquad* pBQ); +MA_API void ma_biquad_uninit(ma_biquad* pBQ, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_biquad_reinit(const ma_biquad_config* pConfig, ma_biquad* pBQ); +MA_API ma_result ma_biquad_clear_cache(ma_biquad* pBQ); +MA_API ma_result ma_biquad_process_pcm_frames(ma_biquad* pBQ, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount); +MA_API ma_uint32 ma_biquad_get_latency(const ma_biquad* pBQ); + + +/************************************************************************************************************************************************************** + +Low-Pass Filtering + +**************************************************************************************************************************************************************/ +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + double cutoffFrequency; + double q; +} ma_lpf1_config, ma_lpf2_config; + +MA_API ma_lpf1_config ma_lpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency); +MA_API ma_lpf2_config ma_lpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q); + +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_biquad_coefficient a; + ma_biquad_coefficient* pR1; + + /* Memory management. */ + void* _pHeap; + ma_bool32 _ownsHeap; +} ma_lpf1; + +MA_API ma_result ma_lpf1_get_heap_size(const ma_lpf1_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_lpf1_init_preallocated(const ma_lpf1_config* pConfig, void* pHeap, ma_lpf1* pLPF); +MA_API ma_result ma_lpf1_init(const ma_lpf1_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf1* pLPF); +MA_API void ma_lpf1_uninit(ma_lpf1* pLPF, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_lpf1_reinit(const ma_lpf1_config* pConfig, ma_lpf1* pLPF); +MA_API ma_result ma_lpf1_clear_cache(ma_lpf1* pLPF); +MA_API ma_result ma_lpf1_process_pcm_frames(ma_lpf1* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount); +MA_API ma_uint32 ma_lpf1_get_latency(const ma_lpf1* pLPF); + +typedef struct +{ + ma_biquad bq; /* The second order low-pass filter is implemented as a biquad filter. */ +} ma_lpf2; + +MA_API ma_result ma_lpf2_get_heap_size(const ma_lpf2_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_lpf2_init_preallocated(const ma_lpf2_config* pConfig, void* pHeap, ma_lpf2* pHPF); +MA_API ma_result ma_lpf2_init(const ma_lpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf2* pLPF); +MA_API void ma_lpf2_uninit(ma_lpf2* pLPF, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_lpf2_reinit(const ma_lpf2_config* pConfig, ma_lpf2* pLPF); +MA_API ma_result ma_lpf2_clear_cache(ma_lpf2* pLPF); +MA_API ma_result ma_lpf2_process_pcm_frames(ma_lpf2* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount); +MA_API ma_uint32 ma_lpf2_get_latency(const ma_lpf2* pLPF); + + +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + double cutoffFrequency; + ma_uint32 order; /* If set to 0, will be treated as a passthrough (no filtering will be applied). */ +} ma_lpf_config; + +MA_API ma_lpf_config ma_lpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order); + +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + ma_uint32 lpf1Count; + ma_uint32 lpf2Count; + ma_lpf1* pLPF1; + ma_lpf2* pLPF2; + + /* Memory management. */ + void* _pHeap; + ma_bool32 _ownsHeap; +} ma_lpf; + +MA_API ma_result ma_lpf_get_heap_size(const ma_lpf_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_lpf_init_preallocated(const ma_lpf_config* pConfig, void* pHeap, ma_lpf* pLPF); +MA_API ma_result ma_lpf_init(const ma_lpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf* pLPF); +MA_API void ma_lpf_uninit(ma_lpf* pLPF, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_lpf_reinit(const ma_lpf_config* pConfig, ma_lpf* pLPF); +MA_API ma_result ma_lpf_clear_cache(ma_lpf* pLPF); +MA_API ma_result ma_lpf_process_pcm_frames(ma_lpf* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount); +MA_API ma_uint32 ma_lpf_get_latency(const ma_lpf* pLPF); + + +/************************************************************************************************************************************************************** + +High-Pass Filtering + +**************************************************************************************************************************************************************/ +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + double cutoffFrequency; + double q; +} ma_hpf1_config, ma_hpf2_config; + +MA_API ma_hpf1_config ma_hpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency); +MA_API ma_hpf2_config ma_hpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q); + +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_biquad_coefficient a; + ma_biquad_coefficient* pR1; + + /* Memory management. */ + void* _pHeap; + ma_bool32 _ownsHeap; +} ma_hpf1; + +MA_API ma_result ma_hpf1_get_heap_size(const ma_hpf1_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_hpf1_init_preallocated(const ma_hpf1_config* pConfig, void* pHeap, ma_hpf1* pLPF); +MA_API ma_result ma_hpf1_init(const ma_hpf1_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf1* pHPF); +MA_API void ma_hpf1_uninit(ma_hpf1* pHPF, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_hpf1_reinit(const ma_hpf1_config* pConfig, ma_hpf1* pHPF); +MA_API ma_result ma_hpf1_process_pcm_frames(ma_hpf1* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount); +MA_API ma_uint32 ma_hpf1_get_latency(const ma_hpf1* pHPF); + +typedef struct +{ + ma_biquad bq; /* The second order high-pass filter is implemented as a biquad filter. */ +} ma_hpf2; + +MA_API ma_result ma_hpf2_get_heap_size(const ma_hpf2_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_hpf2_init_preallocated(const ma_hpf2_config* pConfig, void* pHeap, ma_hpf2* pHPF); +MA_API ma_result ma_hpf2_init(const ma_hpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf2* pHPF); +MA_API void ma_hpf2_uninit(ma_hpf2* pHPF, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_hpf2_reinit(const ma_hpf2_config* pConfig, ma_hpf2* pHPF); +MA_API ma_result ma_hpf2_process_pcm_frames(ma_hpf2* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount); +MA_API ma_uint32 ma_hpf2_get_latency(const ma_hpf2* pHPF); + + +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + double cutoffFrequency; + ma_uint32 order; /* If set to 0, will be treated as a passthrough (no filtering will be applied). */ +} ma_hpf_config; + +MA_API ma_hpf_config ma_hpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order); + +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + ma_uint32 hpf1Count; + ma_uint32 hpf2Count; + ma_hpf1* pHPF1; + ma_hpf2* pHPF2; + + /* Memory management. */ + void* _pHeap; + ma_bool32 _ownsHeap; +} ma_hpf; + +MA_API ma_result ma_hpf_get_heap_size(const ma_hpf_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_hpf_init_preallocated(const ma_hpf_config* pConfig, void* pHeap, ma_hpf* pLPF); +MA_API ma_result ma_hpf_init(const ma_hpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf* pHPF); +MA_API void ma_hpf_uninit(ma_hpf* pHPF, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_hpf_reinit(const ma_hpf_config* pConfig, ma_hpf* pHPF); +MA_API ma_result ma_hpf_process_pcm_frames(ma_hpf* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount); +MA_API ma_uint32 ma_hpf_get_latency(const ma_hpf* pHPF); + + +/************************************************************************************************************************************************************** + +Band-Pass Filtering + +**************************************************************************************************************************************************************/ +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + double cutoffFrequency; + double q; +} ma_bpf2_config; + +MA_API ma_bpf2_config ma_bpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q); + +typedef struct +{ + ma_biquad bq; /* The second order band-pass filter is implemented as a biquad filter. */ +} ma_bpf2; + +MA_API ma_result ma_bpf2_get_heap_size(const ma_bpf2_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_bpf2_init_preallocated(const ma_bpf2_config* pConfig, void* pHeap, ma_bpf2* pBPF); +MA_API ma_result ma_bpf2_init(const ma_bpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf2* pBPF); +MA_API void ma_bpf2_uninit(ma_bpf2* pBPF, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_bpf2_reinit(const ma_bpf2_config* pConfig, ma_bpf2* pBPF); +MA_API ma_result ma_bpf2_process_pcm_frames(ma_bpf2* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount); +MA_API ma_uint32 ma_bpf2_get_latency(const ma_bpf2* pBPF); + + +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + double cutoffFrequency; + ma_uint32 order; /* If set to 0, will be treated as a passthrough (no filtering will be applied). */ +} ma_bpf_config; + +MA_API ma_bpf_config ma_bpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order); + +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_uint32 bpf2Count; + ma_bpf2* pBPF2; + + /* Memory management. */ + void* _pHeap; + ma_bool32 _ownsHeap; +} ma_bpf; + +MA_API ma_result ma_bpf_get_heap_size(const ma_bpf_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_bpf_init_preallocated(const ma_bpf_config* pConfig, void* pHeap, ma_bpf* pBPF); +MA_API ma_result ma_bpf_init(const ma_bpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf* pBPF); +MA_API void ma_bpf_uninit(ma_bpf* pBPF, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_bpf_reinit(const ma_bpf_config* pConfig, ma_bpf* pBPF); +MA_API ma_result ma_bpf_process_pcm_frames(ma_bpf* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount); +MA_API ma_uint32 ma_bpf_get_latency(const ma_bpf* pBPF); + + +/************************************************************************************************************************************************************** + +Notching Filter + +**************************************************************************************************************************************************************/ +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + double q; + double frequency; +} ma_notch2_config, ma_notch_config; + +MA_API ma_notch2_config ma_notch2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double q, double frequency); + +typedef struct +{ + ma_biquad bq; +} ma_notch2; + +MA_API ma_result ma_notch2_get_heap_size(const ma_notch2_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_notch2_init_preallocated(const ma_notch2_config* pConfig, void* pHeap, ma_notch2* pFilter); +MA_API ma_result ma_notch2_init(const ma_notch2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_notch2* pFilter); +MA_API void ma_notch2_uninit(ma_notch2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_notch2_reinit(const ma_notch2_config* pConfig, ma_notch2* pFilter); +MA_API ma_result ma_notch2_process_pcm_frames(ma_notch2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount); +MA_API ma_uint32 ma_notch2_get_latency(const ma_notch2* pFilter); + + +/************************************************************************************************************************************************************** + +Peaking EQ Filter + +**************************************************************************************************************************************************************/ +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + double gainDB; + double q; + double frequency; +} ma_peak2_config, ma_peak_config; + +MA_API ma_peak2_config ma_peak2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency); + +typedef struct +{ + ma_biquad bq; +} ma_peak2; + +MA_API ma_result ma_peak2_get_heap_size(const ma_peak2_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_peak2_init_preallocated(const ma_peak2_config* pConfig, void* pHeap, ma_peak2* pFilter); +MA_API ma_result ma_peak2_init(const ma_peak2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_peak2* pFilter); +MA_API void ma_peak2_uninit(ma_peak2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_peak2_reinit(const ma_peak2_config* pConfig, ma_peak2* pFilter); +MA_API ma_result ma_peak2_process_pcm_frames(ma_peak2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount); +MA_API ma_uint32 ma_peak2_get_latency(const ma_peak2* pFilter); + + +/************************************************************************************************************************************************************** + +Low Shelf Filter + +**************************************************************************************************************************************************************/ +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + double gainDB; + double shelfSlope; + double frequency; +} ma_loshelf2_config, ma_loshelf_config; + +MA_API ma_loshelf2_config ma_loshelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency); + +typedef struct +{ + ma_biquad bq; +} ma_loshelf2; + +MA_API ma_result ma_loshelf2_get_heap_size(const ma_loshelf2_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_loshelf2_init_preallocated(const ma_loshelf2_config* pConfig, void* pHeap, ma_loshelf2* pFilter); +MA_API ma_result ma_loshelf2_init(const ma_loshelf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_loshelf2* pFilter); +MA_API void ma_loshelf2_uninit(ma_loshelf2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_loshelf2_reinit(const ma_loshelf2_config* pConfig, ma_loshelf2* pFilter); +MA_API ma_result ma_loshelf2_process_pcm_frames(ma_loshelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount); +MA_API ma_uint32 ma_loshelf2_get_latency(const ma_loshelf2* pFilter); + + +/************************************************************************************************************************************************************** + +High Shelf Filter + +**************************************************************************************************************************************************************/ +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + double gainDB; + double shelfSlope; + double frequency; +} ma_hishelf2_config, ma_hishelf_config; + +MA_API ma_hishelf2_config ma_hishelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency); + +typedef struct +{ + ma_biquad bq; +} ma_hishelf2; + +MA_API ma_result ma_hishelf2_get_heap_size(const ma_hishelf2_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_hishelf2_init_preallocated(const ma_hishelf2_config* pConfig, void* pHeap, ma_hishelf2* pFilter); +MA_API ma_result ma_hishelf2_init(const ma_hishelf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hishelf2* pFilter); +MA_API void ma_hishelf2_uninit(ma_hishelf2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_hishelf2_reinit(const ma_hishelf2_config* pConfig, ma_hishelf2* pFilter); +MA_API ma_result ma_hishelf2_process_pcm_frames(ma_hishelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount); +MA_API ma_uint32 ma_hishelf2_get_latency(const ma_hishelf2* pFilter); + + + +/* +Delay +*/ +typedef struct +{ + ma_uint32 channels; + ma_uint32 sampleRate; + ma_uint32 delayInFrames; + ma_bool32 delayStart; /* Set to true to delay the start of the output; false otherwise. */ + float wet; /* 0..1. Default = 1. */ + float dry; /* 0..1. Default = 1. */ + float decay; /* 0..1. Default = 0 (no feedback). Feedback decay. Use this for echo. */ +} ma_delay_config; + +MA_API ma_delay_config ma_delay_config_init(ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 delayInFrames, float decay); + + +typedef struct +{ + ma_delay_config config; + ma_uint32 cursor; /* Feedback is written to this cursor. Always equal or in front of the read cursor. */ + ma_uint32 bufferSizeInFrames; + float* pBuffer; +} ma_delay; + +MA_API ma_result ma_delay_init(const ma_delay_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_delay* pDelay); +MA_API void ma_delay_uninit(ma_delay* pDelay, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_delay_process_pcm_frames(ma_delay* pDelay, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount); +MA_API void ma_delay_set_wet(ma_delay* pDelay, float value); +MA_API float ma_delay_get_wet(const ma_delay* pDelay); +MA_API void ma_delay_set_dry(ma_delay* pDelay, float value); +MA_API float ma_delay_get_dry(const ma_delay* pDelay); +MA_API void ma_delay_set_decay(ma_delay* pDelay, float value); +MA_API float ma_delay_get_decay(const ma_delay* pDelay); + + +/* Gainer for smooth volume changes. */ +typedef struct +{ + ma_uint32 channels; + ma_uint32 smoothTimeInFrames; +} ma_gainer_config; + +MA_API ma_gainer_config ma_gainer_config_init(ma_uint32 channels, ma_uint32 smoothTimeInFrames); + + +typedef struct +{ + ma_gainer_config config; + ma_uint32 t; + float masterVolume; + float* pOldGains; + float* pNewGains; + + /* Memory management. */ + void* _pHeap; + ma_bool32 _ownsHeap; +} ma_gainer; + +MA_API ma_result ma_gainer_get_heap_size(const ma_gainer_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_gainer_init_preallocated(const ma_gainer_config* pConfig, void* pHeap, ma_gainer* pGainer); +MA_API ma_result ma_gainer_init(const ma_gainer_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_gainer* pGainer); +MA_API void ma_gainer_uninit(ma_gainer* pGainer, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_gainer_process_pcm_frames(ma_gainer* pGainer, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount); +MA_API ma_result ma_gainer_set_gain(ma_gainer* pGainer, float newGain); +MA_API ma_result ma_gainer_set_gains(ma_gainer* pGainer, float* pNewGains); +MA_API ma_result ma_gainer_set_master_volume(ma_gainer* pGainer, float volume); +MA_API ma_result ma_gainer_get_master_volume(const ma_gainer* pGainer, float* pVolume); + + + +/* Stereo panner. */ +typedef enum +{ + ma_pan_mode_balance = 0, /* Does not blend one side with the other. Technically just a balance. Compatible with other popular audio engines and therefore the default. */ + ma_pan_mode_pan /* A true pan. The sound from one side will "move" to the other side and blend with it. */ +} ma_pan_mode; + +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_pan_mode mode; + float pan; +} ma_panner_config; + +MA_API ma_panner_config ma_panner_config_init(ma_format format, ma_uint32 channels); + + +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_pan_mode mode; + float pan; /* -1..1 where 0 is no pan, -1 is left side, +1 is right side. Defaults to 0. */ +} ma_panner; + +MA_API ma_result ma_panner_init(const ma_panner_config* pConfig, ma_panner* pPanner); +MA_API ma_result ma_panner_process_pcm_frames(ma_panner* pPanner, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount); +MA_API void ma_panner_set_mode(ma_panner* pPanner, ma_pan_mode mode); +MA_API ma_pan_mode ma_panner_get_mode(const ma_panner* pPanner); +MA_API void ma_panner_set_pan(ma_panner* pPanner, float pan); +MA_API float ma_panner_get_pan(const ma_panner* pPanner); + + + +/* Fader. */ +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; +} ma_fader_config; + +MA_API ma_fader_config ma_fader_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate); + +typedef struct +{ + ma_fader_config config; + float volumeBeg; /* If volumeBeg and volumeEnd is equal to 1, no fading happens (ma_fader_process_pcm_frames() will run as a passthrough). */ + float volumeEnd; + ma_uint64 lengthInFrames; /* The total length of the fade. */ + ma_int64 cursorInFrames; /* The current time in frames. Incremented by ma_fader_process_pcm_frames(). Signed because it'll be offset by startOffsetInFrames in set_fade_ex(). */ +} ma_fader; + +MA_API ma_result ma_fader_init(const ma_fader_config* pConfig, ma_fader* pFader); +MA_API ma_result ma_fader_process_pcm_frames(ma_fader* pFader, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount); +MA_API void ma_fader_get_data_format(const ma_fader* pFader, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate); +MA_API void ma_fader_set_fade(ma_fader* pFader, float volumeBeg, float volumeEnd, ma_uint64 lengthInFrames); +MA_API void ma_fader_set_fade_ex(ma_fader* pFader, float volumeBeg, float volumeEnd, ma_uint64 lengthInFrames, ma_int64 startOffsetInFrames); +MA_API float ma_fader_get_current_volume(const ma_fader* pFader); + + + +/* Spatializer. */ +typedef struct +{ + float x; + float y; + float z; +} ma_vec3f; + +typedef struct +{ + ma_vec3f v; + ma_spinlock lock; +} ma_atomic_vec3f; + +typedef enum +{ + ma_attenuation_model_none, /* No distance attenuation and no spatialization. */ + ma_attenuation_model_inverse, /* Equivalent to OpenAL's AL_INVERSE_DISTANCE_CLAMPED. */ + ma_attenuation_model_linear, /* Linear attenuation. Equivalent to OpenAL's AL_LINEAR_DISTANCE_CLAMPED. */ + ma_attenuation_model_exponential /* Exponential attenuation. Equivalent to OpenAL's AL_EXPONENT_DISTANCE_CLAMPED. */ +} ma_attenuation_model; + +typedef enum +{ + ma_positioning_absolute, + ma_positioning_relative +} ma_positioning; + +typedef enum +{ + ma_handedness_right, + ma_handedness_left +} ma_handedness; + + +typedef struct +{ + ma_uint32 channelsOut; + ma_channel* pChannelMapOut; + ma_handedness handedness; /* Defaults to right. Forward is -1 on the Z axis. In a left handed system, forward is +1 on the Z axis. */ + float coneInnerAngleInRadians; + float coneOuterAngleInRadians; + float coneOuterGain; + float speedOfSound; + ma_vec3f worldUp; +} ma_spatializer_listener_config; + +MA_API ma_spatializer_listener_config ma_spatializer_listener_config_init(ma_uint32 channelsOut); + + +typedef struct +{ + ma_spatializer_listener_config config; + ma_atomic_vec3f position; /* The absolute position of the listener. */ + ma_atomic_vec3f direction; /* The direction the listener is facing. The world up vector is config.worldUp. */ + ma_atomic_vec3f velocity; + ma_bool32 isEnabled; + + /* Memory management. */ + ma_bool32 _ownsHeap; + void* _pHeap; +} ma_spatializer_listener; + +MA_API ma_result ma_spatializer_listener_get_heap_size(const ma_spatializer_listener_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_spatializer_listener_init_preallocated(const ma_spatializer_listener_config* pConfig, void* pHeap, ma_spatializer_listener* pListener); +MA_API ma_result ma_spatializer_listener_init(const ma_spatializer_listener_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_spatializer_listener* pListener); +MA_API void ma_spatializer_listener_uninit(ma_spatializer_listener* pListener, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_channel* ma_spatializer_listener_get_channel_map(ma_spatializer_listener* pListener); +MA_API void ma_spatializer_listener_set_cone(ma_spatializer_listener* pListener, float innerAngleInRadians, float outerAngleInRadians, float outerGain); +MA_API void ma_spatializer_listener_get_cone(const ma_spatializer_listener* pListener, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain); +MA_API void ma_spatializer_listener_set_position(ma_spatializer_listener* pListener, float x, float y, float z); +MA_API ma_vec3f ma_spatializer_listener_get_position(const ma_spatializer_listener* pListener); +MA_API void ma_spatializer_listener_set_direction(ma_spatializer_listener* pListener, float x, float y, float z); +MA_API ma_vec3f ma_spatializer_listener_get_direction(const ma_spatializer_listener* pListener); +MA_API void ma_spatializer_listener_set_velocity(ma_spatializer_listener* pListener, float x, float y, float z); +MA_API ma_vec3f ma_spatializer_listener_get_velocity(const ma_spatializer_listener* pListener); +MA_API void ma_spatializer_listener_set_speed_of_sound(ma_spatializer_listener* pListener, float speedOfSound); +MA_API float ma_spatializer_listener_get_speed_of_sound(const ma_spatializer_listener* pListener); +MA_API void ma_spatializer_listener_set_world_up(ma_spatializer_listener* pListener, float x, float y, float z); +MA_API ma_vec3f ma_spatializer_listener_get_world_up(const ma_spatializer_listener* pListener); +MA_API void ma_spatializer_listener_set_enabled(ma_spatializer_listener* pListener, ma_bool32 isEnabled); +MA_API ma_bool32 ma_spatializer_listener_is_enabled(const ma_spatializer_listener* pListener); + + +typedef struct +{ + ma_uint32 channelsIn; + ma_uint32 channelsOut; + ma_channel* pChannelMapIn; + ma_attenuation_model attenuationModel; + ma_positioning positioning; + ma_handedness handedness; /* Defaults to right. Forward is -1 on the Z axis. In a left handed system, forward is +1 on the Z axis. */ + float minGain; + float maxGain; + float minDistance; + float maxDistance; + float rolloff; + float coneInnerAngleInRadians; + float coneOuterAngleInRadians; + float coneOuterGain; + float dopplerFactor; /* Set to 0 to disable doppler effect. */ + float directionalAttenuationFactor; /* Set to 0 to disable directional attenuation. */ + float minSpatializationChannelGain; /* The minimal scaling factor to apply to channel gains when accounting for the direction of the sound relative to the listener. Must be in the range of 0..1. Smaller values means more aggressive directional panning, larger values means more subtle directional panning. */ + ma_uint32 gainSmoothTimeInFrames; /* When the gain of a channel changes during spatialization, the transition will be linearly interpolated over this number of frames. */ +} ma_spatializer_config; + +MA_API ma_spatializer_config ma_spatializer_config_init(ma_uint32 channelsIn, ma_uint32 channelsOut); + + +typedef struct +{ + ma_uint32 channelsIn; + ma_uint32 channelsOut; + ma_channel* pChannelMapIn; + ma_attenuation_model attenuationModel; + ma_positioning positioning; + ma_handedness handedness; /* Defaults to right. Forward is -1 on the Z axis. In a left handed system, forward is +1 on the Z axis. */ + float minGain; + float maxGain; + float minDistance; + float maxDistance; + float rolloff; + float coneInnerAngleInRadians; + float coneOuterAngleInRadians; + float coneOuterGain; + float dopplerFactor; /* Set to 0 to disable doppler effect. */ + float directionalAttenuationFactor; /* Set to 0 to disable directional attenuation. */ + ma_uint32 gainSmoothTimeInFrames; /* When the gain of a channel changes during spatialization, the transition will be linearly interpolated over this number of frames. */ + ma_atomic_vec3f position; + ma_atomic_vec3f direction; + ma_atomic_vec3f velocity; /* For doppler effect. */ + float dopplerPitch; /* Will be updated by ma_spatializer_process_pcm_frames() and can be used by higher level functions to apply a pitch shift for doppler effect. */ + float minSpatializationChannelGain; + ma_gainer gainer; /* For smooth gain transitions. */ + float* pNewChannelGainsOut; /* An offset of _pHeap. Used by ma_spatializer_process_pcm_frames() to store new channel gains. The number of elements in this array is equal to config.channelsOut. */ + + /* Memory management. */ + void* _pHeap; + ma_bool32 _ownsHeap; +} ma_spatializer; + +MA_API ma_result ma_spatializer_get_heap_size(const ma_spatializer_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_spatializer_init_preallocated(const ma_spatializer_config* pConfig, void* pHeap, ma_spatializer* pSpatializer); +MA_API ma_result ma_spatializer_init(const ma_spatializer_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_spatializer* pSpatializer); +MA_API void ma_spatializer_uninit(ma_spatializer* pSpatializer, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_spatializer_process_pcm_frames(ma_spatializer* pSpatializer, ma_spatializer_listener* pListener, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount); +MA_API ma_result ma_spatializer_set_master_volume(ma_spatializer* pSpatializer, float volume); +MA_API ma_result ma_spatializer_get_master_volume(const ma_spatializer* pSpatializer, float* pVolume); +MA_API ma_uint32 ma_spatializer_get_input_channels(const ma_spatializer* pSpatializer); +MA_API ma_uint32 ma_spatializer_get_output_channels(const ma_spatializer* pSpatializer); +MA_API void ma_spatializer_set_attenuation_model(ma_spatializer* pSpatializer, ma_attenuation_model attenuationModel); +MA_API ma_attenuation_model ma_spatializer_get_attenuation_model(const ma_spatializer* pSpatializer); +MA_API void ma_spatializer_set_positioning(ma_spatializer* pSpatializer, ma_positioning positioning); +MA_API ma_positioning ma_spatializer_get_positioning(const ma_spatializer* pSpatializer); +MA_API void ma_spatializer_set_rolloff(ma_spatializer* pSpatializer, float rolloff); +MA_API float ma_spatializer_get_rolloff(const ma_spatializer* pSpatializer); +MA_API void ma_spatializer_set_min_gain(ma_spatializer* pSpatializer, float minGain); +MA_API float ma_spatializer_get_min_gain(const ma_spatializer* pSpatializer); +MA_API void ma_spatializer_set_max_gain(ma_spatializer* pSpatializer, float maxGain); +MA_API float ma_spatializer_get_max_gain(const ma_spatializer* pSpatializer); +MA_API void ma_spatializer_set_min_distance(ma_spatializer* pSpatializer, float minDistance); +MA_API float ma_spatializer_get_min_distance(const ma_spatializer* pSpatializer); +MA_API void ma_spatializer_set_max_distance(ma_spatializer* pSpatializer, float maxDistance); +MA_API float ma_spatializer_get_max_distance(const ma_spatializer* pSpatializer); +MA_API void ma_spatializer_set_cone(ma_spatializer* pSpatializer, float innerAngleInRadians, float outerAngleInRadians, float outerGain); +MA_API void ma_spatializer_get_cone(const ma_spatializer* pSpatializer, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain); +MA_API void ma_spatializer_set_doppler_factor(ma_spatializer* pSpatializer, float dopplerFactor); +MA_API float ma_spatializer_get_doppler_factor(const ma_spatializer* pSpatializer); +MA_API void ma_spatializer_set_directional_attenuation_factor(ma_spatializer* pSpatializer, float directionalAttenuationFactor); +MA_API float ma_spatializer_get_directional_attenuation_factor(const ma_spatializer* pSpatializer); +MA_API void ma_spatializer_set_position(ma_spatializer* pSpatializer, float x, float y, float z); +MA_API ma_vec3f ma_spatializer_get_position(const ma_spatializer* pSpatializer); +MA_API void ma_spatializer_set_direction(ma_spatializer* pSpatializer, float x, float y, float z); +MA_API ma_vec3f ma_spatializer_get_direction(const ma_spatializer* pSpatializer); +MA_API void ma_spatializer_set_velocity(ma_spatializer* pSpatializer, float x, float y, float z); +MA_API ma_vec3f ma_spatializer_get_velocity(const ma_spatializer* pSpatializer); +MA_API void ma_spatializer_get_relative_position_and_direction(const ma_spatializer* pSpatializer, const ma_spatializer_listener* pListener, ma_vec3f* pRelativePos, ma_vec3f* pRelativeDir); + + + +/************************************************************************************************************************************************************ +************************************************************************************************************************************************************* + +DATA CONVERSION +=============== + +This section contains the APIs for data conversion. You will find everything here for channel mapping, sample format conversion, resampling, etc. + +************************************************************************************************************************************************************* +************************************************************************************************************************************************************/ + +/************************************************************************************************************************************************************** + +Resampling + +**************************************************************************************************************************************************************/ +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRateIn; + ma_uint32 sampleRateOut; + ma_uint32 lpfOrder; /* The low-pass filter order. Setting this to 0 will disable low-pass filtering. */ + double lpfNyquistFactor; /* 0..1. Defaults to 1. 1 = Half the sampling frequency (Nyquist Frequency), 0.5 = Quarter the sampling frequency (half Nyquest Frequency), etc. */ +} ma_linear_resampler_config; + +MA_API ma_linear_resampler_config ma_linear_resampler_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut); + +typedef struct +{ + ma_linear_resampler_config config; + ma_uint32 inAdvanceInt; + ma_uint32 inAdvanceFrac; + ma_uint32 inTimeInt; + ma_uint32 inTimeFrac; + union + { + float* f32; + ma_int16* s16; + } x0; /* The previous input frame. */ + union + { + float* f32; + ma_int16* s16; + } x1; /* The next input frame. */ + ma_lpf lpf; + + /* Memory management. */ + void* _pHeap; + ma_bool32 _ownsHeap; +} ma_linear_resampler; + +MA_API ma_result ma_linear_resampler_get_heap_size(const ma_linear_resampler_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_linear_resampler_init_preallocated(const ma_linear_resampler_config* pConfig, void* pHeap, ma_linear_resampler* pResampler); +MA_API ma_result ma_linear_resampler_init(const ma_linear_resampler_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_linear_resampler* pResampler); +MA_API void ma_linear_resampler_uninit(ma_linear_resampler* pResampler, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_linear_resampler_process_pcm_frames(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut); +MA_API ma_result ma_linear_resampler_set_rate(ma_linear_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut); +MA_API ma_result ma_linear_resampler_set_rate_ratio(ma_linear_resampler* pResampler, float ratioInOut); +MA_API ma_uint64 ma_linear_resampler_get_input_latency(const ma_linear_resampler* pResampler); +MA_API ma_uint64 ma_linear_resampler_get_output_latency(const ma_linear_resampler* pResampler); +MA_API ma_result ma_linear_resampler_get_required_input_frame_count(const ma_linear_resampler* pResampler, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount); +MA_API ma_result ma_linear_resampler_get_expected_output_frame_count(const ma_linear_resampler* pResampler, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount); +MA_API ma_result ma_linear_resampler_reset(ma_linear_resampler* pResampler); + + +typedef struct ma_resampler_config ma_resampler_config; + +typedef void ma_resampling_backend; +typedef struct +{ + ma_result (* onGetHeapSize )(void* pUserData, const ma_resampler_config* pConfig, size_t* pHeapSizeInBytes); + ma_result (* onInit )(void* pUserData, const ma_resampler_config* pConfig, void* pHeap, ma_resampling_backend** ppBackend); + void (* onUninit )(void* pUserData, ma_resampling_backend* pBackend, const ma_allocation_callbacks* pAllocationCallbacks); + ma_result (* onProcess )(void* pUserData, ma_resampling_backend* pBackend, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut); + ma_result (* onSetRate )(void* pUserData, ma_resampling_backend* pBackend, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut); /* Optional. Rate changes will be disabled. */ + ma_uint64 (* onGetInputLatency )(void* pUserData, const ma_resampling_backend* pBackend); /* Optional. Latency will be reported as 0. */ + ma_uint64 (* onGetOutputLatency )(void* pUserData, const ma_resampling_backend* pBackend); /* Optional. Latency will be reported as 0. */ + ma_result (* onGetRequiredInputFrameCount )(void* pUserData, const ma_resampling_backend* pBackend, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount); /* Optional. Latency mitigation will be disabled. */ + ma_result (* onGetExpectedOutputFrameCount)(void* pUserData, const ma_resampling_backend* pBackend, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount); /* Optional. Latency mitigation will be disabled. */ + ma_result (* onReset )(void* pUserData, ma_resampling_backend* pBackend); +} ma_resampling_backend_vtable; + +typedef enum +{ + ma_resample_algorithm_linear = 0, /* Fastest, lowest quality. Optional low-pass filtering. Default. */ + ma_resample_algorithm_custom, +} ma_resample_algorithm; + +struct ma_resampler_config +{ + ma_format format; /* Must be either ma_format_f32 or ma_format_s16. */ + ma_uint32 channels; + ma_uint32 sampleRateIn; + ma_uint32 sampleRateOut; + ma_resample_algorithm algorithm; /* When set to ma_resample_algorithm_custom, pBackendVTable will be used. */ + ma_resampling_backend_vtable* pBackendVTable; + void* pBackendUserData; + struct + { + ma_uint32 lpfOrder; + } linear; +}; + +MA_API ma_resampler_config ma_resampler_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut, ma_resample_algorithm algorithm); + +typedef struct +{ + ma_resampling_backend* pBackend; + ma_resampling_backend_vtable* pBackendVTable; + void* pBackendUserData; + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRateIn; + ma_uint32 sampleRateOut; + union + { + ma_linear_resampler linear; + } state; /* State for stock resamplers so we can avoid a malloc. For stock resamplers, pBackend will point here. */ + + /* Memory management. */ + void* _pHeap; + ma_bool32 _ownsHeap; +} ma_resampler; + +MA_API ma_result ma_resampler_get_heap_size(const ma_resampler_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_resampler_init_preallocated(const ma_resampler_config* pConfig, void* pHeap, ma_resampler* pResampler); + +/* +Initializes a new resampler object from a config. +*/ +MA_API ma_result ma_resampler_init(const ma_resampler_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_resampler* pResampler); + +/* +Uninitializes a resampler. +*/ +MA_API void ma_resampler_uninit(ma_resampler* pResampler, const ma_allocation_callbacks* pAllocationCallbacks); + +/* +Converts the given input data. + +Both the input and output frames must be in the format specified in the config when the resampler was initialized. + +On input, [pFrameCountOut] contains the number of output frames to process. On output it contains the number of output frames that +were actually processed, which may be less than the requested amount which will happen if there's not enough input data. You can use +ma_resampler_get_expected_output_frame_count() to know how many output frames will be processed for a given number of input frames. + +On input, [pFrameCountIn] contains the number of input frames contained in [pFramesIn]. On output it contains the number of whole +input frames that were actually processed. You can use ma_resampler_get_required_input_frame_count() to know how many input frames +you should provide for a given number of output frames. [pFramesIn] can be NULL, in which case zeroes will be used instead. + +If [pFramesOut] is NULL, a seek is performed. In this case, if [pFrameCountOut] is not NULL it will seek by the specified number of +output frames. Otherwise, if [pFramesCountOut] is NULL and [pFrameCountIn] is not NULL, it will seek by the specified number of input +frames. When seeking, [pFramesIn] is allowed to NULL, in which case the internal timing state will be updated, but no input will be +processed. In this case, any internal filter state will be updated as if zeroes were passed in. + +It is an error for [pFramesOut] to be non-NULL and [pFrameCountOut] to be NULL. + +It is an error for both [pFrameCountOut] and [pFrameCountIn] to be NULL. +*/ +MA_API ma_result ma_resampler_process_pcm_frames(ma_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut); + + +/* +Sets the input and output sample rate. +*/ +MA_API ma_result ma_resampler_set_rate(ma_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut); + +/* +Sets the input and output sample rate as a ratio. + +The ration is in/out. +*/ +MA_API ma_result ma_resampler_set_rate_ratio(ma_resampler* pResampler, float ratio); + +/* +Retrieves the latency introduced by the resampler in input frames. +*/ +MA_API ma_uint64 ma_resampler_get_input_latency(const ma_resampler* pResampler); + +/* +Retrieves the latency introduced by the resampler in output frames. +*/ +MA_API ma_uint64 ma_resampler_get_output_latency(const ma_resampler* pResampler); + +/* +Calculates the number of whole input frames that would need to be read from the client in order to output the specified +number of output frames. + +The returned value does not include cached input frames. It only returns the number of extra frames that would need to be +read from the input buffer in order to output the specified number of output frames. +*/ +MA_API ma_result ma_resampler_get_required_input_frame_count(const ma_resampler* pResampler, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount); + +/* +Calculates the number of whole output frames that would be output after fully reading and consuming the specified number of +input frames. +*/ +MA_API ma_result ma_resampler_get_expected_output_frame_count(const ma_resampler* pResampler, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount); + +/* +Resets the resampler's timer and clears it's internal cache. +*/ +MA_API ma_result ma_resampler_reset(ma_resampler* pResampler); + + +/************************************************************************************************************************************************************** + +Channel Conversion + +**************************************************************************************************************************************************************/ +typedef enum +{ + ma_channel_conversion_path_unknown, + ma_channel_conversion_path_passthrough, + ma_channel_conversion_path_mono_out, /* Converting to mono. */ + ma_channel_conversion_path_mono_in, /* Converting from mono. */ + ma_channel_conversion_path_shuffle, /* Simple shuffle. Will use this when all channels are present in both input and output channel maps, but just in a different order. */ + ma_channel_conversion_path_weights /* Blended based on weights. */ +} ma_channel_conversion_path; + +typedef enum +{ + ma_mono_expansion_mode_duplicate = 0, /* The default. */ + ma_mono_expansion_mode_average, /* Average the mono channel across all channels. */ + ma_mono_expansion_mode_stereo_only, /* Duplicate to the left and right channels only and ignore the others. */ + ma_mono_expansion_mode_default = ma_mono_expansion_mode_duplicate +} ma_mono_expansion_mode; + +typedef struct +{ + ma_format format; + ma_uint32 channelsIn; + ma_uint32 channelsOut; + const ma_channel* pChannelMapIn; + const ma_channel* pChannelMapOut; + ma_channel_mix_mode mixingMode; + ma_bool32 calculateLFEFromSpatialChannels; /* When an output LFE channel is present, but no input LFE, set to true to set the output LFE to the average of all spatial channels (LR, FR, etc.). Ignored when an input LFE is present. */ + float** ppWeights; /* [in][out]. Only used when mixingMode is set to ma_channel_mix_mode_custom_weights. */ +} ma_channel_converter_config; + +MA_API ma_channel_converter_config ma_channel_converter_config_init(ma_format format, ma_uint32 channelsIn, const ma_channel* pChannelMapIn, ma_uint32 channelsOut, const ma_channel* pChannelMapOut, ma_channel_mix_mode mixingMode); + +typedef struct +{ + ma_format format; + ma_uint32 channelsIn; + ma_uint32 channelsOut; + ma_channel_mix_mode mixingMode; + ma_channel_conversion_path conversionPath; + ma_channel* pChannelMapIn; + ma_channel* pChannelMapOut; + ma_uint8* pShuffleTable; /* Indexed by output channel index. */ + union + { + float** f32; + ma_int32** s16; + } weights; /* [in][out] */ + + /* Memory management. */ + void* _pHeap; + ma_bool32 _ownsHeap; +} ma_channel_converter; + +MA_API ma_result ma_channel_converter_get_heap_size(const ma_channel_converter_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_channel_converter_init_preallocated(const ma_channel_converter_config* pConfig, void* pHeap, ma_channel_converter* pConverter); +MA_API ma_result ma_channel_converter_init(const ma_channel_converter_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_channel_converter* pConverter); +MA_API void ma_channel_converter_uninit(ma_channel_converter* pConverter, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_channel_converter_process_pcm_frames(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount); +MA_API ma_result ma_channel_converter_get_input_channel_map(const ma_channel_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap); +MA_API ma_result ma_channel_converter_get_output_channel_map(const ma_channel_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap); + + +/************************************************************************************************************************************************************** + +Data Conversion + +**************************************************************************************************************************************************************/ +typedef struct +{ + ma_format formatIn; + ma_format formatOut; + ma_uint32 channelsIn; + ma_uint32 channelsOut; + ma_uint32 sampleRateIn; + ma_uint32 sampleRateOut; + ma_channel* pChannelMapIn; + ma_channel* pChannelMapOut; + ma_dither_mode ditherMode; + ma_channel_mix_mode channelMixMode; + ma_bool32 calculateLFEFromSpatialChannels; /* When an output LFE channel is present, but no input LFE, set to true to set the output LFE to the average of all spatial channels (LR, FR, etc.). Ignored when an input LFE is present. */ + float** ppChannelWeights; /* [in][out]. Only used when mixingMode is set to ma_channel_mix_mode_custom_weights. */ + ma_bool32 allowDynamicSampleRate; + ma_resampler_config resampling; +} ma_data_converter_config; + +MA_API ma_data_converter_config ma_data_converter_config_init_default(void); +MA_API ma_data_converter_config ma_data_converter_config_init(ma_format formatIn, ma_format formatOut, ma_uint32 channelsIn, ma_uint32 channelsOut, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut); + + +typedef enum +{ + ma_data_converter_execution_path_passthrough, /* No conversion. */ + ma_data_converter_execution_path_format_only, /* Only format conversion. */ + ma_data_converter_execution_path_channels_only, /* Only channel conversion. */ + ma_data_converter_execution_path_resample_only, /* Only resampling. */ + ma_data_converter_execution_path_resample_first, /* All conversions, but resample as the first step. */ + ma_data_converter_execution_path_channels_first /* All conversions, but channels as the first step. */ +} ma_data_converter_execution_path; + +typedef struct +{ + ma_format formatIn; + ma_format formatOut; + ma_uint32 channelsIn; + ma_uint32 channelsOut; + ma_uint32 sampleRateIn; + ma_uint32 sampleRateOut; + ma_dither_mode ditherMode; + ma_data_converter_execution_path executionPath; /* The execution path the data converter will follow when processing. */ + ma_channel_converter channelConverter; + ma_resampler resampler; + ma_bool8 hasPreFormatConversion; + ma_bool8 hasPostFormatConversion; + ma_bool8 hasChannelConverter; + ma_bool8 hasResampler; + ma_bool8 isPassthrough; + + /* Memory management. */ + ma_bool8 _ownsHeap; + void* _pHeap; +} ma_data_converter; + +MA_API ma_result ma_data_converter_get_heap_size(const ma_data_converter_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_data_converter_init_preallocated(const ma_data_converter_config* pConfig, void* pHeap, ma_data_converter* pConverter); +MA_API ma_result ma_data_converter_init(const ma_data_converter_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_converter* pConverter); +MA_API void ma_data_converter_uninit(ma_data_converter* pConverter, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_data_converter_process_pcm_frames(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut); +MA_API ma_result ma_data_converter_set_rate(ma_data_converter* pConverter, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut); +MA_API ma_result ma_data_converter_set_rate_ratio(ma_data_converter* pConverter, float ratioInOut); +MA_API ma_uint64 ma_data_converter_get_input_latency(const ma_data_converter* pConverter); +MA_API ma_uint64 ma_data_converter_get_output_latency(const ma_data_converter* pConverter); +MA_API ma_result ma_data_converter_get_required_input_frame_count(const ma_data_converter* pConverter, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount); +MA_API ma_result ma_data_converter_get_expected_output_frame_count(const ma_data_converter* pConverter, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount); +MA_API ma_result ma_data_converter_get_input_channel_map(const ma_data_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap); +MA_API ma_result ma_data_converter_get_output_channel_map(const ma_data_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap); +MA_API ma_result ma_data_converter_reset(ma_data_converter* pConverter); + + +/************************************************************************************************************************************************************ + +Format Conversion + +************************************************************************************************************************************************************/ +MA_API void ma_pcm_u8_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +MA_API void ma_pcm_u8_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +MA_API void ma_pcm_u8_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +MA_API void ma_pcm_u8_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +MA_API void ma_pcm_s16_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +MA_API void ma_pcm_s16_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +MA_API void ma_pcm_s16_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +MA_API void ma_pcm_s16_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +MA_API void ma_pcm_s24_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +MA_API void ma_pcm_s24_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +MA_API void ma_pcm_s24_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +MA_API void ma_pcm_s24_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +MA_API void ma_pcm_s32_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +MA_API void ma_pcm_s32_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +MA_API void ma_pcm_s32_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +MA_API void ma_pcm_s32_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +MA_API void ma_pcm_f32_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +MA_API void ma_pcm_f32_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +MA_API void ma_pcm_f32_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +MA_API void ma_pcm_f32_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +MA_API void ma_pcm_convert(void* pOut, ma_format formatOut, const void* pIn, ma_format formatIn, ma_uint64 sampleCount, ma_dither_mode ditherMode); +MA_API void ma_convert_pcm_frames_format(void* pOut, ma_format formatOut, const void* pIn, ma_format formatIn, ma_uint64 frameCount, ma_uint32 channels, ma_dither_mode ditherMode); + +/* +Deinterleaves an interleaved buffer. +*/ +MA_API 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. +*/ +MA_API void ma_interleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void** ppDeinterleavedPCMFrames, void* pInterleavedPCMFrames); + + +/************************************************************************************************************************************************************ + +Channel Maps + +************************************************************************************************************************************************************/ +/* +This is used in the shuffle table to indicate that the channel index is undefined and should be ignored. +*/ +#define MA_CHANNEL_INDEX_NULL 255 + +/* +Retrieves the channel position of the specified channel in the given channel map. + +The pChannelMap parameter can be null, in which case miniaudio's default channel map will be assumed. +*/ +MA_API ma_channel ma_channel_map_get_channel(const ma_channel* pChannelMap, ma_uint32 channelCount, ma_uint32 channelIndex); + +/* +Initializes a blank channel map. + +When a blank channel map is specified anywhere it indicates that the native channel map should be used. +*/ +MA_API void ma_channel_map_init_blank(ma_channel* pChannelMap, ma_uint32 channels); + +/* +Helper for retrieving a standard channel map. + +The output channel map buffer must have a capacity of at least `channelMapCap`. +*/ +MA_API void ma_channel_map_init_standard(ma_standard_channel_map standardChannelMap, ma_channel* pChannelMap, size_t channelMapCap, ma_uint32 channels); + +/* +Copies a channel map. + +Both input and output channel map buffers must have a capacity of at at least `channels`. +*/ +MA_API void ma_channel_map_copy(ma_channel* pOut, const ma_channel* pIn, ma_uint32 channels); + +/* +Copies a channel map if one is specified, otherwise copies the default channel map. + +The output buffer must have a capacity of at least `channels`. If not NULL, the input channel map must also have a capacity of at least `channels`. +*/ +MA_API void ma_channel_map_copy_or_default(ma_channel* pOut, size_t channelMapCapOut, 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 + +The channel map buffer must have a capacity of at least `channels`. +*/ +MA_API ma_bool32 ma_channel_map_is_valid(const ma_channel* pChannelMap, ma_uint32 channels); + +/* +Helper for comparing two channel maps for equality. + +This assumes the channel count is the same between the two. + +Both channels map buffers must have a capacity of at least `channels`. +*/ +MA_API ma_bool32 ma_channel_map_is_equal(const ma_channel* pChannelMapA, const ma_channel* pChannelMapB, ma_uint32 channels); + +/* +Helper for determining if a channel map is blank (all channels set to MA_CHANNEL_NONE). + +The channel map buffer must have a capacity of at least `channels`. +*/ +MA_API ma_bool32 ma_channel_map_is_blank(const ma_channel* pChannelMap, ma_uint32 channels); + +/* +Helper for determining whether or not a channel is present in the given channel map. + +The channel map buffer must have a capacity of at least `channels`. +*/ +MA_API ma_bool32 ma_channel_map_contains_channel_position(ma_uint32 channels, const ma_channel* pChannelMap, ma_channel channelPosition); + +/* +Find a channel position in the given channel map. Returns MA_TRUE if the channel is found; MA_FALSE otherwise. The +index of the channel is output to `pChannelIndex`. + +The channel map buffer must have a capacity of at least `channels`. +*/ +MA_API ma_bool32 ma_channel_map_find_channel_position(ma_uint32 channels, const ma_channel* pChannelMap, ma_channel channelPosition, ma_uint32* pChannelIndex); + +/* +Generates a string representing the given channel map. + +This is for printing and debugging purposes, not serialization/deserialization. + +Returns the length of the string, not including the null terminator. +*/ +MA_API size_t ma_channel_map_to_string(const ma_channel* pChannelMap, ma_uint32 channels, char* pBufferOut, size_t bufferCap); + +/* +Retrieves a human readable version of a channel position. +*/ +MA_API const char* ma_channel_position_to_string(ma_channel channel); + + +/************************************************************************************************************************************************************ + +Conversion Helpers + +************************************************************************************************************************************************************/ + +/* +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. frameCountOut should be set to the capacity of pOut. If pOut is NULL, frameCountOut is +ignored. + +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 ma_data_converter APIs instead. +*/ +MA_API ma_uint64 ma_convert_frames(void* pOut, ma_uint64 frameCountOut, ma_format formatOut, ma_uint32 channelsOut, ma_uint32 sampleRateOut, const void* pIn, ma_uint64 frameCountIn, ma_format formatIn, ma_uint32 channelsIn, ma_uint32 sampleRateIn); +MA_API ma_uint64 ma_convert_frames_ex(void* pOut, ma_uint64 frameCountOut, const void* pIn, ma_uint64 frameCountIn, const ma_data_converter_config* pConfig); + + +/************************************************************************************************************************************************************ + +Data Source + +************************************************************************************************************************************************************/ +typedef void ma_data_source; + +#define MA_DATA_SOURCE_SELF_MANAGED_RANGE_AND_LOOP_POINT 0x00000001 + +typedef struct +{ + ma_result (* onRead)(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead); + ma_result (* onSeek)(ma_data_source* pDataSource, ma_uint64 frameIndex); + ma_result (* onGetDataFormat)(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap); + ma_result (* onGetCursor)(ma_data_source* pDataSource, ma_uint64* pCursor); + ma_result (* onGetLength)(ma_data_source* pDataSource, ma_uint64* pLength); + ma_result (* onSetLooping)(ma_data_source* pDataSource, ma_bool32 isLooping); + ma_uint32 flags; +} ma_data_source_vtable; + +typedef ma_data_source* (* ma_data_source_get_next_proc)(ma_data_source* pDataSource); + +typedef struct +{ + const ma_data_source_vtable* vtable; +} ma_data_source_config; + +MA_API ma_data_source_config ma_data_source_config_init(void); + + +typedef struct +{ + const ma_data_source_vtable* vtable; + ma_uint64 rangeBegInFrames; + ma_uint64 rangeEndInFrames; /* Set to -1 for unranged (default). */ + ma_uint64 loopBegInFrames; /* Relative to rangeBegInFrames. */ + ma_uint64 loopEndInFrames; /* Relative to rangeBegInFrames. Set to -1 for the end of the range. */ + ma_data_source* pCurrent; /* When non-NULL, the data source being initialized will act as a proxy and will route all operations to pCurrent. Used in conjunction with pNext/onGetNext for seamless chaining. */ + ma_data_source* pNext; /* When set to NULL, onGetNext will be used. */ + ma_data_source_get_next_proc onGetNext; /* Will be used when pNext is NULL. If both are NULL, no next will be used. */ + MA_ATOMIC(4, ma_bool32) isLooping; +} ma_data_source_base; + +MA_API ma_result ma_data_source_init(const ma_data_source_config* pConfig, ma_data_source* pDataSource); +MA_API void ma_data_source_uninit(ma_data_source* pDataSource); +MA_API ma_result ma_data_source_read_pcm_frames(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead); /* Must support pFramesOut = NULL in which case a forward seek should be performed. */ +MA_API ma_result ma_data_source_seek_pcm_frames(ma_data_source* pDataSource, ma_uint64 frameCount, ma_uint64* pFramesSeeked); /* Can only seek forward. Equivalent to ma_data_source_read_pcm_frames(pDataSource, NULL, frameCount, &framesRead); */ +MA_API ma_result ma_data_source_seek_to_pcm_frame(ma_data_source* pDataSource, ma_uint64 frameIndex); +MA_API ma_result ma_data_source_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap); +MA_API ma_result ma_data_source_get_cursor_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pCursor); +MA_API ma_result ma_data_source_get_length_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pLength); /* Returns MA_NOT_IMPLEMENTED if the length is unknown or cannot be determined. Decoders can return this. */ +MA_API ma_result ma_data_source_get_cursor_in_seconds(ma_data_source* pDataSource, float* pCursor); +MA_API ma_result ma_data_source_get_length_in_seconds(ma_data_source* pDataSource, float* pLength); +MA_API ma_result ma_data_source_set_looping(ma_data_source* pDataSource, ma_bool32 isLooping); +MA_API ma_bool32 ma_data_source_is_looping(const ma_data_source* pDataSource); +MA_API ma_result ma_data_source_set_range_in_pcm_frames(ma_data_source* pDataSource, ma_uint64 rangeBegInFrames, ma_uint64 rangeEndInFrames); +MA_API void ma_data_source_get_range_in_pcm_frames(const ma_data_source* pDataSource, ma_uint64* pRangeBegInFrames, ma_uint64* pRangeEndInFrames); +MA_API ma_result ma_data_source_set_loop_point_in_pcm_frames(ma_data_source* pDataSource, ma_uint64 loopBegInFrames, ma_uint64 loopEndInFrames); +MA_API void ma_data_source_get_loop_point_in_pcm_frames(const ma_data_source* pDataSource, ma_uint64* pLoopBegInFrames, ma_uint64* pLoopEndInFrames); +MA_API ma_result ma_data_source_set_current(ma_data_source* pDataSource, ma_data_source* pCurrentDataSource); +MA_API ma_data_source* ma_data_source_get_current(const ma_data_source* pDataSource); +MA_API ma_result ma_data_source_set_next(ma_data_source* pDataSource, ma_data_source* pNextDataSource); +MA_API ma_data_source* ma_data_source_get_next(const ma_data_source* pDataSource); +MA_API ma_result ma_data_source_set_next_callback(ma_data_source* pDataSource, ma_data_source_get_next_proc onGetNext); +MA_API ma_data_source_get_next_proc ma_data_source_get_next_callback(const ma_data_source* pDataSource); + + +typedef struct +{ + ma_data_source_base ds; + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + ma_uint64 cursor; + ma_uint64 sizeInFrames; + const void* pData; +} ma_audio_buffer_ref; + +MA_API ma_result ma_audio_buffer_ref_init(ma_format format, ma_uint32 channels, const void* pData, ma_uint64 sizeInFrames, ma_audio_buffer_ref* pAudioBufferRef); +MA_API void ma_audio_buffer_ref_uninit(ma_audio_buffer_ref* pAudioBufferRef); +MA_API ma_result ma_audio_buffer_ref_set_data(ma_audio_buffer_ref* pAudioBufferRef, const void* pData, ma_uint64 sizeInFrames); +MA_API ma_uint64 ma_audio_buffer_ref_read_pcm_frames(ma_audio_buffer_ref* pAudioBufferRef, void* pFramesOut, ma_uint64 frameCount, ma_bool32 loop); +MA_API ma_result ma_audio_buffer_ref_seek_to_pcm_frame(ma_audio_buffer_ref* pAudioBufferRef, ma_uint64 frameIndex); +MA_API ma_result ma_audio_buffer_ref_map(ma_audio_buffer_ref* pAudioBufferRef, void** ppFramesOut, ma_uint64* pFrameCount); +MA_API ma_result ma_audio_buffer_ref_unmap(ma_audio_buffer_ref* pAudioBufferRef, ma_uint64 frameCount); /* Returns MA_AT_END if the end has been reached. This should be considered successful. */ +MA_API ma_bool32 ma_audio_buffer_ref_at_end(const ma_audio_buffer_ref* pAudioBufferRef); +MA_API ma_result ma_audio_buffer_ref_get_cursor_in_pcm_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pCursor); +MA_API ma_result ma_audio_buffer_ref_get_length_in_pcm_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pLength); +MA_API ma_result ma_audio_buffer_ref_get_available_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pAvailableFrames); + + + +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + ma_uint64 sizeInFrames; + const void* pData; /* If set to NULL, will allocate a block of memory for you. */ + ma_allocation_callbacks allocationCallbacks; +} ma_audio_buffer_config; + +MA_API ma_audio_buffer_config ma_audio_buffer_config_init(ma_format format, ma_uint32 channels, ma_uint64 sizeInFrames, const void* pData, const ma_allocation_callbacks* pAllocationCallbacks); + +typedef struct +{ + ma_audio_buffer_ref ref; + ma_allocation_callbacks allocationCallbacks; + ma_bool32 ownsData; /* Used to control whether or not miniaudio owns the data buffer. If set to true, pData will be freed in ma_audio_buffer_uninit(). */ + ma_uint8 _pExtraData[1]; /* For allocating a buffer with the memory located directly after the other memory of the structure. */ +} ma_audio_buffer; + +MA_API ma_result ma_audio_buffer_init(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer); +MA_API ma_result ma_audio_buffer_init_copy(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer); +MA_API ma_result ma_audio_buffer_alloc_and_init(const ma_audio_buffer_config* pConfig, ma_audio_buffer** ppAudioBuffer); /* Always copies the data. Doesn't make sense to use this otherwise. Use ma_audio_buffer_uninit_and_free() to uninit. */ +MA_API void ma_audio_buffer_uninit(ma_audio_buffer* pAudioBuffer); +MA_API void ma_audio_buffer_uninit_and_free(ma_audio_buffer* pAudioBuffer); +MA_API ma_uint64 ma_audio_buffer_read_pcm_frames(ma_audio_buffer* pAudioBuffer, void* pFramesOut, ma_uint64 frameCount, ma_bool32 loop); +MA_API ma_result ma_audio_buffer_seek_to_pcm_frame(ma_audio_buffer* pAudioBuffer, ma_uint64 frameIndex); +MA_API ma_result ma_audio_buffer_map(ma_audio_buffer* pAudioBuffer, void** ppFramesOut, ma_uint64* pFrameCount); +MA_API ma_result ma_audio_buffer_unmap(ma_audio_buffer* pAudioBuffer, ma_uint64 frameCount); /* Returns MA_AT_END if the end has been reached. This should be considered successful. */ +MA_API ma_bool32 ma_audio_buffer_at_end(const ma_audio_buffer* pAudioBuffer); +MA_API ma_result ma_audio_buffer_get_cursor_in_pcm_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pCursor); +MA_API ma_result ma_audio_buffer_get_length_in_pcm_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pLength); +MA_API ma_result ma_audio_buffer_get_available_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pAvailableFrames); + + +/* +Paged Audio Buffer +================== +A paged audio buffer is made up of a linked list of pages. It's expandable, but not shrinkable. It +can be used for cases where audio data is streamed in asynchronously while allowing data to be read +at the same time. + +This is lock-free, but not 100% thread safe. You can append a page and read from the buffer across +simultaneously across different threads, however only one thread at a time can append, and only one +thread at a time can read and seek. +*/ +typedef struct ma_paged_audio_buffer_page ma_paged_audio_buffer_page; +struct ma_paged_audio_buffer_page +{ + MA_ATOMIC(MA_SIZEOF_PTR, ma_paged_audio_buffer_page*) pNext; + ma_uint64 sizeInFrames; + ma_uint8 pAudioData[1]; +}; + +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_paged_audio_buffer_page head; /* Dummy head for the lock-free algorithm. Always has a size of 0. */ + MA_ATOMIC(MA_SIZEOF_PTR, ma_paged_audio_buffer_page*) pTail; /* Never null. Initially set to &head. */ +} ma_paged_audio_buffer_data; + +MA_API ma_result ma_paged_audio_buffer_data_init(ma_format format, ma_uint32 channels, ma_paged_audio_buffer_data* pData); +MA_API void ma_paged_audio_buffer_data_uninit(ma_paged_audio_buffer_data* pData, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_paged_audio_buffer_page* ma_paged_audio_buffer_data_get_head(ma_paged_audio_buffer_data* pData); +MA_API ma_paged_audio_buffer_page* ma_paged_audio_buffer_data_get_tail(ma_paged_audio_buffer_data* pData); +MA_API ma_result ma_paged_audio_buffer_data_get_length_in_pcm_frames(ma_paged_audio_buffer_data* pData, ma_uint64* pLength); +MA_API ma_result ma_paged_audio_buffer_data_allocate_page(ma_paged_audio_buffer_data* pData, ma_uint64 pageSizeInFrames, const void* pInitialData, const ma_allocation_callbacks* pAllocationCallbacks, ma_paged_audio_buffer_page** ppPage); +MA_API ma_result ma_paged_audio_buffer_data_free_page(ma_paged_audio_buffer_data* pData, ma_paged_audio_buffer_page* pPage, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_paged_audio_buffer_data_append_page(ma_paged_audio_buffer_data* pData, ma_paged_audio_buffer_page* pPage); +MA_API ma_result ma_paged_audio_buffer_data_allocate_and_append_page(ma_paged_audio_buffer_data* pData, ma_uint32 pageSizeInFrames, const void* pInitialData, const ma_allocation_callbacks* pAllocationCallbacks); + + +typedef struct +{ + ma_paged_audio_buffer_data* pData; /* Must not be null. */ +} ma_paged_audio_buffer_config; + +MA_API ma_paged_audio_buffer_config ma_paged_audio_buffer_config_init(ma_paged_audio_buffer_data* pData); + + +typedef struct +{ + ma_data_source_base ds; + ma_paged_audio_buffer_data* pData; /* Audio data is read from here. Cannot be null. */ + ma_paged_audio_buffer_page* pCurrent; + ma_uint64 relativeCursor; /* Relative to the current page. */ + ma_uint64 absoluteCursor; +} ma_paged_audio_buffer; + +MA_API ma_result ma_paged_audio_buffer_init(const ma_paged_audio_buffer_config* pConfig, ma_paged_audio_buffer* pPagedAudioBuffer); +MA_API void ma_paged_audio_buffer_uninit(ma_paged_audio_buffer* pPagedAudioBuffer); +MA_API ma_result ma_paged_audio_buffer_read_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead); /* Returns MA_AT_END if no more pages available. */ +MA_API ma_result ma_paged_audio_buffer_seek_to_pcm_frame(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64 frameIndex); +MA_API ma_result ma_paged_audio_buffer_get_cursor_in_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64* pCursor); +MA_API ma_result ma_paged_audio_buffer_get_length_in_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64* pLength); + + + +/************************************************************************************************************************************************************ + +Ring Buffer + +************************************************************************************************************************************************************/ +typedef struct +{ + void* pBuffer; + ma_uint32 subbufferSizeInBytes; + ma_uint32 subbufferCount; + ma_uint32 subbufferStrideInBytes; + MA_ATOMIC(4, ma_uint32) encodedReadOffset; /* Most significant bit is the loop flag. Lower 31 bits contains the actual offset in bytes. Must be used atomically. */ + MA_ATOMIC(4, ma_uint32) encodedWriteOffset; /* Most significant bit is the loop flag. Lower 31 bits contains the actual offset in bytes. Must be used atomically. */ + ma_bool8 ownsBuffer; /* Used to know whether or not miniaudio is responsible for free()-ing the buffer. */ + ma_bool8 clearOnWriteAcquire; /* When set, clears the acquired write buffer before returning from ma_rb_acquire_write(). */ + ma_allocation_callbacks allocationCallbacks; +} ma_rb; + +MA_API ma_result ma_rb_init_ex(size_t subbufferSizeInBytes, size_t subbufferCount, size_t subbufferStrideInBytes, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_rb* pRB); +MA_API ma_result ma_rb_init(size_t bufferSizeInBytes, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_rb* pRB); +MA_API void ma_rb_uninit(ma_rb* pRB); +MA_API void ma_rb_reset(ma_rb* pRB); +MA_API ma_result ma_rb_acquire_read(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut); +MA_API ma_result ma_rb_commit_read(ma_rb* pRB, size_t sizeInBytes); +MA_API ma_result ma_rb_acquire_write(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut); +MA_API ma_result ma_rb_commit_write(ma_rb* pRB, size_t sizeInBytes); +MA_API ma_result ma_rb_seek_read(ma_rb* pRB, size_t offsetInBytes); +MA_API ma_result ma_rb_seek_write(ma_rb* pRB, size_t offsetInBytes); +MA_API 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. Will return the number of bytes that can be read before the read pointer hits the write pointer. */ +MA_API ma_uint32 ma_rb_available_read(ma_rb* pRB); +MA_API ma_uint32 ma_rb_available_write(ma_rb* pRB); +MA_API size_t ma_rb_get_subbuffer_size(ma_rb* pRB); +MA_API size_t ma_rb_get_subbuffer_stride(ma_rb* pRB); +MA_API size_t ma_rb_get_subbuffer_offset(ma_rb* pRB, size_t subbufferIndex); +MA_API void* ma_rb_get_subbuffer_ptr(ma_rb* pRB, size_t subbufferIndex, void* pBuffer); + + +typedef struct +{ + ma_data_source_base ds; + ma_rb rb; + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; /* Not required for the ring buffer itself, but useful for associating the data with some sample rate, particularly for data sources. */ +} ma_pcm_rb; + +MA_API ma_result ma_pcm_rb_init_ex(ma_format format, ma_uint32 channels, ma_uint32 subbufferSizeInFrames, ma_uint32 subbufferCount, ma_uint32 subbufferStrideInFrames, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_pcm_rb* pRB); +MA_API ma_result ma_pcm_rb_init(ma_format format, ma_uint32 channels, ma_uint32 bufferSizeInFrames, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_pcm_rb* pRB); +MA_API void ma_pcm_rb_uninit(ma_pcm_rb* pRB); +MA_API void ma_pcm_rb_reset(ma_pcm_rb* pRB); +MA_API ma_result ma_pcm_rb_acquire_read(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut); +MA_API ma_result ma_pcm_rb_commit_read(ma_pcm_rb* pRB, ma_uint32 sizeInFrames); +MA_API ma_result ma_pcm_rb_acquire_write(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut); +MA_API ma_result ma_pcm_rb_commit_write(ma_pcm_rb* pRB, ma_uint32 sizeInFrames); +MA_API ma_result ma_pcm_rb_seek_read(ma_pcm_rb* pRB, ma_uint32 offsetInFrames); +MA_API ma_result ma_pcm_rb_seek_write(ma_pcm_rb* pRB, ma_uint32 offsetInFrames); +MA_API ma_int32 ma_pcm_rb_pointer_distance(ma_pcm_rb* pRB); /* Return value is in frames. */ +MA_API ma_uint32 ma_pcm_rb_available_read(ma_pcm_rb* pRB); +MA_API ma_uint32 ma_pcm_rb_available_write(ma_pcm_rb* pRB); +MA_API ma_uint32 ma_pcm_rb_get_subbuffer_size(ma_pcm_rb* pRB); +MA_API ma_uint32 ma_pcm_rb_get_subbuffer_stride(ma_pcm_rb* pRB); +MA_API ma_uint32 ma_pcm_rb_get_subbuffer_offset(ma_pcm_rb* pRB, ma_uint32 subbufferIndex); +MA_API void* ma_pcm_rb_get_subbuffer_ptr(ma_pcm_rb* pRB, ma_uint32 subbufferIndex, void* pBuffer); +MA_API ma_format ma_pcm_rb_get_format(const ma_pcm_rb* pRB); +MA_API ma_uint32 ma_pcm_rb_get_channels(const ma_pcm_rb* pRB); +MA_API ma_uint32 ma_pcm_rb_get_sample_rate(const ma_pcm_rb* pRB); +MA_API void ma_pcm_rb_set_sample_rate(ma_pcm_rb* pRB, ma_uint32 sampleRate); + + +/* +The idea of the duplex ring buffer is to act as the intermediary buffer when running two asynchronous devices in a duplex set up. The +capture device writes to it, and then a playback device reads from it. + +At the moment this is just a simple naive implementation, but in the future I want to implement some dynamic resampling to seamlessly +handle desyncs. Note that the API is work in progress and may change at any time in any version. + +The size of the buffer is based on the capture side since that's what'll be written to the buffer. It is based on the capture period size +in frames. The internal sample rate of the capture device is also needed in order to calculate the size. +*/ +typedef struct +{ + ma_pcm_rb rb; +} ma_duplex_rb; + +MA_API ma_result ma_duplex_rb_init(ma_format captureFormat, ma_uint32 captureChannels, ma_uint32 sampleRate, ma_uint32 captureInternalSampleRate, ma_uint32 captureInternalPeriodSizeInFrames, const ma_allocation_callbacks* pAllocationCallbacks, ma_duplex_rb* pRB); +MA_API ma_result ma_duplex_rb_uninit(ma_duplex_rb* pRB); + + +/************************************************************************************************************************************************************ + +Miscellaneous Helpers + +************************************************************************************************************************************************************/ +/* +Retrieves a human readable description of the given result code. +*/ +MA_API const char* ma_result_description(ma_result result); + +/* +malloc() +*/ +MA_API void* ma_malloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks); + +/* +calloc() +*/ +MA_API void* ma_calloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks); + +/* +realloc() +*/ +MA_API void* ma_realloc(void* p, size_t sz, const ma_allocation_callbacks* pAllocationCallbacks); + +/* +free() +*/ +MA_API void ma_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks); + +/* +Performs an aligned malloc, with the assumption that the alignment is a power of 2. +*/ +MA_API void* ma_aligned_malloc(size_t sz, size_t alignment, const ma_allocation_callbacks* pAllocationCallbacks); + +/* +Free's an aligned malloc'd buffer. +*/ +MA_API void ma_aligned_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks); + +/* +Retrieves a friendly name for a format. +*/ +MA_API const char* ma_get_format_name(ma_format format); + +/* +Blends two frames in floating point format. +*/ +MA_API 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 API is pure. +*/ +MA_API 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. +*/ +MA_API const char* ma_log_level_to_string(ma_uint32 logLevel); + + + + +/************************************************************************************************************************************************************ + +Synchronization + +************************************************************************************************************************************************************/ +/* +Locks a spinlock. +*/ +MA_API ma_result ma_spinlock_lock(volatile ma_spinlock* pSpinlock); + +/* +Locks a spinlock, but does not yield() when looping. +*/ +MA_API ma_result ma_spinlock_lock_noyield(volatile ma_spinlock* pSpinlock); + +/* +Unlocks a spinlock. +*/ +MA_API ma_result ma_spinlock_unlock(volatile ma_spinlock* pSpinlock); + + +#ifndef MA_NO_THREADING + +/* +Creates a mutex. + +A mutex must be created from a valid context. A mutex is initially unlocked. +*/ +MA_API ma_result ma_mutex_init(ma_mutex* pMutex); + +/* +Deletes a mutex. +*/ +MA_API void ma_mutex_uninit(ma_mutex* pMutex); + +/* +Locks a mutex with an infinite timeout. +*/ +MA_API void ma_mutex_lock(ma_mutex* pMutex); + +/* +Unlocks a mutex. +*/ +MA_API void ma_mutex_unlock(ma_mutex* pMutex); + + +/* +Initializes an auto-reset event. +*/ +MA_API ma_result ma_event_init(ma_event* pEvent); + +/* +Uninitializes an auto-reset event. +*/ +MA_API void ma_event_uninit(ma_event* pEvent); + +/* +Waits for the specified auto-reset event to become signalled. +*/ +MA_API ma_result ma_event_wait(ma_event* pEvent); + +/* +Signals the specified auto-reset event. +*/ +MA_API ma_result ma_event_signal(ma_event* pEvent); +#endif /* MA_NO_THREADING */ + + +/* +Fence +===== +This locks while the counter is larger than 0. Counter can be incremented and decremented by any +thread, but care needs to be taken when waiting. It is possible for one thread to acquire the +fence just as another thread returns from ma_fence_wait(). + +The idea behind a fence is to allow you to wait for a group of operations to complete. When an +operation starts, the counter is incremented which locks the fence. When the operation completes, +the fence will be released which decrements the counter. ma_fence_wait() will block until the +counter hits zero. + +If threading is disabled, ma_fence_wait() will spin on the counter. +*/ +typedef struct +{ +#ifndef MA_NO_THREADING + ma_event e; +#endif + ma_uint32 counter; +} ma_fence; + +MA_API ma_result ma_fence_init(ma_fence* pFence); +MA_API void ma_fence_uninit(ma_fence* pFence); +MA_API ma_result ma_fence_acquire(ma_fence* pFence); /* Increment counter. */ +MA_API ma_result ma_fence_release(ma_fence* pFence); /* Decrement counter. */ +MA_API ma_result ma_fence_wait(ma_fence* pFence); /* Wait for counter to reach 0. */ + + + +/* +Notification callback for asynchronous operations. +*/ +typedef void ma_async_notification; + +typedef struct +{ + void (* onSignal)(ma_async_notification* pNotification); +} ma_async_notification_callbacks; + +MA_API ma_result ma_async_notification_signal(ma_async_notification* pNotification); + + +/* +Simple polling notification. + +This just sets a variable when the notification has been signalled which is then polled with ma_async_notification_poll_is_signalled() +*/ +typedef struct +{ + ma_async_notification_callbacks cb; + ma_bool32 signalled; +} ma_async_notification_poll; + +MA_API ma_result ma_async_notification_poll_init(ma_async_notification_poll* pNotificationPoll); +MA_API ma_bool32 ma_async_notification_poll_is_signalled(const ma_async_notification_poll* pNotificationPoll); + + +/* +Event Notification + +This uses an ma_event. If threading is disabled (MA_NO_THREADING), initialization will fail. +*/ +typedef struct +{ + ma_async_notification_callbacks cb; +#ifndef MA_NO_THREADING + ma_event e; +#endif +} ma_async_notification_event; + +MA_API ma_result ma_async_notification_event_init(ma_async_notification_event* pNotificationEvent); +MA_API ma_result ma_async_notification_event_uninit(ma_async_notification_event* pNotificationEvent); +MA_API ma_result ma_async_notification_event_wait(ma_async_notification_event* pNotificationEvent); +MA_API ma_result ma_async_notification_event_signal(ma_async_notification_event* pNotificationEvent); + + + + +/************************************************************************************************************************************************************ + +Job Queue + +************************************************************************************************************************************************************/ + +/* +Slot Allocator +-------------- +The idea of the slot allocator is for it to be used in conjunction with a fixed sized buffer. You use the slot allocator to allocator an index that can be used +as the insertion point for an object. + +Slots are reference counted to help mitigate the ABA problem in the lock-free queue we use for tracking jobs. + +The slot index is stored in the low 32 bits. The reference counter is stored in the high 32 bits: + + +-----------------+-----------------+ + | 32 Bits | 32 Bits | + +-----------------+-----------------+ + | Reference Count | Slot Index | + +-----------------+-----------------+ +*/ +typedef struct +{ + ma_uint32 capacity; /* The number of slots to make available. */ +} ma_slot_allocator_config; + +MA_API ma_slot_allocator_config ma_slot_allocator_config_init(ma_uint32 capacity); + + +typedef struct +{ + MA_ATOMIC(4, ma_uint32) bitfield; /* Must be used atomically because the allocation and freeing routines need to make copies of this which must never be optimized away by the compiler. */ +} ma_slot_allocator_group; + +typedef struct +{ + ma_slot_allocator_group* pGroups; /* Slots are grouped in chunks of 32. */ + ma_uint32* pSlots; /* 32 bits for reference counting for ABA mitigation. */ + ma_uint32 count; /* Allocation count. */ + ma_uint32 capacity; + + /* Memory management. */ + ma_bool32 _ownsHeap; + void* _pHeap; +} ma_slot_allocator; + +MA_API ma_result ma_slot_allocator_get_heap_size(const ma_slot_allocator_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_slot_allocator_init_preallocated(const ma_slot_allocator_config* pConfig, void* pHeap, ma_slot_allocator* pAllocator); +MA_API ma_result ma_slot_allocator_init(const ma_slot_allocator_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_slot_allocator* pAllocator); +MA_API void ma_slot_allocator_uninit(ma_slot_allocator* pAllocator, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_slot_allocator_alloc(ma_slot_allocator* pAllocator, ma_uint64* pSlot); +MA_API ma_result ma_slot_allocator_free(ma_slot_allocator* pAllocator, ma_uint64 slot); + + +typedef struct ma_job ma_job; + +/* +Callback for processing a job. Each job type will have their own processing callback which will be +called by ma_job_process(). +*/ +typedef ma_result (* ma_job_proc)(ma_job* pJob); + +/* When a job type is added here an callback needs to be added go "g_jobVTable" in the implementation section. */ +typedef enum +{ + /* Miscellaneous. */ + MA_JOB_TYPE_QUIT = 0, + MA_JOB_TYPE_CUSTOM, + + /* Resource Manager. */ + MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER_NODE, + MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER_NODE, + MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE, + MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER, + MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER, + MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_STREAM, + MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_STREAM, + MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_STREAM, + MA_JOB_TYPE_RESOURCE_MANAGER_SEEK_DATA_STREAM, + + /* Device. */ + MA_JOB_TYPE_DEVICE_AAUDIO_REROUTE, + + /* Count. Must always be last. */ + MA_JOB_TYPE_COUNT +} ma_job_type; + +struct ma_job +{ + union + { + struct + { + ma_uint16 code; /* Job type. */ + ma_uint16 slot; /* Index into a ma_slot_allocator. */ + ma_uint32 refcount; + } breakup; + ma_uint64 allocation; + } toc; /* 8 bytes. We encode the job code into the slot allocation data to save space. */ + MA_ATOMIC(8, ma_uint64) next; /* refcount + slot for the next item. Does not include the job code. */ + ma_uint32 order; /* Execution order. Used to create a data dependency and ensure a job is executed in order. Usage is contextual depending on the job type. */ + + union + { + /* Miscellaneous. */ + struct + { + ma_job_proc proc; + ma_uintptr data0; + ma_uintptr data1; + } custom; + + /* Resource Manager */ + union + { + struct + { + /*ma_resource_manager**/ void* pResourceManager; + /*ma_resource_manager_data_buffer_node**/ void* pDataBufferNode; + char* pFilePath; + wchar_t* pFilePathW; + ma_uint32 flags; /* Resource manager data source flags that were used when initializing the data buffer. */ + ma_async_notification* pInitNotification; /* Signalled when the data buffer has been initialized and the format/channels/rate can be retrieved. */ + ma_async_notification* pDoneNotification; /* Signalled when the data buffer has been fully decoded. Will be passed through to MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE when decoding. */ + ma_fence* pInitFence; /* Released when initialization of the decoder is complete. */ + ma_fence* pDoneFence; /* Released if initialization of the decoder fails. Passed through to PAGE_DATA_BUFFER_NODE untouched if init is successful. */ + } loadDataBufferNode; + struct + { + /*ma_resource_manager**/ void* pResourceManager; + /*ma_resource_manager_data_buffer_node**/ void* pDataBufferNode; + ma_async_notification* pDoneNotification; + ma_fence* pDoneFence; + } freeDataBufferNode; + struct + { + /*ma_resource_manager**/ void* pResourceManager; + /*ma_resource_manager_data_buffer_node**/ void* pDataBufferNode; + /*ma_decoder**/ void* pDecoder; + ma_async_notification* pDoneNotification; /* Signalled when the data buffer has been fully decoded. */ + ma_fence* pDoneFence; /* Passed through from LOAD_DATA_BUFFER_NODE and released when the data buffer completes decoding or an error occurs. */ + } pageDataBufferNode; + + struct + { + /*ma_resource_manager_data_buffer**/ void* pDataBuffer; + ma_async_notification* pInitNotification; /* Signalled when the data buffer has been initialized and the format/channels/rate can be retrieved. */ + ma_async_notification* pDoneNotification; /* Signalled when the data buffer has been fully decoded. */ + ma_fence* pInitFence; /* Released when the data buffer has been initialized and the format/channels/rate can be retrieved. */ + ma_fence* pDoneFence; /* Released when the data buffer has been fully decoded. */ + ma_uint64 rangeBegInPCMFrames; + ma_uint64 rangeEndInPCMFrames; + ma_uint64 loopPointBegInPCMFrames; + ma_uint64 loopPointEndInPCMFrames; + ma_uint32 isLooping; + } loadDataBuffer; + struct + { + /*ma_resource_manager_data_buffer**/ void* pDataBuffer; + ma_async_notification* pDoneNotification; + ma_fence* pDoneFence; + } freeDataBuffer; + + struct + { + /*ma_resource_manager_data_stream**/ void* pDataStream; + char* pFilePath; /* Allocated when the job is posted, freed by the job thread after loading. */ + wchar_t* pFilePathW; /* ^ As above ^. Only used if pFilePath is NULL. */ + ma_uint64 initialSeekPoint; + ma_async_notification* pInitNotification; /* Signalled after the first two pages have been decoded and frames can be read from the stream. */ + ma_fence* pInitFence; + } loadDataStream; + struct + { + /*ma_resource_manager_data_stream**/ void* pDataStream; + ma_async_notification* pDoneNotification; + ma_fence* pDoneFence; + } freeDataStream; + struct + { + /*ma_resource_manager_data_stream**/ void* pDataStream; + ma_uint32 pageIndex; /* The index of the page to decode into. */ + } pageDataStream; + struct + { + /*ma_resource_manager_data_stream**/ void* pDataStream; + ma_uint64 frameIndex; + } seekDataStream; + } resourceManager; + + /* Device. */ + union + { + union + { + struct + { + /*ma_device**/ void* pDevice; + /*ma_device_type*/ ma_uint32 deviceType; + } reroute; + } aaudio; + } device; + } data; +}; + +MA_API ma_job ma_job_init(ma_uint16 code); +MA_API ma_result ma_job_process(ma_job* pJob); + + +/* +When set, ma_job_queue_next() will not wait and no semaphore will be signaled in +ma_job_queue_post(). ma_job_queue_next() will return MA_NO_DATA_AVAILABLE if nothing is available. + +This flag should always be used for platforms that do not support multithreading. +*/ +typedef enum +{ + MA_JOB_QUEUE_FLAG_NON_BLOCKING = 0x00000001 +} ma_job_queue_flags; + +typedef struct +{ + ma_uint32 flags; + ma_uint32 capacity; /* The maximum number of jobs that can fit in the queue at a time. */ +} ma_job_queue_config; + +MA_API ma_job_queue_config ma_job_queue_config_init(ma_uint32 flags, ma_uint32 capacity); + + +typedef struct +{ + ma_uint32 flags; /* Flags passed in at initialization time. */ + ma_uint32 capacity; /* The maximum number of jobs that can fit in the queue at a time. Set by the config. */ + MA_ATOMIC(8, ma_uint64) head; /* The first item in the list. Required for removing from the top of the list. */ + MA_ATOMIC(8, ma_uint64) tail; /* The last item in the list. Required for appending to the end of the list. */ +#ifndef MA_NO_THREADING + ma_semaphore sem; /* Only used when MA_JOB_QUEUE_FLAG_NON_BLOCKING is unset. */ +#endif + ma_slot_allocator allocator; + ma_job* pJobs; +#ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE + ma_spinlock lock; +#endif + + /* Memory management. */ + void* _pHeap; + ma_bool32 _ownsHeap; +} ma_job_queue; + +MA_API ma_result ma_job_queue_get_heap_size(const ma_job_queue_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_job_queue_init_preallocated(const ma_job_queue_config* pConfig, void* pHeap, ma_job_queue* pQueue); +MA_API ma_result ma_job_queue_init(const ma_job_queue_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_job_queue* pQueue); +MA_API void ma_job_queue_uninit(ma_job_queue* pQueue, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_job_queue_post(ma_job_queue* pQueue, const ma_job* pJob); +MA_API ma_result ma_job_queue_next(ma_job_queue* pQueue, ma_job* pJob); /* Returns MA_CANCELLED if the next job is a quit job. */ + + + +/************************************************************************************************************************************************************ +************************************************************************************************************************************************************* + +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 desktops. */ + #define MA_SUPPORT_DSOUND + #define MA_SUPPORT_WINMM + + /* Don't enable JACK here if compiling with Cosmopolitan. It'll be enabled in the Linux section below. */ + #if !defined(__COSMOPOLITAN__) + #define MA_SUPPORT_JACK /* JACK is technically supported on Windows, but I don't know how many people use it in practice... */ + #endif + #endif +#endif +#if defined(MA_UNIX) && !defined(MA_ORBIS) && !defined(MA_PROSPERO) + #if defined(MA_LINUX) + #if !defined(MA_ANDROID) && !defined(__COSMOPOLITAN__) /* 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(__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_ANDROID) + #define MA_SUPPORT_AAUDIO + #define MA_SUPPORT_OPENSL +#endif +#if defined(MA_APPLE) + #define MA_SUPPORT_COREAUDIO +#endif +#if defined(MA_EMSCRIPTEN) + #define MA_SUPPORT_WEBAUDIO +#endif + +/* All platforms should support custom backends. */ +#define MA_SUPPORT_CUSTOM + +/* 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_SUPPORT_WASAPI) && !defined(MA_NO_WASAPI) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_WASAPI)) + #define MA_HAS_WASAPI +#endif +#if defined(MA_SUPPORT_DSOUND) && !defined(MA_NO_DSOUND) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_DSOUND)) + #define MA_HAS_DSOUND +#endif +#if defined(MA_SUPPORT_WINMM) && !defined(MA_NO_WINMM) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_WINMM)) + #define MA_HAS_WINMM +#endif +#if defined(MA_SUPPORT_ALSA) && !defined(MA_NO_ALSA) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_ALSA)) + #define MA_HAS_ALSA +#endif +#if defined(MA_SUPPORT_PULSEAUDIO) && !defined(MA_NO_PULSEAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_PULSEAUDIO)) + #define MA_HAS_PULSEAUDIO +#endif +#if defined(MA_SUPPORT_JACK) && !defined(MA_NO_JACK) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_JACK)) + #define MA_HAS_JACK +#endif +#if defined(MA_SUPPORT_COREAUDIO) && !defined(MA_NO_COREAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_COREAUDIO)) + #define MA_HAS_COREAUDIO +#endif +#if defined(MA_SUPPORT_SNDIO) && !defined(MA_NO_SNDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_SNDIO)) + #define MA_HAS_SNDIO +#endif +#if defined(MA_SUPPORT_AUDIO4) && !defined(MA_NO_AUDIO4) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_AUDIO4)) + #define MA_HAS_AUDIO4 +#endif +#if defined(MA_SUPPORT_OSS) && !defined(MA_NO_OSS) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_OSS)) + #define MA_HAS_OSS +#endif +#if defined(MA_SUPPORT_AAUDIO) && !defined(MA_NO_AAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_AAUDIO)) + #define MA_HAS_AAUDIO +#endif +#if defined(MA_SUPPORT_OPENSL) && !defined(MA_NO_OPENSL) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_OPENSL)) + #define MA_HAS_OPENSL +#endif +#if defined(MA_SUPPORT_WEBAUDIO) && !defined(MA_NO_WEBAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_WEBAUDIO)) + #define MA_HAS_WEBAUDIO +#endif +#if defined(MA_SUPPORT_CUSTOM) && !defined(MA_NO_CUSTOM) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_CUSTOM)) + #define MA_HAS_CUSTOM +#endif +#if defined(MA_SUPPORT_NULL) && !defined(MA_NO_NULL) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_NULL)) + #define MA_HAS_NULL +#endif + +typedef enum +{ + ma_device_state_uninitialized = 0, + ma_device_state_stopped = 1, /* The device's default state after initialization. */ + ma_device_state_started = 2, /* The device is started and is requesting and/or delivering audio data. */ + ma_device_state_starting = 3, /* Transitioning from a stopped state to started. */ + ma_device_state_stopping = 4 /* Transitioning from a started state to stopped. */ +} ma_device_state; + +MA_ATOMIC_SAFE_TYPE_DECL(i32, 4, device_state) + + +#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_custom, /* <-- Custom backend, with callbacks defined by the context config. */ + ma_backend_null /* <-- Must always be the last item. Lowest priority, and used as the terminator for backend enumeration. */ +} ma_backend; + +#define MA_BACKEND_COUNT (ma_backend_null+1) + + +/* +Device job thread. This is used by backends that require asynchronous processing of certain +operations. It is not used by all backends. + +The device job thread is made up of a thread and a job queue. You can post a job to the thread with +ma_device_job_thread_post(). The thread will do the processing of the job. +*/ +typedef struct +{ + ma_bool32 noThread; /* Set this to true if you want to process jobs yourself. */ + ma_uint32 jobQueueCapacity; + ma_uint32 jobQueueFlags; +} ma_device_job_thread_config; + +MA_API ma_device_job_thread_config ma_device_job_thread_config_init(void); + +typedef struct +{ + ma_thread thread; + ma_job_queue jobQueue; + ma_bool32 _hasThread; +} ma_device_job_thread; + +MA_API ma_result ma_device_job_thread_init(const ma_device_job_thread_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_device_job_thread* pJobThread); +MA_API void ma_device_job_thread_uninit(ma_device_job_thread* pJobThread, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_device_job_thread_post(ma_device_job_thread* pJobThread, const ma_job* pJob); +MA_API ma_result ma_device_job_thread_next(ma_device_job_thread* pJobThread, ma_job* pJob); + + + +/* Device notification types. */ +typedef enum +{ + ma_device_notification_type_started, + ma_device_notification_type_stopped, + ma_device_notification_type_rerouted, + ma_device_notification_type_interruption_began, + ma_device_notification_type_interruption_ended, + ma_device_notification_type_unlocked +} ma_device_notification_type; + +typedef struct +{ + ma_device* pDevice; + ma_device_notification_type type; + union + { + struct + { + int _unused; + } started; + struct + { + int _unused; + } stopped; + struct + { + int _unused; + } rerouted; + struct + { + int _unused; + } interruption; + } data; +} ma_device_notification; + +/* +The notification callback for when the application should be notified of a change to the device. + +This callback is used for notifying the application of changes such as when the device has started, +stopped, rerouted or an interruption has occurred. Note that not all backends will post all +notification types. For example, some backends will perform automatic stream routing without any +kind of notification to the host program which means miniaudio will never know about it and will +never be able to fire the rerouted notification. You should keep this in mind when designing your +program. + +The stopped notification will *not* get fired when a device is rerouted. + + +Parameters +---------- +pNotification (in) + A pointer to a structure containing information about the event. Use the `pDevice` member of + this object to retrieve the relevant device. The `type` member can be used to discriminate + against each of the notification types. + + +Remarks +------- +Do not restart or uninitialize the device from the callback. + +Not all notifications will be triggered by all backends, however the started and stopped events +should be reliable for all backends. Some backends do not have a good way to detect device +stoppages due to unplugging the device which may result in the stopped callback not getting +fired. This has been observed with at least one BSD variant. + +The rerouted notification is fired *after* the reroute has occurred. The stopped notification will +*not* get fired when a device is rerouted. The following backends are known to do automatic stream +rerouting, but do not have a way to be notified of the change: + + * DirectSound + +The interruption notifications are used on mobile platforms for detecting when audio is interrupted +due to things like an incoming phone call. Currently this is only implemented on iOS. None of the +Android backends will report this notification. +*/ +typedef void (* ma_device_notification_proc)(const ma_device_notification* pNotification); + + +/* +The callback for processing audio data from the device. + +The data callback is fired by miniaudio whenever the device needs to have more data delivered to a playback device, or when a capture device has some data +available. This is called as soon as the backend asks for more data which means it may be called with inconsistent frame counts. You cannot assume the +callback will be fired with a consistent frame count. + + +Parameters +---------- +pDevice (in) + A pointer to the relevant device. + +pOutput (out) + A pointer to the output 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 and loopback device. + +pInput (in) + A pointer to the buffer containing input data from a recording device. This will be non-null for a capture, full-duplex or loopback device and null for a + playback device. + +frameCount (in) + The number of PCM frames to process. Note that this will not necessarily be equal to what you requested when you initialized the device. The + `periodSizeInFrames` and `periodSizeInMilliseconds` members of the device config are just hints, and are not necessarily exactly what you'll get. You must + not assume this will always be the same value each time the callback is fired. + + +Remarks +------- +You cannot stop and start the device from inside the callback or else you'll get a deadlock. You must also not uninitialize the device from inside the +callback. The following APIs cannot be called from inside the callback: + + ma_device_init() + ma_device_init_ex() + ma_device_uninit() + ma_device_start() + ma_device_stop() + +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_data_proc)(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount); + + + + +/* +DEPRECATED. Use ma_device_notification_proc instead. + +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 occurring. + + +Parameters +---------- +pDevice (in) + A pointer to the device that has just stopped. + + +Remarks +------- +Do not restart or uninitialize the device from the callback. +*/ +typedef void (* ma_stop_proc)(ma_device* pDevice); /* DEPRECATED. Use ma_device_notification_proc instead. */ + +typedef enum +{ + ma_device_type_playback = 1, + ma_device_type_capture = 2, + ma_device_type_duplex = ma_device_type_playback | ma_device_type_capture, /* 3 */ + ma_device_type_loopback = 4 +} ma_device_type; + +typedef enum +{ + ma_share_mode_shared = 0, + ma_share_mode_exclusive +} ma_share_mode; + +/* iOS/tvOS/watchOS session categories. */ +typedef enum +{ + ma_ios_session_category_default = 0, /* AVAudioSessionCategoryPlayAndRecord. */ + ma_ios_session_category_none, /* Leave the session category unchanged. */ + ma_ios_session_category_ambient, /* AVAudioSessionCategoryAmbient */ + ma_ios_session_category_solo_ambient, /* AVAudioSessionCategorySoloAmbient */ + ma_ios_session_category_playback, /* AVAudioSessionCategoryPlayback */ + ma_ios_session_category_record, /* AVAudioSessionCategoryRecord */ + ma_ios_session_category_play_and_record, /* AVAudioSessionCategoryPlayAndRecord */ + ma_ios_session_category_multi_route /* AVAudioSessionCategoryMultiRoute */ +} ma_ios_session_category; + +/* iOS/tvOS/watchOS session category options */ +typedef enum +{ + ma_ios_session_category_option_mix_with_others = 0x01, /* AVAudioSessionCategoryOptionMixWithOthers */ + ma_ios_session_category_option_duck_others = 0x02, /* AVAudioSessionCategoryOptionDuckOthers */ + ma_ios_session_category_option_allow_bluetooth = 0x04, /* AVAudioSessionCategoryOptionAllowBluetooth */ + ma_ios_session_category_option_default_to_speaker = 0x08, /* AVAudioSessionCategoryOptionDefaultToSpeaker */ + ma_ios_session_category_option_interrupt_spoken_audio_and_mix_with_others = 0x11, /* AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers */ + ma_ios_session_category_option_allow_bluetooth_a2dp = 0x20, /* AVAudioSessionCategoryOptionAllowBluetoothA2DP */ + ma_ios_session_category_option_allow_air_play = 0x40, /* AVAudioSessionCategoryOptionAllowAirPlay */ +} ma_ios_session_category_option; + +/* OpenSL stream types. */ +typedef enum +{ + ma_opensl_stream_type_default = 0, /* Leaves the stream type unset. */ + ma_opensl_stream_type_voice, /* SL_ANDROID_STREAM_VOICE */ + ma_opensl_stream_type_system, /* SL_ANDROID_STREAM_SYSTEM */ + ma_opensl_stream_type_ring, /* SL_ANDROID_STREAM_RING */ + ma_opensl_stream_type_media, /* SL_ANDROID_STREAM_MEDIA */ + ma_opensl_stream_type_alarm, /* SL_ANDROID_STREAM_ALARM */ + ma_opensl_stream_type_notification /* SL_ANDROID_STREAM_NOTIFICATION */ +} ma_opensl_stream_type; + +/* OpenSL recording presets. */ +typedef enum +{ + ma_opensl_recording_preset_default = 0, /* Leaves the input preset unset. */ + ma_opensl_recording_preset_generic, /* SL_ANDROID_RECORDING_PRESET_GENERIC */ + ma_opensl_recording_preset_camcorder, /* SL_ANDROID_RECORDING_PRESET_CAMCORDER */ + ma_opensl_recording_preset_voice_recognition, /* SL_ANDROID_RECORDING_PRESET_VOICE_RECOGNITION */ + ma_opensl_recording_preset_voice_communication, /* SL_ANDROID_RECORDING_PRESET_VOICE_COMMUNICATION */ + ma_opensl_recording_preset_voice_unprocessed /* SL_ANDROID_RECORDING_PRESET_UNPROCESSED */ +} ma_opensl_recording_preset; + +/* WASAPI audio thread priority characteristics. */ +typedef enum +{ + ma_wasapi_usage_default = 0, + ma_wasapi_usage_games, + ma_wasapi_usage_pro_audio, +} ma_wasapi_usage; + +/* AAudio usage types. */ +typedef enum +{ + ma_aaudio_usage_default = 0, /* Leaves the usage type unset. */ + ma_aaudio_usage_media, /* AAUDIO_USAGE_MEDIA */ + ma_aaudio_usage_voice_communication, /* AAUDIO_USAGE_VOICE_COMMUNICATION */ + ma_aaudio_usage_voice_communication_signalling, /* AAUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING */ + ma_aaudio_usage_alarm, /* AAUDIO_USAGE_ALARM */ + ma_aaudio_usage_notification, /* AAUDIO_USAGE_NOTIFICATION */ + ma_aaudio_usage_notification_ringtone, /* AAUDIO_USAGE_NOTIFICATION_RINGTONE */ + ma_aaudio_usage_notification_event, /* AAUDIO_USAGE_NOTIFICATION_EVENT */ + ma_aaudio_usage_assistance_accessibility, /* AAUDIO_USAGE_ASSISTANCE_ACCESSIBILITY */ + ma_aaudio_usage_assistance_navigation_guidance, /* AAUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE */ + ma_aaudio_usage_assistance_sonification, /* AAUDIO_USAGE_ASSISTANCE_SONIFICATION */ + ma_aaudio_usage_game, /* AAUDIO_USAGE_GAME */ + ma_aaudio_usage_assitant, /* AAUDIO_USAGE_ASSISTANT */ + ma_aaudio_usage_emergency, /* AAUDIO_SYSTEM_USAGE_EMERGENCY */ + ma_aaudio_usage_safety, /* AAUDIO_SYSTEM_USAGE_SAFETY */ + ma_aaudio_usage_vehicle_status, /* AAUDIO_SYSTEM_USAGE_VEHICLE_STATUS */ + ma_aaudio_usage_announcement /* AAUDIO_SYSTEM_USAGE_ANNOUNCEMENT */ +} ma_aaudio_usage; + +/* AAudio content types. */ +typedef enum +{ + ma_aaudio_content_type_default = 0, /* Leaves the content type unset. */ + ma_aaudio_content_type_speech, /* AAUDIO_CONTENT_TYPE_SPEECH */ + ma_aaudio_content_type_music, /* AAUDIO_CONTENT_TYPE_MUSIC */ + ma_aaudio_content_type_movie, /* AAUDIO_CONTENT_TYPE_MOVIE */ + ma_aaudio_content_type_sonification /* AAUDIO_CONTENT_TYPE_SONIFICATION */ +} ma_aaudio_content_type; + +/* AAudio input presets. */ +typedef enum +{ + ma_aaudio_input_preset_default = 0, /* Leaves the input preset unset. */ + ma_aaudio_input_preset_generic, /* AAUDIO_INPUT_PRESET_GENERIC */ + ma_aaudio_input_preset_camcorder, /* AAUDIO_INPUT_PRESET_CAMCORDER */ + ma_aaudio_input_preset_voice_recognition, /* AAUDIO_INPUT_PRESET_VOICE_RECOGNITION */ + ma_aaudio_input_preset_voice_communication, /* AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION */ + ma_aaudio_input_preset_unprocessed, /* AAUDIO_INPUT_PRESET_UNPROCESSED */ + ma_aaudio_input_preset_voice_performance /* AAUDIO_INPUT_PRESET_VOICE_PERFORMANCE */ +} ma_aaudio_input_preset; + +typedef enum +{ + ma_aaudio_allow_capture_default = 0, /* Leaves the allowed capture policy unset. */ + ma_aaudio_allow_capture_by_all, /* AAUDIO_ALLOW_CAPTURE_BY_ALL */ + ma_aaudio_allow_capture_by_system, /* AAUDIO_ALLOW_CAPTURE_BY_SYSTEM */ + ma_aaudio_allow_capture_by_none /* AAUDIO_ALLOW_CAPTURE_BY_NONE */ +} ma_aaudio_allowed_capture_policy; + +typedef union +{ + ma_int64 counter; + double counterD; +} ma_timer; + +typedef union +{ + ma_wchar_win32 wasapi[64]; /* WASAPI uses a wchar_t string for identification. */ + ma_uint8 dsound[16]; /* DirectSound uses a GUID for identification. */ + /*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. */ + char alsa[256]; /* ALSA uses a name string for identification. */ + char pulse[256]; /* PulseAudio uses a name string for identification. */ + int jack; /* JACK always uses default devices. */ + char coreaudio[256]; /* Core Audio uses a string for identification. */ + char sndio[256]; /* "snd/0", etc. */ + char audio4[256]; /* "/dev/audio", etc. */ + char oss[64]; /* "dev/dsp0", etc. "dev/dsp" for the default device. */ + ma_int32 aaudio; /* AAudio uses a 32-bit integer for identification. */ + ma_uint32 opensl; /* OpenSL|ES uses a 32-bit unsigned integer for identification. */ + char webaudio[32]; /* Web Audio always uses default devices for now, but if this changes it'll be a GUID. */ + union + { + int i; + char s[256]; + void* p; + } custom; /* The custom backend could be anything. Give them a few options. */ + int nullbackend; /* The null backend uses an integer for device IDs. */ +} ma_device_id; + + +typedef struct ma_context_config ma_context_config; +typedef struct ma_device_config ma_device_config; +typedef struct ma_backend_callbacks ma_backend_callbacks; + +#define MA_DATA_FORMAT_FLAG_EXCLUSIVE_MODE (1U << 1) /* If set, this is supported in exclusive mode. Otherwise not natively supported by exclusive mode. */ + +#ifndef MA_MAX_DEVICE_NAME_LENGTH +#define MA_MAX_DEVICE_NAME_LENGTH 255 +#endif + +typedef struct +{ + /* Basic info. This is the only information guaranteed to be filled in during device enumeration. */ + ma_device_id id; + char name[MA_MAX_DEVICE_NAME_LENGTH + 1]; /* +1 for null terminator. */ + ma_bool32 isDefault; + + ma_uint32 nativeDataFormatCount; + struct + { + ma_format format; /* Sample format. If set to ma_format_unknown, all sample formats are supported. */ + ma_uint32 channels; /* If set to 0, all channels are supported. */ + ma_uint32 sampleRate; /* If set to 0, all sample rates are supported. */ + ma_uint32 flags; /* A combination of MA_DATA_FORMAT_FLAG_* flags. */ + } nativeDataFormats[/*ma_format_count * ma_standard_sample_rate_count * MA_MAX_CHANNELS*/ 64]; /* Not sure how big to make this. There can be *many* permutations for virtual devices which can support anything. */ +} ma_device_info; + +struct ma_device_config +{ + ma_device_type deviceType; + ma_uint32 sampleRate; + ma_uint32 periodSizeInFrames; + ma_uint32 periodSizeInMilliseconds; + ma_uint32 periods; + ma_performance_profile performanceProfile; + ma_bool8 noPreSilencedOutputBuffer; /* When set to true, the contents of the output buffer passed into the data callback will be left undefined rather than initialized to silence. */ + ma_bool8 noClip; /* When set to true, the contents of the output buffer passed into the data callback will not be clipped after returning. Only applies when the playback sample format is f32. */ + ma_bool8 noDisableDenormals; /* Do not disable denormals when firing the data callback. */ + ma_bool8 noFixedSizedCallback; /* Disables strict fixed-sized data callbacks. Setting this to true will result in the period size being treated only as a hint to the backend. This is an optimization for those who don't need fixed sized callbacks. */ + ma_device_data_proc dataCallback; + ma_device_notification_proc notificationCallback; + ma_stop_proc stopCallback; + void* pUserData; + ma_resampler_config resampling; + struct + { + const ma_device_id* pDeviceID; + ma_format format; + ma_uint32 channels; + ma_channel* pChannelMap; + ma_channel_mix_mode channelMixMode; + ma_bool32 calculateLFEFromSpatialChannels; /* When an output LFE channel is present, but no input LFE, set to true to set the output LFE to the average of all spatial channels (LR, FR, etc.). Ignored when an input LFE is present. */ + ma_share_mode shareMode; + } playback; + struct + { + const ma_device_id* pDeviceID; + ma_format format; + ma_uint32 channels; + ma_channel* pChannelMap; + ma_channel_mix_mode channelMixMode; + ma_bool32 calculateLFEFromSpatialChannels; /* When an output LFE channel is present, but no input LFE, set to true to set the output LFE to the average of all spatial channels (LR, FR, etc.). Ignored when an input LFE is present. */ + ma_share_mode shareMode; + } capture; + + struct + { + ma_wasapi_usage usage; /* When configured, uses Avrt APIs to set the thread characteristics. */ + ma_bool8 noAutoConvertSRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM. */ + ma_bool8 noDefaultQualitySRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY. */ + ma_bool8 noAutoStreamRouting; /* Disables automatic stream routing. */ + ma_bool8 noHardwareOffloading; /* Disables WASAPI's hardware offloading feature. */ + ma_uint32 loopbackProcessID; /* The process ID to include or exclude for loopback mode. Set to 0 to capture audio from all processes. Ignored when an explicit device ID is specified. */ + ma_bool8 loopbackProcessExclude; /* When set to true, excludes the process specified by loopbackProcessID. By default, the process will be included. */ + } wasapi; + struct + { + ma_bool32 noMMap; /* Disables MMap mode. */ + ma_bool32 noAutoFormat; /* Opens the ALSA device with SND_PCM_NO_AUTO_FORMAT. */ + ma_bool32 noAutoChannels; /* Opens the ALSA device with SND_PCM_NO_AUTO_CHANNELS. */ + ma_bool32 noAutoResample; /* Opens the ALSA device with SND_PCM_NO_AUTO_RESAMPLE. */ + } alsa; + struct + { + const char* pStreamNamePlayback; + const char* pStreamNameCapture; + } pulse; + struct + { + ma_bool32 allowNominalSampleRateChange; /* Desktop only. When enabled, allows changing of the sample rate at the operating system level. */ + } coreaudio; + struct + { + ma_opensl_stream_type streamType; + ma_opensl_recording_preset recordingPreset; + ma_bool32 enableCompatibilityWorkarounds; + } opensl; + struct + { + ma_aaudio_usage usage; + ma_aaudio_content_type contentType; + ma_aaudio_input_preset inputPreset; + ma_aaudio_allowed_capture_policy allowedCapturePolicy; + ma_bool32 noAutoStartAfterReroute; + ma_bool32 enableCompatibilityWorkarounds; + } aaudio; +}; + + +/* +The callback for handling device enumeration. This is fired from `ma_context_enumerate_devices()`. + + +Parameters +---------- +pContext (in) + A pointer to the context performing the enumeration. + +deviceType (in) + The type of the device being enumerated. This will always be either `ma_device_type_playback` or `ma_device_type_capture`. + +pInfo (in) + A pointer to a `ma_device_info` containing the ID and name of the enumerated device. Note that this will not include detailed information about the device, + only basic information (ID and name). The reason for this is that it would otherwise require opening the backend device to probe for the information which + is too inefficient. + +pUserData (in) + The user data pointer passed into `ma_context_enumerate_devices()`. +*/ +typedef ma_bool32 (* ma_enum_devices_callback_proc)(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pInfo, void* pUserData); + + +/* +Describes some basic details about a playback or capture device. +*/ +typedef struct +{ + const ma_device_id* pDeviceID; + ma_share_mode shareMode; + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + ma_channel channelMap[MA_MAX_CHANNELS]; + ma_uint32 periodSizeInFrames; + ma_uint32 periodSizeInMilliseconds; + ma_uint32 periodCount; +} ma_device_descriptor; + +/* +These are the callbacks required to be implemented for a backend. These callbacks are grouped into two parts: context and device. There is one context +to many devices. A device is created from a context. + +The general flow goes like this: + + 1) A context is created with `onContextInit()` + 1a) Available devices can be enumerated with `onContextEnumerateDevices()` if required. + 1b) Detailed information about a device can be queried with `onContextGetDeviceInfo()` if required. + 2) A device is created from the context that was created in the first step using `onDeviceInit()`, and optionally a device ID that was + selected from device enumeration via `onContextEnumerateDevices()`. + 3) A device is started or stopped with `onDeviceStart()` / `onDeviceStop()` + 4) Data is delivered to and from the device by the backend. This is always done based on the native format returned by the prior call + to `onDeviceInit()`. Conversion between the device's native format and the format requested by the application will be handled by + miniaudio internally. + +Initialization of the context is quite simple. You need to do any necessary initialization of internal objects and then output the +callbacks defined in this structure. + +Once the context has been initialized you can initialize a device. Before doing so, however, the application may want to know which +physical devices are available. This is where `onContextEnumerateDevices()` comes in. This is fairly simple. For each device, fire the +given callback with, at a minimum, the basic information filled out in `ma_device_info`. When the callback returns `MA_FALSE`, enumeration +needs to stop and the `onContextEnumerateDevices()` function returns with a success code. + +Detailed device information can be retrieved from a device ID using `onContextGetDeviceInfo()`. This takes as input the device type and ID, +and on output returns detailed information about the device in `ma_device_info`. The `onContextGetDeviceInfo()` callback must handle the +case when the device ID is NULL, in which case information about the default device needs to be retrieved. + +Once the context has been created and the device ID retrieved (if using anything other than the default device), the device can be created. +This is a little bit more complicated than initialization of the context due to it's more complicated configuration. When initializing a +device, a duplex device may be requested. This means a separate data format needs to be specified for both playback and capture. On input, +the data format is set to what the application wants. On output it's set to the native format which should match as closely as possible to +the requested format. The conversion between the format requested by the application and the device's native format will be handled +internally by miniaudio. + +On input, if the sample format is set to `ma_format_unknown`, the backend is free to use whatever sample format it desires, so long as it's +supported by miniaudio. When the channel count is set to 0, the backend should use the device's native channel count. The same applies for +sample rate. For the channel map, the default should be used when `ma_channel_map_is_blank()` returns true (all channels set to +`MA_CHANNEL_NONE`). On input, the `periodSizeInFrames` or `periodSizeInMilliseconds` option should always be set. The backend should +inspect both of these variables. If `periodSizeInFrames` is set, it should take priority, otherwise it needs to be derived from the period +size in milliseconds (`periodSizeInMilliseconds`) and the sample rate, keeping in mind that the sample rate may be 0, in which case the +sample rate will need to be determined before calculating the period size in frames. On output, all members of the `ma_device_descriptor` +object should be set to a valid value, except for `periodSizeInMilliseconds` which is optional (`periodSizeInFrames` *must* be set). + +Starting and stopping of the device is done with `onDeviceStart()` and `onDeviceStop()` and should be self-explanatory. If the backend uses +asynchronous reading and writing, `onDeviceStart()` and `onDeviceStop()` should always be implemented. + +The handling of data delivery between the application and the device is the most complicated part of the process. To make this a bit +easier, some helper callbacks are available. If the backend uses a blocking read/write style of API, the `onDeviceRead()` and +`onDeviceWrite()` callbacks can optionally be implemented. These are blocking and work just like reading and writing from a file. If the +backend uses a callback for data delivery, that callback must call `ma_device_handle_backend_data_callback()` from within it's callback. +This allows miniaudio to then process any necessary data conversion and then pass it to the miniaudio data callback. + +If the backend requires absolute flexibility with it's data delivery, it can optionally implement the `onDeviceDataLoop()` callback +which will allow it to implement the logic that will run on the audio thread. This is much more advanced and is completely optional. + +The audio thread should run data delivery logic in a loop while `ma_device_get_state() == ma_device_state_started` and no errors have been +encountered. Do not start or stop the device here. That will be handled from outside the `onDeviceDataLoop()` callback. + +The invocation of the `onDeviceDataLoop()` callback will be handled by miniaudio. When you start the device, miniaudio will fire this +callback. When the device is stopped, the `ma_device_get_state() == ma_device_state_started` condition will fail and the loop will be terminated +which will then fall through to the part that stops the device. For an example on how to implement the `onDeviceDataLoop()` callback, +look at `ma_device_audio_thread__default_read_write()`. Implement the `onDeviceDataLoopWakeup()` callback if you need a mechanism to +wake up the audio thread. + +If the backend supports an optimized retrieval of device information from an initialized `ma_device` object, it should implement the +`onDeviceGetInfo()` callback. This is optional, in which case it will fall back to `onContextGetDeviceInfo()` which is less efficient. +*/ +struct ma_backend_callbacks +{ + ma_result (* onContextInit)(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks); + ma_result (* onContextUninit)(ma_context* pContext); + ma_result (* onContextEnumerateDevices)(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData); + ma_result (* onContextGetDeviceInfo)(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo); + ma_result (* onDeviceInit)(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture); + ma_result (* onDeviceUninit)(ma_device* pDevice); + ma_result (* onDeviceStart)(ma_device* pDevice); + ma_result (* onDeviceStop)(ma_device* pDevice); + ma_result (* onDeviceRead)(ma_device* pDevice, void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesRead); + ma_result (* onDeviceWrite)(ma_device* pDevice, const void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten); + ma_result (* onDeviceDataLoop)(ma_device* pDevice); + ma_result (* onDeviceDataLoopWakeup)(ma_device* pDevice); + ma_result (* onDeviceGetInfo)(ma_device* pDevice, ma_device_type type, ma_device_info* pDeviceInfo); +}; + +struct ma_context_config +{ + ma_log* pLog; + ma_thread_priority threadPriority; + size_t threadStackSize; + void* pUserData; + ma_allocation_callbacks allocationCallbacks; + 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 + { + ma_ios_session_category sessionCategory; + ma_uint32 sessionCategoryOptions; + ma_bool32 noAudioSessionActivate; /* iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:true] on initialization. */ + ma_bool32 noAudioSessionDeactivate; /* iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:false] on uninitialization. */ + } coreaudio; + struct + { + const char* pClientName; + ma_bool32 tryStartServer; + } jack; + ma_backend_callbacks custom; +}; + +/* WASAPI specific structure for some commands which must run on a common thread due to bugs in WASAPI. */ +typedef struct +{ + int code; + ma_event* pEvent; /* This will be signalled when the event is complete. */ + union + { + struct + { + int _unused; + } quit; + struct + { + ma_device_type deviceType; + void* pAudioClient; + void** ppAudioClientService; + ma_result* pResult; /* The result from creating the audio client service. */ + } createAudioClient; + struct + { + ma_device* pDevice; + ma_device_type deviceType; + } releaseAudioClient; + } data; +} ma_context_command__wasapi; + +struct ma_context +{ + ma_backend_callbacks callbacks; + ma_backend backend; /* DirectSound, ALSA, etc. */ + ma_log* pLog; + ma_log log; /* Only used if the log is owned by the context. The pLog member will be set to &log in this case. */ + ma_thread_priority threadPriority; + size_t threadStackSize; + void* pUserData; + ma_allocation_callbacks allocationCallbacks; + 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. */ + + union + { +#ifdef MA_SUPPORT_WASAPI + struct + { + ma_thread commandThread; + ma_mutex commandLock; + ma_semaphore commandSem; + ma_uint32 commandIndex; + ma_uint32 commandCount; + ma_context_command__wasapi commands[4]; + ma_handle hAvrt; + ma_proc AvSetMmThreadCharacteristicsA; + ma_proc AvRevertMmThreadcharacteristics; + ma_handle hMMDevapi; + ma_proc ActivateAudioInterfaceAsync; + } 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; + ma_proc snd_pcm_hw_params_set_channels_near; + ma_proc snd_pcm_hw_params_set_channels_minmax; + ma_proc snd_pcm_hw_params_set_rate_resample; + ma_proc snd_pcm_hw_params_set_rate; + 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_test_format; + ma_proc snd_pcm_hw_params_test_channels; + ma_proc snd_pcm_hw_params_test_rate; + 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_pcm_reset; + 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_nonblock; + ma_proc snd_pcm_info; + ma_proc snd_pcm_info_sizeof; + ma_proc snd_pcm_info_get_name; + ma_proc snd_pcm_poll_descriptors; + ma_proc snd_pcm_poll_descriptors_count; + ma_proc snd_pcm_poll_descriptors_revents; + ma_proc snd_config_update_free_global; + + ma_mutex internalDeviceEnumLock; + ma_bool32 useVerboseDeviceEnumeration; + } alsa; +#endif +#ifdef MA_SUPPORT_PULSEAUDIO + struct + { + ma_handle pulseSO; + ma_proc pa_mainloop_new; + ma_proc pa_mainloop_free; + ma_proc pa_mainloop_quit; + ma_proc pa_mainloop_get_api; + ma_proc pa_mainloop_iterate; + ma_proc pa_mainloop_wakeup; + ma_proc pa_threaded_mainloop_new; + ma_proc pa_threaded_mainloop_free; + ma_proc pa_threaded_mainloop_start; + ma_proc pa_threaded_mainloop_stop; + ma_proc pa_threaded_mainloop_lock; + ma_proc pa_threaded_mainloop_unlock; + ma_proc pa_threaded_mainloop_wait; + ma_proc pa_threaded_mainloop_signal; + ma_proc pa_threaded_mainloop_accept; + ma_proc pa_threaded_mainloop_get_retval; + ma_proc pa_threaded_mainloop_get_api; + ma_proc pa_threaded_mainloop_in_thread; + ma_proc pa_threaded_mainloop_set_name; + 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_set_suspended_callback; + ma_proc pa_stream_set_moved_callback; + ma_proc pa_stream_is_suspended; + 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; + + /*pa_mainloop**/ ma_ptr pMainLoop; + /*pa_context**/ ma_ptr pPulseContext; + char* pApplicationName; /* Set when the context is initialized. Used by devices for their local pa_context objects. */ + char* pServerName; /* Set when the context is initialized. Used by devices for their local pa_context objects. */ + } 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; + + char* pClientName; + ma_bool32 tryStartServer; + } jack; +#endif +#ifdef MA_SUPPORT_COREAUDIO + struct + { + ma_handle hCoreFoundation; + ma_proc CFStringGetCString; + ma_proc CFRelease; + + ma_handle hCoreAudio; + ma_proc AudioObjectGetPropertyData; + ma_proc AudioObjectGetPropertyDataSize; + ma_proc AudioObjectSetPropertyData; + ma_proc AudioObjectAddPropertyListener; + ma_proc AudioObjectRemovePropertyListener; + + 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; + ma_bool32 noAudioSessionDeactivate; /* For tracking whether or not the iOS audio session should be explicitly deactivated. Set from the config in ma_context_init__coreaudio(). */ + } 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_setErrorCallback; + ma_proc AAudioStreamBuilder_setPerformanceMode; + ma_proc AAudioStreamBuilder_setUsage; + ma_proc AAudioStreamBuilder_setContentType; + ma_proc AAudioStreamBuilder_setInputPreset; + ma_proc AAudioStreamBuilder_setAllowedCapturePolicy; + 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; + ma_device_job_thread jobThread; /* For processing operations outside of the error callback, specifically device disconnections and rerouting. */ + } aaudio; +#endif +#ifdef MA_SUPPORT_OPENSL + struct + { + ma_handle libOpenSLES; + ma_handle SL_IID_ENGINE; + ma_handle SL_IID_AUDIOIODEVICECAPABILITIES; + ma_handle SL_IID_ANDROIDSIMPLEBUFFERQUEUE; + ma_handle SL_IID_RECORD; + ma_handle SL_IID_PLAY; + ma_handle SL_IID_OUTPUTMIX; + ma_handle SL_IID_ANDROIDCONFIGURATION; + ma_proc slCreateEngine; + } opensl; +#endif +#ifdef MA_SUPPORT_WEBAUDIO + struct + { + int _unused; + } webaudio; +#endif +#ifdef MA_SUPPORT_NULL + struct + { + int _unused; + } null_backend; +#endif + }; + + union + { +#if defined(MA_WIN32) + struct + { + /*HMODULE*/ ma_handle hOle32DLL; + ma_proc CoInitialize; + 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; + + /*HRESULT*/ long CoInitializeResult; + } win32; +#endif +#ifdef MA_POSIX + struct + { + int _unused; + } posix; +#endif + int _unused; + }; +}; + +struct ma_device +{ + ma_context* pContext; + ma_device_type type; + ma_uint32 sampleRate; + ma_atomic_device_state state; /* The state of the device is variable and can change at any time on any thread. Must be used atomically. */ + ma_device_data_proc onData; /* Set once at initialization time and should not be changed after. */ + ma_device_notification_proc onNotification; /* Set once at initialization time and should not be changed after. */ + ma_stop_proc onStop; /* DEPRECATED. Use the notification callback instead. Set once at initialization time and should not be changed after. */ + void* pUserData; /* Application defined data. */ + ma_mutex startStopLock; + 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_bool8 isOwnerOfContext; /* When set to true, uninitializing the device will also uninitialize the context. Set to true when NULL is passed into ma_device_init(). */ + ma_bool8 noPreSilencedOutputBuffer; + ma_bool8 noClip; + ma_bool8 noDisableDenormals; + ma_bool8 noFixedSizedCallback; + ma_atomic_float masterVolumeFactor; /* Linear 0..1. Can be read and written simultaneously by different threads. Must be used atomically. */ + ma_duplex_rb duplexRB; /* Intermediary buffer for duplex device on asynchronous backends. */ + struct + { + ma_resample_algorithm algorithm; + ma_resampling_backend_vtable* pBackendVTable; + void* pBackendUserData; + struct + { + ma_uint32 lpfOrder; + } linear; + } resampling; + struct + { + ma_device_id* pID; /* Set to NULL if using default ID, otherwise set to the address of "id". */ + ma_device_id id; /* If using an explicit device, will be set to a copy of the ID used for initialization. Otherwise cleared to 0. */ + char name[MA_MAX_DEVICE_NAME_LENGTH + 1]; /* 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_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 internalPeriodSizeInFrames; + ma_uint32 internalPeriods; + ma_channel_mix_mode channelMixMode; + ma_bool32 calculateLFEFromSpatialChannels; + ma_data_converter converter; + void* pIntermediaryBuffer; /* For implementing fixed sized buffer callbacks. Will be null if using variable sized callbacks. */ + ma_uint32 intermediaryBufferCap; + ma_uint32 intermediaryBufferLen; /* How many valid frames are sitting in the intermediary buffer. */ + void* pInputCache; /* In external format. Can be null. */ + ma_uint64 inputCacheCap; + ma_uint64 inputCacheConsumed; + ma_uint64 inputCacheRemaining; + } playback; + struct + { + ma_device_id* pID; /* Set to NULL if using default ID, otherwise set to the address of "id". */ + ma_device_id id; /* If using an explicit device, will be set to a copy of the ID used for initialization. Otherwise cleared to 0. */ + char name[MA_MAX_DEVICE_NAME_LENGTH + 1]; /* 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_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 internalPeriodSizeInFrames; + ma_uint32 internalPeriods; + ma_channel_mix_mode channelMixMode; + ma_bool32 calculateLFEFromSpatialChannels; + ma_data_converter converter; + void* pIntermediaryBuffer; /* For implementing fixed sized buffer callbacks. Will be null if using variable sized callbacks. */ + ma_uint32 intermediaryBufferCap; + ma_uint32 intermediaryBufferLen; /* How many valid frames are sitting in the intermediary buffer. */ + } 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(). internalPeriodSizeInFrames 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 originalPeriodSizeInFrames; + ma_uint32 originalPeriodSizeInMilliseconds; + ma_uint32 originalPeriods; + ma_performance_profile originalPerformanceProfile; + ma_uint32 periodSizeInFramesPlayback; + ma_uint32 periodSizeInFramesCapture; + void* pMappedBufferCapture; + ma_uint32 mappedBufferCaptureCap; + ma_uint32 mappedBufferCaptureLen; + void* pMappedBufferPlayback; + ma_uint32 mappedBufferPlaybackCap; + ma_uint32 mappedBufferPlaybackLen; + ma_atomic_bool32 isStartedCapture; /* Can be read and written simultaneously across different threads. Must be used atomically, and must be 32-bit. */ + ma_atomic_bool32 isStartedPlayback; /* Can be read and written simultaneously across different threads. Must be used atomically, and must be 32-bit. */ + ma_uint32 loopbackProcessID; + ma_bool8 loopbackProcessExclude; + ma_bool8 noAutoConvertSRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM. */ + ma_bool8 noDefaultQualitySRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY. */ + ma_bool8 noHardwareOffloading; + ma_bool8 allowCaptureAutoStreamRouting; + ma_bool8 allowPlaybackAutoStreamRouting; + ma_bool8 isDetachedPlayback; + ma_bool8 isDetachedCapture; + ma_wasapi_usage usage; + void* hAvrtHandle; + ma_mutex rerouteLock; + } 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 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. */ + } winmm; +#endif +#ifdef MA_SUPPORT_ALSA + struct + { + /*snd_pcm_t**/ ma_ptr pPCMPlayback; + /*snd_pcm_t**/ ma_ptr pPCMCapture; + /*struct pollfd**/ void* pPollDescriptorsPlayback; + /*struct pollfd**/ void* pPollDescriptorsCapture; + int pollDescriptorCountPlayback; + int pollDescriptorCountCapture; + int wakeupfdPlayback; /* eventfd for waking up from poll() when the playback device is stopped. */ + int wakeupfdCapture; /* eventfd for waking up from poll() when the capture device is stopped. */ + ma_bool8 isUsingMMapPlayback; + ma_bool8 isUsingMMapCapture; + } alsa; +#endif +#ifdef MA_SUPPORT_PULSEAUDIO + struct + { + /*pa_mainloop**/ ma_ptr pMainLoop; + /*pa_context**/ ma_ptr pPulseContext; + /*pa_stream**/ ma_ptr pStreamPlayback; + /*pa_stream**/ ma_ptr pStreamCapture; + } pulse; +#endif +#ifdef MA_SUPPORT_JACK + struct + { + /*jack_client_t**/ ma_ptr pClient; + /*jack_port_t**/ ma_ptr* ppPortsPlayback; + /*jack_port_t**/ ma_ptr* ppPortsCapture; + float* pIntermediaryBufferPlayback; /* Typed as a float because JACK is always floating point. */ + float* pIntermediaryBufferCapture; + } 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_uint32 audioBufferCapInFrames; /* Only used for input devices. The capacity in frames of each buffer in pAudioBufferList. */ + ma_event stopEvent; + ma_uint32 originalPeriodSizeInFrames; + ma_uint32 originalPeriodSizeInMilliseconds; + ma_uint32 originalPeriods; + ma_performance_profile originalPerformanceProfile; + 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. */ + void* pNotificationHandler; /* Only used on mobile platforms. Obj-C object for handling route changes. */ + } 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_aaudio_usage usage; + ma_aaudio_content_type contentType; + ma_aaudio_input_preset inputPreset; + ma_aaudio_allowed_capture_policy allowedCapturePolicy; + ma_bool32 noAutoStartAfterReroute; + } 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_bool32 isDrainingCapture; + ma_bool32 isDrainingPlayback; + 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; + } opensl; +#endif +#ifdef MA_SUPPORT_WEBAUDIO + struct + { + /* AudioWorklets path. */ + /* EMSCRIPTEN_WEBAUDIO_T */ int audioContext; + /* EMSCRIPTEN_WEBAUDIO_T */ int audioWorklet; + float* pIntermediaryBuffer; + void* pStackBuffer; + ma_result initResult; /* Set to MA_BUSY while initialization is in progress. */ + int deviceIndex; /* We store the device in a list on the JavaScript side. This is used to map our C object to the JS object. */ + } webaudio; +#endif +#ifdef MA_SUPPORT_NULL + struct + { + ma_thread deviceThread; + ma_event operationEvent; + ma_event operationCompletionEvent; + ma_semaphore operationSemaphore; + ma_uint32 operation; + ma_result operationResult; + ma_timer timer; + double priorRunTime; + ma_uint32 currentPeriodFramesRemainingPlayback; + ma_uint32 currentPeriodFramesRemainingCapture; + ma_uint64 lastProcessedFramePlayback; + ma_uint64 lastProcessedFrameCapture; + ma_atomic_bool32 isStarted; /* Read and written by multiple threads. Must be used atomically, and must be 32-bit for compiler compatibility. */ + } null_device; +#endif + }; +}; +#if defined(_MSC_VER) && !defined(__clang__) + #pragma warning(pop) +#elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))) + #pragma GCC diagnostic pop /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */ +#endif + +/* +Initializes a `ma_context_config` object. + + +Return Value +------------ +A `ma_context_config` initialized to defaults. + + +Remarks +------- +You must always use this to initialize the default state of the `ma_context_config` object. Not using this will result in your program breaking when miniaudio +is updated and new members are added to `ma_context_config`. It also sets logical defaults. + +You can override members of the returned object by changing it's members directly. + + +See Also +-------- +ma_context_init() +*/ +MA_API ma_context_config ma_context_config_init(void); + +/* +Initializes a context. + +The context is used for selecting and initializing an appropriate backend and to represent the backend at a more global level than that of an individual +device. There is one context to many devices, and a device is created from a context. A context is required to enumerate devices. + + +Parameters +---------- +backends (in, optional) + A list of backends to try initializing, in priority order. Can be NULL, in which case it uses default priority order. + +backendCount (in, optional) + The number of items in `backend`. Ignored if `backend` is NULL. + +pConfig (in, optional) + The context configuration. + +pContext (in) + A pointer to the context object being initialized. + + +Return Value +------------ +MA_SUCCESS if successful; any other error code otherwise. + + +Thread Safety +------------- +Unsafe. Do not call this function across multiple threads as some backends read and write to global state. + + +Remarks +------- +When `backends` is NULL, the default priority order will be used. Below is a list of backends in priority order: + + |-------------|-----------------------|--------------------------------------------------------| + | Name | Enum Name | Supported Operating Systems | + |-------------|-----------------------|--------------------------------------------------------| + | WASAPI | ma_backend_wasapi | Windows Vista+ | + | DirectSound | ma_backend_dsound | Windows XP+ | + | WinMM | ma_backend_winmm | Windows XP+ (may work on older versions, but untested) | + | Core Audio | ma_backend_coreaudio | macOS, iOS | + | ALSA | ma_backend_alsa | Linux | + | PulseAudio | ma_backend_pulseaudio | Cross Platform (disabled on Windows, BSD and Android) | + | JACK | ma_backend_jack | Cross Platform (disabled on BSD and Android) | + | sndio | ma_backend_sndio | OpenBSD | + | audio(4) | ma_backend_audio4 | NetBSD, OpenBSD | + | OSS | ma_backend_oss | FreeBSD | + | AAudio | ma_backend_aaudio | Android 8+ | + | OpenSL|ES | ma_backend_opensl | Android (API level 16+) | + | Web Audio | ma_backend_webaudio | Web (via Emscripten) | + | Null | ma_backend_null | Cross Platform (not used on Web) | + |-------------|-----------------------|--------------------------------------------------------| + +The context can be configured via the `pConfig` argument. The config object is initialized with `ma_context_config_init()`. Individual configuration settings +can then be set directly on the structure. Below are the members of the `ma_context_config` object. + + pLog + A pointer to the `ma_log` to post log messages to. Can be NULL if the application does not + require logging. See the `ma_log` API for details on how to use the logging system. + + threadPriority + The desired priority to use for the audio thread. Allowable values include the following: + + |--------------------------------------| + | Thread Priority | + |--------------------------------------| + | ma_thread_priority_idle | + | ma_thread_priority_lowest | + | ma_thread_priority_low | + | ma_thread_priority_normal | + | ma_thread_priority_high | + | ma_thread_priority_highest (default) | + | ma_thread_priority_realtime | + | ma_thread_priority_default | + |--------------------------------------| + + threadStackSize + The desired size of the stack for the audio thread. Defaults to the operating system's default. + + pUserData + A pointer to application-defined data. This can be accessed from the context object directly such as `context.pUserData`. + + allocationCallbacks + Structure containing custom allocation callbacks. Leaving this at defaults will cause it to use MA_MALLOC, MA_REALLOC and MA_FREE. These allocation + callbacks will be used for anything tied to the context, including devices. + + alsa.useVerboseDeviceEnumeration + ALSA will typically enumerate many different devices which can be intrusive and not user-friendly. To combat this, miniaudio will enumerate only unique + card/device pairs by default. The problem with this is that you lose a bit of flexibility and control. Setting alsa.useVerboseDeviceEnumeration makes + it so the ALSA backend includes all devices. Defaults to false. + + pulse.pApplicationName + PulseAudio only. The application name to use when initializing the PulseAudio context with `pa_context_new()`. + + pulse.pServerName + PulseAudio only. The name of the server to connect to with `pa_context_connect()`. + + pulse.tryAutoSpawn + PulseAudio only. Whether or not to try automatically starting the PulseAudio daemon. Defaults to false. If you set this to true, keep in mind that + miniaudio uses a trial and error method to find the most appropriate backend, and this will result in the PulseAudio daemon starting which may be + intrusive for the end user. + + coreaudio.sessionCategory + iOS only. The session category to use for the shared AudioSession instance. Below is a list of allowable values and their Core Audio equivalents. + + |-----------------------------------------|-------------------------------------| + | miniaudio Token | Core Audio Token | + |-----------------------------------------|-------------------------------------| + | ma_ios_session_category_ambient | AVAudioSessionCategoryAmbient | + | ma_ios_session_category_solo_ambient | AVAudioSessionCategorySoloAmbient | + | ma_ios_session_category_playback | AVAudioSessionCategoryPlayback | + | ma_ios_session_category_record | AVAudioSessionCategoryRecord | + | ma_ios_session_category_play_and_record | AVAudioSessionCategoryPlayAndRecord | + | ma_ios_session_category_multi_route | AVAudioSessionCategoryMultiRoute | + | ma_ios_session_category_none | AVAudioSessionCategoryAmbient | + | ma_ios_session_category_default | AVAudioSessionCategoryAmbient | + |-----------------------------------------|-------------------------------------| + + coreaudio.sessionCategoryOptions + iOS only. Session category options to use with the shared AudioSession instance. Below is a list of allowable values and their Core Audio equivalents. + + |---------------------------------------------------------------------------|------------------------------------------------------------------| + | miniaudio Token | Core Audio Token | + |---------------------------------------------------------------------------|------------------------------------------------------------------| + | ma_ios_session_category_option_mix_with_others | AVAudioSessionCategoryOptionMixWithOthers | + | ma_ios_session_category_option_duck_others | AVAudioSessionCategoryOptionDuckOthers | + | ma_ios_session_category_option_allow_bluetooth | AVAudioSessionCategoryOptionAllowBluetooth | + | ma_ios_session_category_option_default_to_speaker | AVAudioSessionCategoryOptionDefaultToSpeaker | + | ma_ios_session_category_option_interrupt_spoken_audio_and_mix_with_others | AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers | + | ma_ios_session_category_option_allow_bluetooth_a2dp | AVAudioSessionCategoryOptionAllowBluetoothA2DP | + | ma_ios_session_category_option_allow_air_play | AVAudioSessionCategoryOptionAllowAirPlay | + |---------------------------------------------------------------------------|------------------------------------------------------------------| + + coreaudio.noAudioSessionActivate + iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:true] on initialization. + + coreaudio.noAudioSessionDeactivate + iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:false] on uninitialization. + + jack.pClientName + The name of the client to pass to `jack_client_open()`. + + jack.tryStartServer + Whether or not to try auto-starting the JACK server. Defaults to false. + + +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. + +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. + + +Example 1 - Default Initialization +---------------------------------- +The example below shows how to initialize the context using the default configuration. + +```c +ma_context context; +ma_result result = ma_context_init(NULL, 0, NULL, &context); +if (result != MA_SUCCESS) { + // Error. +} +``` + + +Example 2 - Custom Configuration +-------------------------------- +The example below shows how to initialize the context using custom backend priorities and a custom configuration. In this hypothetical example, the program +wants to prioritize ALSA over PulseAudio on Linux. They also want to avoid using the WinMM backend on Windows because it's latency is too high. They also +want an error to be returned if no valid backend is available which they achieve by excluding the Null backend. + +For the configuration, the program wants to capture any log messages so they can, for example, route it to a log file and user interface. + +```c +ma_backend backends[] = { + ma_backend_alsa, + ma_backend_pulseaudio, + ma_backend_wasapi, + ma_backend_dsound +}; + +ma_log log; +ma_log_init(&log); +ma_log_register_callback(&log, ma_log_callback_init(my_log_callbac, pMyLogUserData)); + +ma_context_config config = ma_context_config_init(); +config.pLog = &log; // Specify a custom log object in the config so any logs that are posted from ma_context_init() are captured. + +ma_context context; +ma_result result = ma_context_init(backends, sizeof(backends)/sizeof(backends[0]), &config, &context); +if (result != MA_SUCCESS) { + // Error. + if (result == MA_NO_BACKEND) { + // Couldn't find an appropriate backend. + } +} + +// You could also attach a log callback post-initialization: +ma_log_register_callback(ma_context_get_log(&context), ma_log_callback_init(my_log_callback, pMyLogUserData)); +``` + + +See Also +-------- +ma_context_config_init() +ma_context_uninit() +*/ +MA_API ma_result ma_context_init(const ma_backend backends[], ma_uint32 backendCount, const ma_context_config* pConfig, ma_context* pContext); + +/* +Uninitializes a context. + + +Return Value +------------ +MA_SUCCESS if successful; any other error code otherwise. + + +Thread Safety +------------- +Unsafe. Do not call this function across multiple threads as some backends read and write to global state. + + +Remarks +------- +Results are undefined if you call this while any device created by this context is still active. + + +See Also +-------- +ma_context_init() +*/ +MA_API ma_result ma_context_uninit(ma_context* pContext); + +/* +Retrieves the size of the ma_context object. + +This is mainly for the purpose of bindings to know how much memory to allocate. +*/ +MA_API size_t ma_context_sizeof(void); + +/* +Retrieves a pointer to the log object associated with this context. + + +Remarks +------- +Pass the returned pointer to `ma_log_post()`, `ma_log_postv()` or `ma_log_postf()` to post a log +message. + +You can attach your own logging callback to the log with `ma_log_register_callback()` + + +Return Value +------------ +A pointer to the `ma_log` object that the context uses to post log messages. If some error occurs, +NULL will be returned. +*/ +MA_API ma_log* ma_context_get_log(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. + +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. + +Returning false from the callback will stop enumeration. Returning true will continue enumeration. + + +Parameters +---------- +pContext (in) + A pointer to the context performing the enumeration. + +callback (in) + The callback to fire for each enumerated device. + +pUserData (in) + A pointer to application-defined data passed to the callback. + + +Return Value +------------ +MA_SUCCESS if successful; any other error code otherwise. + + +Thread Safety +------------- +Safe. This is guarded using a simple mutex lock. + + +Remarks +------- +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. + +In general, you should not do anything complicated from within the callback. In particular, do not try initializing a device from within the callback. Also, +do not try to call `ma_context_get_device_info()` 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. + + +Example 1 - Simple Enumeration +------------------------------ +ma_bool32 ma_device_enum_callback(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pInfo, void* pUserData) +{ + printf("Device Name: %s\n", pInfo->name); + return MA_TRUE; +} + +ma_result result = ma_context_enumerate_devices(&context, my_device_enum_callback, pMyUserData); +if (result != MA_SUCCESS) { + // Error. +} + + +See Also +-------- +ma_context_get_devices() +*/ +MA_API 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. + +This function will allocate memory internally for the device lists and return a pointer to them through the `ppPlaybackDeviceInfos` and `ppCaptureDeviceInfos` +parameters. If you do not want to incur the overhead of these allocations consider using `ma_context_enumerate_devices()` which will instead use a callback. + + +Parameters +---------- +pContext (in) + A pointer to the context performing the enumeration. + +ppPlaybackDeviceInfos (out) + A pointer to a pointer that will receive the address of a buffer containing the list of `ma_device_info` structures for playback devices. + +pPlaybackDeviceCount (out) + A pointer to an unsigned integer that will receive the number of playback devices. + +ppCaptureDeviceInfos (out) + A pointer to a pointer that will receive the address of a buffer containing the list of `ma_device_info` structures for capture devices. + +pCaptureDeviceCount (out) + A pointer to an unsigned integer that will receive the number of capture devices. + + +Return Value +------------ +MA_SUCCESS if successful; any other error code otherwise. + + +Thread Safety +------------- +Unsafe. 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. + + +Remarks +------- +It is _not_ safe to assume the first device in the list is the default device. + +You can pass in NULL for the playback or capture lists in which case they'll be ignored. + +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. + + +See Also +-------- +ma_context_get_devices() +*/ +MA_API 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 of the given type, with the specified ID and share mode. + + +Parameters +---------- +pContext (in) + A pointer to the context performing the query. + +deviceType (in) + The type of the device being queried. Must be either `ma_device_type_playback` or `ma_device_type_capture`. + +pDeviceID (in) + The ID of the device being queried. + +pDeviceInfo (out) + A pointer to the `ma_device_info` structure that will receive the device information. + + +Return Value +------------ +MA_SUCCESS if successful; any other error code otherwise. + + +Thread Safety +------------- +Safe. This is guarded using a simple mutex lock. + + +Remarks +------- +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 whether 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. +*/ +MA_API ma_result ma_context_get_device_info(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo); + +/* +Determines if the given context supports loopback mode. + + +Parameters +---------- +pContext (in) + A pointer to the context getting queried. + + +Return Value +------------ +MA_TRUE if the context supports loopback mode; MA_FALSE otherwise. +*/ +MA_API ma_bool32 ma_context_is_loopback_supported(ma_context* pContext); + + + +/* +Initializes a device config with default settings. + + +Parameters +---------- +deviceType (in) + The type of the device this config is being initialized for. This must set to one of the following: + + |-------------------------| + | Device Type | + |-------------------------| + | ma_device_type_playback | + | ma_device_type_capture | + | ma_device_type_duplex | + | ma_device_type_loopback | + |-------------------------| + + +Return Value +------------ +A new device config object with default settings. You will typically want to adjust the config after this function returns. See remarks. + + +Thread Safety +------------- +Safe. + + +Callback Safety +--------------- +Safe, but don't try initializing a device in a callback. + + +Remarks +------- +The returned config will be initialized to defaults. You will normally want to customize a few variables before initializing the device. See Example 1 for a +typical configuration which sets the sample format, channel count, sample rate, data callback and user data. These are usually things you will want to change +before initializing the device. + +See `ma_device_init()` for details on specific configuration options. + + +Example 1 - Simple Configuration +-------------------------------- +The example below is what a program will typically want to configure for each device at a minimum. Notice how `ma_device_config_init()` is called first, and +then the returned object is modified directly. This is important because it ensures that your program continues to work as new configuration options are added +to the `ma_device_config` structure. + +```c +ma_device_config config = ma_device_config_init(ma_device_type_playback); +config.playback.format = ma_format_f32; +config.playback.channels = 2; +config.sampleRate = 48000; +config.dataCallback = ma_data_callback; +config.pUserData = pMyUserData; +``` + + +See Also +-------- +ma_device_init() +ma_device_init_ex() +*/ +MA_API ma_device_config ma_device_config_init(ma_device_type deviceType); + + +/* +Initializes a device. + +A device represents a physical audio device. The idea is you send or receive audio data from the device to either play it back through a speaker, or capture it +from a microphone. Whether or not you should send or receive data from the device (or both) depends on the type of device you are initializing which can be +playback, capture, full-duplex or loopback. (Note that loopback mode is only supported on select backends.) Sending and receiving audio data to and from the +device is done via a callback which is fired by miniaudio at periodic time intervals. + +The frequency at which data is delivered to and from a device depends on the size of it's period. The size of the period can be defined in terms of PCM frames +or milliseconds, whichever is more convenient. Generally speaking, the smaller the period, the lower the latency at the expense of higher CPU usage and +increased risk of glitching due to the more frequent and granular data deliver intervals. The size of a period will depend on your requirements, but +miniaudio's defaults should work fine for most scenarios. If you're building a game you should leave this fairly small, whereas if you're building a simple +media player you can make it larger. Note that the period size you request is actually just a hint - miniaudio will tell the backend what you want, but the +backend is ultimately responsible for what it gives you. You cannot assume you will get exactly what you ask for. + +When delivering data to and from a device you need to make sure it's in the correct format which you can set through the device configuration. You just set the +format that you want to use and miniaudio will perform all of the necessary conversion for you internally. When delivering data to and from the callback you +can assume the format is the same as what you requested when you initialized the device. See Remarks for more details on miniaudio's data conversion pipeline. + + +Parameters +---------- +pContext (in, optional) + A pointer to the context that owns the device. This can be null, in which case it creates a default context internally. + +pConfig (in) + A pointer to the device configuration. Cannot be null. See remarks for details. + +pDevice (out) + A pointer to the device object being initialized. + + +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. The same applies to +calling this at the same time as `ma_device_uninit()`. + + +Callback Safety +--------------- +Unsafe. It is not safe to call this inside any callback. + + +Remarks +------- +Setting `pContext` to NULL will result in miniaudio creating a default context internally and is equivalent to passing in a context initialized like so: + + ```c + ma_context_init(NULL, 0, NULL, &context); + ``` + +Do not set `pContext` to NULL 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 can be configured via the `pConfig` argument. The config object is initialized with `ma_device_config_init()`. Individual configuration settings can +then be set directly on the structure. Below are the members of the `ma_device_config` object. + + deviceType + Must be `ma_device_type_playback`, `ma_device_type_capture`, `ma_device_type_duplex` of `ma_device_type_loopback`. + + sampleRate + The sample rate, in hertz. The most common sample rates are 48000 and 44100. Setting this to 0 will use the device's native sample rate. + + periodSizeInFrames + The desired size of a period in PCM frames. If this is 0, `periodSizeInMilliseconds` will be used instead. If both are 0 the default buffer size will + be used depending on the selected performance profile. This value affects latency. See below for details. + + periodSizeInMilliseconds + The desired size of a period in milliseconds. If this is 0, `periodSizeInFrames` will be used instead. If both are 0 the default buffer size will be + used depending on the selected performance profile. The value affects latency. See below for details. + + periods + The number of periods making up the device's entire buffer. The total buffer size is `periodSizeInFrames` or `periodSizeInMilliseconds` multiplied by + this value. This is just a hint as backends will be the ones who ultimately decide how your periods will be configured. + + performanceProfile + A hint to miniaudio as to the performance requirements of your program. Can be either `ma_performance_profile_low_latency` (default) or + `ma_performance_profile_conservative`. This mainly affects the size of default buffers and can usually be left at it's default value. + + noPreSilencedOutputBuffer + When set to true, the contents of the output buffer passed into the data callback will be left undefined. When set to false (default), the contents of + the output buffer will be cleared the zero. You can use this to avoid the overhead of zeroing out the buffer if you can guarantee that your data + callback will write to every sample in the output buffer, or if you are doing your own clearing. + + noClip + When set to true, the contents of the output buffer are left alone after returning and it will be left up to the backend itself to decide whether or + not to clip. When set to false (default), the contents of the output buffer passed into the data callback will be clipped after returning. This only + applies when the playback sample format is f32. + + noDisableDenormals + By default, miniaudio will disable denormals when the data callback is called. Setting this to true will prevent the disabling of denormals. + + noFixedSizedCallback + Allows miniaudio to fire the data callback with any frame count. When this is set to false (the default), the data callback will be fired with a + consistent frame count as specified by `periodSizeInFrames` or `periodSizeInMilliseconds`. When set to true, miniaudio will fire the callback with + whatever the backend requests, which could be anything. + + dataCallback + The callback to fire whenever data is ready to be delivered to or from the device. + + notificationCallback + The callback to fire when something has changed with the device, such as whether or not it has been started or stopped. + + pUserData + The user data pointer to use with the device. You can access this directly from the device object like `device.pUserData`. + + resampling.algorithm + The resampling algorithm to use when miniaudio needs to perform resampling between the rate specified by `sampleRate` and the device's native rate. The + default value is `ma_resample_algorithm_linear`, and the quality can be configured with `resampling.linear.lpfOrder`. + + resampling.pBackendVTable + A pointer to an optional vtable that can be used for plugging in a custom resampler. + + resampling.pBackendUserData + A pointer that will passed to callbacks in pBackendVTable. + + resampling.linear.lpfOrder + The linear resampler applies a low-pass filter as part of it's processing for anti-aliasing. This setting controls the order of the filter. The higher + the value, the better the quality, in general. Setting this to 0 will disable low-pass filtering altogether. The maximum value is + `MA_MAX_FILTER_ORDER`. The default value is `min(4, MA_MAX_FILTER_ORDER)`. + + playback.pDeviceID + A pointer to a `ma_device_id` structure containing the ID of the playback device to initialize. Setting this NULL (default) will use the system's + default playback device. Retrieve the device ID from the `ma_device_info` structure, which can be retrieved using device enumeration. + + playback.format + The sample format to use for playback. When set to `ma_format_unknown` the device's native format will be used. This can be retrieved after + initialization from the device object directly with `device.playback.format`. + + playback.channels + The number of channels to use for playback. When set to 0 the device's native channel count will be used. This can be retrieved after initialization + from the device object directly with `device.playback.channels`. + + playback.pChannelMap + The channel map to use for playback. When left empty, the device's native channel map will be used. This can be retrieved after initialization from the + device object direct with `device.playback.pChannelMap`. When set, the buffer should contain `channels` items. + + playback.shareMode + The preferred share mode to use for playback. Can be either `ma_share_mode_shared` (default) or `ma_share_mode_exclusive`. Note that if you specify + exclusive mode, but it's not supported by the backend, initialization will fail. You can then fall back to shared mode if desired by changing this to + ma_share_mode_shared and reinitializing. + + capture.pDeviceID + A pointer to a `ma_device_id` structure containing the ID of the capture device to initialize. Setting this NULL (default) will use the system's + default capture device. Retrieve the device ID from the `ma_device_info` structure, which can be retrieved using device enumeration. + + capture.format + The sample format to use for capture. When set to `ma_format_unknown` the device's native format will be used. This can be retrieved after + initialization from the device object directly with `device.capture.format`. + + capture.channels + The number of channels to use for capture. When set to 0 the device's native channel count will be used. This can be retrieved after initialization + from the device object directly with `device.capture.channels`. + + capture.pChannelMap + The channel map to use for capture. When left empty, the device's native channel map will be used. This can be retrieved after initialization from the + device object direct with `device.capture.pChannelMap`. When set, the buffer should contain `channels` items. + + capture.shareMode + The preferred share mode to use for capture. Can be either `ma_share_mode_shared` (default) or `ma_share_mode_exclusive`. Note that if you specify + exclusive mode, but it's not supported by the backend, initialization will fail. You can then fall back to shared mode if desired by changing this to + ma_share_mode_shared and reinitializing. + + wasapi.noAutoConvertSRC + WASAPI only. When set to true, disables WASAPI's automatic resampling and forces the use of miniaudio's resampler. Defaults to false. + + wasapi.noDefaultQualitySRC + WASAPI only. Only used when `wasapi.noAutoConvertSRC` is set to false. When set to true, disables the use of `AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY`. + You should usually leave this set to false, which is the default. + + wasapi.noAutoStreamRouting + WASAPI only. When set to true, disables automatic stream routing on the WASAPI backend. Defaults to false. + + wasapi.noHardwareOffloading + WASAPI only. When set to true, disables the use of WASAPI's hardware offloading feature. Defaults to false. + + alsa.noMMap + ALSA only. When set to true, disables MMap mode. Defaults to false. + + alsa.noAutoFormat + ALSA only. When set to true, disables ALSA's automatic format conversion by including the SND_PCM_NO_AUTO_FORMAT flag. Defaults to false. + + alsa.noAutoChannels + ALSA only. When set to true, disables ALSA's automatic channel conversion by including the SND_PCM_NO_AUTO_CHANNELS flag. Defaults to false. + + alsa.noAutoResample + ALSA only. When set to true, disables ALSA's automatic resampling by including the SND_PCM_NO_AUTO_RESAMPLE flag. Defaults to false. + + pulse.pStreamNamePlayback + PulseAudio only. Sets the stream name for playback. + + pulse.pStreamNameCapture + PulseAudio only. Sets the stream name for capture. + + coreaudio.allowNominalSampleRateChange + Core Audio only. Desktop only. When enabled, allows the sample rate of the device to be changed at the operating system level. This + is disabled by default in order to prevent intrusive changes to the user's system. This is useful if you want to use a sample rate + that is known to be natively supported by the hardware thereby avoiding the cost of resampling. When set to true, miniaudio will + find the closest match between the sample rate requested in the device config and the sample rates natively supported by the + hardware. When set to false, the sample rate currently set by the operating system will always be used. + + opensl.streamType + OpenSL only. Explicitly sets the stream type. If left unset (`ma_opensl_stream_type_default`), the + stream type will be left unset. Think of this as the type of audio you're playing. + + opensl.recordingPreset + OpenSL only. Explicitly sets the type of recording your program will be doing. When left + unset, the recording preset will be left unchanged. + + aaudio.usage + AAudio only. Explicitly sets the nature of the audio the program will be consuming. When + left unset, the usage will be left unchanged. + + aaudio.contentType + AAudio only. Sets the content type. When left unset, the content type will be left unchanged. + + aaudio.inputPreset + AAudio only. Explicitly sets the type of recording your program will be doing. When left + unset, the input preset will be left unchanged. + + aaudio.noAutoStartAfterReroute + AAudio only. Controls whether or not the device should be automatically restarted after a + stream reroute. When set to false (default) the device will be restarted automatically; + otherwise the device will be stopped. + + +Once initialized, the device's config is immutable. If you need to change the config you will need to initialize a new device. + +After initializing the device it will be in a stopped state. To start it, use `ma_device_start()`. + +If both `periodSizeInFrames` and `periodSizeInMilliseconds` are set to zero, it will default to `MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY` or +`MA_DEFAULT_PERIOD_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 the config +and the format used internally by the backend. If you pass in 0 for the sample format, channel count, sample rate _and_ channel map, data transmission will run +on an optimized pass-through fast path. You can retrieve the format, channel count and sample rate by inspecting the `playback/capture.format`, +`playback/capture.channels` and `sampleRate` members of the device object. + +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. + + +Example 1 - Simple Initialization +--------------------------------- +This example shows how to initialize a simple playback device using a standard configuration. If you are just needing to do simple playback from the default +playback device this is usually all you need. + +```c +ma_device_config config = ma_device_config_init(ma_device_type_playback); +config.playback.format = ma_format_f32; +config.playback.channels = 2; +config.sampleRate = 48000; +config.dataCallback = ma_data_callback; +config.pMyUserData = pMyUserData; + +ma_device device; +ma_result result = ma_device_init(NULL, &config, &device); +if (result != MA_SUCCESS) { + // Error +} +``` + + +Example 2 - Advanced Initialization +----------------------------------- +This example shows how you might do some more advanced initialization. In this hypothetical example we want to control the latency by setting the buffer size +and period count. We also want to allow the user to be able to choose which device to output from which means we need a context so we can perform device +enumeration. + +```c +ma_context context; +ma_result result = ma_context_init(NULL, 0, NULL, &context); +if (result != MA_SUCCESS) { + // Error +} + +ma_device_info* pPlaybackDeviceInfos; +ma_uint32 playbackDeviceCount; +result = ma_context_get_devices(&context, &pPlaybackDeviceInfos, &playbackDeviceCount, NULL, NULL); +if (result != MA_SUCCESS) { + // Error +} + +// ... choose a device from pPlaybackDeviceInfos ... + +ma_device_config config = ma_device_config_init(ma_device_type_playback); +config.playback.pDeviceID = pMyChosenDeviceID; // <-- Get this from the `id` member of one of the `ma_device_info` objects returned by ma_context_get_devices(). +config.playback.format = ma_format_f32; +config.playback.channels = 2; +config.sampleRate = 48000; +config.dataCallback = ma_data_callback; +config.pUserData = pMyUserData; +config.periodSizeInMilliseconds = 10; +config.periods = 3; + +ma_device device; +result = ma_device_init(&context, &config, &device); +if (result != MA_SUCCESS) { + // Error +} +``` + + +See Also +-------- +ma_device_config_init() +ma_device_uninit() +ma_device_start() +ma_context_init() +ma_context_get_devices() +ma_context_enumerate_devices() +*/ +MA_API 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. + +This is the same as `ma_device_init()`, only instead of a context being passed in, the parameters from `ma_context_init()` are passed in instead. This function +allows you to configure the internally created context. + + +Parameters +---------- +backends (in, optional) + A list of backends to try initializing, in priority order. Can be NULL, in which case it uses default priority order. + +backendCount (in, optional) + The number of items in `backend`. Ignored if `backend` is NULL. + +pContextConfig (in, optional) + The context configuration. + +pConfig (in) + A pointer to the device configuration. Cannot be null. See remarks for details. + +pDevice (out) + A pointer to the device object being initialized. + + +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. The same applies to +calling this at the same time as `ma_device_uninit()`. + + +Callback Safety +--------------- +Unsafe. It is not safe to call this inside any callback. + + +Remarks +------- +You only need to use this function if you want to configure the context differently to it's defaults. You should never use this function if you want to manage +your own context. + +See the documentation for `ma_context_init()` for information on the different context configuration options. + + +See Also +-------- +ma_device_init() +ma_device_uninit() +ma_device_config_init() +ma_context_init() +*/ +MA_API 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. + + +Parameters +---------- +pDevice (in) + A pointer to the device to stop. + + +Return Value +------------ +Nothing + + +Thread Safety +------------- +Unsafe. As soon as this API is called the device should be considered undefined. + + +Callback Safety +--------------- +Unsafe. It is not safe to call this inside any callback. Doing this will result in a deadlock. + + +See Also +-------- +ma_device_init() +ma_device_stop() +*/ +MA_API void ma_device_uninit(ma_device* pDevice); + + +/* +Retrieves a pointer to the context that owns the given device. +*/ +MA_API ma_context* ma_device_get_context(ma_device* pDevice); + +/* +Helper function for retrieving the log object associated with the context that owns this device. +*/ +MA_API ma_log* ma_device_get_log(ma_device* pDevice); + + +/* +Retrieves information about the device. + + +Parameters +---------- +pDevice (in) + A pointer to the device whose information is being retrieved. + +type (in) + The device type. This parameter is required for duplex devices. When retrieving device + information, you are doing so for an individual playback or capture device. + +pDeviceInfo (out) + A pointer to the `ma_device_info` that will receive the device information. + + +Return Value +------------ +MA_SUCCESS if successful; any other error code otherwise. + + +Thread Safety +------------- +Unsafe. This should be considered unsafe because it may be calling into the backend which may or +may not be safe. + + +Callback Safety +--------------- +Unsafe. You should avoid calling this in the data callback because it may call into the backend +which may or may not be safe. +*/ +MA_API ma_result ma_device_get_info(ma_device* pDevice, ma_device_type type, ma_device_info* pDeviceInfo); + + +/* +Retrieves the name of the device. + + +Parameters +---------- +pDevice (in) + A pointer to the device whose information is being retrieved. + +type (in) + The device type. This parameter is required for duplex devices. When retrieving device + information, you are doing so for an individual playback or capture device. + +pName (out) + A pointer to the buffer that will receive the name. + +nameCap (in) + The capacity of the output buffer, including space for the null terminator. + +pLengthNotIncludingNullTerminator (out, optional) + A pointer to the variable that will receive the length of the name, not including the null + terminator. + + +Return Value +------------ +MA_SUCCESS if successful; any other error code otherwise. + + +Thread Safety +------------- +Unsafe. This should be considered unsafe because it may be calling into the backend which may or +may not be safe. + + +Callback Safety +--------------- +Unsafe. You should avoid calling this in the data callback because it may call into the backend +which may or may not be safe. + + +Remarks +------- +If the name does not fully fit into the output buffer, it'll be truncated. You can pass in NULL to +`pName` if you want to first get the length of the name for the purpose of memory allocation of the +output buffer. Allocating a buffer of size `MA_MAX_DEVICE_NAME_LENGTH + 1` should be enough for +most cases and will avoid the need for the inefficiency of calling this function twice. + +This is implemented in terms of `ma_device_get_info()`. +*/ +MA_API ma_result ma_device_get_name(ma_device* pDevice, ma_device_type type, char* pName, size_t nameCap, size_t* pLengthNotIncludingNullTerminator); + + +/* +Starts the device. For playback devices this begins playback. For capture devices it begins recording. + +Use `ma_device_stop()` to stop the device. + + +Parameters +---------- +pDevice (in) + A pointer to the device to start. + + +Return Value +------------ +MA_SUCCESS if successful; any other error code otherwise. + + +Thread Safety +------------- +Safe. It's safe to call this from any thread with the exception of the callback thread. + + +Callback Safety +--------------- +Unsafe. It is not safe to call this inside any callback. + + +Remarks +------- +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. + +Do not call this in any callback. + + +See Also +-------- +ma_device_stop() +*/ +MA_API ma_result ma_device_start(ma_device* pDevice); + +/* +Stops the device. For playback devices this stops playback. For capture devices it stops recording. + +Use `ma_device_start()` to start the device again. + + +Parameters +---------- +pDevice (in) + A pointer to the device to stop. + + +Return Value +------------ +MA_SUCCESS if successful; any other error code otherwise. + + +Thread Safety +------------- +Safe. It's safe to call this from any thread with the exception of the callback thread. + + +Callback Safety +--------------- +Unsafe. It is not safe to call this inside any callback. Doing this will result in a deadlock. + + +Remarks +------- +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). + +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. + +Do not call this in any callback. + + +See Also +-------- +ma_device_start() +*/ +MA_API ma_result ma_device_stop(ma_device* pDevice); + +/* +Determines whether or not the device is started. + + +Parameters +---------- +pDevice (in) + A pointer to the device whose start state is being retrieved. + + +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. + + +Callback Safety +--------------- +Safe. This is implemented as a simple accessor. + + +See Also +-------- +ma_device_start() +ma_device_stop() +*/ +MA_API ma_bool32 ma_device_is_started(const ma_device* pDevice); + + +/* +Retrieves the state of the device. + + +Parameters +---------- +pDevice (in) + A pointer to the device whose state is being retrieved. + + +Return Value +------------ +The current state of the device. The return value will be one of the following: + + +-------------------------------+------------------------------------------------------------------------------+ + | ma_device_state_uninitialized | Will only be returned if the device is in the middle of initialization. | + +-------------------------------+------------------------------------------------------------------------------+ + | ma_device_state_stopped | The device is stopped. The initial state of the device after initialization. | + +-------------------------------+------------------------------------------------------------------------------+ + | ma_device_state_started | The device started and requesting and/or delivering audio data. | + +-------------------------------+------------------------------------------------------------------------------+ + | ma_device_state_starting | The device is in the process of starting. | + +-------------------------------+------------------------------------------------------------------------------+ + | ma_device_state_stopping | The device is in the process of stopping. | + +-------------------------------+------------------------------------------------------------------------------+ + + +Thread Safety +------------- +Safe. This is implemented as a simple accessor. Note that if the device is started or stopped at the same time as this function is called, +there's a possibility the return value could be out of sync. See remarks. + + +Callback Safety +--------------- +Safe. This is implemented as a simple accessor. + + +Remarks +------- +The general flow of a devices state goes like this: + + ``` + ma_device_init() -> ma_device_state_uninitialized -> ma_device_state_stopped + ma_device_start() -> ma_device_state_starting -> ma_device_state_started + ma_device_stop() -> ma_device_state_stopping -> ma_device_state_stopped + ``` + +When the state of the device is changed with `ma_device_start()` or `ma_device_stop()` at this same time as this function is called, the +value returned by this function could potentially be out of sync. If this is significant to your program you need to implement your own +synchronization. +*/ +MA_API ma_device_state ma_device_get_state(const ma_device* pDevice); + + +/* +Performs post backend initialization routines for setting up internal data conversion. + +This should be called whenever the backend is initialized. The only time this should be called from +outside of miniaudio is if you're implementing a custom backend, and you would only do it if you +are reinitializing the backend due to rerouting or reinitializing for some reason. + + +Parameters +---------- +pDevice [in] + A pointer to the device. + +deviceType [in] + The type of the device that was just reinitialized. + +pPlaybackDescriptor [in] + The descriptor of the playback device containing the internal data format and buffer sizes. + +pPlaybackDescriptor [in] + The descriptor of the capture device containing the internal data format and buffer sizes. + + +Return Value +------------ +MA_SUCCESS if successful; any other error otherwise. + + +Thread Safety +------------- +Unsafe. This will be reinitializing internal data converters which may be in use by another thread. + + +Callback Safety +--------------- +Unsafe. This will be reinitializing internal data converters which may be in use by the callback. + + +Remarks +------- +For a duplex device, you can call this for only one side of the system. This is why the deviceType +is specified as a parameter rather than deriving it from the device. + +You do not need to call this manually unless you are doing a custom backend, in which case you need +only do it if you're manually performing rerouting or reinitialization. +*/ +MA_API ma_result ma_device_post_init(ma_device* pDevice, ma_device_type deviceType, const ma_device_descriptor* pPlaybackDescriptor, const ma_device_descriptor* pCaptureDescriptor); + + +/* +Sets the master volume factor for the device. + +The volume factor must be between 0 (silence) and 1 (full volume). Use `ma_device_set_master_volume_db()` to use decibel notation, where 0 is full volume and +values less than 0 decreases the volume. + + +Parameters +---------- +pDevice (in) + A pointer to the device whose volume is being set. + +volume (in) + The new volume factor. Must be >= 0. + + +Return Value +------------ +MA_SUCCESS if the volume was set successfully. +MA_INVALID_ARGS if pDevice is NULL. +MA_INVALID_ARGS if volume is negative. + + +Thread Safety +------------- +Safe. This just sets a local member of the device object. + + +Callback Safety +--------------- +Safe. If you set the volume in the data callback, that data written to the output buffer will have the new volume applied. + + +Remarks +------- +This applies the volume factor across all channels. + +This does not change the operating system's volume. It only affects the volume for the given `ma_device` object's audio stream. + + +See Also +-------- +ma_device_get_master_volume() +ma_device_set_master_volume_db() +ma_device_get_master_volume_db() +*/ +MA_API ma_result ma_device_set_master_volume(ma_device* pDevice, float volume); + +/* +Retrieves the master volume factor for the device. + + +Parameters +---------- +pDevice (in) + A pointer to the device whose volume factor is being retrieved. + +pVolume (in) + A pointer to the variable that will receive the volume factor. The returned value will be in the range of [0, 1]. + + +Return Value +------------ +MA_SUCCESS if successful. +MA_INVALID_ARGS if pDevice is NULL. +MA_INVALID_ARGS if pVolume is NULL. + + +Thread Safety +------------- +Safe. This just a simple member retrieval. + + +Callback Safety +--------------- +Safe. + + +Remarks +------- +If an error occurs, `*pVolume` will be set to 0. + + +See Also +-------- +ma_device_set_master_volume() +ma_device_set_master_volume_gain_db() +ma_device_get_master_volume_gain_db() +*/ +MA_API ma_result ma_device_get_master_volume(ma_device* pDevice, float* pVolume); + +/* +Sets the master volume for the device as gain in decibels. + +A gain of 0 is full volume, whereas a gain of < 0 will decrease the volume. + + +Parameters +---------- +pDevice (in) + A pointer to the device whose gain is being set. + +gainDB (in) + The new volume as gain in decibels. Must be less than or equal to 0, where 0 is full volume and anything less than 0 decreases the volume. + + +Return Value +------------ +MA_SUCCESS if the volume was set successfully. +MA_INVALID_ARGS if pDevice is NULL. +MA_INVALID_ARGS if the gain is > 0. + + +Thread Safety +------------- +Safe. This just sets a local member of the device object. + + +Callback Safety +--------------- +Safe. If you set the volume in the data callback, that data written to the output buffer will have the new volume applied. + + +Remarks +------- +This applies the gain across all channels. + +This does not change the operating system's volume. It only affects the volume for the given `ma_device` object's audio stream. + + +See Also +-------- +ma_device_get_master_volume_gain_db() +ma_device_set_master_volume() +ma_device_get_master_volume() +*/ +MA_API ma_result ma_device_set_master_volume_db(ma_device* pDevice, float gainDB); + +/* +Retrieves the master gain in decibels. + + +Parameters +---------- +pDevice (in) + A pointer to the device whose gain is being retrieved. + +pGainDB (in) + A pointer to the variable that will receive the gain in decibels. The returned value will be <= 0. + + +Return Value +------------ +MA_SUCCESS if successful. +MA_INVALID_ARGS if pDevice is NULL. +MA_INVALID_ARGS if pGainDB is NULL. + + +Thread Safety +------------- +Safe. This just a simple member retrieval. + + +Callback Safety +--------------- +Safe. + + +Remarks +------- +If an error occurs, `*pGainDB` will be set to 0. + + +See Also +-------- +ma_device_set_master_volume_db() +ma_device_set_master_volume() +ma_device_get_master_volume() +*/ +MA_API ma_result ma_device_get_master_volume_db(ma_device* pDevice, float* pGainDB); + + +/* +Called from the data callback of asynchronous backends to allow miniaudio to process the data and fire the miniaudio data callback. + + +Parameters +---------- +pDevice (in) + A pointer to device whose processing the data callback. + +pOutput (out) + A pointer to the buffer that will receive the output PCM frame data. On a playback device this must not be NULL. On a duplex device + this can be NULL, in which case pInput must not be NULL. + +pInput (in) + A pointer to the buffer containing input PCM frame data. On a capture device this must not be NULL. On a duplex device this can be + NULL, in which case `pOutput` must not be NULL. + +frameCount (in) + The number of frames being processed. + + +Return Value +------------ +MA_SUCCESS if successful; any other result code otherwise. + + +Thread Safety +------------- +This function should only ever be called from the internal data callback of the backend. It is safe to call this simultaneously between a +playback and capture device in duplex setups. + + +Callback Safety +--------------- +Do not call this from the miniaudio data callback. It should only ever be called from the internal data callback of the backend. + + +Remarks +------- +If both `pOutput` and `pInput` are NULL, and error will be returned. In duplex scenarios, both `pOutput` and `pInput` can be non-NULL, in +which case `pInput` will be processed first, followed by `pOutput`. + +If you are implementing a custom backend, and that backend uses a callback for data delivery, you'll need to call this from inside that +callback. +*/ +MA_API ma_result ma_device_handle_backend_data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount); + + +/* +Calculates an appropriate buffer size from a descriptor, native sample rate and performance profile. + +This function is used by backends for helping determine an appropriately sized buffer to use with +the device depending on the values of `periodSizeInFrames` and `periodSizeInMilliseconds` in the +`pDescriptor` object. Since buffer size calculations based on time depends on the sample rate, a +best guess at the device's native sample rate is also required which is where `nativeSampleRate` +comes in. In addition, the performance profile is also needed for cases where both the period size +in frames and milliseconds are both zero. + + +Parameters +---------- +pDescriptor (in) + A pointer to device descriptor whose `periodSizeInFrames` and `periodSizeInMilliseconds` members + will be used for the calculation of the buffer size. + +nativeSampleRate (in) + The device's native sample rate. This is only ever used when the `periodSizeInFrames` member of + `pDescriptor` is zero. In this case, `periodSizeInMilliseconds` will be used instead, in which + case a sample rate is required to convert to a size in frames. + +performanceProfile (in) + When both the `periodSizeInFrames` and `periodSizeInMilliseconds` members of `pDescriptor` are + zero, miniaudio will fall back to a buffer size based on the performance profile. The profile + to use for this calculation is determine by this parameter. + + +Return Value +------------ +The calculated buffer size in frames. + + +Thread Safety +------------- +This is safe so long as nothing modifies `pDescriptor` at the same time. However, this function +should only ever be called from within the backend's device initialization routine and therefore +shouldn't have any multithreading concerns. + + +Callback Safety +--------------- +This is safe to call within the data callback, but there is no reason to ever do this. + + +Remarks +------- +If `nativeSampleRate` is zero, this function will fall back to `pDescriptor->sampleRate`. If that +is also zero, `MA_DEFAULT_SAMPLE_RATE` will be used instead. +*/ +MA_API ma_uint32 ma_calculate_buffer_size_in_frames_from_descriptor(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile); + + + +/* +Retrieves a friendly name for a backend. +*/ +MA_API const char* ma_get_backend_name(ma_backend backend); + +/* +Retrieves the backend enum from the given name. +*/ +MA_API ma_result ma_get_backend_from_name(const char* pBackendName, ma_backend* pBackend); + +/* +Determines whether or not the given backend is available by the compilation environment. +*/ +MA_API ma_bool32 ma_is_backend_enabled(ma_backend backend); + +/* +Retrieves compile-time enabled backends. + + +Parameters +---------- +pBackends (out, optional) + A pointer to the buffer that will receive the enabled backends. Set to NULL to retrieve the backend count. Setting + the capacity of the buffer to `MA_BUFFER_COUNT` will guarantee it's large enough for all backends. + +backendCap (in) + The capacity of the `pBackends` buffer. + +pBackendCount (out) + A pointer to the variable that will receive the enabled backend count. + + +Return Value +------------ +MA_SUCCESS if successful. +MA_INVALID_ARGS if `pBackendCount` is NULL. +MA_NO_SPACE if the capacity of `pBackends` is not large enough. + +If `MA_NO_SPACE` is returned, the `pBackends` buffer will be filled with `*pBackendCount` values. + + +Thread Safety +------------- +Safe. + + +Callback Safety +--------------- +Safe. + + +Remarks +------- +If you want to retrieve the number of backends so you can determine the capacity of `pBackends` buffer, you can call +this function with `pBackends` set to NULL. + +This will also enumerate the null backend. If you don't want to include this you need to check for `ma_backend_null` +when you enumerate over the returned backends and handle it appropriately. Alternatively, you can disable it at +compile time with `MA_NO_NULL`. + +The returned backends are determined based on compile time settings, not the platform it's currently running on. For +example, PulseAudio will be returned if it was enabled at compile time, even when the user doesn't actually have +PulseAudio installed. + + +Example 1 +--------- +The example below retrieves the enabled backend count using a fixed sized buffer allocated on the stack. The buffer is +given a capacity of `MA_BACKEND_COUNT` which will guarantee it'll be large enough to store all available backends. +Since `MA_BACKEND_COUNT` is always a relatively small value, this should be suitable for most scenarios. + +``` +ma_backend enabledBackends[MA_BACKEND_COUNT]; +size_t enabledBackendCount; + +result = ma_get_enabled_backends(enabledBackends, MA_BACKEND_COUNT, &enabledBackendCount); +if (result != MA_SUCCESS) { + // Failed to retrieve enabled backends. Should never happen in this example since all inputs are valid. +} +``` + + +See Also +-------- +ma_is_backend_enabled() +*/ +MA_API ma_result ma_get_enabled_backends(ma_backend* pBackends, size_t backendCap, size_t* pBackendCount); + +/* +Determines whether or not loopback mode is support by a backend. +*/ +MA_API ma_bool32 ma_is_loopback_supported(ma_backend backend); + +#endif /* MA_NO_DEVICE_IO */ + + + +/************************************************************************************************************************************************************ + +Utilities + +************************************************************************************************************************************************************/ + +/* +Calculates a buffer size in milliseconds from the specified number of frames and sample rate. +*/ +MA_API 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_API ma_uint32 ma_calculate_buffer_size_in_frames_from_milliseconds(ma_uint32 bufferSizeInMilliseconds, ma_uint32 sampleRate); + +/* +Copies PCM frames from one buffer to another. +*/ +MA_API void ma_copy_pcm_frames(void* dst, const void* src, ma_uint64 frameCount, ma_format format, ma_uint32 channels); + +/* +Copies silent frames into the given buffer. + +Remarks +------- +For all formats except `ma_format_u8`, the output buffer will be filled with 0. For `ma_format_u8` it will be filled with 128. The reason for this is that it +makes more sense for the purpose of mixing to initialize it to the center point. +*/ +MA_API void ma_silence_pcm_frames(void* p, ma_uint64 frameCount, ma_format format, ma_uint32 channels); + + +/* +Offsets a pointer by the specified number of PCM frames. +*/ +MA_API void* ma_offset_pcm_frames_ptr(void* p, ma_uint64 offsetInFrames, ma_format format, ma_uint32 channels); +MA_API const void* ma_offset_pcm_frames_const_ptr(const void* p, ma_uint64 offsetInFrames, ma_format format, ma_uint32 channels); +static MA_INLINE float* ma_offset_pcm_frames_ptr_f32(float* p, ma_uint64 offsetInFrames, ma_uint32 channels) { return (float*)ma_offset_pcm_frames_ptr((void*)p, offsetInFrames, ma_format_f32, channels); } +static MA_INLINE const float* ma_offset_pcm_frames_const_ptr_f32(const float* p, ma_uint64 offsetInFrames, ma_uint32 channels) { return (const float*)ma_offset_pcm_frames_const_ptr((const void*)p, offsetInFrames, ma_format_f32, channels); } + + +/* +Clips samples. +*/ +MA_API void ma_clip_samples_u8(ma_uint8* pDst, const ma_int16* pSrc, ma_uint64 count); +MA_API void ma_clip_samples_s16(ma_int16* pDst, const ma_int32* pSrc, ma_uint64 count); +MA_API void ma_clip_samples_s24(ma_uint8* pDst, const ma_int64* pSrc, ma_uint64 count); +MA_API void ma_clip_samples_s32(ma_int32* pDst, const ma_int64* pSrc, ma_uint64 count); +MA_API void ma_clip_samples_f32(float* pDst, const float* pSrc, ma_uint64 count); +MA_API void ma_clip_pcm_frames(void* pDst, const void* pSrc, ma_uint64 frameCount, ma_format format, ma_uint32 channels); + +/* +Helper for applying a volume factor to samples. + +Note that the source and destination buffers can be the same, in which case it'll perform the operation in-place. +*/ +MA_API void ma_copy_and_apply_volume_factor_u8(ma_uint8* pSamplesOut, const ma_uint8* pSamplesIn, ma_uint64 sampleCount, float factor); +MA_API void ma_copy_and_apply_volume_factor_s16(ma_int16* pSamplesOut, const ma_int16* pSamplesIn, ma_uint64 sampleCount, float factor); +MA_API void ma_copy_and_apply_volume_factor_s24(void* pSamplesOut, const void* pSamplesIn, ma_uint64 sampleCount, float factor); +MA_API void ma_copy_and_apply_volume_factor_s32(ma_int32* pSamplesOut, const ma_int32* pSamplesIn, ma_uint64 sampleCount, float factor); +MA_API void ma_copy_and_apply_volume_factor_f32(float* pSamplesOut, const float* pSamplesIn, ma_uint64 sampleCount, float factor); + +MA_API void ma_apply_volume_factor_u8(ma_uint8* pSamples, ma_uint64 sampleCount, float factor); +MA_API void ma_apply_volume_factor_s16(ma_int16* pSamples, ma_uint64 sampleCount, float factor); +MA_API void ma_apply_volume_factor_s24(void* pSamples, ma_uint64 sampleCount, float factor); +MA_API void ma_apply_volume_factor_s32(ma_int32* pSamples, ma_uint64 sampleCount, float factor); +MA_API void ma_apply_volume_factor_f32(float* pSamples, ma_uint64 sampleCount, float factor); + +MA_API void ma_copy_and_apply_volume_factor_pcm_frames_u8(ma_uint8* pFramesOut, const ma_uint8* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor); +MA_API void ma_copy_and_apply_volume_factor_pcm_frames_s16(ma_int16* pFramesOut, const ma_int16* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor); +MA_API void ma_copy_and_apply_volume_factor_pcm_frames_s24(void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor); +MA_API void ma_copy_and_apply_volume_factor_pcm_frames_s32(ma_int32* pFramesOut, const ma_int32* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor); +MA_API void ma_copy_and_apply_volume_factor_pcm_frames_f32(float* pFramesOut, const float* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor); +MA_API void ma_copy_and_apply_volume_factor_pcm_frames(void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount, ma_format format, ma_uint32 channels, float factor); + +MA_API void ma_apply_volume_factor_pcm_frames_u8(ma_uint8* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor); +MA_API void ma_apply_volume_factor_pcm_frames_s16(ma_int16* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor); +MA_API void ma_apply_volume_factor_pcm_frames_s24(void* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor); +MA_API void ma_apply_volume_factor_pcm_frames_s32(ma_int32* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor); +MA_API void ma_apply_volume_factor_pcm_frames_f32(float* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor); +MA_API void ma_apply_volume_factor_pcm_frames(void* pFrames, ma_uint64 frameCount, ma_format format, ma_uint32 channels, float factor); + +MA_API void ma_copy_and_apply_volume_factor_per_channel_f32(float* pFramesOut, const float* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float* pChannelGains); + + +MA_API void ma_copy_and_apply_volume_and_clip_samples_u8(ma_uint8* pDst, const ma_int16* pSrc, ma_uint64 count, float volume); +MA_API void ma_copy_and_apply_volume_and_clip_samples_s16(ma_int16* pDst, const ma_int32* pSrc, ma_uint64 count, float volume); +MA_API void ma_copy_and_apply_volume_and_clip_samples_s24(ma_uint8* pDst, const ma_int64* pSrc, ma_uint64 count, float volume); +MA_API void ma_copy_and_apply_volume_and_clip_samples_s32(ma_int32* pDst, const ma_int64* pSrc, ma_uint64 count, float volume); +MA_API void ma_copy_and_apply_volume_and_clip_samples_f32(float* pDst, const float* pSrc, ma_uint64 count, float volume); +MA_API void ma_copy_and_apply_volume_and_clip_pcm_frames(void* pDst, const void* pSrc, ma_uint64 frameCount, ma_format format, ma_uint32 channels, float volume); + + +/* +Helper for converting a linear factor to gain in decibels. +*/ +MA_API float ma_volume_linear_to_db(float factor); + +/* +Helper for converting gain in decibels to a linear factor. +*/ +MA_API float ma_volume_db_to_linear(float gain); + + +/* +Mixes the specified number of frames in floating point format with a volume factor. + +This will run on an optimized path when the volume is equal to 1. +*/ +MA_API ma_result ma_mix_pcm_frames_f32(float* pDst, const float* pSrc, ma_uint64 frameCount, ma_uint32 channels, float volume); + + + + +/************************************************************************************************************************************************************ + +VFS +=== + +The VFS object (virtual file system) is what's used to customize file access. This is useful in cases where stdio FILE* based APIs may not be entirely +appropriate for a given situation. + +************************************************************************************************************************************************************/ +typedef void ma_vfs; +typedef ma_handle ma_vfs_file; + +typedef enum +{ + MA_OPEN_MODE_READ = 0x00000001, + MA_OPEN_MODE_WRITE = 0x00000002 +} ma_open_mode_flags; + +typedef enum +{ + ma_seek_origin_start, + ma_seek_origin_current, + ma_seek_origin_end /* Not used by decoders. */ +} ma_seek_origin; + +typedef struct +{ + ma_uint64 sizeInBytes; +} ma_file_info; + +typedef struct +{ + ma_result (* onOpen) (ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile); + ma_result (* onOpenW)(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile); + ma_result (* onClose)(ma_vfs* pVFS, ma_vfs_file file); + ma_result (* onRead) (ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead); + ma_result (* onWrite)(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten); + ma_result (* onSeek) (ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin); + ma_result (* onTell) (ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor); + ma_result (* onInfo) (ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo); +} ma_vfs_callbacks; + +MA_API ma_result ma_vfs_open(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile); +MA_API ma_result ma_vfs_open_w(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile); +MA_API ma_result ma_vfs_close(ma_vfs* pVFS, ma_vfs_file file); +MA_API ma_result ma_vfs_read(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead); +MA_API ma_result ma_vfs_write(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten); +MA_API ma_result ma_vfs_seek(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin); +MA_API ma_result ma_vfs_tell(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor); +MA_API ma_result ma_vfs_info(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo); +MA_API ma_result ma_vfs_open_and_read_file(ma_vfs* pVFS, const char* pFilePath, void** ppData, size_t* pSize, const ma_allocation_callbacks* pAllocationCallbacks); + +typedef struct +{ + ma_vfs_callbacks cb; + ma_allocation_callbacks allocationCallbacks; /* Only used for the wchar_t version of open() on non-Windows platforms. */ +} ma_default_vfs; + +MA_API ma_result ma_default_vfs_init(ma_default_vfs* pVFS, const ma_allocation_callbacks* pAllocationCallbacks); + + + +typedef ma_result (* ma_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead); +typedef ma_result (* ma_seek_proc)(void* pUserData, ma_int64 offset, ma_seek_origin origin); +typedef ma_result (* ma_tell_proc)(void* pUserData, ma_int64* pCursor); + + + +#if !defined(MA_NO_DECODING) || !defined(MA_NO_ENCODING) +typedef enum +{ + ma_encoding_format_unknown = 0, + ma_encoding_format_wav, + ma_encoding_format_flac, + ma_encoding_format_mp3, + ma_encoding_format_vorbis +} ma_encoding_format; +#endif + +/************************************************************************************************************************************************************ + +Decoding +======== + +Decoders are independent of the main device API. Decoding APIs can be called freely inside the device's data callback, but they are not thread safe unless +you do your own synchronization. + +************************************************************************************************************************************************************/ +#ifndef MA_NO_DECODING +typedef struct ma_decoder ma_decoder; + + +typedef struct +{ + ma_format preferredFormat; + ma_uint32 seekPointCount; /* Set to > 0 to generate a seektable if the decoding backend supports it. */ +} ma_decoding_backend_config; + +MA_API ma_decoding_backend_config ma_decoding_backend_config_init(ma_format preferredFormat, ma_uint32 seekPointCount); + + +typedef struct +{ + ma_result (* onInit )(void* pUserData, ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend); + ma_result (* onInitFile )(void* pUserData, const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend); /* Optional. */ + ma_result (* onInitFileW )(void* pUserData, const wchar_t* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend); /* Optional. */ + ma_result (* onInitMemory)(void* pUserData, const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend); /* Optional. */ + void (* onUninit )(void* pUserData, ma_data_source* pBackend, const ma_allocation_callbacks* pAllocationCallbacks); +} ma_decoding_backend_vtable; + + +typedef ma_result (* ma_decoder_read_proc)(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead); /* Returns the number of bytes read. */ +typedef ma_result (* ma_decoder_seek_proc)(ma_decoder* pDecoder, ma_int64 byteOffset, ma_seek_origin origin); +typedef ma_result (* ma_decoder_tell_proc)(ma_decoder* pDecoder, ma_int64* pCursor); + +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* pChannelMap; + ma_channel_mix_mode channelMixMode; + ma_dither_mode ditherMode; + ma_resampler_config resampling; + ma_allocation_callbacks allocationCallbacks; + ma_encoding_format encodingFormat; + ma_uint32 seekPointCount; /* When set to > 0, specifies the number of seek points to use for the generation of a seek table. Not all decoding backends support this. */ + ma_decoding_backend_vtable** ppCustomBackendVTables; + ma_uint32 customBackendCount; + void* pCustomBackendUserData; +} ma_decoder_config; + +struct ma_decoder +{ + ma_data_source_base ds; + ma_data_source* pBackend; /* The decoding backend we'll be pulling data from. */ + const ma_decoding_backend_vtable* pBackendVTable; /* The vtable for the decoding backend. This needs to be stored so we can access the onUninit() callback. */ + void* pBackendUserData; + ma_decoder_read_proc onRead; + ma_decoder_seek_proc onSeek; + ma_decoder_tell_proc onTell; + void* pUserData; + ma_uint64 readPointerInPCMFrames; /* In output sample rate. Used for keeping track of how many frames are available for decoding. */ + ma_format outputFormat; + ma_uint32 outputChannels; + ma_uint32 outputSampleRate; + ma_data_converter converter; /* Data conversion is achieved by running frames through this. */ + void* pInputCache; /* In input format. Can be null if it's not needed. */ + ma_uint64 inputCacheCap; /* The capacity of the input cache. */ + ma_uint64 inputCacheConsumed; /* The number of frames that have been consumed in the cache. Used for determining the next valid frame. */ + ma_uint64 inputCacheRemaining; /* The number of valid frames remaining in the cahce. */ + ma_allocation_callbacks allocationCallbacks; + union + { + struct + { + ma_vfs* pVFS; + ma_vfs_file file; + } vfs; + struct + { + const ma_uint8* pData; + size_t dataSize; + size_t currentReadPos; + } memory; /* Only used for decoders that were opened against a block of memory. */ + } data; +}; + +MA_API ma_decoder_config ma_decoder_config_init(ma_format outputFormat, ma_uint32 outputChannels, ma_uint32 outputSampleRate); +MA_API ma_decoder_config ma_decoder_config_init_default(void); + +MA_API 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_API ma_result ma_decoder_init_memory(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder); +MA_API ma_result ma_decoder_init_vfs(ma_vfs* pVFS, const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder); +MA_API ma_result ma_decoder_init_vfs_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder); +MA_API ma_result ma_decoder_init_file(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder); +MA_API ma_result ma_decoder_init_file_w(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder); + +/* +Uninitializes a decoder. +*/ +MA_API ma_result ma_decoder_uninit(ma_decoder* pDecoder); + +/* +Reads PCM frames from the given decoder. + +This is not thread safe without your own synchronization. +*/ +MA_API ma_result ma_decoder_read_pcm_frames(ma_decoder* pDecoder, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead); + +/* +Seeks to a PCM frame based on it's absolute index. + +This is not thread safe without your own synchronization. +*/ +MA_API ma_result ma_decoder_seek_to_pcm_frame(ma_decoder* pDecoder, ma_uint64 frameIndex); + +/* +Retrieves the decoder's output data format. +*/ +MA_API ma_result ma_decoder_get_data_format(ma_decoder* pDecoder, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap); + +/* +Retrieves the current position of the read cursor in PCM frames. +*/ +MA_API ma_result ma_decoder_get_cursor_in_pcm_frames(ma_decoder* pDecoder, ma_uint64* pCursor); + +/* +Retrieves the length of the decoder in PCM frames. + +Do not call this on streams of an undefined length, such as internet radio. + +If the length is unknown or an error occurs, 0 will be returned. + +This will always return 0 for Vorbis decoders. This is due to a limitation with stb_vorbis in push mode which is what miniaudio +uses internally. + +For MP3's, this will decode the entire file. Do not call this in time critical scenarios. + +This function is not thread safe without your own synchronization. +*/ +MA_API ma_result ma_decoder_get_length_in_pcm_frames(ma_decoder* pDecoder, ma_uint64* pLength); + +/* +Retrieves the number of frames that can be read before reaching the end. + +This calls `ma_decoder_get_length_in_pcm_frames()` so you need to be aware of the rules for that function, in +particular ensuring you do not call it on streams of an undefined length, such as internet radio. + +If the total length of the decoder cannot be retrieved, such as with Vorbis decoders, `MA_NOT_IMPLEMENTED` will be +returned. +*/ +MA_API ma_result ma_decoder_get_available_frames(ma_decoder* pDecoder, ma_uint64* pAvailableFrames); + +/* +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. +*/ +MA_API ma_result ma_decode_from_vfs(ma_vfs* pVFS, const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut); +MA_API ma_result ma_decode_file(const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut); +MA_API ma_result ma_decode_memory(const void* pData, size_t dataSize, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut); + +#endif /* MA_NO_DECODING */ + + +/************************************************************************************************************************************************************ + +Encoding +======== + +Encoders do not perform any format conversion for you. If your target format does not support the format, and error will be returned. + +************************************************************************************************************************************************************/ +#ifndef MA_NO_ENCODING +typedef struct ma_encoder ma_encoder; + +typedef ma_result (* ma_encoder_write_proc) (ma_encoder* pEncoder, const void* pBufferIn, size_t bytesToWrite, size_t* pBytesWritten); +typedef ma_result (* ma_encoder_seek_proc) (ma_encoder* pEncoder, ma_int64 offset, ma_seek_origin origin); +typedef ma_result (* ma_encoder_init_proc) (ma_encoder* pEncoder); +typedef void (* ma_encoder_uninit_proc) (ma_encoder* pEncoder); +typedef ma_result (* ma_encoder_write_pcm_frames_proc)(ma_encoder* pEncoder, const void* pFramesIn, ma_uint64 frameCount, ma_uint64* pFramesWritten); + +typedef struct +{ + ma_encoding_format encodingFormat; + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + ma_allocation_callbacks allocationCallbacks; +} ma_encoder_config; + +MA_API ma_encoder_config ma_encoder_config_init(ma_encoding_format encodingFormat, ma_format format, ma_uint32 channels, ma_uint32 sampleRate); + +struct ma_encoder +{ + ma_encoder_config config; + ma_encoder_write_proc onWrite; + ma_encoder_seek_proc onSeek; + ma_encoder_init_proc onInit; + ma_encoder_uninit_proc onUninit; + ma_encoder_write_pcm_frames_proc onWritePCMFrames; + void* pUserData; + void* pInternalEncoder; + union + { + struct + { + ma_vfs* pVFS; + ma_vfs_file file; + } vfs; + } data; +}; + +MA_API ma_result ma_encoder_init(ma_encoder_write_proc onWrite, ma_encoder_seek_proc onSeek, void* pUserData, const ma_encoder_config* pConfig, ma_encoder* pEncoder); +MA_API ma_result ma_encoder_init_vfs(ma_vfs* pVFS, const char* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder); +MA_API ma_result ma_encoder_init_vfs_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder); +MA_API ma_result ma_encoder_init_file(const char* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder); +MA_API ma_result ma_encoder_init_file_w(const wchar_t* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder); +MA_API void ma_encoder_uninit(ma_encoder* pEncoder); +MA_API ma_result ma_encoder_write_pcm_frames(ma_encoder* pEncoder, const void* pFramesIn, ma_uint64 frameCount, ma_uint64* pFramesWritten); + +#endif /* MA_NO_ENCODING */ + + +/************************************************************************************************************************************************************ + +Generation + +************************************************************************************************************************************************************/ +#ifndef MA_NO_GENERATION +typedef enum +{ + ma_waveform_type_sine, + ma_waveform_type_square, + ma_waveform_type_triangle, + ma_waveform_type_sawtooth +} ma_waveform_type; + +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + ma_waveform_type type; + double amplitude; + double frequency; +} ma_waveform_config; + +MA_API ma_waveform_config ma_waveform_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_waveform_type type, double amplitude, double frequency); + +typedef struct +{ + ma_data_source_base ds; + ma_waveform_config config; + double advance; + double time; +} ma_waveform; + +MA_API ma_result ma_waveform_init(const ma_waveform_config* pConfig, ma_waveform* pWaveform); +MA_API void ma_waveform_uninit(ma_waveform* pWaveform); +MA_API ma_result ma_waveform_read_pcm_frames(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead); +MA_API ma_result ma_waveform_seek_to_pcm_frame(ma_waveform* pWaveform, ma_uint64 frameIndex); +MA_API ma_result ma_waveform_set_amplitude(ma_waveform* pWaveform, double amplitude); +MA_API ma_result ma_waveform_set_frequency(ma_waveform* pWaveform, double frequency); +MA_API ma_result ma_waveform_set_type(ma_waveform* pWaveform, ma_waveform_type type); +MA_API ma_result ma_waveform_set_sample_rate(ma_waveform* pWaveform, ma_uint32 sampleRate); + +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + double dutyCycle; + double amplitude; + double frequency; +} ma_pulsewave_config; + +MA_API ma_pulsewave_config ma_pulsewave_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double dutyCycle, double amplitude, double frequency); + +typedef struct +{ + ma_waveform waveform; + ma_pulsewave_config config; +} ma_pulsewave; + +MA_API ma_result ma_pulsewave_init(const ma_pulsewave_config* pConfig, ma_pulsewave* pWaveform); +MA_API void ma_pulsewave_uninit(ma_pulsewave* pWaveform); +MA_API ma_result ma_pulsewave_read_pcm_frames(ma_pulsewave* pWaveform, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead); +MA_API ma_result ma_pulsewave_seek_to_pcm_frame(ma_pulsewave* pWaveform, ma_uint64 frameIndex); +MA_API ma_result ma_pulsewave_set_amplitude(ma_pulsewave* pWaveform, double amplitude); +MA_API ma_result ma_pulsewave_set_frequency(ma_pulsewave* pWaveform, double frequency); +MA_API ma_result ma_pulsewave_set_sample_rate(ma_pulsewave* pWaveform, ma_uint32 sampleRate); +MA_API ma_result ma_pulsewave_set_duty_cycle(ma_pulsewave* pWaveform, double dutyCycle); + +typedef enum +{ + ma_noise_type_white, + ma_noise_type_pink, + ma_noise_type_brownian +} ma_noise_type; + + +typedef struct +{ + ma_format format; + ma_uint32 channels; + ma_noise_type type; + ma_int32 seed; + double amplitude; + ma_bool32 duplicateChannels; +} ma_noise_config; + +MA_API ma_noise_config ma_noise_config_init(ma_format format, ma_uint32 channels, ma_noise_type type, ma_int32 seed, double amplitude); + +typedef struct +{ + ma_data_source_base ds; + ma_noise_config config; + ma_lcg lcg; + union + { + struct + { + double** bin; + double* accumulation; + ma_uint32* counter; + } pink; + struct + { + double* accumulation; + } brownian; + } state; + + /* Memory management. */ + void* _pHeap; + ma_bool32 _ownsHeap; +} ma_noise; + +MA_API ma_result ma_noise_get_heap_size(const ma_noise_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_noise_init_preallocated(const ma_noise_config* pConfig, void* pHeap, ma_noise* pNoise); +MA_API ma_result ma_noise_init(const ma_noise_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_noise* pNoise); +MA_API void ma_noise_uninit(ma_noise* pNoise, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_noise_read_pcm_frames(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead); +MA_API ma_result ma_noise_set_amplitude(ma_noise* pNoise, double amplitude); +MA_API ma_result ma_noise_set_seed(ma_noise* pNoise, ma_int32 seed); +MA_API ma_result ma_noise_set_type(ma_noise* pNoise, ma_noise_type type); + +#endif /* MA_NO_GENERATION */ + + + +/************************************************************************************************************************************************************ + +Resource Manager + +************************************************************************************************************************************************************/ +/* The resource manager cannot be enabled if there is no decoder. */ +#if !defined(MA_NO_RESOURCE_MANAGER) && defined(MA_NO_DECODING) +#define MA_NO_RESOURCE_MANAGER +#endif + +#ifndef MA_NO_RESOURCE_MANAGER +typedef struct ma_resource_manager ma_resource_manager; +typedef struct ma_resource_manager_data_buffer_node ma_resource_manager_data_buffer_node; +typedef struct ma_resource_manager_data_buffer ma_resource_manager_data_buffer; +typedef struct ma_resource_manager_data_stream ma_resource_manager_data_stream; +typedef struct ma_resource_manager_data_source ma_resource_manager_data_source; + +typedef enum +{ + MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM = 0x00000001, /* When set, does not load the entire data source in memory. Disk I/O will happen on job threads. */ + MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE = 0x00000002, /* Decode data before storing in memory. When set, decoding is done at the resource manager level rather than the mixing thread. Results in faster mixing, but higher memory usage. */ + MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC = 0x00000004, /* When set, the resource manager will load the data source asynchronously. */ + MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT = 0x00000008, /* When set, waits for initialization of the underlying data source before returning from ma_resource_manager_data_source_init(). */ + MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_UNKNOWN_LENGTH = 0x00000010 /* Gives the resource manager a hint that the length of the data source is unknown and calling `ma_data_source_get_length_in_pcm_frames()` should be avoided. */ +} ma_resource_manager_data_source_flags; + + +/* +Pipeline notifications used by the resource manager. Made up of both an async notification and a fence, both of which are optional. +*/ +typedef struct +{ + ma_async_notification* pNotification; + ma_fence* pFence; +} ma_resource_manager_pipeline_stage_notification; + +typedef struct +{ + ma_resource_manager_pipeline_stage_notification init; /* Initialization of the decoder. */ + ma_resource_manager_pipeline_stage_notification done; /* Decoding fully completed. */ +} ma_resource_manager_pipeline_notifications; + +MA_API ma_resource_manager_pipeline_notifications ma_resource_manager_pipeline_notifications_init(void); + + + +/* BEGIN BACKWARDS COMPATIBILITY */ +/* TODO: Remove this block in version 0.12. */ +#if 1 +#define ma_resource_manager_job ma_job +#define ma_resource_manager_job_init ma_job_init +#define MA_JOB_TYPE_RESOURCE_MANAGER_QUEUE_FLAG_NON_BLOCKING MA_JOB_QUEUE_FLAG_NON_BLOCKING +#define ma_resource_manager_job_queue_config ma_job_queue_config +#define ma_resource_manager_job_queue_config_init ma_job_queue_config_init +#define ma_resource_manager_job_queue ma_job_queue +#define ma_resource_manager_job_queue_get_heap_size ma_job_queue_get_heap_size +#define ma_resource_manager_job_queue_init_preallocated ma_job_queue_init_preallocated +#define ma_resource_manager_job_queue_init ma_job_queue_init +#define ma_resource_manager_job_queue_uninit ma_job_queue_uninit +#define ma_resource_manager_job_queue_post ma_job_queue_post +#define ma_resource_manager_job_queue_next ma_job_queue_next +#endif +/* END BACKWARDS COMPATIBILITY */ + + + + +/* Maximum job thread count will be restricted to this, but this may be removed later and replaced with a heap allocation thereby removing any limitation. */ +#ifndef MA_RESOURCE_MANAGER_MAX_JOB_THREAD_COUNT +#define MA_RESOURCE_MANAGER_MAX_JOB_THREAD_COUNT 64 +#endif + +typedef enum +{ + /* Indicates ma_resource_manager_next_job() should not block. Only valid when the job thread count is 0. */ + MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING = 0x00000001, + + /* Disables any kind of multithreading. Implicitly enables MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING. */ + MA_RESOURCE_MANAGER_FLAG_NO_THREADING = 0x00000002 +} ma_resource_manager_flags; + +typedef struct +{ + const char* pFilePath; + const wchar_t* pFilePathW; + const ma_resource_manager_pipeline_notifications* pNotifications; + ma_uint64 initialSeekPointInPCMFrames; + ma_uint64 rangeBegInPCMFrames; + ma_uint64 rangeEndInPCMFrames; + ma_uint64 loopPointBegInPCMFrames; + ma_uint64 loopPointEndInPCMFrames; + ma_bool32 isLooping; + ma_uint32 flags; +} ma_resource_manager_data_source_config; + +MA_API ma_resource_manager_data_source_config ma_resource_manager_data_source_config_init(void); + + +typedef enum +{ + ma_resource_manager_data_supply_type_unknown = 0, /* Used for determining whether or the data supply has been initialized. */ + ma_resource_manager_data_supply_type_encoded, /* Data supply is an encoded buffer. Connector is ma_decoder. */ + ma_resource_manager_data_supply_type_decoded, /* Data supply is a decoded buffer. Connector is ma_audio_buffer. */ + ma_resource_manager_data_supply_type_decoded_paged /* Data supply is a linked list of decoded buffers. Connector is ma_paged_audio_buffer. */ +} ma_resource_manager_data_supply_type; + +typedef struct +{ + MA_ATOMIC(4, ma_resource_manager_data_supply_type) type; /* Read and written from different threads so needs to be accessed atomically. */ + union + { + struct + { + const void* pData; + size_t sizeInBytes; + } encoded; + struct + { + const void* pData; + ma_uint64 totalFrameCount; + ma_uint64 decodedFrameCount; + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + } decoded; + struct + { + ma_paged_audio_buffer_data data; + ma_uint64 decodedFrameCount; + ma_uint32 sampleRate; + } decodedPaged; + } backend; +} ma_resource_manager_data_supply; + +struct ma_resource_manager_data_buffer_node +{ + ma_uint32 hashedName32; /* The hashed name. This is the key. */ + ma_uint32 refCount; + MA_ATOMIC(4, ma_result) result; /* Result from asynchronous loading. When loading set to MA_BUSY. When fully loaded set to MA_SUCCESS. When deleting set to MA_UNAVAILABLE. */ + MA_ATOMIC(4, ma_uint32) executionCounter; /* For allocating execution orders for jobs. */ + MA_ATOMIC(4, ma_uint32) executionPointer; /* For managing the order of execution for asynchronous jobs relating to this object. Incremented as jobs complete processing. */ + ma_bool32 isDataOwnedByResourceManager; /* Set to true when the underlying data buffer was allocated the resource manager. Set to false if it is owned by the application (via ma_resource_manager_register_*()). */ + ma_resource_manager_data_supply data; + ma_resource_manager_data_buffer_node* pParent; + ma_resource_manager_data_buffer_node* pChildLo; + ma_resource_manager_data_buffer_node* pChildHi; +}; + +struct ma_resource_manager_data_buffer +{ + ma_data_source_base ds; /* Base data source. A data buffer is a data source. */ + ma_resource_manager* pResourceManager; /* A pointer to the resource manager that owns this buffer. */ + ma_resource_manager_data_buffer_node* pNode; /* The data node. This is reference counted and is what supplies the data. */ + ma_uint32 flags; /* The flags that were passed used to initialize the buffer. */ + MA_ATOMIC(4, ma_uint32) executionCounter; /* For allocating execution orders for jobs. */ + MA_ATOMIC(4, ma_uint32) executionPointer; /* For managing the order of execution for asynchronous jobs relating to this object. Incremented as jobs complete processing. */ + ma_uint64 seekTargetInPCMFrames; /* Only updated by the public API. Never written nor read from the job thread. */ + ma_bool32 seekToCursorOnNextRead; /* On the next read we need to seek to the frame cursor. */ + MA_ATOMIC(4, ma_result) result; /* Keeps track of a result of decoding. Set to MA_BUSY while the buffer is still loading. Set to MA_SUCCESS when loading is finished successfully. Otherwise set to some other code. */ + MA_ATOMIC(4, ma_bool32) isLooping; /* Can be read and written by different threads at the same time. Must be used atomically. */ + ma_atomic_bool32 isConnectorInitialized; /* Used for asynchronous loading to ensure we don't try to initialize the connector multiple times while waiting for the node to fully load. */ + union + { + ma_decoder decoder; /* Supply type is ma_resource_manager_data_supply_type_encoded */ + ma_audio_buffer buffer; /* Supply type is ma_resource_manager_data_supply_type_decoded */ + ma_paged_audio_buffer pagedBuffer; /* Supply type is ma_resource_manager_data_supply_type_decoded_paged */ + } connector; /* Connects this object to the node's data supply. */ +}; + +struct ma_resource_manager_data_stream +{ + ma_data_source_base ds; /* Base data source. A data stream is a data source. */ + ma_resource_manager* pResourceManager; /* A pointer to the resource manager that owns this data stream. */ + ma_uint32 flags; /* The flags that were passed used to initialize the stream. */ + ma_decoder decoder; /* Used for filling pages with data. This is only ever accessed by the job thread. The public API should never touch this. */ + ma_bool32 isDecoderInitialized; /* Required for determining whether or not the decoder should be uninitialized in MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_STREAM. */ + ma_uint64 totalLengthInPCMFrames; /* This is calculated when first loaded by the MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_STREAM. */ + ma_uint32 relativeCursor; /* The playback cursor, relative to the current page. Only ever accessed by the public API. Never accessed by the job thread. */ + MA_ATOMIC(8, ma_uint64) absoluteCursor; /* The playback cursor, in absolute position starting from the start of the file. */ + ma_uint32 currentPageIndex; /* Toggles between 0 and 1. Index 0 is the first half of pPageData. Index 1 is the second half. Only ever accessed by the public API. Never accessed by the job thread. */ + MA_ATOMIC(4, ma_uint32) executionCounter; /* For allocating execution orders for jobs. */ + MA_ATOMIC(4, ma_uint32) executionPointer; /* For managing the order of execution for asynchronous jobs relating to this object. Incremented as jobs complete processing. */ + + /* Written by the public API, read by the job thread. */ + MA_ATOMIC(4, ma_bool32) isLooping; /* Whether or not the stream is looping. It's important to set the looping flag at the data stream level for smooth loop transitions. */ + + /* Written by the job thread, read by the public API. */ + void* pPageData; /* Buffer containing the decoded data of each page. Allocated once at initialization time. */ + MA_ATOMIC(4, ma_uint32) pageFrameCount[2]; /* The number of valid PCM frames in each page. Used to determine the last valid frame. */ + + /* Written and read by both the public API and the job thread. These must be atomic. */ + MA_ATOMIC(4, ma_result) result; /* Result from asynchronous loading. When loading set to MA_BUSY. When initialized set to MA_SUCCESS. When deleting set to MA_UNAVAILABLE. If an error occurs when loading, set to an error code. */ + MA_ATOMIC(4, ma_bool32) isDecoderAtEnd; /* Whether or not the decoder has reached the end. */ + MA_ATOMIC(4, ma_bool32) isPageValid[2]; /* Booleans to indicate whether or not a page is valid. Set to false by the public API, set to true by the job thread. Set to false as the pages are consumed, true when they are filled. */ + MA_ATOMIC(4, ma_bool32) seekCounter; /* When 0, no seeking is being performed. When > 0, a seek is being performed and reading should be delayed with MA_BUSY. */ +}; + +struct ma_resource_manager_data_source +{ + union + { + ma_resource_manager_data_buffer buffer; + ma_resource_manager_data_stream stream; + } backend; /* Must be the first item because we need the first item to be the data source callbacks for the buffer or stream. */ + + ma_uint32 flags; /* The flags that were passed in to ma_resource_manager_data_source_init(). */ + MA_ATOMIC(4, ma_uint32) executionCounter; /* For allocating execution orders for jobs. */ + MA_ATOMIC(4, ma_uint32) executionPointer; /* For managing the order of execution for asynchronous jobs relating to this object. Incremented as jobs complete processing. */ +}; + +typedef struct +{ + ma_allocation_callbacks allocationCallbacks; + ma_log* pLog; + ma_format decodedFormat; /* The decoded format to use. Set to ma_format_unknown (default) to use the file's native format. */ + ma_uint32 decodedChannels; /* The decoded channel count to use. Set to 0 (default) to use the file's native channel count. */ + ma_uint32 decodedSampleRate; /* the decoded sample rate to use. Set to 0 (default) to use the file's native sample rate. */ + ma_uint32 jobThreadCount; /* Set to 0 if you want to self-manage your job threads. Defaults to 1. */ + size_t jobThreadStackSize; + ma_uint32 jobQueueCapacity; /* The maximum number of jobs that can fit in the queue at a time. Defaults to MA_JOB_TYPE_RESOURCE_MANAGER_QUEUE_CAPACITY. Cannot be zero. */ + ma_uint32 flags; + ma_vfs* pVFS; /* Can be NULL in which case defaults will be used. */ + ma_decoding_backend_vtable** ppCustomDecodingBackendVTables; + ma_uint32 customDecodingBackendCount; + void* pCustomDecodingBackendUserData; +} ma_resource_manager_config; + +MA_API ma_resource_manager_config ma_resource_manager_config_init(void); + +struct ma_resource_manager +{ + ma_resource_manager_config config; + ma_resource_manager_data_buffer_node* pRootDataBufferNode; /* The root buffer in the binary tree. */ +#ifndef MA_NO_THREADING + ma_mutex dataBufferBSTLock; /* For synchronizing access to the data buffer binary tree. */ + ma_thread jobThreads[MA_RESOURCE_MANAGER_MAX_JOB_THREAD_COUNT]; /* The threads for executing jobs. */ +#endif + ma_job_queue jobQueue; /* Multi-consumer, multi-producer job queue for managing jobs for asynchronous decoding and streaming. */ + ma_default_vfs defaultVFS; /* Only used if a custom VFS is not specified. */ + ma_log log; /* Only used if no log was specified in the config. */ +}; + +/* Init. */ +MA_API ma_result ma_resource_manager_init(const ma_resource_manager_config* pConfig, ma_resource_manager* pResourceManager); +MA_API void ma_resource_manager_uninit(ma_resource_manager* pResourceManager); +MA_API ma_log* ma_resource_manager_get_log(ma_resource_manager* pResourceManager); + +/* Registration. */ +MA_API ma_result ma_resource_manager_register_file(ma_resource_manager* pResourceManager, const char* pFilePath, ma_uint32 flags); +MA_API ma_result ma_resource_manager_register_file_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath, ma_uint32 flags); +MA_API ma_result ma_resource_manager_register_decoded_data(ma_resource_manager* pResourceManager, const char* pName, const void* pData, ma_uint64 frameCount, ma_format format, ma_uint32 channels, ma_uint32 sampleRate); /* Does not copy. Increments the reference count if already exists and returns MA_SUCCESS. */ +MA_API ma_result ma_resource_manager_register_decoded_data_w(ma_resource_manager* pResourceManager, const wchar_t* pName, const void* pData, ma_uint64 frameCount, ma_format format, ma_uint32 channels, ma_uint32 sampleRate); +MA_API ma_result ma_resource_manager_register_encoded_data(ma_resource_manager* pResourceManager, const char* pName, const void* pData, size_t sizeInBytes); /* Does not copy. Increments the reference count if already exists and returns MA_SUCCESS. */ +MA_API ma_result ma_resource_manager_register_encoded_data_w(ma_resource_manager* pResourceManager, const wchar_t* pName, const void* pData, size_t sizeInBytes); +MA_API ma_result ma_resource_manager_unregister_file(ma_resource_manager* pResourceManager, const char* pFilePath); +MA_API ma_result ma_resource_manager_unregister_file_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath); +MA_API ma_result ma_resource_manager_unregister_data(ma_resource_manager* pResourceManager, const char* pName); +MA_API ma_result ma_resource_manager_unregister_data_w(ma_resource_manager* pResourceManager, const wchar_t* pName); + +/* Data Buffers. */ +MA_API ma_result ma_resource_manager_data_buffer_init_ex(ma_resource_manager* pResourceManager, const ma_resource_manager_data_source_config* pConfig, ma_resource_manager_data_buffer* pDataBuffer); +MA_API ma_result ma_resource_manager_data_buffer_init(ma_resource_manager* pResourceManager, const char* pFilePath, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_buffer* pDataBuffer); +MA_API ma_result ma_resource_manager_data_buffer_init_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_buffer* pDataBuffer); +MA_API ma_result ma_resource_manager_data_buffer_init_copy(ma_resource_manager* pResourceManager, const ma_resource_manager_data_buffer* pExistingDataBuffer, ma_resource_manager_data_buffer* pDataBuffer); +MA_API ma_result ma_resource_manager_data_buffer_uninit(ma_resource_manager_data_buffer* pDataBuffer); +MA_API ma_result ma_resource_manager_data_buffer_read_pcm_frames(ma_resource_manager_data_buffer* pDataBuffer, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead); +MA_API ma_result ma_resource_manager_data_buffer_seek_to_pcm_frame(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64 frameIndex); +MA_API ma_result ma_resource_manager_data_buffer_get_data_format(ma_resource_manager_data_buffer* pDataBuffer, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap); +MA_API ma_result ma_resource_manager_data_buffer_get_cursor_in_pcm_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pCursor); +MA_API ma_result ma_resource_manager_data_buffer_get_length_in_pcm_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pLength); +MA_API ma_result ma_resource_manager_data_buffer_result(const ma_resource_manager_data_buffer* pDataBuffer); +MA_API ma_result ma_resource_manager_data_buffer_set_looping(ma_resource_manager_data_buffer* pDataBuffer, ma_bool32 isLooping); +MA_API ma_bool32 ma_resource_manager_data_buffer_is_looping(const ma_resource_manager_data_buffer* pDataBuffer); +MA_API ma_result ma_resource_manager_data_buffer_get_available_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pAvailableFrames); + +/* Data Streams. */ +MA_API ma_result ma_resource_manager_data_stream_init_ex(ma_resource_manager* pResourceManager, const ma_resource_manager_data_source_config* pConfig, ma_resource_manager_data_stream* pDataStream); +MA_API ma_result ma_resource_manager_data_stream_init(ma_resource_manager* pResourceManager, const char* pFilePath, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_stream* pDataStream); +MA_API ma_result ma_resource_manager_data_stream_init_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_stream* pDataStream); +MA_API ma_result ma_resource_manager_data_stream_uninit(ma_resource_manager_data_stream* pDataStream); +MA_API ma_result ma_resource_manager_data_stream_read_pcm_frames(ma_resource_manager_data_stream* pDataStream, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead); +MA_API ma_result ma_resource_manager_data_stream_seek_to_pcm_frame(ma_resource_manager_data_stream* pDataStream, ma_uint64 frameIndex); +MA_API ma_result ma_resource_manager_data_stream_get_data_format(ma_resource_manager_data_stream* pDataStream, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap); +MA_API ma_result ma_resource_manager_data_stream_get_cursor_in_pcm_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pCursor); +MA_API ma_result ma_resource_manager_data_stream_get_length_in_pcm_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pLength); +MA_API ma_result ma_resource_manager_data_stream_result(const ma_resource_manager_data_stream* pDataStream); +MA_API ma_result ma_resource_manager_data_stream_set_looping(ma_resource_manager_data_stream* pDataStream, ma_bool32 isLooping); +MA_API ma_bool32 ma_resource_manager_data_stream_is_looping(const ma_resource_manager_data_stream* pDataStream); +MA_API ma_result ma_resource_manager_data_stream_get_available_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pAvailableFrames); + +/* Data Sources. */ +MA_API ma_result ma_resource_manager_data_source_init_ex(ma_resource_manager* pResourceManager, const ma_resource_manager_data_source_config* pConfig, ma_resource_manager_data_source* pDataSource); +MA_API ma_result ma_resource_manager_data_source_init(ma_resource_manager* pResourceManager, const char* pName, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_source* pDataSource); +MA_API ma_result ma_resource_manager_data_source_init_w(ma_resource_manager* pResourceManager, const wchar_t* pName, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_source* pDataSource); +MA_API ma_result ma_resource_manager_data_source_init_copy(ma_resource_manager* pResourceManager, const ma_resource_manager_data_source* pExistingDataSource, ma_resource_manager_data_source* pDataSource); +MA_API ma_result ma_resource_manager_data_source_uninit(ma_resource_manager_data_source* pDataSource); +MA_API ma_result ma_resource_manager_data_source_read_pcm_frames(ma_resource_manager_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead); +MA_API ma_result ma_resource_manager_data_source_seek_to_pcm_frame(ma_resource_manager_data_source* pDataSource, ma_uint64 frameIndex); +MA_API ma_result ma_resource_manager_data_source_get_data_format(ma_resource_manager_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap); +MA_API ma_result ma_resource_manager_data_source_get_cursor_in_pcm_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pCursor); +MA_API ma_result ma_resource_manager_data_source_get_length_in_pcm_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pLength); +MA_API ma_result ma_resource_manager_data_source_result(const ma_resource_manager_data_source* pDataSource); +MA_API ma_result ma_resource_manager_data_source_set_looping(ma_resource_manager_data_source* pDataSource, ma_bool32 isLooping); +MA_API ma_bool32 ma_resource_manager_data_source_is_looping(const ma_resource_manager_data_source* pDataSource); +MA_API ma_result ma_resource_manager_data_source_get_available_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pAvailableFrames); + +/* Job management. */ +MA_API ma_result ma_resource_manager_post_job(ma_resource_manager* pResourceManager, const ma_job* pJob); +MA_API ma_result ma_resource_manager_post_job_quit(ma_resource_manager* pResourceManager); /* Helper for posting a quit job. */ +MA_API ma_result ma_resource_manager_next_job(ma_resource_manager* pResourceManager, ma_job* pJob); +MA_API ma_result ma_resource_manager_process_job(ma_resource_manager* pResourceManager, ma_job* pJob); /* DEPRECATED. Use ma_job_process(). Will be removed in version 0.12. */ +MA_API ma_result ma_resource_manager_process_next_job(ma_resource_manager* pResourceManager); /* Returns MA_CANCELLED if a MA_JOB_TYPE_QUIT job is found. In non-blocking mode, returns MA_NO_DATA_AVAILABLE if no jobs are available. */ +#endif /* MA_NO_RESOURCE_MANAGER */ + + + +/************************************************************************************************************************************************************ + +Node Graph + +************************************************************************************************************************************************************/ +#ifndef MA_NO_NODE_GRAPH +/* Must never exceed 254. */ +#ifndef MA_MAX_NODE_BUS_COUNT +#define MA_MAX_NODE_BUS_COUNT 254 +#endif + +/* Used internally by miniaudio for memory management. Must never exceed MA_MAX_NODE_BUS_COUNT. */ +#ifndef MA_MAX_NODE_LOCAL_BUS_COUNT +#define MA_MAX_NODE_LOCAL_BUS_COUNT 2 +#endif + +/* Use this when the bus count is determined by the node instance rather than the vtable. */ +#define MA_NODE_BUS_COUNT_UNKNOWN 255 + +typedef struct ma_node_graph ma_node_graph; +typedef void ma_node; + + +/* Node flags. */ +typedef enum +{ + MA_NODE_FLAG_PASSTHROUGH = 0x00000001, + MA_NODE_FLAG_CONTINUOUS_PROCESSING = 0x00000002, + MA_NODE_FLAG_ALLOW_NULL_INPUT = 0x00000004, + MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES = 0x00000008, + MA_NODE_FLAG_SILENT_OUTPUT = 0x00000010 +} ma_node_flags; + + +/* The playback state of a node. Either started or stopped. */ +typedef enum +{ + ma_node_state_started = 0, + ma_node_state_stopped = 1 +} ma_node_state; + + +typedef struct +{ + /* + Extended processing callback. This callback is used for effects that process input and output + at different rates (i.e. they perform resampling). This is similar to the simple version, only + they take two separate frame counts: one for input, and one for output. + + On input, `pFrameCountOut` is equal to the capacity of the output buffer for each bus, whereas + `pFrameCountIn` will be equal to the number of PCM frames in each of the buffers in `ppFramesIn`. + + On output, set `pFrameCountOut` to the number of PCM frames that were actually output and set + `pFrameCountIn` to the number of input frames that were consumed. + */ + void (* onProcess)(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut); + + /* + A callback for retrieving the number of a input frames that are required to output the + specified number of output frames. You would only want to implement this when the node performs + resampling. This is optional, even for nodes that perform resampling, but it does offer a + small reduction in latency as it allows miniaudio to calculate the exact number of input frames + to read at a time instead of having to estimate. + */ + ma_result (* onGetRequiredInputFrameCount)(ma_node* pNode, ma_uint32 outputFrameCount, ma_uint32* pInputFrameCount); + + /* + The number of input buses. This is how many sub-buffers will be contained in the `ppFramesIn` + parameters of the callbacks above. + */ + ma_uint8 inputBusCount; + + /* + The number of output buses. This is how many sub-buffers will be contained in the `ppFramesOut` + parameters of the callbacks above. + */ + ma_uint8 outputBusCount; + + /* + Flags describing characteristics of the node. This is currently just a placeholder for some + ideas for later on. + */ + ma_uint32 flags; +} ma_node_vtable; + +typedef struct +{ + const ma_node_vtable* vtable; /* Should never be null. Initialization of the node will fail if so. */ + ma_node_state initialState; /* Defaults to ma_node_state_started. */ + ma_uint32 inputBusCount; /* Only used if the vtable specifies an input bus count of `MA_NODE_BUS_COUNT_UNKNOWN`, otherwise must be set to `MA_NODE_BUS_COUNT_UNKNOWN` (default). */ + ma_uint32 outputBusCount; /* Only used if the vtable specifies an output bus count of `MA_NODE_BUS_COUNT_UNKNOWN`, otherwise be set to `MA_NODE_BUS_COUNT_UNKNOWN` (default). */ + const ma_uint32* pInputChannels; /* The number of elements are determined by the input bus count as determined by the vtable, or `inputBusCount` if the vtable specifies `MA_NODE_BUS_COUNT_UNKNOWN`. */ + const ma_uint32* pOutputChannels; /* The number of elements are determined by the output bus count as determined by the vtable, or `outputBusCount` if the vtable specifies `MA_NODE_BUS_COUNT_UNKNOWN`. */ +} ma_node_config; + +MA_API ma_node_config ma_node_config_init(void); + + +/* +A node has multiple output buses. An output bus is attached to an input bus as an item in a linked +list. Think of the input bus as a linked list, with the output bus being an item in that list. +*/ +typedef struct ma_node_output_bus ma_node_output_bus; +struct ma_node_output_bus +{ + /* Immutable. */ + ma_node* pNode; /* The node that owns this output bus. The input node. Will be null for dummy head and tail nodes. */ + ma_uint8 outputBusIndex; /* The index of the output bus on pNode that this output bus represents. */ + ma_uint8 channels; /* The number of channels in the audio stream for this bus. */ + + /* Mutable via multiple threads. Must be used atomically. The weird ordering here is for packing reasons. */ + ma_uint8 inputNodeInputBusIndex; /* The index of the input bus on the input. Required for detaching. Will only be used within the spinlock so does not need to be atomic. */ + MA_ATOMIC(4, ma_uint32) flags; /* Some state flags for tracking the read state of the output buffer. A combination of MA_NODE_OUTPUT_BUS_FLAG_*. */ + MA_ATOMIC(4, ma_uint32) refCount; /* Reference count for some thread-safety when detaching. */ + MA_ATOMIC(4, ma_bool32) isAttached; /* This is used to prevent iteration of nodes that are in the middle of being detached. Used for thread safety. */ + MA_ATOMIC(4, ma_spinlock) lock; /* Unfortunate lock, but significantly simplifies the implementation. Required for thread-safe attaching and detaching. */ + MA_ATOMIC(4, float) volume; /* Linear. */ + MA_ATOMIC(MA_SIZEOF_PTR, ma_node_output_bus*) pNext; /* If null, it's the tail node or detached. */ + MA_ATOMIC(MA_SIZEOF_PTR, ma_node_output_bus*) pPrev; /* If null, it's the head node or detached. */ + MA_ATOMIC(MA_SIZEOF_PTR, ma_node*) pInputNode; /* The node that this output bus is attached to. Required for detaching. */ +}; + +/* +A node has multiple input buses. The output buses of a node are connecting to the input busses of +another. An input bus is essentially just a linked list of output buses. +*/ +typedef struct ma_node_input_bus ma_node_input_bus; +struct ma_node_input_bus +{ + /* Mutable via multiple threads. */ + ma_node_output_bus head; /* Dummy head node for simplifying some lock-free thread-safety stuff. */ + MA_ATOMIC(4, ma_uint32) nextCounter; /* This is used to determine whether or not the input bus is finding the next node in the list. Used for thread safety when detaching output buses. */ + MA_ATOMIC(4, ma_spinlock) lock; /* Unfortunate lock, but significantly simplifies the implementation. Required for thread-safe attaching and detaching. */ + + /* Set once at startup. */ + ma_uint8 channels; /* The number of channels in the audio stream for this bus. */ +}; + + +typedef struct ma_node_base ma_node_base; +struct ma_node_base +{ + /* These variables are set once at startup. */ + ma_node_graph* pNodeGraph; /* The graph this node belongs to. */ + const ma_node_vtable* vtable; + float* pCachedData; /* Allocated on the heap. Fixed size. Needs to be stored on the heap because reading from output buses is done in separate function calls. */ + ma_uint16 cachedDataCapInFramesPerBus; /* The capacity of the input data cache in frames, per bus. */ + + /* These variables are read and written only from the audio thread. */ + ma_uint16 cachedFrameCountOut; + ma_uint16 cachedFrameCountIn; + ma_uint16 consumedFrameCountIn; + + /* These variables are read and written between different threads. */ + MA_ATOMIC(4, ma_node_state) state; /* When set to stopped, nothing will be read, regardless of the times in stateTimes. */ + MA_ATOMIC(8, ma_uint64) stateTimes[2]; /* Indexed by ma_node_state. Specifies the time based on the global clock that a node should be considered to be in the relevant state. */ + MA_ATOMIC(8, ma_uint64) localTime; /* The node's local clock. This is just a running sum of the number of output frames that have been processed. Can be modified by any thread with `ma_node_set_time()`. */ + ma_uint32 inputBusCount; + ma_uint32 outputBusCount; + ma_node_input_bus* pInputBuses; + ma_node_output_bus* pOutputBuses; + + /* Memory management. */ + ma_node_input_bus _inputBuses[MA_MAX_NODE_LOCAL_BUS_COUNT]; + ma_node_output_bus _outputBuses[MA_MAX_NODE_LOCAL_BUS_COUNT]; + void* _pHeap; /* A heap allocation for internal use only. pInputBuses and/or pOutputBuses will point to this if the bus count exceeds MA_MAX_NODE_LOCAL_BUS_COUNT. */ + ma_bool32 _ownsHeap; /* If set to true, the node owns the heap allocation and _pHeap will be freed in ma_node_uninit(). */ +}; + +MA_API ma_result ma_node_get_heap_size(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_node_init_preallocated(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, void* pHeap, ma_node* pNode); +MA_API ma_result ma_node_init(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_node* pNode); +MA_API void ma_node_uninit(ma_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_node_graph* ma_node_get_node_graph(const ma_node* pNode); +MA_API ma_uint32 ma_node_get_input_bus_count(const ma_node* pNode); +MA_API ma_uint32 ma_node_get_output_bus_count(const ma_node* pNode); +MA_API ma_uint32 ma_node_get_input_channels(const ma_node* pNode, ma_uint32 inputBusIndex); +MA_API ma_uint32 ma_node_get_output_channels(const ma_node* pNode, ma_uint32 outputBusIndex); +MA_API ma_result ma_node_attach_output_bus(ma_node* pNode, ma_uint32 outputBusIndex, ma_node* pOtherNode, ma_uint32 otherNodeInputBusIndex); +MA_API ma_result ma_node_detach_output_bus(ma_node* pNode, ma_uint32 outputBusIndex); +MA_API ma_result ma_node_detach_all_output_buses(ma_node* pNode); +MA_API ma_result ma_node_set_output_bus_volume(ma_node* pNode, ma_uint32 outputBusIndex, float volume); +MA_API float ma_node_get_output_bus_volume(const ma_node* pNode, ma_uint32 outputBusIndex); +MA_API ma_result ma_node_set_state(ma_node* pNode, ma_node_state state); +MA_API ma_node_state ma_node_get_state(const ma_node* pNode); +MA_API ma_result ma_node_set_state_time(ma_node* pNode, ma_node_state state, ma_uint64 globalTime); +MA_API ma_uint64 ma_node_get_state_time(const ma_node* pNode, ma_node_state state); +MA_API ma_node_state ma_node_get_state_by_time(const ma_node* pNode, ma_uint64 globalTime); +MA_API ma_node_state ma_node_get_state_by_time_range(const ma_node* pNode, ma_uint64 globalTimeBeg, ma_uint64 globalTimeEnd); +MA_API ma_uint64 ma_node_get_time(const ma_node* pNode); +MA_API ma_result ma_node_set_time(ma_node* pNode, ma_uint64 localTime); + + +typedef struct +{ + ma_uint32 channels; + ma_uint16 nodeCacheCapInFrames; +} ma_node_graph_config; + +MA_API ma_node_graph_config ma_node_graph_config_init(ma_uint32 channels); + + +struct ma_node_graph +{ + /* Immutable. */ + ma_node_base base; /* The node graph itself is a node so it can be connected as an input to different node graph. This has zero inputs and calls ma_node_graph_read_pcm_frames() to generate it's output. */ + ma_node_base endpoint; /* Special node that all nodes eventually connect to. Data is read from this node in ma_node_graph_read_pcm_frames(). */ + ma_uint16 nodeCacheCapInFrames; + + /* Read and written by multiple threads. */ + MA_ATOMIC(4, ma_bool32) isReading; +}; + +MA_API ma_result ma_node_graph_init(const ma_node_graph_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_node_graph* pNodeGraph); +MA_API void ma_node_graph_uninit(ma_node_graph* pNodeGraph, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_node* ma_node_graph_get_endpoint(ma_node_graph* pNodeGraph); +MA_API ma_result ma_node_graph_read_pcm_frames(ma_node_graph* pNodeGraph, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead); +MA_API ma_uint32 ma_node_graph_get_channels(const ma_node_graph* pNodeGraph); +MA_API ma_uint64 ma_node_graph_get_time(const ma_node_graph* pNodeGraph); +MA_API ma_result ma_node_graph_set_time(ma_node_graph* pNodeGraph, ma_uint64 globalTime); + + + +/* Data source node. 0 input buses, 1 output bus. Used for reading from a data source. */ +typedef struct +{ + ma_node_config nodeConfig; + ma_data_source* pDataSource; +} ma_data_source_node_config; + +MA_API ma_data_source_node_config ma_data_source_node_config_init(ma_data_source* pDataSource); + + +typedef struct +{ + ma_node_base base; + ma_data_source* pDataSource; +} ma_data_source_node; + +MA_API ma_result ma_data_source_node_init(ma_node_graph* pNodeGraph, const ma_data_source_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source_node* pDataSourceNode); +MA_API void ma_data_source_node_uninit(ma_data_source_node* pDataSourceNode, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_data_source_node_set_looping(ma_data_source_node* pDataSourceNode, ma_bool32 isLooping); +MA_API ma_bool32 ma_data_source_node_is_looping(ma_data_source_node* pDataSourceNode); + + +/* Splitter Node. 1 input, many outputs. Used for splitting/copying a stream so it can be as input into two separate output nodes. */ +typedef struct +{ + ma_node_config nodeConfig; + ma_uint32 channels; + ma_uint32 outputBusCount; +} ma_splitter_node_config; + +MA_API ma_splitter_node_config ma_splitter_node_config_init(ma_uint32 channels); + + +typedef struct +{ + ma_node_base base; +} ma_splitter_node; + +MA_API ma_result ma_splitter_node_init(ma_node_graph* pNodeGraph, const ma_splitter_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_splitter_node* pSplitterNode); +MA_API void ma_splitter_node_uninit(ma_splitter_node* pSplitterNode, const ma_allocation_callbacks* pAllocationCallbacks); + + +/* +Biquad Node +*/ +typedef struct +{ + ma_node_config nodeConfig; + ma_biquad_config biquad; +} ma_biquad_node_config; + +MA_API ma_biquad_node_config ma_biquad_node_config_init(ma_uint32 channels, float b0, float b1, float b2, float a0, float a1, float a2); + + +typedef struct +{ + ma_node_base baseNode; + ma_biquad biquad; +} ma_biquad_node; + +MA_API ma_result ma_biquad_node_init(ma_node_graph* pNodeGraph, const ma_biquad_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_biquad_node* pNode); +MA_API ma_result ma_biquad_node_reinit(const ma_biquad_config* pConfig, ma_biquad_node* pNode); +MA_API void ma_biquad_node_uninit(ma_biquad_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks); + + +/* +Low Pass Filter Node +*/ +typedef struct +{ + ma_node_config nodeConfig; + ma_lpf_config lpf; +} ma_lpf_node_config; + +MA_API ma_lpf_node_config ma_lpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order); + + +typedef struct +{ + ma_node_base baseNode; + ma_lpf lpf; +} ma_lpf_node; + +MA_API ma_result ma_lpf_node_init(ma_node_graph* pNodeGraph, const ma_lpf_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf_node* pNode); +MA_API ma_result ma_lpf_node_reinit(const ma_lpf_config* pConfig, ma_lpf_node* pNode); +MA_API void ma_lpf_node_uninit(ma_lpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks); + + +/* +High Pass Filter Node +*/ +typedef struct +{ + ma_node_config nodeConfig; + ma_hpf_config hpf; +} ma_hpf_node_config; + +MA_API ma_hpf_node_config ma_hpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order); + + +typedef struct +{ + ma_node_base baseNode; + ma_hpf hpf; +} ma_hpf_node; + +MA_API ma_result ma_hpf_node_init(ma_node_graph* pNodeGraph, const ma_hpf_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf_node* pNode); +MA_API ma_result ma_hpf_node_reinit(const ma_hpf_config* pConfig, ma_hpf_node* pNode); +MA_API void ma_hpf_node_uninit(ma_hpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks); + + +/* +Band Pass Filter Node +*/ +typedef struct +{ + ma_node_config nodeConfig; + ma_bpf_config bpf; +} ma_bpf_node_config; + +MA_API ma_bpf_node_config ma_bpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order); + + +typedef struct +{ + ma_node_base baseNode; + ma_bpf bpf; +} ma_bpf_node; + +MA_API ma_result ma_bpf_node_init(ma_node_graph* pNodeGraph, const ma_bpf_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf_node* pNode); +MA_API ma_result ma_bpf_node_reinit(const ma_bpf_config* pConfig, ma_bpf_node* pNode); +MA_API void ma_bpf_node_uninit(ma_bpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks); + + +/* +Notching Filter Node +*/ +typedef struct +{ + ma_node_config nodeConfig; + ma_notch_config notch; +} ma_notch_node_config; + +MA_API ma_notch_node_config ma_notch_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double q, double frequency); + + +typedef struct +{ + ma_node_base baseNode; + ma_notch2 notch; +} ma_notch_node; + +MA_API ma_result ma_notch_node_init(ma_node_graph* pNodeGraph, const ma_notch_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_notch_node* pNode); +MA_API ma_result ma_notch_node_reinit(const ma_notch_config* pConfig, ma_notch_node* pNode); +MA_API void ma_notch_node_uninit(ma_notch_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks); + + +/* +Peaking Filter Node +*/ +typedef struct +{ + ma_node_config nodeConfig; + ma_peak_config peak; +} ma_peak_node_config; + +MA_API ma_peak_node_config ma_peak_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency); + + +typedef struct +{ + ma_node_base baseNode; + ma_peak2 peak; +} ma_peak_node; + +MA_API ma_result ma_peak_node_init(ma_node_graph* pNodeGraph, const ma_peak_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_peak_node* pNode); +MA_API ma_result ma_peak_node_reinit(const ma_peak_config* pConfig, ma_peak_node* pNode); +MA_API void ma_peak_node_uninit(ma_peak_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks); + + +/* +Low Shelf Filter Node +*/ +typedef struct +{ + ma_node_config nodeConfig; + ma_loshelf_config loshelf; +} ma_loshelf_node_config; + +MA_API ma_loshelf_node_config ma_loshelf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency); + + +typedef struct +{ + ma_node_base baseNode; + ma_loshelf2 loshelf; +} ma_loshelf_node; + +MA_API ma_result ma_loshelf_node_init(ma_node_graph* pNodeGraph, const ma_loshelf_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_loshelf_node* pNode); +MA_API ma_result ma_loshelf_node_reinit(const ma_loshelf_config* pConfig, ma_loshelf_node* pNode); +MA_API void ma_loshelf_node_uninit(ma_loshelf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks); + + +/* +High Shelf Filter Node +*/ +typedef struct +{ + ma_node_config nodeConfig; + ma_hishelf_config hishelf; +} ma_hishelf_node_config; + +MA_API ma_hishelf_node_config ma_hishelf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency); + + +typedef struct +{ + ma_node_base baseNode; + ma_hishelf2 hishelf; +} ma_hishelf_node; + +MA_API ma_result ma_hishelf_node_init(ma_node_graph* pNodeGraph, const ma_hishelf_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hishelf_node* pNode); +MA_API ma_result ma_hishelf_node_reinit(const ma_hishelf_config* pConfig, ma_hishelf_node* pNode); +MA_API void ma_hishelf_node_uninit(ma_hishelf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks); + + +typedef struct +{ + ma_node_config nodeConfig; + ma_delay_config delay; +} ma_delay_node_config; + +MA_API ma_delay_node_config ma_delay_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 delayInFrames, float decay); + + +typedef struct +{ + ma_node_base baseNode; + ma_delay delay; +} ma_delay_node; + +MA_API ma_result ma_delay_node_init(ma_node_graph* pNodeGraph, const ma_delay_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_delay_node* pDelayNode); +MA_API void ma_delay_node_uninit(ma_delay_node* pDelayNode, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API void ma_delay_node_set_wet(ma_delay_node* pDelayNode, float value); +MA_API float ma_delay_node_get_wet(const ma_delay_node* pDelayNode); +MA_API void ma_delay_node_set_dry(ma_delay_node* pDelayNode, float value); +MA_API float ma_delay_node_get_dry(const ma_delay_node* pDelayNode); +MA_API void ma_delay_node_set_decay(ma_delay_node* pDelayNode, float value); +MA_API float ma_delay_node_get_decay(const ma_delay_node* pDelayNode); +#endif /* MA_NO_NODE_GRAPH */ + + +/* SECTION: miniaudio_engine.h */ +/************************************************************************************************************************************************************ + +Engine + +************************************************************************************************************************************************************/ +#if !defined(MA_NO_ENGINE) && !defined(MA_NO_NODE_GRAPH) +typedef struct ma_engine ma_engine; +typedef struct ma_sound ma_sound; + + +/* Sound flags. */ +typedef enum +{ + /* Resource manager flags. */ + MA_SOUND_FLAG_STREAM = 0x00000001, /* MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM */ + MA_SOUND_FLAG_DECODE = 0x00000002, /* MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE */ + MA_SOUND_FLAG_ASYNC = 0x00000004, /* MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC */ + MA_SOUND_FLAG_WAIT_INIT = 0x00000008, /* MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT */ + MA_SOUND_FLAG_UNKNOWN_LENGTH = 0x00000010, /* MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_UNKNOWN_LENGTH */ + + /* ma_sound specific flags. */ + MA_SOUND_FLAG_NO_DEFAULT_ATTACHMENT = 0x00001000, /* Do not attach to the endpoint by default. Useful for when setting up nodes in a complex graph system. */ + MA_SOUND_FLAG_NO_PITCH = 0x00002000, /* Disable pitch shifting with ma_sound_set_pitch() and ma_sound_group_set_pitch(). This is an optimization. */ + MA_SOUND_FLAG_NO_SPATIALIZATION = 0x00004000 /* Disable spatialization. */ +} ma_sound_flags; + +#ifndef MA_ENGINE_MAX_LISTENERS +#define MA_ENGINE_MAX_LISTENERS 4 +#endif + +#define MA_LISTENER_INDEX_CLOSEST ((ma_uint8)-1) + +typedef enum +{ + ma_engine_node_type_sound, + ma_engine_node_type_group +} ma_engine_node_type; + +typedef struct +{ + ma_engine* pEngine; + ma_engine_node_type type; + ma_uint32 channelsIn; + ma_uint32 channelsOut; + ma_uint32 sampleRate; /* Only used when the type is set to ma_engine_node_type_sound. */ + ma_uint32 volumeSmoothTimeInPCMFrames; /* The number of frames to smooth over volume changes. Defaults to 0 in which case no smoothing is used. */ + ma_mono_expansion_mode monoExpansionMode; + ma_bool8 isPitchDisabled; /* Pitching can be explicitly disabled with MA_SOUND_FLAG_NO_PITCH to optimize processing. */ + ma_bool8 isSpatializationDisabled; /* Spatialization can be explicitly disabled with MA_SOUND_FLAG_NO_SPATIALIZATION. */ + ma_uint8 pinnedListenerIndex; /* The index of the listener this node should always use for spatialization. If set to MA_LISTENER_INDEX_CLOSEST the engine will use the closest listener. */ +} ma_engine_node_config; + +MA_API ma_engine_node_config ma_engine_node_config_init(ma_engine* pEngine, ma_engine_node_type type, ma_uint32 flags); + + +/* Base node object for both ma_sound and ma_sound_group. */ +typedef struct +{ + ma_node_base baseNode; /* Must be the first member for compatiblity with the ma_node API. */ + ma_engine* pEngine; /* A pointer to the engine. Set based on the value from the config. */ + ma_uint32 sampleRate; /* The sample rate of the input data. For sounds backed by a data source, this will be the data source's sample rate. Otherwise it'll be the engine's sample rate. */ + ma_uint32 volumeSmoothTimeInPCMFrames; + ma_mono_expansion_mode monoExpansionMode; + ma_fader fader; + ma_linear_resampler resampler; /* For pitch shift. */ + ma_spatializer spatializer; + ma_panner panner; + ma_gainer volumeGainer; /* This will only be used if volumeSmoothTimeInPCMFrames is > 0. */ + ma_atomic_float volume; /* Defaults to 1. */ + MA_ATOMIC(4, float) pitch; + float oldPitch; /* For determining whether or not the resampler needs to be updated to reflect the new pitch. The resampler will be updated on the mixing thread. */ + float oldDopplerPitch; /* For determining whether or not the resampler needs to be updated to take a new doppler pitch into account. */ + MA_ATOMIC(4, ma_bool32) isPitchDisabled; /* When set to true, pitching will be disabled which will allow the resampler to be bypassed to save some computation. */ + MA_ATOMIC(4, ma_bool32) isSpatializationDisabled; /* Set to false by default. When set to false, will not have spatialisation applied. */ + MA_ATOMIC(4, ma_uint32) pinnedListenerIndex; /* The index of the listener this node should always use for spatialization. If set to MA_LISTENER_INDEX_CLOSEST the engine will use the closest listener. */ + + /* When setting a fade, it's not done immediately in ma_sound_set_fade(). It's deferred to the audio thread which means we need to store the settings here. */ + struct + { + ma_atomic_float volumeBeg; + ma_atomic_float volumeEnd; + ma_atomic_uint64 fadeLengthInFrames; /* <-- Defaults to (~(ma_uint64)0) which is used to indicate that no fade should be applied. */ + ma_atomic_uint64 absoluteGlobalTimeInFrames; /* <-- The time to start the fade. */ + } fadeSettings; + + /* Memory management. */ + ma_bool8 _ownsHeap; + void* _pHeap; +} ma_engine_node; + +MA_API ma_result ma_engine_node_get_heap_size(const ma_engine_node_config* pConfig, size_t* pHeapSizeInBytes); +MA_API ma_result ma_engine_node_init_preallocated(const ma_engine_node_config* pConfig, void* pHeap, ma_engine_node* pEngineNode); +MA_API ma_result ma_engine_node_init(const ma_engine_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_engine_node* pEngineNode); +MA_API void ma_engine_node_uninit(ma_engine_node* pEngineNode, const ma_allocation_callbacks* pAllocationCallbacks); + + +#define MA_SOUND_SOURCE_CHANNEL_COUNT 0xFFFFFFFF + +/* Callback for when a sound reaches the end. */ +typedef void (* ma_sound_end_proc)(void* pUserData, ma_sound* pSound); + +typedef struct +{ + const char* pFilePath; /* Set this to load from the resource manager. */ + const wchar_t* pFilePathW; /* Set this to load from the resource manager. */ + ma_data_source* pDataSource; /* Set this to load from an existing data source. */ + ma_node* pInitialAttachment; /* If set, the sound will be attached to an input of this node. This can be set to a ma_sound. If set to NULL, the sound will be attached directly to the endpoint unless MA_SOUND_FLAG_NO_DEFAULT_ATTACHMENT is set in `flags`. */ + ma_uint32 initialAttachmentInputBusIndex; /* The index of the input bus of pInitialAttachment to attach the sound to. */ + ma_uint32 channelsIn; /* Ignored if using a data source as input (the data source's channel count will be used always). Otherwise, setting to 0 will cause the engine's channel count to be used. */ + ma_uint32 channelsOut; /* Set this to 0 (default) to use the engine's channel count. Set to MA_SOUND_SOURCE_CHANNEL_COUNT to use the data source's channel count (only used if using a data source as input). */ + ma_mono_expansion_mode monoExpansionMode; /* Controls how the mono channel should be expanded to other channels when spatialization is disabled on a sound. */ + ma_uint32 flags; /* A combination of MA_SOUND_FLAG_* flags. */ + ma_uint32 volumeSmoothTimeInPCMFrames; /* The number of frames to smooth over volume changes. Defaults to 0 in which case no smoothing is used. */ + ma_uint64 initialSeekPointInPCMFrames; /* Initializes the sound such that it's seeked to this location by default. */ + ma_uint64 rangeBegInPCMFrames; + ma_uint64 rangeEndInPCMFrames; + ma_uint64 loopPointBegInPCMFrames; + ma_uint64 loopPointEndInPCMFrames; + ma_bool32 isLooping; + ma_sound_end_proc endCallback; /* Fired when the sound reaches the end. Will be fired from the audio thread. Do not restart, uninitialize or otherwise change the state of the sound from here. Instead fire an event or set a variable to indicate to a different thread to change the start of the sound. Will not be fired in response to a scheduled stop with ma_sound_set_stop_time_*(). */ + void* pEndCallbackUserData; +#ifndef MA_NO_RESOURCE_MANAGER + ma_resource_manager_pipeline_notifications initNotifications; +#endif + ma_fence* pDoneFence; /* Deprecated. Use initNotifications instead. Released when the resource manager has finished decoding the entire sound. Not used with streams. */ +} ma_sound_config; + +MA_API ma_sound_config ma_sound_config_init(void); /* Deprecated. Will be removed in version 0.12. Use ma_sound_config_2() instead. */ +MA_API ma_sound_config ma_sound_config_init_2(ma_engine* pEngine); /* Will be renamed to ma_sound_config_init() in version 0.12. */ + +struct ma_sound +{ + ma_engine_node engineNode; /* Must be the first member for compatibility with the ma_node API. */ + ma_data_source* pDataSource; + MA_ATOMIC(8, ma_uint64) seekTarget; /* The PCM frame index to seek to in the mixing thread. Set to (~(ma_uint64)0) to not perform any seeking. */ + MA_ATOMIC(4, ma_bool32) atEnd; + ma_sound_end_proc endCallback; + void* pEndCallbackUserData; + ma_bool8 ownsDataSource; + + /* + We're declaring a resource manager data source object here to save us a malloc when loading a + sound via the resource manager, which I *think* will be the most common scenario. + */ +#ifndef MA_NO_RESOURCE_MANAGER + ma_resource_manager_data_source* pResourceManagerDataSource; +#endif +}; + +/* Structure specifically for sounds played with ma_engine_play_sound(). Making this a separate structure to reduce overhead. */ +typedef struct ma_sound_inlined ma_sound_inlined; +struct ma_sound_inlined +{ + ma_sound sound; + ma_sound_inlined* pNext; + ma_sound_inlined* pPrev; +}; + +/* A sound group is just a sound. */ +typedef ma_sound_config ma_sound_group_config; +typedef ma_sound ma_sound_group; + +MA_API ma_sound_group_config ma_sound_group_config_init(void); /* Deprecated. Will be removed in version 0.12. Use ma_sound_config_2() instead. */ +MA_API ma_sound_group_config ma_sound_group_config_init_2(ma_engine* pEngine); /* Will be renamed to ma_sound_config_init() in version 0.12. */ + +typedef void (* ma_engine_process_proc)(void* pUserData, float* pFramesOut, ma_uint64 frameCount); + +typedef struct +{ +#if !defined(MA_NO_RESOURCE_MANAGER) + ma_resource_manager* pResourceManager; /* Can be null in which case a resource manager will be created for you. */ +#endif +#if !defined(MA_NO_DEVICE_IO) + ma_context* pContext; + ma_device* pDevice; /* If set, the caller is responsible for calling ma_engine_data_callback() in the device's data callback. */ + ma_device_id* pPlaybackDeviceID; /* The ID of the playback device to use with the default listener. */ + ma_device_data_proc dataCallback; /* Can be null. Can be used to provide a custom device data callback. */ + ma_device_notification_proc notificationCallback; +#endif + ma_log* pLog; /* When set to NULL, will use the context's log. */ + ma_uint32 listenerCount; /* Must be between 1 and MA_ENGINE_MAX_LISTENERS. */ + ma_uint32 channels; /* The number of channels to use when mixing and spatializing. When set to 0, will use the native channel count of the device. */ + ma_uint32 sampleRate; /* The sample rate. When set to 0 will use the native channel count of the device. */ + ma_uint32 periodSizeInFrames; /* If set to something other than 0, updates will always be exactly this size. The underlying device may be a different size, but from the perspective of the mixer that won't matter.*/ + ma_uint32 periodSizeInMilliseconds; /* Used if periodSizeInFrames is unset. */ + ma_uint32 gainSmoothTimeInFrames; /* The number of frames to interpolate the gain of spatialized sounds across. If set to 0, will use gainSmoothTimeInMilliseconds. */ + ma_uint32 gainSmoothTimeInMilliseconds; /* When set to 0, gainSmoothTimeInFrames will be used. If both are set to 0, a default value will be used. */ + ma_uint32 defaultVolumeSmoothTimeInPCMFrames; /* Defaults to 0. Controls the default amount of smoothing to apply to volume changes to sounds. High values means more smoothing at the expense of high latency (will take longer to reach the new volume). */ + ma_allocation_callbacks allocationCallbacks; + ma_bool32 noAutoStart; /* When set to true, requires an explicit call to ma_engine_start(). This is false by default, meaning the engine will be started automatically in ma_engine_init(). */ + ma_bool32 noDevice; /* When set to true, don't create a default device. ma_engine_read_pcm_frames() can be called manually to read data. */ + ma_mono_expansion_mode monoExpansionMode; /* Controls how the mono channel should be expanded to other channels when spatialization is disabled on a sound. */ + ma_vfs* pResourceManagerVFS; /* A pointer to a pre-allocated VFS object to use with the resource manager. This is ignored if pResourceManager is not NULL. */ + ma_engine_process_proc onProcess; /* Fired at the end of each call to ma_engine_read_pcm_frames(). For engine's that manage their own internal device (the default configuration), this will be fired from the audio thread, and you do not need to call ma_engine_read_pcm_frames() manually in order to trigger this. */ + void* pProcessUserData; /* User data that's passed into onProcess. */ +} ma_engine_config; + +MA_API ma_engine_config ma_engine_config_init(void); + + +struct ma_engine +{ + ma_node_graph nodeGraph; /* An engine is a node graph. It should be able to be plugged into any ma_node_graph API (with a cast) which means this must be the first member of this struct. */ +#if !defined(MA_NO_RESOURCE_MANAGER) + ma_resource_manager* pResourceManager; +#endif +#if !defined(MA_NO_DEVICE_IO) + ma_device* pDevice; /* Optionally set via the config, otherwise allocated by the engine in ma_engine_init(). */ +#endif + ma_log* pLog; + ma_uint32 sampleRate; + ma_uint32 listenerCount; + ma_spatializer_listener listeners[MA_ENGINE_MAX_LISTENERS]; + ma_allocation_callbacks allocationCallbacks; + ma_bool8 ownsResourceManager; + ma_bool8 ownsDevice; + ma_spinlock inlinedSoundLock; /* For synchronizing access so the inlined sound list. */ + ma_sound_inlined* pInlinedSoundHead; /* The first inlined sound. Inlined sounds are tracked in a linked list. */ + MA_ATOMIC(4, ma_uint32) inlinedSoundCount; /* The total number of allocated inlined sound objects. Used for debugging. */ + ma_uint32 gainSmoothTimeInFrames; /* The number of frames to interpolate the gain of spatialized sounds across. */ + ma_uint32 defaultVolumeSmoothTimeInPCMFrames; + ma_mono_expansion_mode monoExpansionMode; + ma_engine_process_proc onProcess; + void* pProcessUserData; +}; + +MA_API ma_result ma_engine_init(const ma_engine_config* pConfig, ma_engine* pEngine); +MA_API void ma_engine_uninit(ma_engine* pEngine); +MA_API ma_result ma_engine_read_pcm_frames(ma_engine* pEngine, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead); +MA_API ma_node_graph* ma_engine_get_node_graph(ma_engine* pEngine); +#if !defined(MA_NO_RESOURCE_MANAGER) +MA_API ma_resource_manager* ma_engine_get_resource_manager(ma_engine* pEngine); +#endif +MA_API ma_device* ma_engine_get_device(ma_engine* pEngine); +MA_API ma_log* ma_engine_get_log(ma_engine* pEngine); +MA_API ma_node* ma_engine_get_endpoint(ma_engine* pEngine); +MA_API ma_uint64 ma_engine_get_time_in_pcm_frames(const ma_engine* pEngine); +MA_API ma_uint64 ma_engine_get_time_in_milliseconds(const ma_engine* pEngine); +MA_API ma_result ma_engine_set_time_in_pcm_frames(ma_engine* pEngine, ma_uint64 globalTime); +MA_API ma_result ma_engine_set_time_in_milliseconds(ma_engine* pEngine, ma_uint64 globalTime); +MA_API ma_uint64 ma_engine_get_time(const ma_engine* pEngine); /* Deprecated. Use ma_engine_get_time_in_pcm_frames(). Will be removed in version 0.12. */ +MA_API ma_result ma_engine_set_time(ma_engine* pEngine, ma_uint64 globalTime); /* Deprecated. Use ma_engine_set_time_in_pcm_frames(). Will be removed in version 0.12. */ +MA_API ma_uint32 ma_engine_get_channels(const ma_engine* pEngine); +MA_API ma_uint32 ma_engine_get_sample_rate(const ma_engine* pEngine); + +MA_API ma_result ma_engine_start(ma_engine* pEngine); +MA_API ma_result ma_engine_stop(ma_engine* pEngine); +MA_API ma_result ma_engine_set_volume(ma_engine* pEngine, float volume); +MA_API float ma_engine_get_volume(ma_engine* pEngine); +MA_API ma_result ma_engine_set_gain_db(ma_engine* pEngine, float gainDB); +MA_API float ma_engine_get_gain_db(ma_engine* pEngine); + +MA_API ma_uint32 ma_engine_get_listener_count(const ma_engine* pEngine); +MA_API ma_uint32 ma_engine_find_closest_listener(const ma_engine* pEngine, float absolutePosX, float absolutePosY, float absolutePosZ); +MA_API void ma_engine_listener_set_position(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z); +MA_API ma_vec3f ma_engine_listener_get_position(const ma_engine* pEngine, ma_uint32 listenerIndex); +MA_API void ma_engine_listener_set_direction(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z); +MA_API ma_vec3f ma_engine_listener_get_direction(const ma_engine* pEngine, ma_uint32 listenerIndex); +MA_API void ma_engine_listener_set_velocity(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z); +MA_API ma_vec3f ma_engine_listener_get_velocity(const ma_engine* pEngine, ma_uint32 listenerIndex); +MA_API void ma_engine_listener_set_cone(ma_engine* pEngine, ma_uint32 listenerIndex, float innerAngleInRadians, float outerAngleInRadians, float outerGain); +MA_API void ma_engine_listener_get_cone(const ma_engine* pEngine, ma_uint32 listenerIndex, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain); +MA_API void ma_engine_listener_set_world_up(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z); +MA_API ma_vec3f ma_engine_listener_get_world_up(const ma_engine* pEngine, ma_uint32 listenerIndex); +MA_API void ma_engine_listener_set_enabled(ma_engine* pEngine, ma_uint32 listenerIndex, ma_bool32 isEnabled); +MA_API ma_bool32 ma_engine_listener_is_enabled(const ma_engine* pEngine, ma_uint32 listenerIndex); + +#ifndef MA_NO_RESOURCE_MANAGER +MA_API ma_result ma_engine_play_sound_ex(ma_engine* pEngine, const char* pFilePath, ma_node* pNode, ma_uint32 nodeInputBusIndex); +MA_API ma_result ma_engine_play_sound(ma_engine* pEngine, const char* pFilePath, ma_sound_group* pGroup); /* Fire and forget. */ +#endif + +#ifndef MA_NO_RESOURCE_MANAGER +MA_API ma_result ma_sound_init_from_file(ma_engine* pEngine, const char* pFilePath, ma_uint32 flags, ma_sound_group* pGroup, ma_fence* pDoneFence, ma_sound* pSound); +MA_API ma_result ma_sound_init_from_file_w(ma_engine* pEngine, const wchar_t* pFilePath, ma_uint32 flags, ma_sound_group* pGroup, ma_fence* pDoneFence, ma_sound* pSound); +MA_API ma_result ma_sound_init_copy(ma_engine* pEngine, const ma_sound* pExistingSound, ma_uint32 flags, ma_sound_group* pGroup, ma_sound* pSound); +#endif +MA_API ma_result ma_sound_init_from_data_source(ma_engine* pEngine, ma_data_source* pDataSource, ma_uint32 flags, ma_sound_group* pGroup, ma_sound* pSound); +MA_API ma_result ma_sound_init_ex(ma_engine* pEngine, const ma_sound_config* pConfig, ma_sound* pSound); +MA_API void ma_sound_uninit(ma_sound* pSound); +MA_API ma_engine* ma_sound_get_engine(const ma_sound* pSound); +MA_API ma_data_source* ma_sound_get_data_source(const ma_sound* pSound); +MA_API ma_result ma_sound_start(ma_sound* pSound); +MA_API ma_result ma_sound_stop(ma_sound* pSound); +MA_API ma_result ma_sound_stop_with_fade_in_pcm_frames(ma_sound* pSound, ma_uint64 fadeLengthInFrames); /* Will overwrite any scheduled stop and fade. */ +MA_API ma_result ma_sound_stop_with_fade_in_milliseconds(ma_sound* pSound, ma_uint64 fadeLengthInFrames); /* Will overwrite any scheduled stop and fade. */ +MA_API void ma_sound_set_volume(ma_sound* pSound, float volume); +MA_API float ma_sound_get_volume(const ma_sound* pSound); +MA_API void ma_sound_set_pan(ma_sound* pSound, float pan); +MA_API float ma_sound_get_pan(const ma_sound* pSound); +MA_API void ma_sound_set_pan_mode(ma_sound* pSound, ma_pan_mode panMode); +MA_API ma_pan_mode ma_sound_get_pan_mode(const ma_sound* pSound); +MA_API void ma_sound_set_pitch(ma_sound* pSound, float pitch); +MA_API float ma_sound_get_pitch(const ma_sound* pSound); +MA_API void ma_sound_set_spatialization_enabled(ma_sound* pSound, ma_bool32 enabled); +MA_API ma_bool32 ma_sound_is_spatialization_enabled(const ma_sound* pSound); +MA_API void ma_sound_set_pinned_listener_index(ma_sound* pSound, ma_uint32 listenerIndex); +MA_API ma_uint32 ma_sound_get_pinned_listener_index(const ma_sound* pSound); +MA_API ma_uint32 ma_sound_get_listener_index(const ma_sound* pSound); +MA_API ma_vec3f ma_sound_get_direction_to_listener(const ma_sound* pSound); +MA_API void ma_sound_set_position(ma_sound* pSound, float x, float y, float z); +MA_API ma_vec3f ma_sound_get_position(const ma_sound* pSound); +MA_API void ma_sound_set_direction(ma_sound* pSound, float x, float y, float z); +MA_API ma_vec3f ma_sound_get_direction(const ma_sound* pSound); +MA_API void ma_sound_set_velocity(ma_sound* pSound, float x, float y, float z); +MA_API ma_vec3f ma_sound_get_velocity(const ma_sound* pSound); +MA_API void ma_sound_set_attenuation_model(ma_sound* pSound, ma_attenuation_model attenuationModel); +MA_API ma_attenuation_model ma_sound_get_attenuation_model(const ma_sound* pSound); +MA_API void ma_sound_set_positioning(ma_sound* pSound, ma_positioning positioning); +MA_API ma_positioning ma_sound_get_positioning(const ma_sound* pSound); +MA_API void ma_sound_set_rolloff(ma_sound* pSound, float rolloff); +MA_API float ma_sound_get_rolloff(const ma_sound* pSound); +MA_API void ma_sound_set_min_gain(ma_sound* pSound, float minGain); +MA_API float ma_sound_get_min_gain(const ma_sound* pSound); +MA_API void ma_sound_set_max_gain(ma_sound* pSound, float maxGain); +MA_API float ma_sound_get_max_gain(const ma_sound* pSound); +MA_API void ma_sound_set_min_distance(ma_sound* pSound, float minDistance); +MA_API float ma_sound_get_min_distance(const ma_sound* pSound); +MA_API void ma_sound_set_max_distance(ma_sound* pSound, float maxDistance); +MA_API float ma_sound_get_max_distance(const ma_sound* pSound); +MA_API void ma_sound_set_cone(ma_sound* pSound, float innerAngleInRadians, float outerAngleInRadians, float outerGain); +MA_API void ma_sound_get_cone(const ma_sound* pSound, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain); +MA_API void ma_sound_set_doppler_factor(ma_sound* pSound, float dopplerFactor); +MA_API float ma_sound_get_doppler_factor(const ma_sound* pSound); +MA_API void ma_sound_set_directional_attenuation_factor(ma_sound* pSound, float directionalAttenuationFactor); +MA_API float ma_sound_get_directional_attenuation_factor(const ma_sound* pSound); +MA_API void ma_sound_set_fade_in_pcm_frames(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInFrames); +MA_API void ma_sound_set_fade_in_milliseconds(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInMilliseconds); +MA_API void ma_sound_set_fade_start_in_pcm_frames(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInFrames, ma_uint64 absoluteGlobalTimeInFrames); +MA_API void ma_sound_set_fade_start_in_milliseconds(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInMilliseconds, ma_uint64 absoluteGlobalTimeInMilliseconds); +MA_API float ma_sound_get_current_fade_volume(const ma_sound* pSound); +MA_API void ma_sound_set_start_time_in_pcm_frames(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInFrames); +MA_API void ma_sound_set_start_time_in_milliseconds(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInMilliseconds); +MA_API void ma_sound_set_stop_time_in_pcm_frames(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInFrames); +MA_API void ma_sound_set_stop_time_in_milliseconds(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInMilliseconds); +MA_API void ma_sound_set_stop_time_with_fade_in_pcm_frames(ma_sound* pSound, ma_uint64 stopAbsoluteGlobalTimeInFrames, ma_uint64 fadeLengthInFrames); +MA_API void ma_sound_set_stop_time_with_fade_in_milliseconds(ma_sound* pSound, ma_uint64 stopAbsoluteGlobalTimeInMilliseconds, ma_uint64 fadeLengthInMilliseconds); +MA_API ma_bool32 ma_sound_is_playing(const ma_sound* pSound); +MA_API ma_uint64 ma_sound_get_time_in_pcm_frames(const ma_sound* pSound); +MA_API ma_uint64 ma_sound_get_time_in_milliseconds(const ma_sound* pSound); +MA_API void ma_sound_set_looping(ma_sound* pSound, ma_bool32 isLooping); +MA_API ma_bool32 ma_sound_is_looping(const ma_sound* pSound); +MA_API ma_bool32 ma_sound_at_end(const ma_sound* pSound); +MA_API ma_result ma_sound_seek_to_pcm_frame(ma_sound* pSound, ma_uint64 frameIndex); /* Just a wrapper around ma_data_source_seek_to_pcm_frame(). */ +MA_API ma_result ma_sound_get_data_format(ma_sound* pSound, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap); +MA_API ma_result ma_sound_get_cursor_in_pcm_frames(ma_sound* pSound, ma_uint64* pCursor); +MA_API ma_result ma_sound_get_length_in_pcm_frames(ma_sound* pSound, ma_uint64* pLength); +MA_API ma_result ma_sound_get_cursor_in_seconds(ma_sound* pSound, float* pCursor); +MA_API ma_result ma_sound_get_length_in_seconds(ma_sound* pSound, float* pLength); +MA_API ma_result ma_sound_set_end_callback(ma_sound* pSound, ma_sound_end_proc callback, void* pUserData); + +MA_API ma_result ma_sound_group_init(ma_engine* pEngine, ma_uint32 flags, ma_sound_group* pParentGroup, ma_sound_group* pGroup); +MA_API ma_result ma_sound_group_init_ex(ma_engine* pEngine, const ma_sound_group_config* pConfig, ma_sound_group* pGroup); +MA_API void ma_sound_group_uninit(ma_sound_group* pGroup); +MA_API ma_engine* ma_sound_group_get_engine(const ma_sound_group* pGroup); +MA_API ma_result ma_sound_group_start(ma_sound_group* pGroup); +MA_API ma_result ma_sound_group_stop(ma_sound_group* pGroup); +MA_API void ma_sound_group_set_volume(ma_sound_group* pGroup, float volume); +MA_API float ma_sound_group_get_volume(const ma_sound_group* pGroup); +MA_API void ma_sound_group_set_pan(ma_sound_group* pGroup, float pan); +MA_API float ma_sound_group_get_pan(const ma_sound_group* pGroup); +MA_API void ma_sound_group_set_pan_mode(ma_sound_group* pGroup, ma_pan_mode panMode); +MA_API ma_pan_mode ma_sound_group_get_pan_mode(const ma_sound_group* pGroup); +MA_API void ma_sound_group_set_pitch(ma_sound_group* pGroup, float pitch); +MA_API float ma_sound_group_get_pitch(const ma_sound_group* pGroup); +MA_API void ma_sound_group_set_spatialization_enabled(ma_sound_group* pGroup, ma_bool32 enabled); +MA_API ma_bool32 ma_sound_group_is_spatialization_enabled(const ma_sound_group* pGroup); +MA_API void ma_sound_group_set_pinned_listener_index(ma_sound_group* pGroup, ma_uint32 listenerIndex); +MA_API ma_uint32 ma_sound_group_get_pinned_listener_index(const ma_sound_group* pGroup); +MA_API ma_uint32 ma_sound_group_get_listener_index(const ma_sound_group* pGroup); +MA_API ma_vec3f ma_sound_group_get_direction_to_listener(const ma_sound_group* pGroup); +MA_API void ma_sound_group_set_position(ma_sound_group* pGroup, float x, float y, float z); +MA_API ma_vec3f ma_sound_group_get_position(const ma_sound_group* pGroup); +MA_API void ma_sound_group_set_direction(ma_sound_group* pGroup, float x, float y, float z); +MA_API ma_vec3f ma_sound_group_get_direction(const ma_sound_group* pGroup); +MA_API void ma_sound_group_set_velocity(ma_sound_group* pGroup, float x, float y, float z); +MA_API ma_vec3f ma_sound_group_get_velocity(const ma_sound_group* pGroup); +MA_API void ma_sound_group_set_attenuation_model(ma_sound_group* pGroup, ma_attenuation_model attenuationModel); +MA_API ma_attenuation_model ma_sound_group_get_attenuation_model(const ma_sound_group* pGroup); +MA_API void ma_sound_group_set_positioning(ma_sound_group* pGroup, ma_positioning positioning); +MA_API ma_positioning ma_sound_group_get_positioning(const ma_sound_group* pGroup); +MA_API void ma_sound_group_set_rolloff(ma_sound_group* pGroup, float rolloff); +MA_API float ma_sound_group_get_rolloff(const ma_sound_group* pGroup); +MA_API void ma_sound_group_set_min_gain(ma_sound_group* pGroup, float minGain); +MA_API float ma_sound_group_get_min_gain(const ma_sound_group* pGroup); +MA_API void ma_sound_group_set_max_gain(ma_sound_group* pGroup, float maxGain); +MA_API float ma_sound_group_get_max_gain(const ma_sound_group* pGroup); +MA_API void ma_sound_group_set_min_distance(ma_sound_group* pGroup, float minDistance); +MA_API float ma_sound_group_get_min_distance(const ma_sound_group* pGroup); +MA_API void ma_sound_group_set_max_distance(ma_sound_group* pGroup, float maxDistance); +MA_API float ma_sound_group_get_max_distance(const ma_sound_group* pGroup); +MA_API void ma_sound_group_set_cone(ma_sound_group* pGroup, float innerAngleInRadians, float outerAngleInRadians, float outerGain); +MA_API void ma_sound_group_get_cone(const ma_sound_group* pGroup, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain); +MA_API void ma_sound_group_set_doppler_factor(ma_sound_group* pGroup, float dopplerFactor); +MA_API float ma_sound_group_get_doppler_factor(const ma_sound_group* pGroup); +MA_API void ma_sound_group_set_directional_attenuation_factor(ma_sound_group* pGroup, float directionalAttenuationFactor); +MA_API float ma_sound_group_get_directional_attenuation_factor(const ma_sound_group* pGroup); +MA_API void ma_sound_group_set_fade_in_pcm_frames(ma_sound_group* pGroup, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInFrames); +MA_API void ma_sound_group_set_fade_in_milliseconds(ma_sound_group* pGroup, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInMilliseconds); +MA_API float ma_sound_group_get_current_fade_volume(ma_sound_group* pGroup); +MA_API void ma_sound_group_set_start_time_in_pcm_frames(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInFrames); +MA_API void ma_sound_group_set_start_time_in_milliseconds(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInMilliseconds); +MA_API void ma_sound_group_set_stop_time_in_pcm_frames(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInFrames); +MA_API void ma_sound_group_set_stop_time_in_milliseconds(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInMilliseconds); +MA_API ma_bool32 ma_sound_group_is_playing(const ma_sound_group* pGroup); +MA_API ma_uint64 ma_sound_group_get_time_in_pcm_frames(const ma_sound_group* pGroup); +#endif /* MA_NO_ENGINE */ +/* END SECTION: miniaudio_engine.h */ + +#ifdef __cplusplus +} +#endif +#endif /* miniaudio_h */ + + +/* +This is for preventing greying out of the implementation section. +*/ +#if defined(Q_CREATOR_RUN) || defined(__INTELLISENSE__) || defined(__CDT_PARSER__) +#define MINIAUDIO_IMPLEMENTATION +#endif + +/************************************************************************************************************************************************************ +************************************************************************************************************************************************************* + +IMPLEMENTATION + +************************************************************************************************************************************************************* +************************************************************************************************************************************************************/ +#if defined(MINIAUDIO_IMPLEMENTATION) || defined(MA_IMPLEMENTATION) +#ifndef miniaudio_c +#define miniaudio_c + +#include +#include /* For INT_MAX */ +#include /* sin(), etc. */ +#include /* For malloc(), free(), wcstombs(). */ +#include /* For memset() */ + +#include +#include +#if !defined(_MSC_VER) && !defined(__DMC__) + #include /* For strcasecmp(). */ + #include /* For wcslen(), wcsrtombs() */ +#endif +#ifdef _MSC_VER + #include /* For _controlfp_s constants */ +#endif + +#if defined(MA_WIN32) + #include + + /* + There's a possibility that WIN32_LEAN_AND_MEAN has been defined which will exclude some symbols + such as STGM_READ and CLSCTL_ALL. We need to check these and define them ourselves if they're + unavailable. + */ + #ifndef STGM_READ + #define STGM_READ 0x00000000L + #endif + #ifndef CLSCTX_ALL + #define CLSCTX_ALL 23 + #endif + + /* IUnknown is used by both the WASAPI and DirectSound backends. It easier to just declare our version here. */ + typedef struct ma_IUnknown ma_IUnknown; +#endif + +#if !defined(MA_WIN32) +#include +#include /* select() (used for ma_sleep()). */ +#include +#endif + +#ifdef MA_NX +#include /* For nanosleep() */ +#endif + +#include /* For fstat(), etc. */ + +#ifdef MA_EMSCRIPTEN +#include +#endif + + +/* Architecture Detection */ +#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 + +#if defined(__arm__) || defined(_M_ARM) +#define MA_ARM32 +#endif +#if defined(__arm64) || defined(__arm64__) || defined(__aarch64__) || defined(_M_ARM64) +#define MA_ARM64 +#endif + +#if defined(__x86_64__) || defined(_M_X64) +#define MA_X64 +#elif defined(__i386) || defined(_M_IX86) +#define MA_X86 +#elif defined(MA_ARM32) || defined(MA_ARM64) +#define MA_ARM +#endif + +/* Intrinsics Support */ +#if (defined(MA_X64) || defined(MA_X86)) && !defined(__COSMOPOLITAN__) + #if defined(_MSC_VER) && !defined(__clang__) + /* 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 */ + #define MA_SUPPORT_AVX2 + #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 + #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 + #endif + + #if 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 + #include + #endif +#endif + +/* Begin globally disabled warnings. */ +#if defined(_MSC_VER) + #pragma warning(push) + #pragma warning(disable:4752) /* found Intel(R) Advanced Vector Extensions; consider using /arch:AVX */ + #pragma warning(disable:4049) /* compiler limit : terminating line number emission */ +#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 && (defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 160040219) + 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(MA_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 ma_uint64 ma_xgetbv(int reg) + { + unsigned int hi; + unsigned int lo; + + __asm__ __volatile__ ( + "xgetbv" : "=a"(lo), "=d"(hi) : "c"(reg) + ); + + return ((ma_uint64)hi << 32) | (ma_uint64)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(void) +{ +#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(void) +{ +#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_neon(void) +{ +#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 +} + +#if defined(__has_builtin) + #define MA_COMPILER_HAS_BUILTIN(x) __has_builtin(x) +#else + #define MA_COMPILER_HAS_BUILTIN(x) 0 +#endif + +#ifndef MA_ASSUME + #if MA_COMPILER_HAS_BUILTIN(__builtin_assume) + #define MA_ASSUME(x) __builtin_assume(x) + #elif MA_COMPILER_HAS_BUILTIN(__builtin_unreachable) + #define MA_ASSUME(x) do { if (!(x)) __builtin_unreachable(); } while (0) + #elif defined(_MSC_VER) + #define MA_ASSUME(x) __assume(x) + #else + #define MA_ASSUME(x) (void)(x) + #endif +#endif + +#ifndef MA_RESTRICT + #if defined(__clang__) || defined(__GNUC__) || defined(_MSC_VER) + #define MA_RESTRICT __restrict + #else + #define MA_RESTRICT + #endif +#endif + +#if defined(_MSC_VER) && _MSC_VER >= 1400 + #define MA_HAS_BYTESWAP16_INTRINSIC + #define MA_HAS_BYTESWAP32_INTRINSIC + #define MA_HAS_BYTESWAP64_INTRINSIC +#elif defined(__clang__) + #if MA_COMPILER_HAS_BUILTIN(__builtin_bswap16) + #define MA_HAS_BYTESWAP16_INTRINSIC + #endif + #if MA_COMPILER_HAS_BUILTIN(__builtin_bswap32) + #define MA_HAS_BYTESWAP32_INTRINSIC + #endif + #if MA_COMPILER_HAS_BUILTIN(__builtin_bswap64) + #define MA_HAS_BYTESWAP64_INTRINSIC + #endif +#elif defined(__GNUC__) + #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) + #define MA_HAS_BYTESWAP32_INTRINSIC + #define MA_HAS_BYTESWAP64_INTRINSIC + #endif + #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)) + #define MA_HAS_BYTESWAP16_INTRINSIC + #endif +#endif + + +static MA_INLINE ma_bool32 ma_is_little_endian(void) +{ +#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(void) +{ + return !ma_is_little_endian(); +} + + +static MA_INLINE ma_uint32 ma_swap_endian_uint32(ma_uint32 n) +{ +#ifdef MA_HAS_BYTESWAP32_INTRINSIC + #if defined(_MSC_VER) + return _byteswap_ulong(n); + #elif defined(__GNUC__) || defined(__clang__) + #if defined(MA_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 6) && !defined(MA_64BIT) /* <-- 64-bit inline assembly has not been tested, so disabling for now. */ + /* Inline assembly optimized implementation for ARM. In my testing, GCC does not generate optimized code with __builtin_bswap32(). */ + ma_uint32 r; + __asm__ __volatile__ ( + #if defined(MA_64BIT) + "rev %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(n) /* <-- This is untested. If someone in the community could test this, that would be appreciated! */ + #else + "rev %[out], %[in]" : [out]"=r"(r) : [in]"r"(n) + #endif + ); + return r; + #else + return __builtin_bswap32(n); + #endif + #else + #error "This compiler does not support the byte swap intrinsic." + #endif +#else + return ((n & 0xFF000000) >> 24) | + ((n & 0x00FF0000) >> 8) | + ((n & 0x0000FF00) << 8) | + ((n & 0x000000FF) << 24); +#endif +} + + +#if !defined(MA_EMSCRIPTEN) +#ifdef MA_WIN32 +static void ma_sleep__win32(ma_uint32 milliseconds) +{ + Sleep((DWORD)milliseconds); +} +#endif +#ifdef MA_POSIX +static void ma_sleep__posix(ma_uint32 milliseconds) +{ +#ifdef MA_EMSCRIPTEN + (void)milliseconds; + MA_ASSERT(MA_FALSE); /* The Emscripten build should never sleep. */ +#else + #if (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309L) || defined(MA_NX) + struct timespec ts; + ts.tv_sec = milliseconds / 1000; + ts.tv_nsec = milliseconds % 1000 * 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 +} +#endif + +static MA_INLINE void ma_sleep(ma_uint32 milliseconds) +{ +#ifdef MA_WIN32 + ma_sleep__win32(milliseconds); +#endif +#ifdef MA_POSIX + ma_sleep__posix(milliseconds); +#endif +} +#endif + +static MA_INLINE void ma_yield(void) +{ +#if defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64) + /* x86/x64 */ + #if (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__DMC__)) && !defined(__clang__) + #if _MSC_VER >= 1400 + _mm_pause(); + #else + #if defined(__DMC__) + /* Digital Mars does not recognize the PAUSE opcode. Fall back to NOP. */ + __asm nop; + #else + __asm pause; + #endif + #endif + #else + __asm__ __volatile__ ("pause"); + #endif +#elif (defined(__arm__) && defined(__ARM_ARCH) && __ARM_ARCH >= 7) || defined(_M_ARM64) || (defined(_M_ARM) && _M_ARM >= 7) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6T2__) + /* ARM */ + #if defined(_MSC_VER) + /* Apparently there is a __yield() intrinsic that's compatible with ARM, but I cannot find documentation for it nor can I find where it's declared. */ + __yield(); + #else + __asm__ __volatile__ ("yield"); /* ARMv6K/ARMv6T2 and above. */ + #endif +#else + /* Unknown or unsupported architecture. No-op. */ +#endif +} + + +#define MA_MM_DENORMALS_ZERO_MASK 0x0040 +#define MA_MM_FLUSH_ZERO_MASK 0x8000 + +static MA_INLINE unsigned int ma_disable_denormals(void) +{ + unsigned int prevState; + + #if defined(_MSC_VER) + { + /* + Older versions of Visual Studio don't support the "safe" versions of _controlfp_s(). I don't + know which version of Visual Studio first added support for _controlfp_s(), but I do know + that VC6 lacks support. _MSC_VER = 1200 is VC6, but if you get compilation errors on older + versions of Visual Studio, let me know and I'll make the necessary adjustment. + */ + #if _MSC_VER <= 1200 + { + prevState = _statusfp(); + _controlfp(prevState | _DN_FLUSH, _MCW_DN); + } + #else + { + unsigned int unused; + _controlfp_s(&prevState, 0, 0); + _controlfp_s(&unused, prevState | _DN_FLUSH, _MCW_DN); + } + #endif + } + #elif defined(MA_X86) || defined(MA_X64) + { + #if defined(__SSE2__) && !(defined(__TINYC__) || defined(__WATCOMC__) || defined(__COSMOPOLITAN__)) /* <-- Add compilers that lack support for _mm_getcsr() and _mm_setcsr() to this list. */ + { + prevState = _mm_getcsr(); + _mm_setcsr(prevState | MA_MM_DENORMALS_ZERO_MASK | MA_MM_FLUSH_ZERO_MASK); + } + #else + { + /* x88/64, but no support for _mm_getcsr()/_mm_setcsr(). May need to fall back to inlined assembly here. */ + prevState = 0; + } + #endif + } + #else + { + /* Unknown or unsupported architecture. No-op. */ + prevState = 0; + } + #endif + + return prevState; +} + +static MA_INLINE void ma_restore_denormals(unsigned int prevState) +{ + #if defined(_MSC_VER) + { + /* Older versions of Visual Studio do not support _controlfp_s(). See ma_disable_denormals(). */ + #if _MSC_VER <= 1200 + { + _controlfp(prevState, _MCW_DN); + } + #else + { + unsigned int unused; + _controlfp_s(&unused, prevState, _MCW_DN); + } + #endif + } + #elif defined(MA_X86) || defined(MA_X64) + { + #if defined(__SSE2__) && !(defined(__TINYC__) || defined(__WATCOMC__) || defined(__COSMOPOLITAN__)) /* <-- Add compilers that lack support for _mm_getcsr() and _mm_setcsr() to this list. */ + { + _mm_setcsr(prevState); + } + #else + { + /* x88/64, but no support for _mm_getcsr()/_mm_setcsr(). May need to fall back to inlined assembly here. */ + (void)prevState; + } + #endif + } + #else + { + /* Unknown or unsupported architecture. No-op. */ + (void)prevState; + } + #endif +} + + +#ifdef MA_ANDROID +#include + +int ma_android_sdk_version() +{ + char sdkVersion[PROP_VALUE_MAX + 1] = {0, }; + if (__system_property_get("ro.build.version.sdk", sdkVersion)) { + return atoi(sdkVersion); + } + + return 0; +} +#endif + + +#ifndef MA_COINIT_VALUE +#define MA_COINIT_VALUE 0 /* 0 = COINIT_MULTITHREADED */ +#endif + + +#ifndef MA_FLT_MAX + #ifdef FLT_MAX + #define MA_FLT_MAX FLT_MAX + #else + #define MA_FLT_MAX 3.402823466e+38F + #endif +#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 default period size in milliseconds for low latency mode. */ +#ifndef MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY +#define MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY 10 +#endif + +/* The default buffer size in milliseconds for conservative mode. */ +#ifndef MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE +#define MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE 100 +#endif + +/* The default LPF filter order for linear resampling. Note that this is clamped to MA_MAX_FILTER_ORDER. */ +#ifndef MA_DEFAULT_RESAMPLER_LPF_ORDER + #if MA_MAX_FILTER_ORDER >= 4 + #define MA_DEFAULT_RESAMPLER_LPF_ORDER 4 + #else + #define MA_DEFAULT_RESAMPLER_LPF_ORDER MA_MAX_FILTER_ORDER + #endif +#endif + + +#if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wunused-variable" +#endif + +/* Standard sample rates, in order of priority. */ +static ma_uint32 g_maStandardSampleRatePriorities[] = { + (ma_uint32)ma_standard_sample_rate_48000, + (ma_uint32)ma_standard_sample_rate_44100, + + (ma_uint32)ma_standard_sample_rate_32000, + (ma_uint32)ma_standard_sample_rate_24000, + (ma_uint32)ma_standard_sample_rate_22050, + + (ma_uint32)ma_standard_sample_rate_88200, + (ma_uint32)ma_standard_sample_rate_96000, + (ma_uint32)ma_standard_sample_rate_176400, + (ma_uint32)ma_standard_sample_rate_192000, + + (ma_uint32)ma_standard_sample_rate_16000, + (ma_uint32)ma_standard_sample_rate_11025, + (ma_uint32)ma_standard_sample_rate_8000, + + (ma_uint32)ma_standard_sample_rate_352800, + (ma_uint32)ma_standard_sample_rate_384000 +}; + +static MA_INLINE ma_bool32 ma_is_standard_sample_rate(ma_uint32 sampleRate) +{ + ma_uint32 iSampleRate; + + for (iSampleRate = 0; iSampleRate < sizeof(g_maStandardSampleRatePriorities) / sizeof(g_maStandardSampleRatePriorities[0]); iSampleRate += 1) { + if (g_maStandardSampleRatePriorities[iSampleRate] == sampleRate) { + return MA_TRUE; + } + } + + /* Getting here means the sample rate is not supported. */ + return MA_FALSE; +} + + +static 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 */ +}; +#if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))) + #pragma GCC diagnostic pop +#endif + + +MA_API void ma_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision) +{ + if (pMajor) { + *pMajor = MA_VERSION_MAJOR; + } + + if (pMinor) { + *pMinor = MA_VERSION_MINOR; + } + + if (pRevision) { + *pRevision = MA_VERSION_REVISION; + } +} + +MA_API const char* ma_version_string(void) +{ + return MA_VERSION_STRING; +} + + +/****************************************************************************** + +Standard Library Stuff + +******************************************************************************/ +#ifndef MA_ASSERT +#define MA_ASSERT(condition) assert(condition) +#endif + +#ifndef MA_MALLOC +#define MA_MALLOC(sz) malloc((sz)) +#endif +#ifndef MA_REALLOC +#define MA_REALLOC(p, sz) realloc((p), (sz)) +#endif +#ifndef MA_FREE +#define MA_FREE(p) free((p)) +#endif + +static MA_INLINE void ma_zero_memory_default(void* p, size_t sz) +{ + if (p == NULL) { + MA_ASSERT(sz == 0); /* If this is triggered there's an error with the calling code. */ + return; + } + + if (sz > 0) { + memset(p, 0, sz); + } +} + + +#ifndef MA_ZERO_MEMORY +#define MA_ZERO_MEMORY(p, sz) ma_zero_memory_default((p), (sz)) +#endif +#ifndef MA_COPY_MEMORY +#define MA_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz)) +#endif +#ifndef MA_MOVE_MEMORY +#define MA_MOVE_MEMORY(dst, src, sz) memmove((dst), (src), (sz)) +#endif + +#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_abs(x) (((x) > 0) ? (x) : -(x)) +#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_align(x, a) (((x) + ((a)-1)) & ~((a)-1)) +#define ma_align_64(x) ma_align(x, 8) + +#define ma_buffer_frame_capacity(buffer, channels, format) (sizeof(buffer) / ma_get_bytes_per_sample(format) / (channels)) + +static MA_INLINE double ma_sind(double x) +{ + /* TODO: Implement custom sin(x). */ + return sin(x); +} + +static MA_INLINE double ma_expd(double x) +{ + /* TODO: Implement custom exp(x). */ + return exp(x); +} + +static MA_INLINE double ma_logd(double x) +{ + /* TODO: Implement custom log(x). */ + return log(x); +} + +static MA_INLINE double ma_powd(double x, double y) +{ + /* TODO: Implement custom pow(x, y). */ + return pow(x, y); +} + +static MA_INLINE double ma_sqrtd(double x) +{ + /* TODO: Implement custom sqrt(x). */ + return sqrt(x); +} + + +static MA_INLINE float ma_rsqrtf(float x) +{ + #if defined(MA_SUPPORT_SSE2) && !defined(MA_NO_SSE2) && (defined(MA_X64) || (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__)) + { + /* + For SSE we can use RSQRTSS. + + This Stack Overflow post suggests that compilers don't necessarily generate optimal code + when using intrinsics: + + https://web.archive.org/web/20221211012522/https://stackoverflow.com/questions/32687079/getting-fewest-instructions-for-rsqrtss-wrapper + + I'm going to do something similar here, but a bit simpler. + */ + #if defined(__GNUC__) || defined(__clang__) + { + float result; + __asm__ __volatile__("rsqrtss %1, %0" : "=x"(result) : "x"(x)); + return result; + } + #else + { + return _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ps1(x))); + } + #endif + } + #else + { + return 1 / (float)ma_sqrtd(x); + } + #endif +} + + +static MA_INLINE float ma_sinf(float x) +{ + return (float)ma_sind((float)x); +} + +static MA_INLINE double ma_cosd(double x) +{ + return ma_sind((MA_PI_D*0.5) - x); +} + +static MA_INLINE float ma_cosf(float x) +{ + return (float)ma_cosd((float)x); +} + +static MA_INLINE double ma_log10d(double x) +{ + return ma_logd(x) * 0.43429448190325182765; +} + +static MA_INLINE float ma_powf(float x, float y) +{ + return (float)ma_powd((double)x, (double)y); +} + +static MA_INLINE float ma_log10f(float x) +{ + return (float)ma_log10d((double)x); +} + + +static MA_INLINE double ma_degrees_to_radians(double degrees) +{ + return degrees * 0.01745329252; +} + +static MA_INLINE double ma_radians_to_degrees(double radians) +{ + return radians * 57.295779512896; +} + +static MA_INLINE float ma_degrees_to_radians_f(float degrees) +{ + return degrees * 0.01745329252f; +} + +static MA_INLINE float ma_radians_to_degrees_f(float radians) +{ + return radians * 57.295779512896f; +} + + +/* +Return Values: + 0: Success + 22: EINVAL + 34: ERANGE + +Not using symbolic constants for errors because I want to avoid #including errno.h + +These are marked as no-inline because of some bad code generation by Clang. None of these functions +are used in any performance-critical code within miniaudio. +*/ +MA_API MA_NO_INLINE int ma_strcpy_s(char* dst, size_t dstSizeInBytes, const char* src) +{ + size_t i; + + if (dst == 0) { + return 22; + } + if (dstSizeInBytes == 0) { + return 34; + } + if (src == 0) { + dst[0] = '\0'; + return 22; + } + + 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; +} + +MA_API MA_NO_INLINE int ma_wcscpy_s(wchar_t* dst, size_t dstCap, const wchar_t* src) +{ + size_t i; + + if (dst == 0) { + return 22; + } + if (dstCap == 0) { + return 34; + } + if (src == 0) { + dst[0] = '\0'; + return 22; + } + + for (i = 0; i < dstCap && src[i] != '\0'; ++i) { + dst[i] = src[i]; + } + + if (i < dstCap) { + dst[i] = '\0'; + return 0; + } + + dst[0] = '\0'; + return 34; +} + + +MA_API MA_NO_INLINE 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; + } + if (dstSizeInBytes == 0) { + return 34; + } + if (src == 0) { + dst[0] = '\0'; + return 22; + } + + maxcount = count; + if (count == ((size_t)-1) || count >= dstSizeInBytes) { /* -1 = _TRUNCATE */ + maxcount = dstSizeInBytes - 1; + } + + 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; +} + +MA_API MA_NO_INLINE int ma_strcat_s(char* dst, size_t dstSizeInBytes, const char* src) +{ + char* dstorig; + + if (dst == 0) { + return 22; + } + if (dstSizeInBytes == 0) { + return 34; + } + if (src == 0) { + dst[0] = '\0'; + return 22; + } + + 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; +} + +MA_API MA_NO_INLINE int ma_strncat_s(char* dst, size_t dstSizeInBytes, const char* src, size_t count) +{ + char* dstorig; + + if (dst == 0) { + return 22; + } + if (dstSizeInBytes == 0) { + return 34; + } + if (src == 0) { + return 22; + } + + dstorig = dst; + + while (dstSizeInBytes > 0 && dst[0] != '\0') { + dst += 1; + dstSizeInBytes -= 1; + } + + if (dstSizeInBytes == 0) { + return 22; /* Unterminated. */ + } + + + if (count == ((size_t)-1)) { /* _TRUNCATE */ + count = dstSizeInBytes - 1; + } + + while (dstSizeInBytes > 0 && src[0] != '\0' && count > 0) { + *dst++ = *src++; + dstSizeInBytes -= 1; + count -= 1; + } + + if (dstSizeInBytes > 0) { + dst[0] = '\0'; + } else { + dstorig[0] = '\0'; + return 34; + } + + return 0; +} + +MA_API MA_NO_INLINE 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; + } + if (radix < 2 || radix > 36) { + dst[0] = '\0'; + return 22; + } + + sign = (value < 0 && radix == 10) ? -1 : 1; /* The negative sign is only used when the base is 10. */ + + if (value < 0) { + valueU = -value; + } else { + valueU = value; + } + + 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; +} + +MA_API MA_NO_INLINE 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]; +} + +MA_API MA_NO_INLINE int ma_strappend(char* dst, size_t dstSize, const char* srcA, const char* srcB) +{ + int result; + + result = ma_strncpy_s(dst, dstSize, srcA, (size_t)-1); + if (result != 0) { + return result; + } + + result = ma_strncat_s(dst, dstSize, srcB, (size_t)-1); + if (result != 0) { + return result; + } + + return result; +} + +MA_API MA_NO_INLINE char* ma_copy_string(const char* src, const ma_allocation_callbacks* pAllocationCallbacks) +{ + size_t sz; + char* dst; + + if (src == NULL) { + return NULL; + } + + sz = strlen(src)+1; + dst = (char*)ma_malloc(sz, pAllocationCallbacks); + if (dst == NULL) { + return NULL; + } + + ma_strcpy_s(dst, sz, src); + + return dst; +} + +MA_API MA_NO_INLINE wchar_t* ma_copy_string_w(const wchar_t* src, const ma_allocation_callbacks* pAllocationCallbacks) +{ + size_t sz = wcslen(src)+1; + wchar_t* dst = (wchar_t*)ma_malloc(sz * sizeof(*dst), pAllocationCallbacks); + if (dst == NULL) { + return NULL; + } + + ma_wcscpy_s(dst, sz, src); + + return dst; +} + + + +#include +static ma_result ma_result_from_errno(int e) +{ + if (e == 0) { + return MA_SUCCESS; + } +#ifdef EPERM + else if (e == EPERM) { return MA_INVALID_OPERATION; } +#endif +#ifdef ENOENT + else if (e == ENOENT) { return MA_DOES_NOT_EXIST; } +#endif +#ifdef ESRCH + else if (e == ESRCH) { return MA_DOES_NOT_EXIST; } +#endif +#ifdef EINTR + else if (e == EINTR) { return MA_INTERRUPT; } +#endif +#ifdef EIO + else if (e == EIO) { return MA_IO_ERROR; } +#endif +#ifdef ENXIO + else if (e == ENXIO) { return MA_DOES_NOT_EXIST; } +#endif +#ifdef E2BIG + else if (e == E2BIG) { return MA_INVALID_ARGS; } +#endif +#ifdef ENOEXEC + else if (e == ENOEXEC) { return MA_INVALID_FILE; } +#endif +#ifdef EBADF + else if (e == EBADF) { return MA_INVALID_FILE; } +#endif +#ifdef ECHILD + else if (e == ECHILD) { return MA_ERROR; } +#endif +#ifdef EAGAIN + else if (e == EAGAIN) { return MA_UNAVAILABLE; } +#endif +#ifdef ENOMEM + else if (e == ENOMEM) { return MA_OUT_OF_MEMORY; } +#endif +#ifdef EACCES + else if (e == EACCES) { return MA_ACCESS_DENIED; } +#endif +#ifdef EFAULT + else if (e == EFAULT) { return MA_BAD_ADDRESS; } +#endif +#ifdef ENOTBLK + else if (e == ENOTBLK) { return MA_ERROR; } +#endif +#ifdef EBUSY + else if (e == EBUSY) { return MA_BUSY; } +#endif +#ifdef EEXIST + else if (e == EEXIST) { return MA_ALREADY_EXISTS; } +#endif +#ifdef EXDEV + else if (e == EXDEV) { return MA_ERROR; } +#endif +#ifdef ENODEV + else if (e == ENODEV) { return MA_DOES_NOT_EXIST; } +#endif +#ifdef ENOTDIR + else if (e == ENOTDIR) { return MA_NOT_DIRECTORY; } +#endif +#ifdef EISDIR + else if (e == EISDIR) { return MA_IS_DIRECTORY; } +#endif +#ifdef EINVAL + else if (e == EINVAL) { return MA_INVALID_ARGS; } +#endif +#ifdef ENFILE + else if (e == ENFILE) { return MA_TOO_MANY_OPEN_FILES; } +#endif +#ifdef EMFILE + else if (e == EMFILE) { return MA_TOO_MANY_OPEN_FILES; } +#endif +#ifdef ENOTTY + else if (e == ENOTTY) { return MA_INVALID_OPERATION; } +#endif +#ifdef ETXTBSY + else if (e == ETXTBSY) { return MA_BUSY; } +#endif +#ifdef EFBIG + else if (e == EFBIG) { return MA_TOO_BIG; } +#endif +#ifdef ENOSPC + else if (e == ENOSPC) { return MA_NO_SPACE; } +#endif +#ifdef ESPIPE + else if (e == ESPIPE) { return MA_BAD_SEEK; } +#endif +#ifdef EROFS + else if (e == EROFS) { return MA_ACCESS_DENIED; } +#endif +#ifdef EMLINK + else if (e == EMLINK) { return MA_TOO_MANY_LINKS; } +#endif +#ifdef EPIPE + else if (e == EPIPE) { return MA_BAD_PIPE; } +#endif +#ifdef EDOM + else if (e == EDOM) { return MA_OUT_OF_RANGE; } +#endif +#ifdef ERANGE + else if (e == ERANGE) { return MA_OUT_OF_RANGE; } +#endif +#ifdef EDEADLK + else if (e == EDEADLK) { return MA_DEADLOCK; } +#endif +#ifdef ENAMETOOLONG + else if (e == ENAMETOOLONG) { return MA_PATH_TOO_LONG; } +#endif +#ifdef ENOLCK + else if (e == ENOLCK) { return MA_ERROR; } +#endif +#ifdef ENOSYS + else if (e == ENOSYS) { return MA_NOT_IMPLEMENTED; } +#endif +#ifdef ENOTEMPTY + else if (e == ENOTEMPTY) { return MA_DIRECTORY_NOT_EMPTY; } +#endif +#ifdef ELOOP + else if (e == ELOOP) { return MA_TOO_MANY_LINKS; } +#endif +#ifdef ENOMSG + else if (e == ENOMSG) { return MA_NO_MESSAGE; } +#endif +#ifdef EIDRM + else if (e == EIDRM) { return MA_ERROR; } +#endif +#ifdef ECHRNG + else if (e == ECHRNG) { return MA_ERROR; } +#endif +#ifdef EL2NSYNC + else if (e == EL2NSYNC) { return MA_ERROR; } +#endif +#ifdef EL3HLT + else if (e == EL3HLT) { return MA_ERROR; } +#endif +#ifdef EL3RST + else if (e == EL3RST) { return MA_ERROR; } +#endif +#ifdef ELNRNG + else if (e == ELNRNG) { return MA_OUT_OF_RANGE; } +#endif +#ifdef EUNATCH + else if (e == EUNATCH) { return MA_ERROR; } +#endif +#ifdef ENOCSI + else if (e == ENOCSI) { return MA_ERROR; } +#endif +#ifdef EL2HLT + else if (e == EL2HLT) { return MA_ERROR; } +#endif +#ifdef EBADE + else if (e == EBADE) { return MA_ERROR; } +#endif +#ifdef EBADR + else if (e == EBADR) { return MA_ERROR; } +#endif +#ifdef EXFULL + else if (e == EXFULL) { return MA_ERROR; } +#endif +#ifdef ENOANO + else if (e == ENOANO) { return MA_ERROR; } +#endif +#ifdef EBADRQC + else if (e == EBADRQC) { return MA_ERROR; } +#endif +#ifdef EBADSLT + else if (e == EBADSLT) { return MA_ERROR; } +#endif +#ifdef EBFONT + else if (e == EBFONT) { return MA_INVALID_FILE; } +#endif +#ifdef ENOSTR + else if (e == ENOSTR) { return MA_ERROR; } +#endif +#ifdef ENODATA + else if (e == ENODATA) { return MA_NO_DATA_AVAILABLE; } +#endif +#ifdef ETIME + else if (e == ETIME) { return MA_TIMEOUT; } +#endif +#ifdef ENOSR + else if (e == ENOSR) { return MA_NO_DATA_AVAILABLE; } +#endif +#ifdef ENONET + else if (e == ENONET) { return MA_NO_NETWORK; } +#endif +#ifdef ENOPKG + else if (e == ENOPKG) { return MA_ERROR; } +#endif +#ifdef EREMOTE + else if (e == EREMOTE) { return MA_ERROR; } +#endif +#ifdef ENOLINK + else if (e == ENOLINK) { return MA_ERROR; } +#endif +#ifdef EADV + else if (e == EADV) { return MA_ERROR; } +#endif +#ifdef ESRMNT + else if (e == ESRMNT) { return MA_ERROR; } +#endif +#ifdef ECOMM + else if (e == ECOMM) { return MA_ERROR; } +#endif +#ifdef EPROTO + else if (e == EPROTO) { return MA_ERROR; } +#endif +#ifdef EMULTIHOP + else if (e == EMULTIHOP) { return MA_ERROR; } +#endif +#ifdef EDOTDOT + else if (e == EDOTDOT) { return MA_ERROR; } +#endif +#ifdef EBADMSG + else if (e == EBADMSG) { return MA_BAD_MESSAGE; } +#endif +#ifdef EOVERFLOW + else if (e == EOVERFLOW) { return MA_TOO_BIG; } +#endif +#ifdef ENOTUNIQ + else if (e == ENOTUNIQ) { return MA_NOT_UNIQUE; } +#endif +#ifdef EBADFD + else if (e == EBADFD) { return MA_ERROR; } +#endif +#ifdef EREMCHG + else if (e == EREMCHG) { return MA_ERROR; } +#endif +#ifdef ELIBACC + else if (e == ELIBACC) { return MA_ACCESS_DENIED; } +#endif +#ifdef ELIBBAD + else if (e == ELIBBAD) { return MA_INVALID_FILE; } +#endif +#ifdef ELIBSCN + else if (e == ELIBSCN) { return MA_INVALID_FILE; } +#endif +#ifdef ELIBMAX + else if (e == ELIBMAX) { return MA_ERROR; } +#endif +#ifdef ELIBEXEC + else if (e == ELIBEXEC) { return MA_ERROR; } +#endif +#ifdef EILSEQ + else if (e == EILSEQ) { return MA_INVALID_DATA; } +#endif +#ifdef ERESTART + else if (e == ERESTART) { return MA_ERROR; } +#endif +#ifdef ESTRPIPE + else if (e == ESTRPIPE) { return MA_ERROR; } +#endif +#ifdef EUSERS + else if (e == EUSERS) { return MA_ERROR; } +#endif +#ifdef ENOTSOCK + else if (e == ENOTSOCK) { return MA_NOT_SOCKET; } +#endif +#ifdef EDESTADDRREQ + else if (e == EDESTADDRREQ) { return MA_NO_ADDRESS; } +#endif +#ifdef EMSGSIZE + else if (e == EMSGSIZE) { return MA_TOO_BIG; } +#endif +#ifdef EPROTOTYPE + else if (e == EPROTOTYPE) { return MA_BAD_PROTOCOL; } +#endif +#ifdef ENOPROTOOPT + else if (e == ENOPROTOOPT) { return MA_PROTOCOL_UNAVAILABLE; } +#endif +#ifdef EPROTONOSUPPORT + else if (e == EPROTONOSUPPORT) { return MA_PROTOCOL_NOT_SUPPORTED; } +#endif +#ifdef ESOCKTNOSUPPORT + else if (e == ESOCKTNOSUPPORT) { return MA_SOCKET_NOT_SUPPORTED; } +#endif +#ifdef EOPNOTSUPP + else if (e == EOPNOTSUPP) { return MA_INVALID_OPERATION; } +#endif +#ifdef EPFNOSUPPORT + else if (e == EPFNOSUPPORT) { return MA_PROTOCOL_FAMILY_NOT_SUPPORTED; } +#endif +#ifdef EAFNOSUPPORT + else if (e == EAFNOSUPPORT) { return MA_ADDRESS_FAMILY_NOT_SUPPORTED; } +#endif +#ifdef EADDRINUSE + else if (e == EADDRINUSE) { return MA_ALREADY_IN_USE; } +#endif +#ifdef EADDRNOTAVAIL + else if (e == EADDRNOTAVAIL) { return MA_ERROR; } +#endif +#ifdef ENETDOWN + else if (e == ENETDOWN) { return MA_NO_NETWORK; } +#endif +#ifdef ENETUNREACH + else if (e == ENETUNREACH) { return MA_NO_NETWORK; } +#endif +#ifdef ENETRESET + else if (e == ENETRESET) { return MA_NO_NETWORK; } +#endif +#ifdef ECONNABORTED + else if (e == ECONNABORTED) { return MA_NO_NETWORK; } +#endif +#ifdef ECONNRESET + else if (e == ECONNRESET) { return MA_CONNECTION_RESET; } +#endif +#ifdef ENOBUFS + else if (e == ENOBUFS) { return MA_NO_SPACE; } +#endif +#ifdef EISCONN + else if (e == EISCONN) { return MA_ALREADY_CONNECTED; } +#endif +#ifdef ENOTCONN + else if (e == ENOTCONN) { return MA_NOT_CONNECTED; } +#endif +#ifdef ESHUTDOWN + else if (e == ESHUTDOWN) { return MA_ERROR; } +#endif +#ifdef ETOOMANYREFS + else if (e == ETOOMANYREFS) { return MA_ERROR; } +#endif +#ifdef ETIMEDOUT + else if (e == ETIMEDOUT) { return MA_TIMEOUT; } +#endif +#ifdef ECONNREFUSED + else if (e == ECONNREFUSED) { return MA_CONNECTION_REFUSED; } +#endif +#ifdef EHOSTDOWN + else if (e == EHOSTDOWN) { return MA_NO_HOST; } +#endif +#ifdef EHOSTUNREACH + else if (e == EHOSTUNREACH) { return MA_NO_HOST; } +#endif +#ifdef EALREADY + else if (e == EALREADY) { return MA_IN_PROGRESS; } +#endif +#ifdef EINPROGRESS + else if (e == EINPROGRESS) { return MA_IN_PROGRESS; } +#endif +#ifdef ESTALE + else if (e == ESTALE) { return MA_INVALID_FILE; } +#endif +#ifdef EUCLEAN + else if (e == EUCLEAN) { return MA_ERROR; } +#endif +#ifdef ENOTNAM + else if (e == ENOTNAM) { return MA_ERROR; } +#endif +#ifdef ENAVAIL + else if (e == ENAVAIL) { return MA_ERROR; } +#endif +#ifdef EISNAM + else if (e == EISNAM) { return MA_ERROR; } +#endif +#ifdef EREMOTEIO + else if (e == EREMOTEIO) { return MA_IO_ERROR; } +#endif +#ifdef EDQUOT + else if (e == EDQUOT) { return MA_NO_SPACE; } +#endif +#ifdef ENOMEDIUM + else if (e == ENOMEDIUM) { return MA_DOES_NOT_EXIST; } +#endif +#ifdef EMEDIUMTYPE + else if (e == EMEDIUMTYPE) { return MA_ERROR; } +#endif +#ifdef ECANCELED + else if (e == ECANCELED) { return MA_CANCELLED; } +#endif +#ifdef ENOKEY + else if (e == ENOKEY) { return MA_ERROR; } +#endif +#ifdef EKEYEXPIRED + else if (e == EKEYEXPIRED) { return MA_ERROR; } +#endif +#ifdef EKEYREVOKED + else if (e == EKEYREVOKED) { return MA_ERROR; } +#endif +#ifdef EKEYREJECTED + else if (e == EKEYREJECTED) { return MA_ERROR; } +#endif +#ifdef EOWNERDEAD + else if (e == EOWNERDEAD) { return MA_ERROR; } +#endif +#ifdef ENOTRECOVERABLE + else if (e == ENOTRECOVERABLE) { return MA_ERROR; } +#endif +#ifdef ERFKILL + else if (e == ERFKILL) { return MA_ERROR; } +#endif +#ifdef EHWPOISON + else if (e == EHWPOISON) { return MA_ERROR; } +#endif + else { + return MA_ERROR; + } +} + +MA_API ma_result ma_fopen(FILE** ppFile, const char* pFilePath, const char* pOpenMode) +{ +#if defined(_MSC_VER) && _MSC_VER >= 1400 + errno_t err; +#endif + + if (ppFile != NULL) { + *ppFile = NULL; /* Safety. */ + } + + if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) { + return MA_INVALID_ARGS; + } + +#if defined(_MSC_VER) && _MSC_VER >= 1400 + err = fopen_s(ppFile, pFilePath, pOpenMode); + if (err != 0) { + return ma_result_from_errno(err); + } +#else +#if defined(_WIN32) || defined(__APPLE__) + *ppFile = fopen(pFilePath, pOpenMode); +#else + #if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64 && defined(_LARGEFILE64_SOURCE) + *ppFile = fopen64(pFilePath, pOpenMode); + #else + *ppFile = fopen(pFilePath, pOpenMode); + #endif +#endif + if (*ppFile == NULL) { + ma_result result = ma_result_from_errno(errno); + if (result == MA_SUCCESS) { + result = MA_ERROR; /* Just a safety check to make sure we never ever return success when pFile == NULL. */ + } + + return result; + } +#endif + + return MA_SUCCESS; +} + + + +/* +_wfopen() isn't always available in all compilation environments. + + * Windows only. + * MSVC seems to support it universally as far back as VC6 from what I can tell (haven't checked further back). + * MinGW-64 (both 32- and 64-bit) seems to support it. + * MinGW wraps it in !defined(__STRICT_ANSI__). + * OpenWatcom wraps it in !defined(_NO_EXT_KEYS). + +This can be reviewed as compatibility issues arise. The preference is to use _wfopen_s() and _wfopen() as opposed to the wcsrtombs() +fallback, so if you notice your compiler not detecting this properly I'm happy to look at adding support. +*/ +#if defined(_WIN32) + #if defined(_MSC_VER) || defined(__MINGW64__) || (!defined(__STRICT_ANSI__) && !defined(_NO_EXT_KEYS)) + #define MA_HAS_WFOPEN + #endif +#endif + +MA_API ma_result ma_wfopen(FILE** ppFile, const wchar_t* pFilePath, const wchar_t* pOpenMode, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (ppFile != NULL) { + *ppFile = NULL; /* Safety. */ + } + + if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) { + return MA_INVALID_ARGS; + } + +#if defined(MA_HAS_WFOPEN) + { + /* Use _wfopen() on Windows. */ + #if defined(_MSC_VER) && _MSC_VER >= 1400 + errno_t err = _wfopen_s(ppFile, pFilePath, pOpenMode); + if (err != 0) { + return ma_result_from_errno(err); + } + #else + *ppFile = _wfopen(pFilePath, pOpenMode); + if (*ppFile == NULL) { + return ma_result_from_errno(errno); + } + #endif + (void)pAllocationCallbacks; + } +#else + /* + Use fopen() on anything other than Windows. Requires a conversion. This is annoying because fopen() is locale specific. The only real way I can + think of to do this is with wcsrtombs(). Note that wcstombs() is apparently not thread-safe because it uses a static global mbstate_t object for + maintaining state. I've checked this with -std=c89 and it works, but if somebody get's a compiler error I'll look into improving compatibility. + */ + { + mbstate_t mbs; + size_t lenMB; + const wchar_t* pFilePathTemp = pFilePath; + char* pFilePathMB = NULL; + char pOpenModeMB[32] = {0}; + + /* Get the length first. */ + MA_ZERO_OBJECT(&mbs); + lenMB = wcsrtombs(NULL, &pFilePathTemp, 0, &mbs); + if (lenMB == (size_t)-1) { + return ma_result_from_errno(errno); + } + + pFilePathMB = (char*)ma_malloc(lenMB + 1, pAllocationCallbacks); + if (pFilePathMB == NULL) { + return MA_OUT_OF_MEMORY; + } + + pFilePathTemp = pFilePath; + MA_ZERO_OBJECT(&mbs); + wcsrtombs(pFilePathMB, &pFilePathTemp, lenMB + 1, &mbs); + + /* The open mode should always consist of ASCII characters so we should be able to do a trivial conversion. */ + { + size_t i = 0; + for (;;) { + if (pOpenMode[i] == 0) { + pOpenModeMB[i] = '\0'; + break; + } + + pOpenModeMB[i] = (char)pOpenMode[i]; + i += 1; + } + } + + *ppFile = fopen(pFilePathMB, pOpenModeMB); + + ma_free(pFilePathMB, pAllocationCallbacks); + } + + if (*ppFile == NULL) { + return MA_ERROR; + } +#endif + + return MA_SUCCESS; +} + + + +static MA_INLINE 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 +} + +static MA_INLINE 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 +} + + +/* 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; +} + + + +/************************************************************************************************************************************************************** + +Allocation Callbacks + +**************************************************************************************************************************************************************/ +static void* ma__malloc_default(size_t sz, void* pUserData) +{ + (void)pUserData; + return MA_MALLOC(sz); +} + +static void* ma__realloc_default(void* p, size_t sz, void* pUserData) +{ + (void)pUserData; + return MA_REALLOC(p, sz); +} + +static void ma__free_default(void* p, void* pUserData) +{ + (void)pUserData; + MA_FREE(p); +} + +static ma_allocation_callbacks ma_allocation_callbacks_init_default(void) +{ + ma_allocation_callbacks callbacks; + callbacks.pUserData = NULL; + callbacks.onMalloc = ma__malloc_default; + callbacks.onRealloc = ma__realloc_default; + callbacks.onFree = ma__free_default; + + return callbacks; +} + +static ma_result ma_allocation_callbacks_init_copy(ma_allocation_callbacks* pDst, const ma_allocation_callbacks* pSrc) +{ + if (pDst == NULL) { + return MA_INVALID_ARGS; + } + + if (pSrc == NULL) { + *pDst = ma_allocation_callbacks_init_default(); + } else { + if (pSrc->pUserData == NULL && pSrc->onFree == NULL && pSrc->onMalloc == NULL && pSrc->onRealloc == NULL) { + *pDst = ma_allocation_callbacks_init_default(); + } else { + if (pSrc->onFree == NULL || (pSrc->onMalloc == NULL && pSrc->onRealloc == NULL)) { + return MA_INVALID_ARGS; /* Invalid allocation callbacks. */ + } else { + *pDst = *pSrc; + } + } + } + + return MA_SUCCESS; +} + + + + +/************************************************************************************************************************************************************** + +Logging + +**************************************************************************************************************************************************************/ +MA_API const char* ma_log_level_to_string(ma_uint32 logLevel) +{ + switch (logLevel) + { + case MA_LOG_LEVEL_DEBUG: return "DEBUG"; + case MA_LOG_LEVEL_INFO: return "INFO"; + case MA_LOG_LEVEL_WARNING: return "WARNING"; + case MA_LOG_LEVEL_ERROR: return "ERROR"; + default: return "ERROR"; + } +} + +#if defined(MA_DEBUG_OUTPUT) +#if defined(MA_ANDROID) + #include +#endif + +/* Customize this to use a specific tag in __android_log_print() for debug output messages. */ +#ifndef MA_ANDROID_LOG_TAG +#define MA_ANDROID_LOG_TAG "miniaudio" +#endif + +void ma_log_callback_debug(void* pUserData, ma_uint32 level, const char* pMessage) +{ + (void)pUserData; + + /* Special handling for some platforms. */ + #if defined(MA_ANDROID) + { + /* Android. */ + __android_log_print(ANDROID_LOG_DEBUG, MA_ANDROID_LOG_TAG, "%s: %s", ma_log_level_to_string(level), pMessage); + } + #else + { + /* Everything else. */ + printf("%s: %s", ma_log_level_to_string(level), pMessage); + } + #endif +} +#endif + +MA_API ma_log_callback ma_log_callback_init(ma_log_callback_proc onLog, void* pUserData) +{ + ma_log_callback callback; + + MA_ZERO_OBJECT(&callback); + callback.onLog = onLog; + callback.pUserData = pUserData; + + return callback; +} + + +MA_API ma_result ma_log_init(const ma_allocation_callbacks* pAllocationCallbacks, ma_log* pLog) +{ + if (pLog == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pLog); + ma_allocation_callbacks_init_copy(&pLog->allocationCallbacks, pAllocationCallbacks); + + /* We need a mutex for thread safety. */ + #ifndef MA_NO_THREADING + { + ma_result result = ma_mutex_init(&pLog->lock); + if (result != MA_SUCCESS) { + return result; + } + } + #endif + + /* If we're using debug output, enable it. */ + #if defined(MA_DEBUG_OUTPUT) + { + ma_log_register_callback(pLog, ma_log_callback_init(ma_log_callback_debug, NULL)); /* Doesn't really matter if this fails. */ + } + #endif + + return MA_SUCCESS; +} + +MA_API void ma_log_uninit(ma_log* pLog) +{ + if (pLog == NULL) { + return; + } + +#ifndef MA_NO_THREADING + ma_mutex_uninit(&pLog->lock); +#endif +} + +static void ma_log_lock(ma_log* pLog) +{ +#ifndef MA_NO_THREADING + ma_mutex_lock(&pLog->lock); +#else + (void)pLog; +#endif +} + +static void ma_log_unlock(ma_log* pLog) +{ +#ifndef MA_NO_THREADING + ma_mutex_unlock(&pLog->lock); +#else + (void)pLog; +#endif +} + +MA_API ma_result ma_log_register_callback(ma_log* pLog, ma_log_callback callback) +{ + ma_result result = MA_SUCCESS; + + if (pLog == NULL || callback.onLog == NULL) { + return MA_INVALID_ARGS; + } + + ma_log_lock(pLog); + { + if (pLog->callbackCount == ma_countof(pLog->callbacks)) { + result = MA_OUT_OF_MEMORY; /* Reached the maximum allowed log callbacks. */ + } else { + pLog->callbacks[pLog->callbackCount] = callback; + pLog->callbackCount += 1; + } + } + ma_log_unlock(pLog); + + return result; +} + +MA_API ma_result ma_log_unregister_callback(ma_log* pLog, ma_log_callback callback) +{ + if (pLog == NULL) { + return MA_INVALID_ARGS; + } + + ma_log_lock(pLog); + { + ma_uint32 iLog; + for (iLog = 0; iLog < pLog->callbackCount; ) { + if (pLog->callbacks[iLog].onLog == callback.onLog) { + /* Found. Move everything down a slot. */ + ma_uint32 jLog; + for (jLog = iLog; jLog < pLog->callbackCount-1; jLog += 1) { + pLog->callbacks[jLog] = pLog->callbacks[jLog + 1]; + } + + pLog->callbackCount -= 1; + } else { + /* Not found. */ + iLog += 1; + } + } + } + ma_log_unlock(pLog); + + return MA_SUCCESS; +} + +MA_API ma_result ma_log_post(ma_log* pLog, ma_uint32 level, const char* pMessage) +{ + if (pLog == NULL || pMessage == NULL) { + return MA_INVALID_ARGS; + } + + ma_log_lock(pLog); + { + ma_uint32 iLog; + for (iLog = 0; iLog < pLog->callbackCount; iLog += 1) { + if (pLog->callbacks[iLog].onLog) { + pLog->callbacks[iLog].onLog(pLog->callbacks[iLog].pUserData, level, pMessage); + } + } + } + ma_log_unlock(pLog); + + return MA_SUCCESS; +} + + +/* +We need to emulate _vscprintf() for the VC6 build. This can be more efficient, but since it's only VC6, and it's just a +logging function, I'm happy to keep this simple. In the VC6 build we can implement this in terms of _vsnprintf(). +*/ +#if defined(_MSC_VER) && _MSC_VER < 1900 +static int ma_vscprintf(const ma_allocation_callbacks* pAllocationCallbacks, const char* format, va_list args) +{ +#if _MSC_VER > 1200 + return _vscprintf(format, args); +#else + int result; + char* pTempBuffer = NULL; + size_t tempBufferCap = 1024; + + if (format == NULL) { + errno = EINVAL; + return -1; + } + + for (;;) { + char* pNewTempBuffer = (char*)ma_realloc(pTempBuffer, tempBufferCap, pAllocationCallbacks); + if (pNewTempBuffer == NULL) { + ma_free(pTempBuffer, pAllocationCallbacks); + errno = ENOMEM; + return -1; /* Out of memory. */ + } + + pTempBuffer = pNewTempBuffer; + + result = _vsnprintf(pTempBuffer, tempBufferCap, format, args); + ma_free(pTempBuffer, NULL); + + if (result != -1) { + break; /* Got it. */ + } + + /* Buffer wasn't big enough. Ideally it'd be nice to use an error code to know the reason for sure, but this is reliable enough. */ + tempBufferCap *= 2; + } + + return result; +#endif +} +#endif + +MA_API ma_result ma_log_postv(ma_log* pLog, ma_uint32 level, const char* pFormat, va_list args) +{ + if (pLog == NULL || pFormat == NULL) { + return MA_INVALID_ARGS; + } + + #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || ((!defined(_MSC_VER) || _MSC_VER >= 1900) && !defined(__STRICT_ANSI__) && !defined(_NO_EXT_KEYS)) || (defined(__cplusplus) && __cplusplus >= 201103L) + { + ma_result result; + int length; + char pFormattedMessageStack[1024]; + char* pFormattedMessageHeap = NULL; + + /* First try formatting into our fixed sized stack allocated buffer. If this is too small we'll fallback to a heap allocation. */ + length = vsnprintf(pFormattedMessageStack, sizeof(pFormattedMessageStack), pFormat, args); + if (length < 0) { + return MA_INVALID_OPERATION; /* An error occurred when trying to convert the buffer. */ + } + + if ((size_t)length < sizeof(pFormattedMessageStack)) { + /* The string was written to the stack. */ + result = ma_log_post(pLog, level, pFormattedMessageStack); + } else { + /* The stack buffer was too small, try the heap. */ + pFormattedMessageHeap = (char*)ma_malloc(length + 1, &pLog->allocationCallbacks); + if (pFormattedMessageHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + + length = vsnprintf(pFormattedMessageHeap, length + 1, pFormat, args); + if (length < 0) { + ma_free(pFormattedMessageHeap, &pLog->allocationCallbacks); + return MA_INVALID_OPERATION; + } + + result = ma_log_post(pLog, level, pFormattedMessageHeap); + ma_free(pFormattedMessageHeap, &pLog->allocationCallbacks); + } + + return result; + } + #else + { + /* + Without snprintf() we need to first measure the string and then heap allocate it. I'm only aware of Visual Studio having support for this without snprintf(), so we'll + need to restrict this branch to Visual Studio. For other compilers we need to just not support formatted logging because I don't want the security risk of overflowing + a fixed sized stack allocated buffer. + */ + #if defined(_MSC_VER) && _MSC_VER >= 1200 /* 1200 = VC6 */ + { + ma_result result; + int formattedLen; + char* pFormattedMessage = NULL; + va_list args2; + + #if _MSC_VER >= 1800 + { + va_copy(args2, args); + } + #else + { + args2 = args; + } + #endif + + formattedLen = ma_vscprintf(&pLog->allocationCallbacks, pFormat, args2); + va_end(args2); + + if (formattedLen <= 0) { + return MA_INVALID_OPERATION; + } + + pFormattedMessage = (char*)ma_malloc(formattedLen + 1, &pLog->allocationCallbacks); + if (pFormattedMessage == NULL) { + return MA_OUT_OF_MEMORY; + } + + /* We'll get errors on newer versions of Visual Studio if we try to use vsprintf(). */ + #if _MSC_VER >= 1400 /* 1400 = Visual Studio 2005 */ + { + vsprintf_s(pFormattedMessage, formattedLen + 1, pFormat, args); + } + #else + { + vsprintf(pFormattedMessage, pFormat, args); + } + #endif + + result = ma_log_post(pLog, level, pFormattedMessage); + ma_free(pFormattedMessage, &pLog->allocationCallbacks); + + return result; + } + #else + { + /* Can't do anything because we don't have a safe way of to emulate vsnprintf() without a manual solution. */ + (void)level; + (void)args; + + return MA_INVALID_OPERATION; + } + #endif + } + #endif +} + +MA_API ma_result ma_log_postf(ma_log* pLog, ma_uint32 level, const char* pFormat, ...) +{ + ma_result result; + va_list args; + + if (pLog == NULL || pFormat == NULL) { + return MA_INVALID_ARGS; + } + + va_start(args, pFormat); + { + result = ma_log_postv(pLog, level, pFormat, args); + } + va_end(args); + + return result; +} + + + +static MA_INLINE ma_uint8 ma_clip_u8(ma_int32 x) +{ + return (ma_uint8)(ma_clamp(x, -128, 127) + 128); +} + +static MA_INLINE ma_int16 ma_clip_s16(ma_int32 x) +{ + return (ma_int16)ma_clamp(x, -32768, 32767); +} + +static MA_INLINE ma_int64 ma_clip_s24(ma_int64 x) +{ + return (ma_int64)ma_clamp(x, -8388608, 8388607); +} + +static MA_INLINE ma_int32 ma_clip_s32(ma_int64 x) +{ + /* This dance is to silence warnings with -std=c89. A good compiler should be able to optimize this away. */ + ma_int64 clipMin; + ma_int64 clipMax; + clipMin = -((ma_int64)2147483647 + 1); + clipMax = (ma_int64)2147483647; + + return (ma_int32)ma_clamp(x, clipMin, clipMax); +} + +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_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); +} + + +/* +Greatest common factor using Euclid's algorithm iteratively. +*/ +static MA_INLINE ma_uint32 ma_gcf_u32(ma_uint32 a, ma_uint32 b) +{ + for (;;) { + if (b == 0) { + break; + } else { + ma_uint32 t = a; + a = b; + b = t % a; + } + } + + return a; +} + + +static ma_uint32 ma_ffs_32(ma_uint32 x) +{ + ma_uint32 i; + + /* Just a naive implementation just to get things working for now. Will optimize this later. */ + for (i = 0; i < 32; i += 1) { + if ((x & (1 << i)) != 0) { + return i; + } + } + + return i; +} + +static MA_INLINE ma_int16 ma_float_to_fixed_16(float x) +{ + return (ma_int16)(x * (1 << 8)); +} + + + +/* +Random Number Generation + +miniaudio uses the LCG random number generation algorithm. This is good enough for audio. + +Note that miniaudio's global 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. +*/ +#ifndef MA_DEFAULT_LCG_SEED +#define MA_DEFAULT_LCG_SEED 4321 +#endif + +#define MA_LCG_M 2147483647 +#define MA_LCG_A 48271 +#define MA_LCG_C 0 + +static ma_lcg g_maLCG = {MA_DEFAULT_LCG_SEED}; /* Non-zero initial seed. Use ma_seed() to use an explicit seed. */ + +static MA_INLINE void ma_lcg_seed(ma_lcg* pLCG, ma_int32 seed) +{ + MA_ASSERT(pLCG != NULL); + pLCG->state = seed; +} + +static MA_INLINE ma_int32 ma_lcg_rand_s32(ma_lcg* pLCG) +{ + pLCG->state = (MA_LCG_A * pLCG->state + MA_LCG_C) % MA_LCG_M; + return pLCG->state; +} + +static MA_INLINE ma_uint32 ma_lcg_rand_u32(ma_lcg* pLCG) +{ + return (ma_uint32)ma_lcg_rand_s32(pLCG); +} + +static MA_INLINE ma_int16 ma_lcg_rand_s16(ma_lcg* pLCG) +{ + return (ma_int16)(ma_lcg_rand_s32(pLCG) & 0xFFFF); +} + +static MA_INLINE double ma_lcg_rand_f64(ma_lcg* pLCG) +{ + return ma_lcg_rand_s32(pLCG) / (double)0x7FFFFFFF; +} + +static MA_INLINE float ma_lcg_rand_f32(ma_lcg* pLCG) +{ + return (float)ma_lcg_rand_f64(pLCG); +} + +static MA_INLINE float ma_lcg_rand_range_f32(ma_lcg* pLCG, float lo, float hi) +{ + return ma_scale_to_range_f32(ma_lcg_rand_f32(pLCG), lo, hi); +} + +static MA_INLINE ma_int32 ma_lcg_rand_range_s32(ma_lcg* pLCG, ma_int32 lo, ma_int32 hi) +{ + if (lo == hi) { + return lo; + } + + return lo + ma_lcg_rand_u32(pLCG) / (0xFFFFFFFF / (hi - lo + 1) + 1); +} + + + +static MA_INLINE void ma_seed(ma_int32 seed) +{ + ma_lcg_seed(&g_maLCG, seed); +} + +static MA_INLINE ma_int32 ma_rand_s32(void) +{ + return ma_lcg_rand_s32(&g_maLCG); +} + +static MA_INLINE ma_uint32 ma_rand_u32(void) +{ + return ma_lcg_rand_u32(&g_maLCG); +} + +static MA_INLINE double ma_rand_f64(void) +{ + return ma_lcg_rand_f64(&g_maLCG); +} + +static MA_INLINE float ma_rand_f32(void) +{ + return ma_lcg_rand_f32(&g_maLCG); +} + +static MA_INLINE float ma_rand_range_f32(float lo, float hi) +{ + return ma_lcg_rand_range_f32(&g_maLCG, lo, hi); +} + +static MA_INLINE ma_int32 ma_rand_range_s32(ma_int32 lo, ma_int32 hi) +{ + return ma_lcg_rand_range_s32(&g_maLCG, lo, hi); +} + + +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; +} + + +/************************************************************************************************************************************************************** + +Atomics + +**************************************************************************************************************************************************************/ +/* ma_atomic.h begin */ +#ifndef ma_atomic_h +#if defined(__cplusplus) +extern "C" { +#endif +#if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wlong-long" + #if defined(__clang__) + #pragma GCC diagnostic ignored "-Wc++11-long-long" + #endif +#endif +typedef int ma_atomic_memory_order; +#define MA_ATOMIC_HAS_8 +#define MA_ATOMIC_HAS_16 +#define MA_ATOMIC_HAS_32 +#define MA_ATOMIC_HAS_64 +#if (defined(_MSC_VER) ) || defined(__WATCOMC__) || defined(__DMC__) + #define MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, intrin, ma_atomicType, msvcType) \ + ma_atomicType result; \ + switch (order) \ + { \ + case ma_atomic_memory_order_relaxed: \ + { \ + result = (ma_atomicType)intrin##_nf((volatile msvcType*)dst, (msvcType)src); \ + } break; \ + case ma_atomic_memory_order_consume: \ + case ma_atomic_memory_order_acquire: \ + { \ + result = (ma_atomicType)intrin##_acq((volatile msvcType*)dst, (msvcType)src); \ + } break; \ + case ma_atomic_memory_order_release: \ + { \ + result = (ma_atomicType)intrin##_rel((volatile msvcType*)dst, (msvcType)src); \ + } break; \ + case ma_atomic_memory_order_acq_rel: \ + case ma_atomic_memory_order_seq_cst: \ + default: \ + { \ + result = (ma_atomicType)intrin((volatile msvcType*)dst, (msvcType)src); \ + } break; \ + } \ + return result; + #define MA_ATOMIC_MSVC_ARM_INTRINSIC_COMPARE_EXCHANGE(ptr, expected, desired, order, intrin, ma_atomicType, msvcType) \ + ma_atomicType result; \ + switch (order) \ + { \ + case ma_atomic_memory_order_relaxed: \ + { \ + result = (ma_atomicType)intrin##_nf((volatile msvcType*)ptr, (msvcType)expected, (msvcType)desired); \ + } break; \ + case ma_atomic_memory_order_consume: \ + case ma_atomic_memory_order_acquire: \ + { \ + result = (ma_atomicType)intrin##_acq((volatile msvcType*)ptr, (msvcType)expected, (msvcType)desired); \ + } break; \ + case ma_atomic_memory_order_release: \ + { \ + result = (ma_atomicType)intrin##_rel((volatile msvcType*)ptr, (msvcType)expected, (msvcType)desired); \ + } break; \ + case ma_atomic_memory_order_acq_rel: \ + case ma_atomic_memory_order_seq_cst: \ + default: \ + { \ + result = (ma_atomicType)intrin((volatile msvcType*)ptr, (msvcType)expected, (msvcType)desired); \ + } break; \ + } \ + return result; + #define ma_atomic_memory_order_relaxed 0 + #define ma_atomic_memory_order_consume 1 + #define ma_atomic_memory_order_acquire 2 + #define ma_atomic_memory_order_release 3 + #define ma_atomic_memory_order_acq_rel 4 + #define ma_atomic_memory_order_seq_cst 5 + #if _MSC_VER < 1600 && defined(MA_X86) + #define MA_ATOMIC_MSVC_USE_INLINED_ASSEMBLY + #endif + #if _MSC_VER < 1600 + #undef MA_ATOMIC_HAS_8 + #undef MA_ATOMIC_HAS_16 + #endif + #if !defined(MA_ATOMIC_MSVC_USE_INLINED_ASSEMBLY) + #include + #endif + #if defined(MA_ATOMIC_MSVC_USE_INLINED_ASSEMBLY) + #if defined(MA_ATOMIC_HAS_8) + static MA_INLINE ma_uint8 __stdcall ma_atomic_compare_and_swap_8(volatile ma_uint8* dst, ma_uint8 expected, ma_uint8 desired) + { + ma_uint8 result = 0; + __asm { + mov ecx, dst + mov al, expected + mov dl, desired + lock cmpxchg [ecx], dl + mov result, al + } + return result; + } + #endif + #if defined(MA_ATOMIC_HAS_16) + static MA_INLINE ma_uint16 __stdcall ma_atomic_compare_and_swap_16(volatile ma_uint16* dst, ma_uint16 expected, ma_uint16 desired) + { + ma_uint16 result = 0; + __asm { + mov ecx, dst + mov ax, expected + mov dx, desired + lock cmpxchg [ecx], dx + mov result, ax + } + return result; + } + #endif + #if defined(MA_ATOMIC_HAS_32) + static MA_INLINE ma_uint32 __stdcall ma_atomic_compare_and_swap_32(volatile ma_uint32* dst, ma_uint32 expected, ma_uint32 desired) + { + ma_uint32 result = 0; + __asm { + mov ecx, dst + mov eax, expected + mov edx, desired + lock cmpxchg [ecx], edx + mov result, eax + } + return result; + } + #endif + #if defined(MA_ATOMIC_HAS_64) + static MA_INLINE ma_uint64 __stdcall ma_atomic_compare_and_swap_64(volatile ma_uint64* dst, ma_uint64 expected, ma_uint64 desired) + { + ma_uint32 resultEAX = 0; + ma_uint32 resultEDX = 0; + __asm { + mov esi, dst + mov eax, dword ptr expected + mov edx, dword ptr expected + 4 + mov ebx, dword ptr desired + mov ecx, dword ptr desired + 4 + lock cmpxchg8b qword ptr [esi] + mov resultEAX, eax + mov resultEDX, edx + } + return ((ma_uint64)resultEDX << 32) | resultEAX; + } + #endif + #else + #if defined(MA_ATOMIC_HAS_8) + #define ma_atomic_compare_and_swap_8( dst, expected, desired) (ma_uint8 )_InterlockedCompareExchange8((volatile char*)dst, (char)desired, (char)expected) + #endif + #if defined(MA_ATOMIC_HAS_16) + #define ma_atomic_compare_and_swap_16(dst, expected, desired) (ma_uint16)_InterlockedCompareExchange16((volatile short*)dst, (short)desired, (short)expected) + #endif + #if defined(MA_ATOMIC_HAS_32) + #define ma_atomic_compare_and_swap_32(dst, expected, desired) (ma_uint32)_InterlockedCompareExchange((volatile long*)dst, (long)desired, (long)expected) + #endif + #if defined(MA_ATOMIC_HAS_64) + #define ma_atomic_compare_and_swap_64(dst, expected, desired) (ma_uint64)_InterlockedCompareExchange64((volatile ma_int64*)dst, (ma_int64)desired, (ma_int64)expected) + #endif + #endif + #if defined(MA_ATOMIC_MSVC_USE_INLINED_ASSEMBLY) + #if defined(MA_ATOMIC_HAS_8) + static MA_INLINE ma_uint8 __stdcall ma_atomic_exchange_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order) + { + ma_uint8 result = 0; + (void)order; + __asm { + mov ecx, dst + mov al, src + lock xchg [ecx], al + mov result, al + } + return result; + } + #endif + #if defined(MA_ATOMIC_HAS_16) + static MA_INLINE ma_uint16 __stdcall ma_atomic_exchange_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order) + { + ma_uint16 result = 0; + (void)order; + __asm { + mov ecx, dst + mov ax, src + lock xchg [ecx], ax + mov result, ax + } + return result; + } + #endif + #if defined(MA_ATOMIC_HAS_32) + static MA_INLINE ma_uint32 __stdcall ma_atomic_exchange_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order) + { + ma_uint32 result = 0; + (void)order; + __asm { + mov ecx, dst + mov eax, src + lock xchg [ecx], eax + mov result, eax + } + return result; + } + #endif + #else + #if defined(MA_ATOMIC_HAS_8) + static MA_INLINE ma_uint8 __stdcall ma_atomic_exchange_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchange8, ma_uint8, char); + #else + (void)order; + return (ma_uint8)_InterlockedExchange8((volatile char*)dst, (char)src); + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_16) + static MA_INLINE ma_uint16 __stdcall ma_atomic_exchange_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchange16, ma_uint16, short); + #else + (void)order; + return (ma_uint16)_InterlockedExchange16((volatile short*)dst, (short)src); + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_32) + static MA_INLINE ma_uint32 __stdcall ma_atomic_exchange_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchange, ma_uint32, long); + #else + (void)order; + return (ma_uint32)_InterlockedExchange((volatile long*)dst, (long)src); + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_64) && defined(MA_64BIT) + static MA_INLINE ma_uint64 __stdcall ma_atomic_exchange_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchange64, ma_uint64, long long); + #else + (void)order; + return (ma_uint64)_InterlockedExchange64((volatile long long*)dst, (long long)src); + #endif + } + #else + #endif + #endif + #if defined(MA_ATOMIC_HAS_64) && !defined(MA_64BIT) + static MA_INLINE ma_uint64 __stdcall ma_atomic_exchange_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order) + { + ma_uint64 oldValue; + do { + oldValue = *dst; + } while (ma_atomic_compare_and_swap_64(dst, oldValue, src) != oldValue); + (void)order; + return oldValue; + } + #endif + #if defined(MA_ATOMIC_MSVC_USE_INLINED_ASSEMBLY) + #if defined(MA_ATOMIC_HAS_8) + static MA_INLINE ma_uint8 __stdcall ma_atomic_fetch_add_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order) + { + ma_uint8 result = 0; + (void)order; + __asm { + mov ecx, dst + mov al, src + lock xadd [ecx], al + mov result, al + } + return result; + } + #endif + #if defined(MA_ATOMIC_HAS_16) + static MA_INLINE ma_uint16 __stdcall ma_atomic_fetch_add_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order) + { + ma_uint16 result = 0; + (void)order; + __asm { + mov ecx, dst + mov ax, src + lock xadd [ecx], ax + mov result, ax + } + return result; + } + #endif + #if defined(MA_ATOMIC_HAS_32) + static MA_INLINE ma_uint32 __stdcall ma_atomic_fetch_add_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order) + { + ma_uint32 result = 0; + (void)order; + __asm { + mov ecx, dst + mov eax, src + lock xadd [ecx], eax + mov result, eax + } + return result; + } + #endif + #else + #if defined(MA_ATOMIC_HAS_8) + static MA_INLINE ma_uint8 __stdcall ma_atomic_fetch_add_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchangeAdd8, ma_uint8, char); + #else + (void)order; + return (ma_uint8)_InterlockedExchangeAdd8((volatile char*)dst, (char)src); + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_16) + static MA_INLINE ma_uint16 __stdcall ma_atomic_fetch_add_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchangeAdd16, ma_uint16, short); + #else + (void)order; + return (ma_uint16)_InterlockedExchangeAdd16((volatile short*)dst, (short)src); + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_32) + static MA_INLINE ma_uint32 __stdcall ma_atomic_fetch_add_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchangeAdd, ma_uint32, long); + #else + (void)order; + return (ma_uint32)_InterlockedExchangeAdd((volatile long*)dst, (long)src); + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_64) && defined(MA_64BIT) + static MA_INLINE ma_uint64 __stdcall ma_atomic_fetch_add_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchangeAdd64, ma_uint64, long long); + #else + (void)order; + return (ma_uint64)_InterlockedExchangeAdd64((volatile long long*)dst, (long long)src); + #endif + } + #else + #endif + #endif + #if defined(MA_ATOMIC_HAS_64) && !defined(MA_64BIT) + static MA_INLINE ma_uint64 __stdcall ma_atomic_fetch_add_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order) + { + ma_uint64 oldValue; + ma_uint64 newValue; + do { + oldValue = *dst; + newValue = oldValue + src; + } while (ma_atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + } + #endif + #if defined(MA_ATOMIC_MSVC_USE_INLINED_ASSEMBLY) + static MA_INLINE void __stdcall ma_atomic_thread_fence(ma_atomic_memory_order order) + { + (void)order; + __asm { + lock add [esp], 0 + } + } + #else + #if defined(MA_X64) + #define ma_atomic_thread_fence(order) __faststorefence(), (void)order + #elif defined(MA_ARM64) + #define ma_atomic_thread_fence(order) __dmb(_ARM64_BARRIER_ISH), (void)order + #else + static MA_INLINE void ma_atomic_thread_fence(ma_atomic_memory_order order) + { + volatile ma_uint32 barrier = 0; + ma_atomic_fetch_add_explicit_32(&barrier, 0, order); + } + #endif + #endif + #define ma_atomic_compiler_fence() ma_atomic_thread_fence(ma_atomic_memory_order_seq_cst) + #define ma_atomic_signal_fence(order) ma_atomic_thread_fence(order) + #if defined(MA_ATOMIC_HAS_8) + static MA_INLINE ma_uint8 ma_atomic_load_explicit_8(volatile const ma_uint8* ptr, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC_COMPARE_EXCHANGE(ptr, 0, 0, order, _InterlockedCompareExchange8, ma_uint8, char); + #else + (void)order; + return ma_atomic_compare_and_swap_8((volatile ma_uint8*)ptr, 0, 0); + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_16) + static MA_INLINE ma_uint16 ma_atomic_load_explicit_16(volatile const ma_uint16* ptr, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC_COMPARE_EXCHANGE(ptr, 0, 0, order, _InterlockedCompareExchange16, ma_uint16, short); + #else + (void)order; + return ma_atomic_compare_and_swap_16((volatile ma_uint16*)ptr, 0, 0); + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_32) + static MA_INLINE ma_uint32 ma_atomic_load_explicit_32(volatile const ma_uint32* ptr, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC_COMPARE_EXCHANGE(ptr, 0, 0, order, _InterlockedCompareExchange, ma_uint32, long); + #else + (void)order; + return ma_atomic_compare_and_swap_32((volatile ma_uint32*)ptr, 0, 0); + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_64) + static MA_INLINE ma_uint64 ma_atomic_load_explicit_64(volatile const ma_uint64* ptr, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC_COMPARE_EXCHANGE(ptr, 0, 0, order, _InterlockedCompareExchange64, ma_uint64, long long); + #else + (void)order; + return ma_atomic_compare_and_swap_64((volatile ma_uint64*)ptr, 0, 0); + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_8) + #define ma_atomic_store_explicit_8( dst, src, order) (void)ma_atomic_exchange_explicit_8 (dst, src, order) + #endif + #if defined(MA_ATOMIC_HAS_16) + #define ma_atomic_store_explicit_16(dst, src, order) (void)ma_atomic_exchange_explicit_16(dst, src, order) + #endif + #if defined(MA_ATOMIC_HAS_32) + #define ma_atomic_store_explicit_32(dst, src, order) (void)ma_atomic_exchange_explicit_32(dst, src, order) + #endif + #if defined(MA_ATOMIC_HAS_64) + #define ma_atomic_store_explicit_64(dst, src, order) (void)ma_atomic_exchange_explicit_64(dst, src, order) + #endif + #if defined(MA_ATOMIC_HAS_8) + static MA_INLINE ma_uint8 __stdcall ma_atomic_fetch_sub_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order) + { + ma_uint8 oldValue; + ma_uint8 newValue; + do { + oldValue = *dst; + newValue = (ma_uint8)(oldValue - src); + } while (ma_atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + } + #endif + #if defined(MA_ATOMIC_HAS_16) + static MA_INLINE ma_uint16 __stdcall ma_atomic_fetch_sub_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order) + { + ma_uint16 oldValue; + ma_uint16 newValue; + do { + oldValue = *dst; + newValue = (ma_uint16)(oldValue - src); + } while (ma_atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + } + #endif + #if defined(MA_ATOMIC_HAS_32) + static MA_INLINE ma_uint32 __stdcall ma_atomic_fetch_sub_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order) + { + ma_uint32 oldValue; + ma_uint32 newValue; + do { + oldValue = *dst; + newValue = oldValue - src; + } while (ma_atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + } + #endif + #if defined(MA_ATOMIC_HAS_64) + static MA_INLINE ma_uint64 __stdcall ma_atomic_fetch_sub_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order) + { + ma_uint64 oldValue; + ma_uint64 newValue; + do { + oldValue = *dst; + newValue = oldValue - src; + } while (ma_atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + } + #endif + #if defined(MA_ATOMIC_HAS_8) + static MA_INLINE ma_uint8 __stdcall ma_atomic_fetch_and_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedAnd8, ma_uint8, char); + #else + ma_uint8 oldValue; + ma_uint8 newValue; + do { + oldValue = *dst; + newValue = (ma_uint8)(oldValue & src); + } while (ma_atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_16) + static MA_INLINE ma_uint16 __stdcall ma_atomic_fetch_and_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedAnd16, ma_uint16, short); + #else + ma_uint16 oldValue; + ma_uint16 newValue; + do { + oldValue = *dst; + newValue = (ma_uint16)(oldValue & src); + } while (ma_atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_32) + static MA_INLINE ma_uint32 __stdcall ma_atomic_fetch_and_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedAnd, ma_uint32, long); + #else + ma_uint32 oldValue; + ma_uint32 newValue; + do { + oldValue = *dst; + newValue = oldValue & src; + } while (ma_atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_64) + static MA_INLINE ma_uint64 __stdcall ma_atomic_fetch_and_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedAnd64, ma_uint64, long long); + #else + ma_uint64 oldValue; + ma_uint64 newValue; + do { + oldValue = *dst; + newValue = oldValue & src; + } while (ma_atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_8) + static MA_INLINE ma_uint8 __stdcall ma_atomic_fetch_xor_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedXor8, ma_uint8, char); + #else + ma_uint8 oldValue; + ma_uint8 newValue; + do { + oldValue = *dst; + newValue = (ma_uint8)(oldValue ^ src); + } while (ma_atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_16) + static MA_INLINE ma_uint16 __stdcall ma_atomic_fetch_xor_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedXor16, ma_uint16, short); + #else + ma_uint16 oldValue; + ma_uint16 newValue; + do { + oldValue = *dst; + newValue = (ma_uint16)(oldValue ^ src); + } while (ma_atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_32) + static MA_INLINE ma_uint32 __stdcall ma_atomic_fetch_xor_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedXor, ma_uint32, long); + #else + ma_uint32 oldValue; + ma_uint32 newValue; + do { + oldValue = *dst; + newValue = oldValue ^ src; + } while (ma_atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_64) + static MA_INLINE ma_uint64 __stdcall ma_atomic_fetch_xor_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedXor64, ma_uint64, long long); + #else + ma_uint64 oldValue; + ma_uint64 newValue; + do { + oldValue = *dst; + newValue = oldValue ^ src; + } while (ma_atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_8) + static MA_INLINE ma_uint8 __stdcall ma_atomic_fetch_or_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedOr8, ma_uint8, char); + #else + ma_uint8 oldValue; + ma_uint8 newValue; + do { + oldValue = *dst; + newValue = (ma_uint8)(oldValue | src); + } while (ma_atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_16) + static MA_INLINE ma_uint16 __stdcall ma_atomic_fetch_or_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedOr16, ma_uint16, short); + #else + ma_uint16 oldValue; + ma_uint16 newValue; + do { + oldValue = *dst; + newValue = (ma_uint16)(oldValue | src); + } while (ma_atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_32) + static MA_INLINE ma_uint32 __stdcall ma_atomic_fetch_or_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedOr, ma_uint32, long); + #else + ma_uint32 oldValue; + ma_uint32 newValue; + do { + oldValue = *dst; + newValue = oldValue | src; + } while (ma_atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_64) + static MA_INLINE ma_uint64 __stdcall ma_atomic_fetch_or_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order) + { + #if defined(MA_ARM) + MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedOr64, ma_uint64, long long); + #else + ma_uint64 oldValue; + ma_uint64 newValue; + do { + oldValue = *dst; + newValue = oldValue | src; + } while (ma_atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + #endif + } + #endif + #if defined(MA_ATOMIC_HAS_8) + #define ma_atomic_test_and_set_explicit_8( dst, order) ma_atomic_exchange_explicit_8 (dst, 1, order) + #endif + #if defined(MA_ATOMIC_HAS_16) + #define ma_atomic_test_and_set_explicit_16(dst, order) ma_atomic_exchange_explicit_16(dst, 1, order) + #endif + #if defined(MA_ATOMIC_HAS_32) + #define ma_atomic_test_and_set_explicit_32(dst, order) ma_atomic_exchange_explicit_32(dst, 1, order) + #endif + #if defined(MA_ATOMIC_HAS_64) + #define ma_atomic_test_and_set_explicit_64(dst, order) ma_atomic_exchange_explicit_64(dst, 1, order) + #endif + #if defined(MA_ATOMIC_HAS_8) + #define ma_atomic_clear_explicit_8( dst, order) ma_atomic_store_explicit_8 (dst, 0, order) + #endif + #if defined(MA_ATOMIC_HAS_16) + #define ma_atomic_clear_explicit_16(dst, order) ma_atomic_store_explicit_16(dst, 0, order) + #endif + #if defined(MA_ATOMIC_HAS_32) + #define ma_atomic_clear_explicit_32(dst, order) ma_atomic_store_explicit_32(dst, 0, order) + #endif + #if defined(MA_ATOMIC_HAS_64) + #define ma_atomic_clear_explicit_64(dst, order) ma_atomic_store_explicit_64(dst, 0, order) + #endif + #if defined(MA_ATOMIC_HAS_8) + typedef ma_uint8 ma_atomic_flag; + #define ma_atomic_flag_test_and_set_explicit(ptr, order) (ma_bool32)ma_atomic_test_and_set_explicit_8(ptr, order) + #define ma_atomic_flag_clear_explicit(ptr, order) ma_atomic_clear_explicit_8(ptr, order) + #define c89atoimc_flag_load_explicit(ptr, order) ma_atomic_load_explicit_8(ptr, order) + #else + typedef ma_uint32 ma_atomic_flag; + #define ma_atomic_flag_test_and_set_explicit(ptr, order) (ma_bool32)ma_atomic_test_and_set_explicit_32(ptr, order) + #define ma_atomic_flag_clear_explicit(ptr, order) ma_atomic_clear_explicit_32(ptr, order) + #define c89atoimc_flag_load_explicit(ptr, order) ma_atomic_load_explicit_32(ptr, order) + #endif +#elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7))) + #define MA_ATOMIC_HAS_NATIVE_COMPARE_EXCHANGE + #define MA_ATOMIC_HAS_NATIVE_IS_LOCK_FREE + #define ma_atomic_memory_order_relaxed __ATOMIC_RELAXED + #define ma_atomic_memory_order_consume __ATOMIC_CONSUME + #define ma_atomic_memory_order_acquire __ATOMIC_ACQUIRE + #define ma_atomic_memory_order_release __ATOMIC_RELEASE + #define ma_atomic_memory_order_acq_rel __ATOMIC_ACQ_REL + #define ma_atomic_memory_order_seq_cst __ATOMIC_SEQ_CST + #define ma_atomic_compiler_fence() __asm__ __volatile__("":::"memory") + #define ma_atomic_thread_fence(order) __atomic_thread_fence(order) + #define ma_atomic_signal_fence(order) __atomic_signal_fence(order) + #define ma_atomic_is_lock_free_8(ptr) __atomic_is_lock_free(1, ptr) + #define ma_atomic_is_lock_free_16(ptr) __atomic_is_lock_free(2, ptr) + #define ma_atomic_is_lock_free_32(ptr) __atomic_is_lock_free(4, ptr) + #define ma_atomic_is_lock_free_64(ptr) __atomic_is_lock_free(8, ptr) + #define ma_atomic_test_and_set_explicit_8( dst, order) __atomic_exchange_n(dst, 1, order) + #define ma_atomic_test_and_set_explicit_16(dst, order) __atomic_exchange_n(dst, 1, order) + #define ma_atomic_test_and_set_explicit_32(dst, order) __atomic_exchange_n(dst, 1, order) + #define ma_atomic_test_and_set_explicit_64(dst, order) __atomic_exchange_n(dst, 1, order) + #define ma_atomic_clear_explicit_8( dst, order) __atomic_store_n(dst, 0, order) + #define ma_atomic_clear_explicit_16(dst, order) __atomic_store_n(dst, 0, order) + #define ma_atomic_clear_explicit_32(dst, order) __atomic_store_n(dst, 0, order) + #define ma_atomic_clear_explicit_64(dst, order) __atomic_store_n(dst, 0, order) + #define ma_atomic_store_explicit_8( dst, src, order) __atomic_store_n(dst, src, order) + #define ma_atomic_store_explicit_16(dst, src, order) __atomic_store_n(dst, src, order) + #define ma_atomic_store_explicit_32(dst, src, order) __atomic_store_n(dst, src, order) + #define ma_atomic_store_explicit_64(dst, src, order) __atomic_store_n(dst, src, order) + #define ma_atomic_load_explicit_8( dst, order) __atomic_load_n(dst, order) + #define ma_atomic_load_explicit_16(dst, order) __atomic_load_n(dst, order) + #define ma_atomic_load_explicit_32(dst, order) __atomic_load_n(dst, order) + #define ma_atomic_load_explicit_64(dst, order) __atomic_load_n(dst, order) + #define ma_atomic_exchange_explicit_8( dst, src, order) __atomic_exchange_n(dst, src, order) + #define ma_atomic_exchange_explicit_16(dst, src, order) __atomic_exchange_n(dst, src, order) + #define ma_atomic_exchange_explicit_32(dst, src, order) __atomic_exchange_n(dst, src, order) + #define ma_atomic_exchange_explicit_64(dst, src, order) __atomic_exchange_n(dst, src, order) + #define ma_atomic_compare_exchange_strong_explicit_8( dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder) + #define ma_atomic_compare_exchange_strong_explicit_16(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder) + #define ma_atomic_compare_exchange_strong_explicit_32(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder) + #define ma_atomic_compare_exchange_strong_explicit_64(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder) + #define ma_atomic_compare_exchange_weak_explicit_8( dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder) + #define ma_atomic_compare_exchange_weak_explicit_16(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder) + #define ma_atomic_compare_exchange_weak_explicit_32(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder) + #define ma_atomic_compare_exchange_weak_explicit_64(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder) + #define ma_atomic_fetch_add_explicit_8( dst, src, order) __atomic_fetch_add(dst, src, order) + #define ma_atomic_fetch_add_explicit_16(dst, src, order) __atomic_fetch_add(dst, src, order) + #define ma_atomic_fetch_add_explicit_32(dst, src, order) __atomic_fetch_add(dst, src, order) + #define ma_atomic_fetch_add_explicit_64(dst, src, order) __atomic_fetch_add(dst, src, order) + #define ma_atomic_fetch_sub_explicit_8( dst, src, order) __atomic_fetch_sub(dst, src, order) + #define ma_atomic_fetch_sub_explicit_16(dst, src, order) __atomic_fetch_sub(dst, src, order) + #define ma_atomic_fetch_sub_explicit_32(dst, src, order) __atomic_fetch_sub(dst, src, order) + #define ma_atomic_fetch_sub_explicit_64(dst, src, order) __atomic_fetch_sub(dst, src, order) + #define ma_atomic_fetch_or_explicit_8( dst, src, order) __atomic_fetch_or(dst, src, order) + #define ma_atomic_fetch_or_explicit_16(dst, src, order) __atomic_fetch_or(dst, src, order) + #define ma_atomic_fetch_or_explicit_32(dst, src, order) __atomic_fetch_or(dst, src, order) + #define ma_atomic_fetch_or_explicit_64(dst, src, order) __atomic_fetch_or(dst, src, order) + #define ma_atomic_fetch_xor_explicit_8( dst, src, order) __atomic_fetch_xor(dst, src, order) + #define ma_atomic_fetch_xor_explicit_16(dst, src, order) __atomic_fetch_xor(dst, src, order) + #define ma_atomic_fetch_xor_explicit_32(dst, src, order) __atomic_fetch_xor(dst, src, order) + #define ma_atomic_fetch_xor_explicit_64(dst, src, order) __atomic_fetch_xor(dst, src, order) + #define ma_atomic_fetch_and_explicit_8( dst, src, order) __atomic_fetch_and(dst, src, order) + #define ma_atomic_fetch_and_explicit_16(dst, src, order) __atomic_fetch_and(dst, src, order) + #define ma_atomic_fetch_and_explicit_32(dst, src, order) __atomic_fetch_and(dst, src, order) + #define ma_atomic_fetch_and_explicit_64(dst, src, order) __atomic_fetch_and(dst, src, order) + static MA_INLINE ma_uint8 ma_atomic_compare_and_swap_8(volatile ma_uint8* dst, ma_uint8 expected, ma_uint8 desired) + { + __atomic_compare_exchange_n(dst, &expected, desired, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); + return expected; + } + static MA_INLINE ma_uint16 ma_atomic_compare_and_swap_16(volatile ma_uint16* dst, ma_uint16 expected, ma_uint16 desired) + { + __atomic_compare_exchange_n(dst, &expected, desired, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); + return expected; + } + static MA_INLINE ma_uint32 ma_atomic_compare_and_swap_32(volatile ma_uint32* dst, ma_uint32 expected, ma_uint32 desired) + { + __atomic_compare_exchange_n(dst, &expected, desired, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); + return expected; + } + static MA_INLINE ma_uint64 ma_atomic_compare_and_swap_64(volatile ma_uint64* dst, ma_uint64 expected, ma_uint64 desired) + { + __atomic_compare_exchange_n(dst, &expected, desired, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); + return expected; + } + typedef ma_uint8 ma_atomic_flag; + #define ma_atomic_flag_test_and_set_explicit(dst, order) (ma_bool32)__atomic_test_and_set(dst, order) + #define ma_atomic_flag_clear_explicit(dst, order) __atomic_clear(dst, order) + #define c89atoimc_flag_load_explicit(ptr, order) ma_atomic_load_explicit_8(ptr, order) +#else + #define ma_atomic_memory_order_relaxed 1 + #define ma_atomic_memory_order_consume 2 + #define ma_atomic_memory_order_acquire 3 + #define ma_atomic_memory_order_release 4 + #define ma_atomic_memory_order_acq_rel 5 + #define ma_atomic_memory_order_seq_cst 6 + #define ma_atomic_compiler_fence() __asm__ __volatile__("":::"memory") + #if defined(__GNUC__) + #define ma_atomic_thread_fence(order) __sync_synchronize(), (void)order + static MA_INLINE ma_uint8 ma_atomic_exchange_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order) + { + if (order > ma_atomic_memory_order_acquire) { + __sync_synchronize(); + } + return __sync_lock_test_and_set(dst, src); + } + static MA_INLINE ma_uint16 ma_atomic_exchange_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order) + { + ma_uint16 oldValue; + do { + oldValue = *dst; + } while (__sync_val_compare_and_swap(dst, oldValue, src) != oldValue); + (void)order; + return oldValue; + } + static MA_INLINE ma_uint32 ma_atomic_exchange_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order) + { + ma_uint32 oldValue; + do { + oldValue = *dst; + } while (__sync_val_compare_and_swap(dst, oldValue, src) != oldValue); + (void)order; + return oldValue; + } + static MA_INLINE ma_uint64 ma_atomic_exchange_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order) + { + ma_uint64 oldValue; + do { + oldValue = *dst; + } while (__sync_val_compare_and_swap(dst, oldValue, src) != oldValue); + (void)order; + return oldValue; + } + static MA_INLINE ma_uint8 ma_atomic_fetch_add_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order) + { + (void)order; + return __sync_fetch_and_add(dst, src); + } + static MA_INLINE ma_uint16 ma_atomic_fetch_add_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order) + { + (void)order; + return __sync_fetch_and_add(dst, src); + } + static MA_INLINE ma_uint32 ma_atomic_fetch_add_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order) + { + (void)order; + return __sync_fetch_and_add(dst, src); + } + static MA_INLINE ma_uint64 ma_atomic_fetch_add_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order) + { + (void)order; + return __sync_fetch_and_add(dst, src); + } + static MA_INLINE ma_uint8 ma_atomic_fetch_sub_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order) + { + (void)order; + return __sync_fetch_and_sub(dst, src); + } + static MA_INLINE ma_uint16 ma_atomic_fetch_sub_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order) + { + (void)order; + return __sync_fetch_and_sub(dst, src); + } + static MA_INLINE ma_uint32 ma_atomic_fetch_sub_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order) + { + (void)order; + return __sync_fetch_and_sub(dst, src); + } + static MA_INLINE ma_uint64 ma_atomic_fetch_sub_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order) + { + (void)order; + return __sync_fetch_and_sub(dst, src); + } + static MA_INLINE ma_uint8 ma_atomic_fetch_or_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order) + { + (void)order; + return __sync_fetch_and_or(dst, src); + } + static MA_INLINE ma_uint16 ma_atomic_fetch_or_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order) + { + (void)order; + return __sync_fetch_and_or(dst, src); + } + static MA_INLINE ma_uint32 ma_atomic_fetch_or_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order) + { + (void)order; + return __sync_fetch_and_or(dst, src); + } + static MA_INLINE ma_uint64 ma_atomic_fetch_or_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order) + { + (void)order; + return __sync_fetch_and_or(dst, src); + } + static MA_INLINE ma_uint8 ma_atomic_fetch_xor_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order) + { + (void)order; + return __sync_fetch_and_xor(dst, src); + } + static MA_INLINE ma_uint16 ma_atomic_fetch_xor_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order) + { + (void)order; + return __sync_fetch_and_xor(dst, src); + } + static MA_INLINE ma_uint32 ma_atomic_fetch_xor_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order) + { + (void)order; + return __sync_fetch_and_xor(dst, src); + } + static MA_INLINE ma_uint64 ma_atomic_fetch_xor_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order) + { + (void)order; + return __sync_fetch_and_xor(dst, src); + } + static MA_INLINE ma_uint8 ma_atomic_fetch_and_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order) + { + (void)order; + return __sync_fetch_and_and(dst, src); + } + static MA_INLINE ma_uint16 ma_atomic_fetch_and_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order) + { + (void)order; + return __sync_fetch_and_and(dst, src); + } + static MA_INLINE ma_uint32 ma_atomic_fetch_and_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order) + { + (void)order; + return __sync_fetch_and_and(dst, src); + } + static MA_INLINE ma_uint64 ma_atomic_fetch_and_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order) + { + (void)order; + return __sync_fetch_and_and(dst, src); + } + #define ma_atomic_compare_and_swap_8( dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired) + #define ma_atomic_compare_and_swap_16(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired) + #define ma_atomic_compare_and_swap_32(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired) + #define ma_atomic_compare_and_swap_64(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired) + #else + #if defined(MA_X86) + #define ma_atomic_thread_fence(order) __asm__ __volatile__("lock; addl $0, (%%esp)" ::: "memory", "cc") + #elif defined(MA_X64) + #define ma_atomic_thread_fence(order) __asm__ __volatile__("lock; addq $0, (%%rsp)" ::: "memory", "cc") + #else + #error Unsupported architecture. Please submit a feature request. + #endif + static MA_INLINE ma_uint8 ma_atomic_compare_and_swap_8(volatile ma_uint8* dst, ma_uint8 expected, ma_uint8 desired) + { + ma_uint8 result; + #if defined(MA_X86) || defined(MA_X64) + __asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc"); + #else + #error Unsupported architecture. Please submit a feature request. + #endif + return result; + } + static MA_INLINE ma_uint16 ma_atomic_compare_and_swap_16(volatile ma_uint16* dst, ma_uint16 expected, ma_uint16 desired) + { + ma_uint16 result; + #if defined(MA_X86) || defined(MA_X64) + __asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc"); + #else + #error Unsupported architecture. Please submit a feature request. + #endif + return result; + } + static MA_INLINE ma_uint32 ma_atomic_compare_and_swap_32(volatile ma_uint32* dst, ma_uint32 expected, ma_uint32 desired) + { + ma_uint32 result; + #if defined(MA_X86) || defined(MA_X64) + __asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc"); + #else + #error Unsupported architecture. Please submit a feature request. + #endif + return result; + } + static MA_INLINE ma_uint64 ma_atomic_compare_and_swap_64(volatile ma_uint64* dst, ma_uint64 expected, ma_uint64 desired) + { + volatile ma_uint64 result; + #if defined(MA_X86) + ma_uint32 resultEAX; + ma_uint32 resultEDX; + __asm__ __volatile__("push %%ebx; xchg %5, %%ebx; lock; cmpxchg8b %0; pop %%ebx" : "+m"(*dst), "=a"(resultEAX), "=d"(resultEDX) : "a"(expected & 0xFFFFFFFF), "d"(expected >> 32), "r"(desired & 0xFFFFFFFF), "c"(desired >> 32) : "cc"); + result = ((ma_uint64)resultEDX << 32) | resultEAX; + #elif defined(MA_X64) + __asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc"); + #else + #error Unsupported architecture. Please submit a feature request. + #endif + return result; + } + static MA_INLINE ma_uint8 ma_atomic_exchange_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order) + { + ma_uint8 result = 0; + (void)order; + #if defined(MA_X86) || defined(MA_X64) + __asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src)); + #else + #error Unsupported architecture. Please submit a feature request. + #endif + return result; + } + static MA_INLINE ma_uint16 ma_atomic_exchange_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order) + { + ma_uint16 result = 0; + (void)order; + #if defined(MA_X86) || defined(MA_X64) + __asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src)); + #else + #error Unsupported architecture. Please submit a feature request. + #endif + return result; + } + static MA_INLINE ma_uint32 ma_atomic_exchange_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order) + { + ma_uint32 result; + (void)order; + #if defined(MA_X86) || defined(MA_X64) + __asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src)); + #else + #error Unsupported architecture. Please submit a feature request. + #endif + return result; + } + static MA_INLINE ma_uint64 ma_atomic_exchange_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order) + { + ma_uint64 result; + (void)order; + #if defined(MA_X86) + do { + result = *dst; + } while (ma_atomic_compare_and_swap_64(dst, result, src) != result); + #elif defined(MA_X64) + __asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src)); + #else + #error Unsupported architecture. Please submit a feature request. + #endif + return result; + } + static MA_INLINE ma_uint8 ma_atomic_fetch_add_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order) + { + ma_uint8 result; + (void)order; + #if defined(MA_X86) || defined(MA_X64) + __asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc"); + #else + #error Unsupported architecture. Please submit a feature request. + #endif + return result; + } + static MA_INLINE ma_uint16 ma_atomic_fetch_add_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order) + { + ma_uint16 result; + (void)order; + #if defined(MA_X86) || defined(MA_X64) + __asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc"); + #else + #error Unsupported architecture. Please submit a feature request. + #endif + return result; + } + static MA_INLINE ma_uint32 ma_atomic_fetch_add_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order) + { + ma_uint32 result; + (void)order; + #if defined(MA_X86) || defined(MA_X64) + __asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc"); + #else + #error Unsupported architecture. Please submit a feature request. + #endif + return result; + } + static MA_INLINE ma_uint64 ma_atomic_fetch_add_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order) + { + #if defined(MA_X86) + ma_uint64 oldValue; + ma_uint64 newValue; + (void)order; + do { + oldValue = *dst; + newValue = oldValue + src; + } while (ma_atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue); + return oldValue; + #elif defined(MA_X64) + ma_uint64 result; + (void)order; + __asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc"); + return result; + #endif + } + static MA_INLINE ma_uint8 ma_atomic_fetch_sub_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order) + { + ma_uint8 oldValue; + ma_uint8 newValue; + do { + oldValue = *dst; + newValue = (ma_uint8)(oldValue - src); + } while (ma_atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + } + static MA_INLINE ma_uint16 ma_atomic_fetch_sub_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order) + { + ma_uint16 oldValue; + ma_uint16 newValue; + do { + oldValue = *dst; + newValue = (ma_uint16)(oldValue - src); + } while (ma_atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + } + static MA_INLINE ma_uint32 ma_atomic_fetch_sub_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order) + { + ma_uint32 oldValue; + ma_uint32 newValue; + do { + oldValue = *dst; + newValue = oldValue - src; + } while (ma_atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + } + static MA_INLINE ma_uint64 ma_atomic_fetch_sub_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order) + { + ma_uint64 oldValue; + ma_uint64 newValue; + do { + oldValue = *dst; + newValue = oldValue - src; + } while (ma_atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + } + static MA_INLINE ma_uint8 ma_atomic_fetch_and_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order) + { + ma_uint8 oldValue; + ma_uint8 newValue; + do { + oldValue = *dst; + newValue = (ma_uint8)(oldValue & src); + } while (ma_atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + } + static MA_INLINE ma_uint16 ma_atomic_fetch_and_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order) + { + ma_uint16 oldValue; + ma_uint16 newValue; + do { + oldValue = *dst; + newValue = (ma_uint16)(oldValue & src); + } while (ma_atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + } + static MA_INLINE ma_uint32 ma_atomic_fetch_and_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order) + { + ma_uint32 oldValue; + ma_uint32 newValue; + do { + oldValue = *dst; + newValue = oldValue & src; + } while (ma_atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + } + static MA_INLINE ma_uint64 ma_atomic_fetch_and_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order) + { + ma_uint64 oldValue; + ma_uint64 newValue; + do { + oldValue = *dst; + newValue = oldValue & src; + } while (ma_atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + } + static MA_INLINE ma_uint8 ma_atomic_fetch_xor_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order) + { + ma_uint8 oldValue; + ma_uint8 newValue; + do { + oldValue = *dst; + newValue = (ma_uint8)(oldValue ^ src); + } while (ma_atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + } + static MA_INLINE ma_uint16 ma_atomic_fetch_xor_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order) + { + ma_uint16 oldValue; + ma_uint16 newValue; + do { + oldValue = *dst; + newValue = (ma_uint16)(oldValue ^ src); + } while (ma_atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + } + static MA_INLINE ma_uint32 ma_atomic_fetch_xor_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order) + { + ma_uint32 oldValue; + ma_uint32 newValue; + do { + oldValue = *dst; + newValue = oldValue ^ src; + } while (ma_atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + } + static MA_INLINE ma_uint64 ma_atomic_fetch_xor_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order) + { + ma_uint64 oldValue; + ma_uint64 newValue; + do { + oldValue = *dst; + newValue = oldValue ^ src; + } while (ma_atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + } + static MA_INLINE ma_uint8 ma_atomic_fetch_or_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order) + { + ma_uint8 oldValue; + ma_uint8 newValue; + do { + oldValue = *dst; + newValue = (ma_uint8)(oldValue | src); + } while (ma_atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + } + static MA_INLINE ma_uint16 ma_atomic_fetch_or_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order) + { + ma_uint16 oldValue; + ma_uint16 newValue; + do { + oldValue = *dst; + newValue = (ma_uint16)(oldValue | src); + } while (ma_atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + } + static MA_INLINE ma_uint32 ma_atomic_fetch_or_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order) + { + ma_uint32 oldValue; + ma_uint32 newValue; + do { + oldValue = *dst; + newValue = oldValue | src; + } while (ma_atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + } + static MA_INLINE ma_uint64 ma_atomic_fetch_or_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order) + { + ma_uint64 oldValue; + ma_uint64 newValue; + do { + oldValue = *dst; + newValue = oldValue | src; + } while (ma_atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue); + (void)order; + return oldValue; + } + #endif + #define ma_atomic_signal_fence(order) ma_atomic_thread_fence(order) + static MA_INLINE ma_uint8 ma_atomic_load_explicit_8(volatile const ma_uint8* ptr, ma_atomic_memory_order order) + { + (void)order; + return ma_atomic_compare_and_swap_8((ma_uint8*)ptr, 0, 0); + } + static MA_INLINE ma_uint16 ma_atomic_load_explicit_16(volatile const ma_uint16* ptr, ma_atomic_memory_order order) + { + (void)order; + return ma_atomic_compare_and_swap_16((ma_uint16*)ptr, 0, 0); + } + static MA_INLINE ma_uint32 ma_atomic_load_explicit_32(volatile const ma_uint32* ptr, ma_atomic_memory_order order) + { + (void)order; + return ma_atomic_compare_and_swap_32((ma_uint32*)ptr, 0, 0); + } + static MA_INLINE ma_uint64 ma_atomic_load_explicit_64(volatile const ma_uint64* ptr, ma_atomic_memory_order order) + { + (void)order; + return ma_atomic_compare_and_swap_64((ma_uint64*)ptr, 0, 0); + } + #define ma_atomic_store_explicit_8( dst, src, order) (void)ma_atomic_exchange_explicit_8 (dst, src, order) + #define ma_atomic_store_explicit_16(dst, src, order) (void)ma_atomic_exchange_explicit_16(dst, src, order) + #define ma_atomic_store_explicit_32(dst, src, order) (void)ma_atomic_exchange_explicit_32(dst, src, order) + #define ma_atomic_store_explicit_64(dst, src, order) (void)ma_atomic_exchange_explicit_64(dst, src, order) + #define ma_atomic_test_and_set_explicit_8( dst, order) ma_atomic_exchange_explicit_8 (dst, 1, order) + #define ma_atomic_test_and_set_explicit_16(dst, order) ma_atomic_exchange_explicit_16(dst, 1, order) + #define ma_atomic_test_and_set_explicit_32(dst, order) ma_atomic_exchange_explicit_32(dst, 1, order) + #define ma_atomic_test_and_set_explicit_64(dst, order) ma_atomic_exchange_explicit_64(dst, 1, order) + #define ma_atomic_clear_explicit_8( dst, order) ma_atomic_store_explicit_8 (dst, 0, order) + #define ma_atomic_clear_explicit_16(dst, order) ma_atomic_store_explicit_16(dst, 0, order) + #define ma_atomic_clear_explicit_32(dst, order) ma_atomic_store_explicit_32(dst, 0, order) + #define ma_atomic_clear_explicit_64(dst, order) ma_atomic_store_explicit_64(dst, 0, order) + typedef ma_uint8 ma_atomic_flag; + #define ma_atomic_flag_test_and_set_explicit(ptr, order) (ma_bool32)ma_atomic_test_and_set_explicit_8(ptr, order) + #define ma_atomic_flag_clear_explicit(ptr, order) ma_atomic_clear_explicit_8(ptr, order) + #define c89atoimc_flag_load_explicit(ptr, order) ma_atomic_load_explicit_8(ptr, order) +#endif +#if !defined(MA_ATOMIC_HAS_NATIVE_COMPARE_EXCHANGE) + #if defined(MA_ATOMIC_HAS_8) + static MA_INLINE ma_bool32 ma_atomic_compare_exchange_strong_explicit_8(volatile ma_uint8* dst, ma_uint8* expected, ma_uint8 desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder) + { + ma_uint8 expectedValue; + ma_uint8 result; + (void)successOrder; + (void)failureOrder; + expectedValue = ma_atomic_load_explicit_8(expected, ma_atomic_memory_order_seq_cst); + result = ma_atomic_compare_and_swap_8(dst, expectedValue, desired); + if (result == expectedValue) { + return 1; + } else { + ma_atomic_store_explicit_8(expected, result, failureOrder); + return 0; + } + } + #endif + #if defined(MA_ATOMIC_HAS_16) + static MA_INLINE ma_bool32 ma_atomic_compare_exchange_strong_explicit_16(volatile ma_uint16* dst, ma_uint16* expected, ma_uint16 desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder) + { + ma_uint16 expectedValue; + ma_uint16 result; + (void)successOrder; + (void)failureOrder; + expectedValue = ma_atomic_load_explicit_16(expected, ma_atomic_memory_order_seq_cst); + result = ma_atomic_compare_and_swap_16(dst, expectedValue, desired); + if (result == expectedValue) { + return 1; + } else { + ma_atomic_store_explicit_16(expected, result, failureOrder); + return 0; + } + } + #endif + #if defined(MA_ATOMIC_HAS_32) + static MA_INLINE ma_bool32 ma_atomic_compare_exchange_strong_explicit_32(volatile ma_uint32* dst, ma_uint32* expected, ma_uint32 desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder) + { + ma_uint32 expectedValue; + ma_uint32 result; + (void)successOrder; + (void)failureOrder; + expectedValue = ma_atomic_load_explicit_32(expected, ma_atomic_memory_order_seq_cst); + result = ma_atomic_compare_and_swap_32(dst, expectedValue, desired); + if (result == expectedValue) { + return 1; + } else { + ma_atomic_store_explicit_32(expected, result, failureOrder); + return 0; + } + } + #endif + #if defined(MA_ATOMIC_HAS_64) + static MA_INLINE ma_bool32 ma_atomic_compare_exchange_strong_explicit_64(volatile ma_uint64* dst, volatile ma_uint64* expected, ma_uint64 desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder) + { + ma_uint64 expectedValue; + ma_uint64 result; + (void)successOrder; + (void)failureOrder; + expectedValue = ma_atomic_load_explicit_64(expected, ma_atomic_memory_order_seq_cst); + result = ma_atomic_compare_and_swap_64(dst, expectedValue, desired); + if (result == expectedValue) { + return 1; + } else { + ma_atomic_store_explicit_64(expected, result, failureOrder); + return 0; + } + } + #endif + #define ma_atomic_compare_exchange_weak_explicit_8( dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_strong_explicit_8 (dst, expected, desired, successOrder, failureOrder) + #define ma_atomic_compare_exchange_weak_explicit_16(dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_strong_explicit_16(dst, expected, desired, successOrder, failureOrder) + #define ma_atomic_compare_exchange_weak_explicit_32(dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_strong_explicit_32(dst, expected, desired, successOrder, failureOrder) + #define ma_atomic_compare_exchange_weak_explicit_64(dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_strong_explicit_64(dst, expected, desired, successOrder, failureOrder) +#endif +#if !defined(MA_ATOMIC_HAS_NATIVE_IS_LOCK_FREE) + static MA_INLINE ma_bool32 ma_atomic_is_lock_free_8(volatile void* ptr) + { + (void)ptr; + return 1; + } + static MA_INLINE ma_bool32 ma_atomic_is_lock_free_16(volatile void* ptr) + { + (void)ptr; + return 1; + } + static MA_INLINE ma_bool32 ma_atomic_is_lock_free_32(volatile void* ptr) + { + (void)ptr; + return 1; + } + static MA_INLINE ma_bool32 ma_atomic_is_lock_free_64(volatile void* ptr) + { + (void)ptr; + #if defined(MA_64BIT) + return 1; + #else + #if defined(MA_X86) || defined(MA_X64) + return 1; + #else + return 0; + #endif + #endif + } +#endif +#if defined(MA_64BIT) + static MA_INLINE ma_bool32 ma_atomic_is_lock_free_ptr(volatile void** ptr) + { + return ma_atomic_is_lock_free_64((volatile ma_uint64*)ptr); + } + static MA_INLINE void* ma_atomic_load_explicit_ptr(volatile void** ptr, ma_atomic_memory_order order) + { + return (void*)ma_atomic_load_explicit_64((volatile ma_uint64*)ptr, order); + } + static MA_INLINE void ma_atomic_store_explicit_ptr(volatile void** dst, void* src, ma_atomic_memory_order order) + { + ma_atomic_store_explicit_64((volatile ma_uint64*)dst, (ma_uint64)src, order); + } + static MA_INLINE void* ma_atomic_exchange_explicit_ptr(volatile void** dst, void* src, ma_atomic_memory_order order) + { + return (void*)ma_atomic_exchange_explicit_64((volatile ma_uint64*)dst, (ma_uint64)src, order); + } + static MA_INLINE ma_bool32 ma_atomic_compare_exchange_strong_explicit_ptr(volatile void** dst, void** expected, void* desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder) + { + return ma_atomic_compare_exchange_strong_explicit_64((volatile ma_uint64*)dst, (ma_uint64*)expected, (ma_uint64)desired, successOrder, failureOrder); + } + static MA_INLINE ma_bool32 ma_atomic_compare_exchange_weak_explicit_ptr(volatile void** dst, void** expected, void* desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder) + { + return ma_atomic_compare_exchange_weak_explicit_64((volatile ma_uint64*)dst, (ma_uint64*)expected, (ma_uint64)desired, successOrder, failureOrder); + } + static MA_INLINE void* ma_atomic_compare_and_swap_ptr(volatile void** dst, void* expected, void* desired) + { + return (void*)ma_atomic_compare_and_swap_64((volatile ma_uint64*)dst, (ma_uint64)expected, (ma_uint64)desired); + } +#elif defined(MA_32BIT) + static MA_INLINE ma_bool32 ma_atomic_is_lock_free_ptr(volatile void** ptr) + { + return ma_atomic_is_lock_free_32((volatile ma_uint32*)ptr); + } + static MA_INLINE void* ma_atomic_load_explicit_ptr(volatile void** ptr, ma_atomic_memory_order order) + { + return (void*)ma_atomic_load_explicit_32((volatile ma_uint32*)ptr, order); + } + static MA_INLINE void ma_atomic_store_explicit_ptr(volatile void** dst, void* src, ma_atomic_memory_order order) + { + ma_atomic_store_explicit_32((volatile ma_uint32*)dst, (ma_uint32)src, order); + } + static MA_INLINE void* ma_atomic_exchange_explicit_ptr(volatile void** dst, void* src, ma_atomic_memory_order order) + { + return (void*)ma_atomic_exchange_explicit_32((volatile ma_uint32*)dst, (ma_uint32)src, order); + } + static MA_INLINE ma_bool32 ma_atomic_compare_exchange_strong_explicit_ptr(volatile void** dst, void** expected, void* desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder) + { + return ma_atomic_compare_exchange_strong_explicit_32((volatile ma_uint32*)dst, (ma_uint32*)expected, (ma_uint32)desired, successOrder, failureOrder); + } + static MA_INLINE ma_bool32 ma_atomic_compare_exchange_weak_explicit_ptr(volatile void** dst, void** expected, void* desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder) + { + return ma_atomic_compare_exchange_weak_explicit_32((volatile ma_uint32*)dst, (ma_uint32*)expected, (ma_uint32)desired, successOrder, failureOrder); + } + static MA_INLINE void* ma_atomic_compare_and_swap_ptr(volatile void** dst, void* expected, void* desired) + { + return (void*)ma_atomic_compare_and_swap_32((volatile ma_uint32*)dst, (ma_uint32)expected, (ma_uint32)desired); + } +#else + #error Unsupported architecture. +#endif +#define ma_atomic_flag_test_and_set(ptr) ma_atomic_flag_test_and_set_explicit(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_flag_clear(ptr) ma_atomic_flag_clear_explicit(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_store_ptr(dst, src) ma_atomic_store_explicit_ptr((volatile void**)dst, (void*)src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_load_ptr(ptr) ma_atomic_load_explicit_ptr((volatile void**)ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_exchange_ptr(dst, src) ma_atomic_exchange_explicit_ptr((volatile void**)dst, (void*)src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_strong_ptr(dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_ptr((volatile void**)dst, (void**)expected, (void*)desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_weak_ptr(dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_ptr((volatile void**)dst, (void**)expected, (void*)desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_test_and_set_8( ptr) ma_atomic_test_and_set_explicit_8( ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_test_and_set_16(ptr) ma_atomic_test_and_set_explicit_16(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_test_and_set_32(ptr) ma_atomic_test_and_set_explicit_32(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_test_and_set_64(ptr) ma_atomic_test_and_set_explicit_64(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_clear_8( ptr) ma_atomic_clear_explicit_8( ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_clear_16(ptr) ma_atomic_clear_explicit_16(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_clear_32(ptr) ma_atomic_clear_explicit_32(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_clear_64(ptr) ma_atomic_clear_explicit_64(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_store_8( dst, src) ma_atomic_store_explicit_8( dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_store_16(dst, src) ma_atomic_store_explicit_16(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_store_32(dst, src) ma_atomic_store_explicit_32(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_store_64(dst, src) ma_atomic_store_explicit_64(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_load_8( ptr) ma_atomic_load_explicit_8( ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_load_16(ptr) ma_atomic_load_explicit_16(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_load_32(ptr) ma_atomic_load_explicit_32(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_load_64(ptr) ma_atomic_load_explicit_64(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_exchange_8( dst, src) ma_atomic_exchange_explicit_8( dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_exchange_16(dst, src) ma_atomic_exchange_explicit_16(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_exchange_32(dst, src) ma_atomic_exchange_explicit_32(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_exchange_64(dst, src) ma_atomic_exchange_explicit_64(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_strong_8( dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_8( dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_strong_16(dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_16(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_strong_32(dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_32(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_strong_64(dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_64(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_weak_8( dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_8( dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_weak_16( dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_16(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_weak_32( dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_32(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_weak_64( dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_64(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_add_8( dst, src) ma_atomic_fetch_add_explicit_8( dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_add_16(dst, src) ma_atomic_fetch_add_explicit_16(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_add_32(dst, src) ma_atomic_fetch_add_explicit_32(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_add_64(dst, src) ma_atomic_fetch_add_explicit_64(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_sub_8( dst, src) ma_atomic_fetch_sub_explicit_8( dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_sub_16(dst, src) ma_atomic_fetch_sub_explicit_16(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_sub_32(dst, src) ma_atomic_fetch_sub_explicit_32(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_sub_64(dst, src) ma_atomic_fetch_sub_explicit_64(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_or_8( dst, src) ma_atomic_fetch_or_explicit_8( dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_or_16(dst, src) ma_atomic_fetch_or_explicit_16(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_or_32(dst, src) ma_atomic_fetch_or_explicit_32(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_or_64(dst, src) ma_atomic_fetch_or_explicit_64(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_xor_8( dst, src) ma_atomic_fetch_xor_explicit_8( dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_xor_16(dst, src) ma_atomic_fetch_xor_explicit_16(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_xor_32(dst, src) ma_atomic_fetch_xor_explicit_32(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_xor_64(dst, src) ma_atomic_fetch_xor_explicit_64(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_and_8( dst, src) ma_atomic_fetch_and_explicit_8 (dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_and_16(dst, src) ma_atomic_fetch_and_explicit_16(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_and_32(dst, src) ma_atomic_fetch_and_explicit_32(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_and_64(dst, src) ma_atomic_fetch_and_explicit_64(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_test_and_set_explicit_i8( ptr, order) (ma_int8 )ma_atomic_test_and_set_explicit_8( (ma_uint8* )ptr, order) +#define ma_atomic_test_and_set_explicit_i16(ptr, order) (ma_int16)ma_atomic_test_and_set_explicit_16((ma_uint16*)ptr, order) +#define ma_atomic_test_and_set_explicit_i32(ptr, order) (ma_int32)ma_atomic_test_and_set_explicit_32((ma_uint32*)ptr, order) +#define ma_atomic_test_and_set_explicit_i64(ptr, order) (ma_int64)ma_atomic_test_and_set_explicit_64((ma_uint64*)ptr, order) +#define ma_atomic_clear_explicit_i8( ptr, order) ma_atomic_clear_explicit_8( (ma_uint8* )ptr, order) +#define ma_atomic_clear_explicit_i16(ptr, order) ma_atomic_clear_explicit_16((ma_uint16*)ptr, order) +#define ma_atomic_clear_explicit_i32(ptr, order) ma_atomic_clear_explicit_32((ma_uint32*)ptr, order) +#define ma_atomic_clear_explicit_i64(ptr, order) ma_atomic_clear_explicit_64((ma_uint64*)ptr, order) +#define ma_atomic_store_explicit_i8( dst, src, order) ma_atomic_store_explicit_8( (ma_uint8* )dst, (ma_uint8 )src, order) +#define ma_atomic_store_explicit_i16(dst, src, order) ma_atomic_store_explicit_16((ma_uint16*)dst, (ma_uint16)src, order) +#define ma_atomic_store_explicit_i32(dst, src, order) ma_atomic_store_explicit_32((ma_uint32*)dst, (ma_uint32)src, order) +#define ma_atomic_store_explicit_i64(dst, src, order) ma_atomic_store_explicit_64((ma_uint64*)dst, (ma_uint64)src, order) +#define ma_atomic_load_explicit_i8( ptr, order) (ma_int8 )ma_atomic_load_explicit_8( (ma_uint8* )ptr, order) +#define ma_atomic_load_explicit_i16(ptr, order) (ma_int16)ma_atomic_load_explicit_16((ma_uint16*)ptr, order) +#define ma_atomic_load_explicit_i32(ptr, order) (ma_int32)ma_atomic_load_explicit_32((ma_uint32*)ptr, order) +#define ma_atomic_load_explicit_i64(ptr, order) (ma_int64)ma_atomic_load_explicit_64((ma_uint64*)ptr, order) +#define ma_atomic_exchange_explicit_i8( dst, src, order) (ma_int8 )ma_atomic_exchange_explicit_8 ((ma_uint8* )dst, (ma_uint8 )src, order) +#define ma_atomic_exchange_explicit_i16(dst, src, order) (ma_int16)ma_atomic_exchange_explicit_16((ma_uint16*)dst, (ma_uint16)src, order) +#define ma_atomic_exchange_explicit_i32(dst, src, order) (ma_int32)ma_atomic_exchange_explicit_32((ma_uint32*)dst, (ma_uint32)src, order) +#define ma_atomic_exchange_explicit_i64(dst, src, order) (ma_int64)ma_atomic_exchange_explicit_64((ma_uint64*)dst, (ma_uint64)src, order) +#define ma_atomic_compare_exchange_strong_explicit_i8( dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_strong_explicit_8( (ma_uint8* )dst, (ma_uint8* )expected, (ma_uint8 )desired, successOrder, failureOrder) +#define ma_atomic_compare_exchange_strong_explicit_i16(dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_strong_explicit_16((ma_uint16*)dst, (ma_uint16*)expected, (ma_uint16)desired, successOrder, failureOrder) +#define ma_atomic_compare_exchange_strong_explicit_i32(dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_strong_explicit_32((ma_uint32*)dst, (ma_uint32*)expected, (ma_uint32)desired, successOrder, failureOrder) +#define ma_atomic_compare_exchange_strong_explicit_i64(dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_strong_explicit_64((ma_uint64*)dst, (ma_uint64*)expected, (ma_uint64)desired, successOrder, failureOrder) +#define ma_atomic_compare_exchange_weak_explicit_i8( dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_weak_explicit_8( (ma_uint8* )dst, (ma_uint8* )expected, (ma_uint8 )desired, successOrder, failureOrder) +#define ma_atomic_compare_exchange_weak_explicit_i16(dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_weak_explicit_16((ma_uint16*)dst, (ma_uint16*)expected, (ma_uint16)desired, successOrder, failureOrder) +#define ma_atomic_compare_exchange_weak_explicit_i32(dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_weak_explicit_32((ma_uint32*)dst, (ma_uint32*)expected, (ma_uint32)desired, successOrder, failureOrder) +#define ma_atomic_compare_exchange_weak_explicit_i64(dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_weak_explicit_64((ma_uint64*)dst, (ma_uint64*)expected, (ma_uint64)desired, successOrder, failureOrder) +#define ma_atomic_fetch_add_explicit_i8( dst, src, order) (ma_int8 )ma_atomic_fetch_add_explicit_8( (ma_uint8* )dst, (ma_uint8 )src, order) +#define ma_atomic_fetch_add_explicit_i16(dst, src, order) (ma_int16)ma_atomic_fetch_add_explicit_16((ma_uint16*)dst, (ma_uint16)src, order) +#define ma_atomic_fetch_add_explicit_i32(dst, src, order) (ma_int32)ma_atomic_fetch_add_explicit_32((ma_uint32*)dst, (ma_uint32)src, order) +#define ma_atomic_fetch_add_explicit_i64(dst, src, order) (ma_int64)ma_atomic_fetch_add_explicit_64((ma_uint64*)dst, (ma_uint64)src, order) +#define ma_atomic_fetch_sub_explicit_i8( dst, src, order) (ma_int8 )ma_atomic_fetch_sub_explicit_8( (ma_uint8* )dst, (ma_uint8 )src, order) +#define ma_atomic_fetch_sub_explicit_i16(dst, src, order) (ma_int16)ma_atomic_fetch_sub_explicit_16((ma_uint16*)dst, (ma_uint16)src, order) +#define ma_atomic_fetch_sub_explicit_i32(dst, src, order) (ma_int32)ma_atomic_fetch_sub_explicit_32((ma_uint32*)dst, (ma_uint32)src, order) +#define ma_atomic_fetch_sub_explicit_i64(dst, src, order) (ma_int64)ma_atomic_fetch_sub_explicit_64((ma_uint64*)dst, (ma_uint64)src, order) +#define ma_atomic_fetch_or_explicit_i8( dst, src, order) (ma_int8 )ma_atomic_fetch_or_explicit_8( (ma_uint8* )dst, (ma_uint8 )src, order) +#define ma_atomic_fetch_or_explicit_i16(dst, src, order) (ma_int16)ma_atomic_fetch_or_explicit_16((ma_uint16*)dst, (ma_uint16)src, order) +#define ma_atomic_fetch_or_explicit_i32(dst, src, order) (ma_int32)ma_atomic_fetch_or_explicit_32((ma_uint32*)dst, (ma_uint32)src, order) +#define ma_atomic_fetch_or_explicit_i64(dst, src, order) (ma_int64)ma_atomic_fetch_or_explicit_64((ma_uint64*)dst, (ma_uint64)src, order) +#define ma_atomic_fetch_xor_explicit_i8( dst, src, order) (ma_int8 )ma_atomic_fetch_xor_explicit_8( (ma_uint8* )dst, (ma_uint8 )src, order) +#define ma_atomic_fetch_xor_explicit_i16(dst, src, order) (ma_int16)ma_atomic_fetch_xor_explicit_16((ma_uint16*)dst, (ma_uint16)src, order) +#define ma_atomic_fetch_xor_explicit_i32(dst, src, order) (ma_int32)ma_atomic_fetch_xor_explicit_32((ma_uint32*)dst, (ma_uint32)src, order) +#define ma_atomic_fetch_xor_explicit_i64(dst, src, order) (ma_int64)ma_atomic_fetch_xor_explicit_64((ma_uint64*)dst, (ma_uint64)src, order) +#define ma_atomic_fetch_and_explicit_i8( dst, src, order) (ma_int8 )ma_atomic_fetch_and_explicit_8( (ma_uint8* )dst, (ma_uint8 )src, order) +#define ma_atomic_fetch_and_explicit_i16(dst, src, order) (ma_int16)ma_atomic_fetch_and_explicit_16((ma_uint16*)dst, (ma_uint16)src, order) +#define ma_atomic_fetch_and_explicit_i32(dst, src, order) (ma_int32)ma_atomic_fetch_and_explicit_32((ma_uint32*)dst, (ma_uint32)src, order) +#define ma_atomic_fetch_and_explicit_i64(dst, src, order) (ma_int64)ma_atomic_fetch_and_explicit_64((ma_uint64*)dst, (ma_uint64)src, order) +#define ma_atomic_test_and_set_i8( ptr) ma_atomic_test_and_set_explicit_i8( ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_test_and_set_i16(ptr) ma_atomic_test_and_set_explicit_i16(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_test_and_set_i32(ptr) ma_atomic_test_and_set_explicit_i32(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_test_and_set_i64(ptr) ma_atomic_test_and_set_explicit_i64(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_clear_i8( ptr) ma_atomic_clear_explicit_i8( ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_clear_i16(ptr) ma_atomic_clear_explicit_i16(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_clear_i32(ptr) ma_atomic_clear_explicit_i32(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_clear_i64(ptr) ma_atomic_clear_explicit_i64(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_store_i8( dst, src) ma_atomic_store_explicit_i8( dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_store_i16(dst, src) ma_atomic_store_explicit_i16(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_store_i32(dst, src) ma_atomic_store_explicit_i32(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_store_i64(dst, src) ma_atomic_store_explicit_i64(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_load_i8( ptr) ma_atomic_load_explicit_i8( ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_load_i16(ptr) ma_atomic_load_explicit_i16(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_load_i32(ptr) ma_atomic_load_explicit_i32(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_load_i64(ptr) ma_atomic_load_explicit_i64(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_exchange_i8( dst, src) ma_atomic_exchange_explicit_i8( dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_exchange_i16(dst, src) ma_atomic_exchange_explicit_i16(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_exchange_i32(dst, src) ma_atomic_exchange_explicit_i32(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_exchange_i64(dst, src) ma_atomic_exchange_explicit_i64(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_strong_i8( dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_i8( dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_strong_i16(dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_i16(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_strong_i32(dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_i32(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_strong_i64(dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_i64(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_weak_i8( dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_i8( dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_weak_i16(dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_i16(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_weak_i32(dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_i32(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_weak_i64(dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_i64(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_add_i8( dst, src) ma_atomic_fetch_add_explicit_i8( dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_add_i16(dst, src) ma_atomic_fetch_add_explicit_i16(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_add_i32(dst, src) ma_atomic_fetch_add_explicit_i32(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_add_i64(dst, src) ma_atomic_fetch_add_explicit_i64(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_sub_i8( dst, src) ma_atomic_fetch_sub_explicit_i8( dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_sub_i16(dst, src) ma_atomic_fetch_sub_explicit_i16(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_sub_i32(dst, src) ma_atomic_fetch_sub_explicit_i32(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_sub_i64(dst, src) ma_atomic_fetch_sub_explicit_i64(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_or_i8( dst, src) ma_atomic_fetch_or_explicit_i8( dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_or_i16(dst, src) ma_atomic_fetch_or_explicit_i16(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_or_i32(dst, src) ma_atomic_fetch_or_explicit_i32(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_or_i64(dst, src) ma_atomic_fetch_or_explicit_i64(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_xor_i8( dst, src) ma_atomic_fetch_xor_explicit_i8( dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_xor_i16(dst, src) ma_atomic_fetch_xor_explicit_i16(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_xor_i32(dst, src) ma_atomic_fetch_xor_explicit_i32(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_xor_i64(dst, src) ma_atomic_fetch_xor_explicit_i64(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_and_i8( dst, src) ma_atomic_fetch_and_explicit_i8( dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_and_i16(dst, src) ma_atomic_fetch_and_explicit_i16(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_and_i32(dst, src) ma_atomic_fetch_and_explicit_i32(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_and_i64(dst, src) ma_atomic_fetch_and_explicit_i64(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_and_swap_i8( dst, expected, dedsired) (ma_int8 )ma_atomic_compare_and_swap_8( (ma_uint8* )dst, (ma_uint8 )expected, (ma_uint8 )dedsired) +#define ma_atomic_compare_and_swap_i16(dst, expected, dedsired) (ma_int16)ma_atomic_compare_and_swap_16((ma_uint16*)dst, (ma_uint16)expected, (ma_uint16)dedsired) +#define ma_atomic_compare_and_swap_i32(dst, expected, dedsired) (ma_int32)ma_atomic_compare_and_swap_32((ma_uint32*)dst, (ma_uint32)expected, (ma_uint32)dedsired) +#define ma_atomic_compare_and_swap_i64(dst, expected, dedsired) (ma_int64)ma_atomic_compare_and_swap_64((ma_uint64*)dst, (ma_uint64)expected, (ma_uint64)dedsired) +typedef union +{ + ma_uint32 i; + float f; +} ma_atomic_if32; +typedef union +{ + ma_uint64 i; + double f; +} ma_atomic_if64; +#define ma_atomic_clear_explicit_f32(ptr, order) ma_atomic_clear_explicit_32((ma_uint32*)ptr, order) +#define ma_atomic_clear_explicit_f64(ptr, order) ma_atomic_clear_explicit_64((ma_uint64*)ptr, order) +static MA_INLINE void ma_atomic_store_explicit_f32(volatile float* dst, float src, ma_atomic_memory_order order) +{ + ma_atomic_if32 x; + x.f = src; + ma_atomic_store_explicit_32((volatile ma_uint32*)dst, x.i, order); +} +static MA_INLINE void ma_atomic_store_explicit_f64(volatile double* dst, double src, ma_atomic_memory_order order) +{ + ma_atomic_if64 x; + x.f = src; + ma_atomic_store_explicit_64((volatile ma_uint64*)dst, x.i, order); +} +static MA_INLINE float ma_atomic_load_explicit_f32(volatile const float* ptr, ma_atomic_memory_order order) +{ + ma_atomic_if32 r; + r.i = ma_atomic_load_explicit_32((volatile const ma_uint32*)ptr, order); + return r.f; +} +static MA_INLINE double ma_atomic_load_explicit_f64(volatile const double* ptr, ma_atomic_memory_order order) +{ + ma_atomic_if64 r; + r.i = ma_atomic_load_explicit_64((volatile const ma_uint64*)ptr, order); + return r.f; +} +static MA_INLINE float ma_atomic_exchange_explicit_f32(volatile float* dst, float src, ma_atomic_memory_order order) +{ + ma_atomic_if32 r; + ma_atomic_if32 x; + x.f = src; + r.i = ma_atomic_exchange_explicit_32((volatile ma_uint32*)dst, x.i, order); + return r.f; +} +static MA_INLINE double ma_atomic_exchange_explicit_f64(volatile double* dst, double src, ma_atomic_memory_order order) +{ + ma_atomic_if64 r; + ma_atomic_if64 x; + x.f = src; + r.i = ma_atomic_exchange_explicit_64((volatile ma_uint64*)dst, x.i, order); + return r.f; +} +static MA_INLINE ma_bool32 ma_atomic_compare_exchange_strong_explicit_f32(volatile float* dst, float* expected, float desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder) +{ + ma_atomic_if32 d; + d.f = desired; + return ma_atomic_compare_exchange_strong_explicit_32((volatile ma_uint32*)dst, (ma_uint32*)expected, d.i, successOrder, failureOrder); +} +static MA_INLINE ma_bool32 ma_atomic_compare_exchange_strong_explicit_f64(volatile double* dst, double* expected, double desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder) +{ + ma_atomic_if64 d; + d.f = desired; + return ma_atomic_compare_exchange_strong_explicit_64((volatile ma_uint64*)dst, (ma_uint64*)expected, d.i, successOrder, failureOrder); +} +static MA_INLINE ma_bool32 ma_atomic_compare_exchange_weak_explicit_f32(volatile float* dst, float* expected, float desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder) +{ + ma_atomic_if32 d; + d.f = desired; + return ma_atomic_compare_exchange_weak_explicit_32((volatile ma_uint32*)dst, (ma_uint32*)expected, d.i, successOrder, failureOrder); +} +static MA_INLINE ma_bool32 ma_atomic_compare_exchange_weak_explicit_f64(volatile double* dst, double* expected, double desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder) +{ + ma_atomic_if64 d; + d.f = desired; + return ma_atomic_compare_exchange_weak_explicit_64((volatile ma_uint64*)dst, (ma_uint64*)expected, d.i, successOrder, failureOrder); +} +static MA_INLINE float ma_atomic_fetch_add_explicit_f32(volatile float* dst, float src, ma_atomic_memory_order order) +{ + ma_atomic_if32 r; + ma_atomic_if32 x; + x.f = src; + r.i = ma_atomic_fetch_add_explicit_32((volatile ma_uint32*)dst, x.i, order); + return r.f; +} +static MA_INLINE double ma_atomic_fetch_add_explicit_f64(volatile double* dst, double src, ma_atomic_memory_order order) +{ + ma_atomic_if64 r; + ma_atomic_if64 x; + x.f = src; + r.i = ma_atomic_fetch_add_explicit_64((volatile ma_uint64*)dst, x.i, order); + return r.f; +} +static MA_INLINE float ma_atomic_fetch_sub_explicit_f32(volatile float* dst, float src, ma_atomic_memory_order order) +{ + ma_atomic_if32 r; + ma_atomic_if32 x; + x.f = src; + r.i = ma_atomic_fetch_sub_explicit_32((volatile ma_uint32*)dst, x.i, order); + return r.f; +} +static MA_INLINE double ma_atomic_fetch_sub_explicit_f64(volatile double* dst, double src, ma_atomic_memory_order order) +{ + ma_atomic_if64 r; + ma_atomic_if64 x; + x.f = src; + r.i = ma_atomic_fetch_sub_explicit_64((volatile ma_uint64*)dst, x.i, order); + return r.f; +} +static MA_INLINE float ma_atomic_fetch_or_explicit_f32(volatile float* dst, float src, ma_atomic_memory_order order) +{ + ma_atomic_if32 r; + ma_atomic_if32 x; + x.f = src; + r.i = ma_atomic_fetch_or_explicit_32((volatile ma_uint32*)dst, x.i, order); + return r.f; +} +static MA_INLINE double ma_atomic_fetch_or_explicit_f64(volatile double* dst, double src, ma_atomic_memory_order order) +{ + ma_atomic_if64 r; + ma_atomic_if64 x; + x.f = src; + r.i = ma_atomic_fetch_or_explicit_64((volatile ma_uint64*)dst, x.i, order); + return r.f; +} +static MA_INLINE float ma_atomic_fetch_xor_explicit_f32(volatile float* dst, float src, ma_atomic_memory_order order) +{ + ma_atomic_if32 r; + ma_atomic_if32 x; + x.f = src; + r.i = ma_atomic_fetch_xor_explicit_32((volatile ma_uint32*)dst, x.i, order); + return r.f; +} +static MA_INLINE double ma_atomic_fetch_xor_explicit_f64(volatile double* dst, double src, ma_atomic_memory_order order) +{ + ma_atomic_if64 r; + ma_atomic_if64 x; + x.f = src; + r.i = ma_atomic_fetch_xor_explicit_64((volatile ma_uint64*)dst, x.i, order); + return r.f; +} +static MA_INLINE float ma_atomic_fetch_and_explicit_f32(volatile float* dst, float src, ma_atomic_memory_order order) +{ + ma_atomic_if32 r; + ma_atomic_if32 x; + x.f = src; + r.i = ma_atomic_fetch_and_explicit_32((volatile ma_uint32*)dst, x.i, order); + return r.f; +} +static MA_INLINE double ma_atomic_fetch_and_explicit_f64(volatile double* dst, double src, ma_atomic_memory_order order) +{ + ma_atomic_if64 r; + ma_atomic_if64 x; + x.f = src; + r.i = ma_atomic_fetch_and_explicit_64((volatile ma_uint64*)dst, x.i, order); + return r.f; +} +#define ma_atomic_clear_f32(ptr) (float )ma_atomic_clear_explicit_f32(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_clear_f64(ptr) (double)ma_atomic_clear_explicit_f64(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_store_f32(dst, src) ma_atomic_store_explicit_f32(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_store_f64(dst, src) ma_atomic_store_explicit_f64(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_load_f32(ptr) (float )ma_atomic_load_explicit_f32(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_load_f64(ptr) (double)ma_atomic_load_explicit_f64(ptr, ma_atomic_memory_order_seq_cst) +#define ma_atomic_exchange_f32(dst, src) (float )ma_atomic_exchange_explicit_f32(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_exchange_f64(dst, src) (double)ma_atomic_exchange_explicit_f64(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_strong_f32(dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_f32(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_strong_f64(dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_f64(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_weak_f32(dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_f32(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_compare_exchange_weak_f64(dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_f64(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_add_f32(dst, src) ma_atomic_fetch_add_explicit_f32(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_add_f64(dst, src) ma_atomic_fetch_add_explicit_f64(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_sub_f32(dst, src) ma_atomic_fetch_sub_explicit_f32(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_sub_f64(dst, src) ma_atomic_fetch_sub_explicit_f64(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_or_f32(dst, src) ma_atomic_fetch_or_explicit_f32(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_or_f64(dst, src) ma_atomic_fetch_or_explicit_f64(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_xor_f32(dst, src) ma_atomic_fetch_xor_explicit_f32(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_xor_f64(dst, src) ma_atomic_fetch_xor_explicit_f64(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_and_f32(dst, src) ma_atomic_fetch_and_explicit_f32(dst, src, ma_atomic_memory_order_seq_cst) +#define ma_atomic_fetch_and_f64(dst, src) ma_atomic_fetch_and_explicit_f64(dst, src, ma_atomic_memory_order_seq_cst) +static MA_INLINE float ma_atomic_compare_and_swap_f32(volatile float* dst, float expected, float desired) +{ + ma_atomic_if32 r; + ma_atomic_if32 e, d; + e.f = expected; + d.f = desired; + r.i = ma_atomic_compare_and_swap_32((volatile ma_uint32*)dst, e.i, d.i); + return r.f; +} +static MA_INLINE double ma_atomic_compare_and_swap_f64(volatile double* dst, double expected, double desired) +{ + ma_atomic_if64 r; + ma_atomic_if64 e, d; + e.f = expected; + d.f = desired; + r.i = ma_atomic_compare_and_swap_64((volatile ma_uint64*)dst, e.i, d.i); + return r.f; +} +typedef ma_atomic_flag ma_atomic_spinlock; +static MA_INLINE void ma_atomic_spinlock_lock(volatile ma_atomic_spinlock* pSpinlock) +{ + for (;;) { + if (ma_atomic_flag_test_and_set_explicit(pSpinlock, ma_atomic_memory_order_acquire) == 0) { + break; + } + while (c89atoimc_flag_load_explicit(pSpinlock, ma_atomic_memory_order_relaxed) == 1) { + } + } +} +static MA_INLINE void ma_atomic_spinlock_unlock(volatile ma_atomic_spinlock* pSpinlock) +{ + ma_atomic_flag_clear_explicit(pSpinlock, ma_atomic_memory_order_release); +} +#if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))) + #pragma GCC diagnostic pop +#endif +#if defined(__cplusplus) +} +#endif +#endif +/* ma_atomic.h end */ + +#define MA_ATOMIC_SAFE_TYPE_IMPL(c89TypeExtension, type) \ + static MA_INLINE ma_##type ma_atomic_##type##_get(ma_atomic_##type* x) \ + { \ + return (ma_##type)ma_atomic_load_##c89TypeExtension(&x->value); \ + } \ + static MA_INLINE void ma_atomic_##type##_set(ma_atomic_##type* x, ma_##type value) \ + { \ + ma_atomic_store_##c89TypeExtension(&x->value, value); \ + } \ + static MA_INLINE ma_##type ma_atomic_##type##_exchange(ma_atomic_##type* x, ma_##type value) \ + { \ + return (ma_##type)ma_atomic_exchange_##c89TypeExtension(&x->value, value); \ + } \ + static MA_INLINE ma_bool32 ma_atomic_##type##_compare_exchange(ma_atomic_##type* x, ma_##type* expected, ma_##type desired) \ + { \ + return ma_atomic_compare_exchange_weak_##c89TypeExtension(&x->value, expected, desired); \ + } \ + static MA_INLINE ma_##type ma_atomic_##type##_fetch_add(ma_atomic_##type* x, ma_##type y) \ + { \ + return (ma_##type)ma_atomic_fetch_add_##c89TypeExtension(&x->value, y); \ + } \ + static MA_INLINE ma_##type ma_atomic_##type##_fetch_sub(ma_atomic_##type* x, ma_##type y) \ + { \ + return (ma_##type)ma_atomic_fetch_sub_##c89TypeExtension(&x->value, y); \ + } \ + static MA_INLINE ma_##type ma_atomic_##type##_fetch_or(ma_atomic_##type* x, ma_##type y) \ + { \ + return (ma_##type)ma_atomic_fetch_or_##c89TypeExtension(&x->value, y); \ + } \ + static MA_INLINE ma_##type ma_atomic_##type##_fetch_xor(ma_atomic_##type* x, ma_##type y) \ + { \ + return (ma_##type)ma_atomic_fetch_xor_##c89TypeExtension(&x->value, y); \ + } \ + static MA_INLINE ma_##type ma_atomic_##type##_fetch_and(ma_atomic_##type* x, ma_##type y) \ + { \ + return (ma_##type)ma_atomic_fetch_and_##c89TypeExtension(&x->value, y); \ + } \ + static MA_INLINE ma_##type ma_atomic_##type##_compare_and_swap(ma_atomic_##type* x, ma_##type expected, ma_##type desired) \ + { \ + return (ma_##type)ma_atomic_compare_and_swap_##c89TypeExtension(&x->value, expected, desired); \ + } \ + +#define MA_ATOMIC_SAFE_TYPE_IMPL_PTR(type) \ + static MA_INLINE ma_##type* ma_atomic_ptr_##type##_get(ma_atomic_ptr_##type* x) \ + { \ + return ma_atomic_load_ptr((void**)&x->value); \ + } \ + static MA_INLINE void ma_atomic_ptr_##type##_set(ma_atomic_ptr_##type* x, ma_##type* value) \ + { \ + ma_atomic_store_ptr((void**)&x->value, (void*)value); \ + } \ + static MA_INLINE ma_##type* ma_atomic_ptr_##type##_exchange(ma_atomic_ptr_##type* x, ma_##type* value) \ + { \ + return ma_atomic_exchange_ptr((void**)&x->value, (void*)value); \ + } \ + static MA_INLINE ma_bool32 ma_atomic_ptr_##type##_compare_exchange(ma_atomic_ptr_##type* x, ma_##type** expected, ma_##type* desired) \ + { \ + return ma_atomic_compare_exchange_weak_ptr((void**)&x->value, (void*)expected, (void*)desired); \ + } \ + static MA_INLINE ma_##type* ma_atomic_ptr_##type##_compare_and_swap(ma_atomic_ptr_##type* x, ma_##type* expected, ma_##type* desired) \ + { \ + return (ma_##type*)ma_atomic_compare_and_swap_ptr((void**)&x->value, (void*)expected, (void*)desired); \ + } \ + +MA_ATOMIC_SAFE_TYPE_IMPL(32, uint32) +MA_ATOMIC_SAFE_TYPE_IMPL(i32, int32) +MA_ATOMIC_SAFE_TYPE_IMPL(64, uint64) +MA_ATOMIC_SAFE_TYPE_IMPL(f32, float) +MA_ATOMIC_SAFE_TYPE_IMPL(32, bool32) + +#if !defined(MA_NO_DEVICE_IO) +MA_ATOMIC_SAFE_TYPE_IMPL(i32, device_state) +#endif + + +MA_API ma_uint64 ma_calculate_frame_count_after_resampling(ma_uint32 sampleRateOut, ma_uint32 sampleRateIn, ma_uint64 frameCountIn) +{ + /* This is based on the calculation in ma_linear_resampler_get_expected_output_frame_count(). */ + ma_uint64 outputFrameCount; + ma_uint64 preliminaryInputFrameCountFromFrac; + ma_uint64 preliminaryInputFrameCount; + + if (sampleRateIn == 0 || sampleRateOut == 0 || frameCountIn == 0) { + return 0; + } + + if (sampleRateOut == sampleRateIn) { + return frameCountIn; + } + + outputFrameCount = (frameCountIn * sampleRateOut) / sampleRateIn; + + preliminaryInputFrameCountFromFrac = (outputFrameCount * (sampleRateIn / sampleRateOut)) / sampleRateOut; + preliminaryInputFrameCount = (outputFrameCount * (sampleRateIn % sampleRateOut)) + preliminaryInputFrameCountFromFrac; + + if (preliminaryInputFrameCount <= frameCountIn) { + outputFrameCount += 1; + } + + return outputFrameCount; +} + +#ifndef MA_DATA_CONVERTER_STACK_BUFFER_SIZE +#define MA_DATA_CONVERTER_STACK_BUFFER_SIZE 4096 +#endif + + + +#if defined(MA_WIN32) +static ma_result ma_result_from_GetLastError(DWORD error) +{ + switch (error) + { + case ERROR_SUCCESS: return MA_SUCCESS; + case ERROR_PATH_NOT_FOUND: return MA_DOES_NOT_EXIST; + case ERROR_TOO_MANY_OPEN_FILES: return MA_TOO_MANY_OPEN_FILES; + case ERROR_NOT_ENOUGH_MEMORY: return MA_OUT_OF_MEMORY; + case ERROR_DISK_FULL: return MA_NO_SPACE; + case ERROR_HANDLE_EOF: return MA_AT_END; + case ERROR_NEGATIVE_SEEK: return MA_BAD_SEEK; + case ERROR_INVALID_PARAMETER: return MA_INVALID_ARGS; + case ERROR_ACCESS_DENIED: return MA_ACCESS_DENIED; + case ERROR_SEM_TIMEOUT: return MA_TIMEOUT; + case ERROR_FILE_NOT_FOUND: return MA_DOES_NOT_EXIST; + default: break; + } + + return MA_ERROR; +} +#endif /* MA_WIN32 */ + + +/******************************************************************************* + +Threading + +*******************************************************************************/ +static MA_INLINE ma_result ma_spinlock_lock_ex(volatile ma_spinlock* pSpinlock, ma_bool32 yield) +{ + if (pSpinlock == NULL) { + return MA_INVALID_ARGS; + } + + for (;;) { + if (ma_atomic_exchange_explicit_32(pSpinlock, 1, ma_atomic_memory_order_acquire) == 0) { + break; + } + + while (ma_atomic_load_explicit_32(pSpinlock, ma_atomic_memory_order_relaxed) == 1) { + if (yield) { + ma_yield(); + } + } + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_spinlock_lock(volatile ma_spinlock* pSpinlock) +{ + return ma_spinlock_lock_ex(pSpinlock, MA_TRUE); +} + +MA_API ma_result ma_spinlock_lock_noyield(volatile ma_spinlock* pSpinlock) +{ + return ma_spinlock_lock_ex(pSpinlock, MA_FALSE); +} + +MA_API ma_result ma_spinlock_unlock(volatile ma_spinlock* pSpinlock) +{ + if (pSpinlock == NULL) { + return MA_INVALID_ARGS; + } + + ma_atomic_store_explicit_32(pSpinlock, 0, ma_atomic_memory_order_release); + return MA_SUCCESS; +} + + +#ifndef MA_NO_THREADING +#if defined(MA_POSIX) + #define MA_THREADCALL + typedef void* ma_thread_result; +#elif defined(MA_WIN32) + #define MA_THREADCALL WINAPI + typedef unsigned long ma_thread_result; +#endif + +typedef ma_thread_result (MA_THREADCALL * ma_thread_entry_proc)(void* pData); + +#ifdef MA_POSIX +static ma_result ma_thread_create__posix(ma_thread* pThread, ma_thread_priority priority, size_t stackSize, 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. */ + pthread_attr_t attr; + if (pthread_attr_init(&attr) == 0) { + int scheduler = -1; + + /* We successfully initialized our attributes object so we can assign the pointer so it's passed into pthread_create(). */ + pAttr = &attr; + + /* We need to set the scheduler policy. Only do this if the OS supports pthread_attr_setschedpolicy() */ + #if !defined(MA_BEOS) + { + if (priority == ma_thread_priority_idle) { + #ifdef SCHED_IDLE + if (pthread_attr_setschedpolicy(&attr, SCHED_IDLE) == 0) { + scheduler = SCHED_IDLE; + } + #endif + } else if (priority == ma_thread_priority_realtime) { + #ifdef SCHED_FIFO + if (pthread_attr_setschedpolicy(&attr, SCHED_FIFO) == 0) { + scheduler = SCHED_FIFO; + } + #endif + #ifdef MA_LINUX + } else { + scheduler = sched_getscheduler(0); + #endif + } + } + #endif + + if (stackSize > 0) { + pthread_attr_setstacksize(&attr, stackSize); + } + + 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 (pthread_attr_getschedparam(&attr, &sched) == 0) { + if (priority == ma_thread_priority_idle) { + sched.sched_priority = priorityMin; + } else if (priority == ma_thread_priority_realtime) { + sched.sched_priority = priorityMax; + } else { + sched.sched_priority += ((int)priority + 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; + } + } + + /* I'm not treating a failure of setting the priority as a critical error so not checking the return value here. */ + pthread_attr_setschedparam(&attr, &sched); + } + } + } +#else + /* It's the emscripten build. We'll have a few unused parameters. */ + (void)priority; + (void)stackSize; +#endif + + result = pthread_create((pthread_t*)pThread, pAttr, entryProc, pData); + + /* The thread attributes object is no longer required. */ + if (pAttr != NULL) { + pthread_attr_destroy(pAttr); + } + + if (result != 0) { + return ma_result_from_errno(result); + } + + return MA_SUCCESS; +} + +static void ma_thread_wait__posix(ma_thread* pThread) +{ + pthread_join((pthread_t)*pThread, NULL); +} + + +static ma_result ma_mutex_init__posix(ma_mutex* pMutex) +{ + int result; + + if (pMutex == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pMutex); + + result = pthread_mutex_init((pthread_mutex_t*)pMutex, NULL); + if (result != 0) { + return ma_result_from_errno(result); + } + + return MA_SUCCESS; +} + +static void ma_mutex_uninit__posix(ma_mutex* pMutex) +{ + pthread_mutex_destroy((pthread_mutex_t*)pMutex); +} + +static void ma_mutex_lock__posix(ma_mutex* pMutex) +{ + pthread_mutex_lock((pthread_mutex_t*)pMutex); +} + +static void ma_mutex_unlock__posix(ma_mutex* pMutex) +{ + pthread_mutex_unlock((pthread_mutex_t*)pMutex); +} + + +static ma_result ma_event_init__posix(ma_event* pEvent) +{ + int result; + + result = pthread_mutex_init((pthread_mutex_t*)&pEvent->lock, NULL); + if (result != 0) { + return ma_result_from_errno(result); + } + + result = pthread_cond_init((pthread_cond_t*)&pEvent->cond, NULL); + if (result != 0) { + pthread_mutex_destroy((pthread_mutex_t*)&pEvent->lock); + return ma_result_from_errno(result); + } + + pEvent->value = 0; + return MA_SUCCESS; +} + +static void ma_event_uninit__posix(ma_event* pEvent) +{ + pthread_cond_destroy((pthread_cond_t*)&pEvent->cond); + pthread_mutex_destroy((pthread_mutex_t*)&pEvent->lock); +} + +static ma_result ma_event_wait__posix(ma_event* pEvent) +{ + pthread_mutex_lock((pthread_mutex_t*)&pEvent->lock); + { + while (pEvent->value == 0) { + pthread_cond_wait((pthread_cond_t*)&pEvent->cond, (pthread_mutex_t*)&pEvent->lock); + } + pEvent->value = 0; /* Auto-reset. */ + } + pthread_mutex_unlock((pthread_mutex_t*)&pEvent->lock); + + return MA_SUCCESS; +} + +static ma_result ma_event_signal__posix(ma_event* pEvent) +{ + pthread_mutex_lock((pthread_mutex_t*)&pEvent->lock); + { + pEvent->value = 1; + pthread_cond_signal((pthread_cond_t*)&pEvent->cond); + } + pthread_mutex_unlock((pthread_mutex_t*)&pEvent->lock); + + return MA_SUCCESS; +} + + +static ma_result ma_semaphore_init__posix(int initialValue, ma_semaphore* pSemaphore) +{ + int result; + + if (pSemaphore == NULL) { + return MA_INVALID_ARGS; + } + + pSemaphore->value = initialValue; + + result = pthread_mutex_init((pthread_mutex_t*)&pSemaphore->lock, NULL); + if (result != 0) { + return ma_result_from_errno(result); /* Failed to create mutex. */ + } + + result = pthread_cond_init((pthread_cond_t*)&pSemaphore->cond, NULL); + if (result != 0) { + pthread_mutex_destroy((pthread_mutex_t*)&pSemaphore->lock); + return ma_result_from_errno(result); /* Failed to create condition variable. */ + } + + return MA_SUCCESS; +} + +static void ma_semaphore_uninit__posix(ma_semaphore* pSemaphore) +{ + if (pSemaphore == NULL) { + return; + } + + pthread_cond_destroy((pthread_cond_t*)&pSemaphore->cond); + pthread_mutex_destroy((pthread_mutex_t*)&pSemaphore->lock); +} + +static ma_result ma_semaphore_wait__posix(ma_semaphore* pSemaphore) +{ + if (pSemaphore == NULL) { + return MA_INVALID_ARGS; + } + + pthread_mutex_lock((pthread_mutex_t*)&pSemaphore->lock); + { + /* We need to wait on a condition variable before escaping. We can't return from this function until the semaphore has been signaled. */ + while (pSemaphore->value == 0) { + pthread_cond_wait((pthread_cond_t*)&pSemaphore->cond, (pthread_mutex_t*)&pSemaphore->lock); + } + + pSemaphore->value -= 1; + } + pthread_mutex_unlock((pthread_mutex_t*)&pSemaphore->lock); + + return MA_SUCCESS; +} + +static ma_result ma_semaphore_release__posix(ma_semaphore* pSemaphore) +{ + if (pSemaphore == NULL) { + return MA_INVALID_ARGS; + } + + pthread_mutex_lock((pthread_mutex_t*)&pSemaphore->lock); + { + pSemaphore->value += 1; + pthread_cond_signal((pthread_cond_t*)&pSemaphore->cond); + } + pthread_mutex_unlock((pthread_mutex_t*)&pSemaphore->lock); + + return MA_SUCCESS; +} +#elif defined(MA_WIN32) +static 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 THREAD_PRIORITY_NORMAL; + } +} + +static ma_result ma_thread_create__win32(ma_thread* pThread, ma_thread_priority priority, size_t stackSize, ma_thread_entry_proc entryProc, void* pData) +{ + DWORD threadID; /* Not used. Only used for passing into CreateThread() so it doesn't fail on Windows 98. */ + + *pThread = CreateThread(NULL, stackSize, entryProc, pData, 0, &threadID); + if (*pThread == NULL) { + return ma_result_from_GetLastError(GetLastError()); + } + + SetThreadPriority((HANDLE)*pThread, ma_thread_priority_to_win32(priority)); + + return MA_SUCCESS; +} + +static void ma_thread_wait__win32(ma_thread* pThread) +{ + WaitForSingleObject((HANDLE)*pThread, INFINITE); + CloseHandle((HANDLE)*pThread); +} + + +static ma_result ma_mutex_init__win32(ma_mutex* pMutex) +{ + *pMutex = CreateEventA(NULL, FALSE, TRUE, NULL); + if (*pMutex == NULL) { + return ma_result_from_GetLastError(GetLastError()); + } + + return MA_SUCCESS; +} + +static void ma_mutex_uninit__win32(ma_mutex* pMutex) +{ + CloseHandle((HANDLE)*pMutex); +} + +static void ma_mutex_lock__win32(ma_mutex* pMutex) +{ + WaitForSingleObject((HANDLE)*pMutex, INFINITE); +} + +static void ma_mutex_unlock__win32(ma_mutex* pMutex) +{ + SetEvent((HANDLE)*pMutex); +} + + +static ma_result ma_event_init__win32(ma_event* pEvent) +{ + *pEvent = CreateEventA(NULL, FALSE, FALSE, NULL); + if (*pEvent == NULL) { + return ma_result_from_GetLastError(GetLastError()); + } + + return MA_SUCCESS; +} + +static void ma_event_uninit__win32(ma_event* pEvent) +{ + CloseHandle((HANDLE)*pEvent); +} + +static ma_result ma_event_wait__win32(ma_event* pEvent) +{ + DWORD result = WaitForSingleObject((HANDLE)*pEvent, INFINITE); + if (result == WAIT_OBJECT_0) { + return MA_SUCCESS; + } + + if (result == WAIT_TIMEOUT) { + return MA_TIMEOUT; + } + + return ma_result_from_GetLastError(GetLastError()); +} + +static ma_result ma_event_signal__win32(ma_event* pEvent) +{ + BOOL result = SetEvent((HANDLE)*pEvent); + if (result == 0) { + return ma_result_from_GetLastError(GetLastError()); + } + + return MA_SUCCESS; +} + + +static ma_result ma_semaphore_init__win32(int initialValue, ma_semaphore* pSemaphore) +{ + *pSemaphore = CreateSemaphoreW(NULL, (LONG)initialValue, LONG_MAX, NULL); + if (*pSemaphore == NULL) { + return ma_result_from_GetLastError(GetLastError()); + } + + return MA_SUCCESS; +} + +static void ma_semaphore_uninit__win32(ma_semaphore* pSemaphore) +{ + CloseHandle((HANDLE)*pSemaphore); +} + +static ma_result ma_semaphore_wait__win32(ma_semaphore* pSemaphore) +{ + DWORD result = WaitForSingleObject((HANDLE)*pSemaphore, INFINITE); + if (result == WAIT_OBJECT_0) { + return MA_SUCCESS; + } + + if (result == WAIT_TIMEOUT) { + return MA_TIMEOUT; + } + + return ma_result_from_GetLastError(GetLastError()); +} + +static ma_result ma_semaphore_release__win32(ma_semaphore* pSemaphore) +{ + BOOL result = ReleaseSemaphore((HANDLE)*pSemaphore, 1, NULL); + if (result == 0) { + return ma_result_from_GetLastError(GetLastError()); + } + + return MA_SUCCESS; +} +#endif + +typedef struct +{ + ma_thread_entry_proc entryProc; + void* pData; + ma_allocation_callbacks allocationCallbacks; +} ma_thread_proxy_data; + +static ma_thread_result MA_THREADCALL ma_thread_entry_proxy(void* pData) +{ + ma_thread_proxy_data* pProxyData = (ma_thread_proxy_data*)pData; + ma_thread_entry_proc entryProc; + void* pEntryProcData; + ma_thread_result result; + + #if defined(MA_ON_THREAD_ENTRY) + MA_ON_THREAD_ENTRY + #endif + + entryProc = pProxyData->entryProc; + pEntryProcData = pProxyData->pData; + + /* Free the proxy data before getting into the real thread entry proc. */ + ma_free(pProxyData, &pProxyData->allocationCallbacks); + + result = entryProc(pEntryProcData); + + #if defined(MA_ON_THREAD_EXIT) + MA_ON_THREAD_EXIT + #endif + + return result; +} + +static ma_result ma_thread_create(ma_thread* pThread, ma_thread_priority priority, size_t stackSize, ma_thread_entry_proc entryProc, void* pData, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_result result; + ma_thread_proxy_data* pProxyData; + + if (pThread == NULL || entryProc == NULL) { + return MA_INVALID_ARGS; + } + + pProxyData = (ma_thread_proxy_data*)ma_malloc(sizeof(*pProxyData), pAllocationCallbacks); /* Will be freed by the proxy entry proc. */ + if (pProxyData == NULL) { + return MA_OUT_OF_MEMORY; + } + +#if defined(MA_THREAD_DEFAULT_STACK_SIZE) + if (stackSize == 0) { + stackSize = MA_THREAD_DEFAULT_STACK_SIZE; + } +#endif + + pProxyData->entryProc = entryProc; + pProxyData->pData = pData; + ma_allocation_callbacks_init_copy(&pProxyData->allocationCallbacks, pAllocationCallbacks); + +#if defined(MA_POSIX) + result = ma_thread_create__posix(pThread, priority, stackSize, ma_thread_entry_proxy, pProxyData); +#elif defined(MA_WIN32) + result = ma_thread_create__win32(pThread, priority, stackSize, ma_thread_entry_proxy, pProxyData); +#endif + + if (result != MA_SUCCESS) { + ma_free(pProxyData, pAllocationCallbacks); + return result; + } + + return MA_SUCCESS; +} + +static void ma_thread_wait(ma_thread* pThread) +{ + if (pThread == NULL) { + return; + } + +#if defined(MA_POSIX) + ma_thread_wait__posix(pThread); +#elif defined(MA_WIN32) + ma_thread_wait__win32(pThread); +#endif +} + + +MA_API ma_result ma_mutex_init(ma_mutex* pMutex) +{ + if (pMutex == NULL) { + MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */ + return MA_INVALID_ARGS; + } + +#if defined(MA_POSIX) + return ma_mutex_init__posix(pMutex); +#elif defined(MA_WIN32) + return ma_mutex_init__win32(pMutex); +#endif +} + +MA_API void ma_mutex_uninit(ma_mutex* pMutex) +{ + if (pMutex == NULL) { + return; + } + +#if defined(MA_POSIX) + ma_mutex_uninit__posix(pMutex); +#elif defined(MA_WIN32) + ma_mutex_uninit__win32(pMutex); +#endif +} + +MA_API void ma_mutex_lock(ma_mutex* pMutex) +{ + if (pMutex == NULL) { + MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */ + return; + } + +#if defined(MA_POSIX) + ma_mutex_lock__posix(pMutex); +#elif defined(MA_WIN32) + ma_mutex_lock__win32(pMutex); +#endif +} + +MA_API void ma_mutex_unlock(ma_mutex* pMutex) +{ + if (pMutex == NULL) { + MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */ + return; + } + +#if defined(MA_POSIX) + ma_mutex_unlock__posix(pMutex); +#elif defined(MA_WIN32) + ma_mutex_unlock__win32(pMutex); +#endif +} + + +MA_API ma_result ma_event_init(ma_event* pEvent) +{ + if (pEvent == NULL) { + MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */ + return MA_INVALID_ARGS; + } + +#if defined(MA_POSIX) + return ma_event_init__posix(pEvent); +#elif defined(MA_WIN32) + return ma_event_init__win32(pEvent); +#endif +} + +#if 0 +static ma_result ma_event_alloc_and_init(ma_event** ppEvent, ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_result result; + ma_event* pEvent; + + if (ppEvent == NULL) { + return MA_INVALID_ARGS; + } + + *ppEvent = NULL; + + pEvent = ma_malloc(sizeof(*pEvent), pAllocationCallbacks); + if (pEvent == NULL) { + return MA_OUT_OF_MEMORY; + } + + result = ma_event_init(pEvent); + if (result != MA_SUCCESS) { + ma_free(pEvent, pAllocationCallbacks); + return result; + } + + *ppEvent = pEvent; + return result; +} +#endif + +MA_API void ma_event_uninit(ma_event* pEvent) +{ + if (pEvent == NULL) { + return; + } + +#if defined(MA_POSIX) + ma_event_uninit__posix(pEvent); +#elif defined(MA_WIN32) + ma_event_uninit__win32(pEvent); +#endif +} + +#if 0 +static void ma_event_uninit_and_free(ma_event* pEvent, ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pEvent == NULL) { + return; + } + + ma_event_uninit(pEvent); + ma_free(pEvent, pAllocationCallbacks); +} +#endif + +MA_API ma_result ma_event_wait(ma_event* pEvent) +{ + if (pEvent == NULL) { + MA_ASSERT(MA_FALSE); /* Fire an assert to the caller is aware of this bug. */ + return MA_INVALID_ARGS; + } + +#if defined(MA_POSIX) + return ma_event_wait__posix(pEvent); +#elif defined(MA_WIN32) + return ma_event_wait__win32(pEvent); +#endif +} + +MA_API ma_result ma_event_signal(ma_event* pEvent) +{ + if (pEvent == NULL) { + MA_ASSERT(MA_FALSE); /* Fire an assert to the caller is aware of this bug. */ + return MA_INVALID_ARGS; + } + +#if defined(MA_POSIX) + return ma_event_signal__posix(pEvent); +#elif defined(MA_WIN32) + return ma_event_signal__win32(pEvent); +#endif +} + + +MA_API ma_result ma_semaphore_init(int initialValue, ma_semaphore* pSemaphore) +{ + if (pSemaphore == NULL) { + MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */ + return MA_INVALID_ARGS; + } + +#if defined(MA_POSIX) + return ma_semaphore_init__posix(initialValue, pSemaphore); +#elif defined(MA_WIN32) + return ma_semaphore_init__win32(initialValue, pSemaphore); +#endif +} + +MA_API void ma_semaphore_uninit(ma_semaphore* pSemaphore) +{ + if (pSemaphore == NULL) { + MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */ + return; + } + +#if defined(MA_POSIX) + ma_semaphore_uninit__posix(pSemaphore); +#elif defined(MA_WIN32) + ma_semaphore_uninit__win32(pSemaphore); +#endif +} + +MA_API ma_result ma_semaphore_wait(ma_semaphore* pSemaphore) +{ + if (pSemaphore == NULL) { + MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */ + return MA_INVALID_ARGS; + } + +#if defined(MA_POSIX) + return ma_semaphore_wait__posix(pSemaphore); +#elif defined(MA_WIN32) + return ma_semaphore_wait__win32(pSemaphore); +#endif +} + +MA_API ma_result ma_semaphore_release(ma_semaphore* pSemaphore) +{ + if (pSemaphore == NULL) { + MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */ + return MA_INVALID_ARGS; + } + +#if defined(MA_POSIX) + return ma_semaphore_release__posix(pSemaphore); +#elif defined(MA_WIN32) + return ma_semaphore_release__win32(pSemaphore); +#endif +} +#else +/* MA_NO_THREADING is set which means threading is disabled. Threading is required by some API families. If any of these are enabled we need to throw an error. */ +#ifndef MA_NO_DEVICE_IO +#error "MA_NO_THREADING cannot be used without MA_NO_DEVICE_IO"; +#endif +#endif /* MA_NO_THREADING */ + + + +#define MA_FENCE_COUNTER_MAX 0x7FFFFFFF + +MA_API ma_result ma_fence_init(ma_fence* pFence) +{ + if (pFence == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pFence); + pFence->counter = 0; + + #ifndef MA_NO_THREADING + { + ma_result result; + + result = ma_event_init(&pFence->e); + if (result != MA_SUCCESS) { + return result; + } + } + #endif + + return MA_SUCCESS; +} + +MA_API void ma_fence_uninit(ma_fence* pFence) +{ + if (pFence == NULL) { + return; + } + + #ifndef MA_NO_THREADING + { + ma_event_uninit(&pFence->e); + } + #endif + + MA_ZERO_OBJECT(pFence); +} + +MA_API ma_result ma_fence_acquire(ma_fence* pFence) +{ + if (pFence == NULL) { + return MA_INVALID_ARGS; + } + + for (;;) { + ma_uint32 oldCounter = ma_atomic_load_32(&pFence->counter); + ma_uint32 newCounter = oldCounter + 1; + + /* Make sure we're not about to exceed our maximum value. */ + if (newCounter > MA_FENCE_COUNTER_MAX) { + MA_ASSERT(MA_FALSE); + return MA_OUT_OF_RANGE; + } + + if (ma_atomic_compare_exchange_weak_32(&pFence->counter, &oldCounter, newCounter)) { + return MA_SUCCESS; + } else { + if (oldCounter == MA_FENCE_COUNTER_MAX) { + MA_ASSERT(MA_FALSE); + return MA_OUT_OF_RANGE; /* The other thread took the last available slot. Abort. */ + } + } + } + + /* Should never get here. */ + /*return MA_SUCCESS;*/ +} + +MA_API ma_result ma_fence_release(ma_fence* pFence) +{ + if (pFence == NULL) { + return MA_INVALID_ARGS; + } + + for (;;) { + ma_uint32 oldCounter = ma_atomic_load_32(&pFence->counter); + ma_uint32 newCounter = oldCounter - 1; + + if (oldCounter == 0) { + MA_ASSERT(MA_FALSE); + return MA_INVALID_OPERATION; /* Acquire/release mismatch. */ + } + + if (ma_atomic_compare_exchange_weak_32(&pFence->counter, &oldCounter, newCounter)) { + #ifndef MA_NO_THREADING + { + if (newCounter == 0) { + ma_event_signal(&pFence->e); /* <-- ma_fence_wait() will be waiting on this. */ + } + } + #endif + + return MA_SUCCESS; + } else { + if (oldCounter == 0) { + MA_ASSERT(MA_FALSE); + return MA_INVALID_OPERATION; /* Another thread has taken the 0 slot. Acquire/release mismatch. */ + } + } + } + + /* Should never get here. */ + /*return MA_SUCCESS;*/ +} + +MA_API ma_result ma_fence_wait(ma_fence* pFence) +{ + if (pFence == NULL) { + return MA_INVALID_ARGS; + } + + for (;;) { + ma_uint32 counter; + + counter = ma_atomic_load_32(&pFence->counter); + if (counter == 0) { + /* + Counter has hit zero. By the time we get here some other thread may have acquired the + fence again, but that is where the caller needs to take care with how they se the fence. + */ + return MA_SUCCESS; + } + + /* Getting here means the counter is > 0. We'll need to wait for something to happen. */ + #ifndef MA_NO_THREADING + { + ma_result result; + + result = ma_event_wait(&pFence->e); + if (result != MA_SUCCESS) { + return result; + } + } + #endif + } + + /* Should never get here. */ + /*return MA_INVALID_OPERATION;*/ +} + + +MA_API ma_result ma_async_notification_signal(ma_async_notification* pNotification) +{ + ma_async_notification_callbacks* pNotificationCallbacks = (ma_async_notification_callbacks*)pNotification; + + if (pNotification == NULL) { + return MA_INVALID_ARGS; + } + + if (pNotificationCallbacks->onSignal == NULL) { + return MA_NOT_IMPLEMENTED; + } + + pNotificationCallbacks->onSignal(pNotification); + return MA_INVALID_ARGS; +} + + +static void ma_async_notification_poll__on_signal(ma_async_notification* pNotification) +{ + ((ma_async_notification_poll*)pNotification)->signalled = MA_TRUE; +} + +MA_API ma_result ma_async_notification_poll_init(ma_async_notification_poll* pNotificationPoll) +{ + if (pNotificationPoll == NULL) { + return MA_INVALID_ARGS; + } + + pNotificationPoll->cb.onSignal = ma_async_notification_poll__on_signal; + pNotificationPoll->signalled = MA_FALSE; + + return MA_SUCCESS; +} + +MA_API ma_bool32 ma_async_notification_poll_is_signalled(const ma_async_notification_poll* pNotificationPoll) +{ + if (pNotificationPoll == NULL) { + return MA_FALSE; + } + + return pNotificationPoll->signalled; +} + + +static void ma_async_notification_event__on_signal(ma_async_notification* pNotification) +{ + ma_async_notification_event_signal((ma_async_notification_event*)pNotification); +} + +MA_API ma_result ma_async_notification_event_init(ma_async_notification_event* pNotificationEvent) +{ + if (pNotificationEvent == NULL) { + return MA_INVALID_ARGS; + } + + pNotificationEvent->cb.onSignal = ma_async_notification_event__on_signal; + + #ifndef MA_NO_THREADING + { + ma_result result; + + result = ma_event_init(&pNotificationEvent->e); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; + } + #else + { + return MA_NOT_IMPLEMENTED; /* Threading is disabled. */ + } + #endif +} + +MA_API ma_result ma_async_notification_event_uninit(ma_async_notification_event* pNotificationEvent) +{ + if (pNotificationEvent == NULL) { + return MA_INVALID_ARGS; + } + + #ifndef MA_NO_THREADING + { + ma_event_uninit(&pNotificationEvent->e); + return MA_SUCCESS; + } + #else + { + return MA_NOT_IMPLEMENTED; /* Threading is disabled. */ + } + #endif +} + +MA_API ma_result ma_async_notification_event_wait(ma_async_notification_event* pNotificationEvent) +{ + if (pNotificationEvent == NULL) { + return MA_INVALID_ARGS; + } + + #ifndef MA_NO_THREADING + { + return ma_event_wait(&pNotificationEvent->e); + } + #else + { + return MA_NOT_IMPLEMENTED; /* Threading is disabled. */ + } + #endif +} + +MA_API ma_result ma_async_notification_event_signal(ma_async_notification_event* pNotificationEvent) +{ + if (pNotificationEvent == NULL) { + return MA_INVALID_ARGS; + } + + #ifndef MA_NO_THREADING + { + return ma_event_signal(&pNotificationEvent->e); + } + #else + { + return MA_NOT_IMPLEMENTED; /* Threading is disabled. */ + } + #endif +} + + + +/************************************************************************************************************************************************************ + +Job Queue + +************************************************************************************************************************************************************/ +MA_API ma_slot_allocator_config ma_slot_allocator_config_init(ma_uint32 capacity) +{ + ma_slot_allocator_config config; + + MA_ZERO_OBJECT(&config); + config.capacity = capacity; + + return config; +} + + +static MA_INLINE ma_uint32 ma_slot_allocator_calculate_group_capacity(ma_uint32 slotCapacity) +{ + ma_uint32 cap = slotCapacity / 32; + if ((slotCapacity % 32) != 0) { + cap += 1; + } + + return cap; +} + +static MA_INLINE ma_uint32 ma_slot_allocator_group_capacity(const ma_slot_allocator* pAllocator) +{ + return ma_slot_allocator_calculate_group_capacity(pAllocator->capacity); +} + + +typedef struct +{ + size_t sizeInBytes; + size_t groupsOffset; + size_t slotsOffset; +} ma_slot_allocator_heap_layout; + +static ma_result ma_slot_allocator_get_heap_layout(const ma_slot_allocator_config* pConfig, ma_slot_allocator_heap_layout* pHeapLayout) +{ + MA_ASSERT(pHeapLayout != NULL); + + MA_ZERO_OBJECT(pHeapLayout); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->capacity == 0) { + return MA_INVALID_ARGS; + } + + pHeapLayout->sizeInBytes = 0; + + /* Groups. */ + pHeapLayout->groupsOffset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += ma_align_64(ma_slot_allocator_calculate_group_capacity(pConfig->capacity) * sizeof(ma_slot_allocator_group)); + + /* Slots. */ + pHeapLayout->slotsOffset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += ma_align_64(pConfig->capacity * sizeof(ma_uint32)); + + return MA_SUCCESS; +} + +MA_API ma_result ma_slot_allocator_get_heap_size(const ma_slot_allocator_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_result result; + ma_slot_allocator_heap_layout layout; + + if (pHeapSizeInBytes == NULL) { + return MA_INVALID_ARGS; + } + + *pHeapSizeInBytes = 0; + + result = ma_slot_allocator_get_heap_layout(pConfig, &layout); + if (result != MA_SUCCESS) { + return result; + } + + *pHeapSizeInBytes = layout.sizeInBytes; + + return result; +} + +MA_API ma_result ma_slot_allocator_init_preallocated(const ma_slot_allocator_config* pConfig, void* pHeap, ma_slot_allocator* pAllocator) +{ + ma_result result; + ma_slot_allocator_heap_layout heapLayout; + + if (pAllocator == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pAllocator); + + if (pHeap == NULL) { + return MA_INVALID_ARGS; + } + + result = ma_slot_allocator_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + pAllocator->_pHeap = pHeap; + MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes); + + pAllocator->pGroups = (ma_slot_allocator_group*)ma_offset_ptr(pHeap, heapLayout.groupsOffset); + pAllocator->pSlots = (ma_uint32*)ma_offset_ptr(pHeap, heapLayout.slotsOffset); + pAllocator->capacity = pConfig->capacity; + + return MA_SUCCESS; +} + +MA_API ma_result ma_slot_allocator_init(const ma_slot_allocator_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_slot_allocator* pAllocator) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_slot_allocator_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; /* Failed to retrieve the size of the heap allocation. */ + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_slot_allocator_init_preallocated(pConfig, pHeap, pAllocator); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pAllocator->_ownsHeap = MA_TRUE; + return MA_SUCCESS; +} + +MA_API void ma_slot_allocator_uninit(ma_slot_allocator* pAllocator, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pAllocator == NULL) { + return; + } + + if (pAllocator->_ownsHeap) { + ma_free(pAllocator->_pHeap, pAllocationCallbacks); + } +} + +MA_API ma_result ma_slot_allocator_alloc(ma_slot_allocator* pAllocator, ma_uint64* pSlot) +{ + ma_uint32 iAttempt; + const ma_uint32 maxAttempts = 2; /* The number of iterations to perform until returning MA_OUT_OF_MEMORY if no slots can be found. */ + + if (pAllocator == NULL || pSlot == NULL) { + return MA_INVALID_ARGS; + } + + for (iAttempt = 0; iAttempt < maxAttempts; iAttempt += 1) { + /* We need to acquire a suitable bitfield first. This is a bitfield that's got an available slot within it. */ + ma_uint32 iGroup; + for (iGroup = 0; iGroup < ma_slot_allocator_group_capacity(pAllocator); iGroup += 1) { + /* CAS */ + for (;;) { + ma_uint32 oldBitfield; + ma_uint32 newBitfield; + ma_uint32 bitOffset; + + oldBitfield = ma_atomic_load_32(&pAllocator->pGroups[iGroup].bitfield); /* <-- This copy must happen. The compiler must not optimize this away. */ + + /* Fast check to see if anything is available. */ + if (oldBitfield == 0xFFFFFFFF) { + break; /* No available bits in this bitfield. */ + } + + bitOffset = ma_ffs_32(~oldBitfield); + MA_ASSERT(bitOffset < 32); + + newBitfield = oldBitfield | (1 << bitOffset); + + if (ma_atomic_compare_and_swap_32(&pAllocator->pGroups[iGroup].bitfield, oldBitfield, newBitfield) == oldBitfield) { + ma_uint32 slotIndex; + + /* Increment the counter as soon as possible to have other threads report out-of-memory sooner than later. */ + ma_atomic_fetch_add_32(&pAllocator->count, 1); + + /* The slot index is required for constructing the output value. */ + slotIndex = (iGroup << 5) + bitOffset; /* iGroup << 5 = iGroup * 32 */ + if (slotIndex >= pAllocator->capacity) { + return MA_OUT_OF_MEMORY; + } + + /* Increment the reference count before constructing the output value. */ + pAllocator->pSlots[slotIndex] += 1; + + /* Construct the output value. */ + *pSlot = (((ma_uint64)pAllocator->pSlots[slotIndex] << 32) | slotIndex); + + return MA_SUCCESS; + } + } + } + + /* We weren't able to find a slot. If it's because we've reached our capacity we need to return MA_OUT_OF_MEMORY. Otherwise we need to do another iteration and try again. */ + if (pAllocator->count < pAllocator->capacity) { + ma_yield(); + } else { + return MA_OUT_OF_MEMORY; + } + } + + /* We couldn't find a slot within the maximum number of attempts. */ + return MA_OUT_OF_MEMORY; +} + +MA_API ma_result ma_slot_allocator_free(ma_slot_allocator* pAllocator, ma_uint64 slot) +{ + ma_uint32 iGroup; + ma_uint32 iBit; + + if (pAllocator == NULL) { + return MA_INVALID_ARGS; + } + + iGroup = (ma_uint32)((slot & 0xFFFFFFFF) >> 5); /* slot / 32 */ + iBit = (ma_uint32)((slot & 0xFFFFFFFF) & 31); /* slot % 32 */ + + if (iGroup >= ma_slot_allocator_group_capacity(pAllocator)) { + return MA_INVALID_ARGS; + } + + MA_ASSERT(iBit < 32); /* This must be true due to the logic we used to actually calculate it. */ + + while (ma_atomic_load_32(&pAllocator->count) > 0) { + /* CAS */ + ma_uint32 oldBitfield; + ma_uint32 newBitfield; + + oldBitfield = ma_atomic_load_32(&pAllocator->pGroups[iGroup].bitfield); /* <-- This copy must happen. The compiler must not optimize this away. */ + newBitfield = oldBitfield & ~(1 << iBit); + + /* Debugging for checking for double-frees. */ + #if defined(MA_DEBUG_OUTPUT) + { + if ((oldBitfield & (1 << iBit)) == 0) { + MA_ASSERT(MA_FALSE); /* Double free detected.*/ + } + } + #endif + + if (ma_atomic_compare_and_swap_32(&pAllocator->pGroups[iGroup].bitfield, oldBitfield, newBitfield) == oldBitfield) { + ma_atomic_fetch_sub_32(&pAllocator->count, 1); + return MA_SUCCESS; + } + } + + /* Getting here means there are no allocations available for freeing. */ + return MA_INVALID_OPERATION; +} + + +#define MA_JOB_ID_NONE ~((ma_uint64)0) +#define MA_JOB_SLOT_NONE (ma_uint16)(~0) + +static MA_INLINE ma_uint32 ma_job_extract_refcount(ma_uint64 toc) +{ + return (ma_uint32)(toc >> 32); +} + +static MA_INLINE ma_uint16 ma_job_extract_slot(ma_uint64 toc) +{ + return (ma_uint16)(toc & 0x0000FFFF); +} + +static MA_INLINE ma_uint16 ma_job_extract_code(ma_uint64 toc) +{ + return (ma_uint16)((toc & 0xFFFF0000) >> 16); +} + +static MA_INLINE ma_uint64 ma_job_toc_to_allocation(ma_uint64 toc) +{ + return ((ma_uint64)ma_job_extract_refcount(toc) << 32) | (ma_uint64)ma_job_extract_slot(toc); +} + +static MA_INLINE ma_uint64 ma_job_set_refcount(ma_uint64 toc, ma_uint32 refcount) +{ + /* Clear the reference count first. */ + toc = toc & ~((ma_uint64)0xFFFFFFFF << 32); + toc = toc | ((ma_uint64)refcount << 32); + + return toc; +} + + +MA_API ma_job ma_job_init(ma_uint16 code) +{ + ma_job job; + + MA_ZERO_OBJECT(&job); + job.toc.breakup.code = code; + job.toc.breakup.slot = MA_JOB_SLOT_NONE; /* Temp value. Will be allocated when posted to a queue. */ + job.next = MA_JOB_ID_NONE; + + return job; +} + + +static ma_result ma_job_process__noop(ma_job* pJob); +static ma_result ma_job_process__quit(ma_job* pJob); +static ma_result ma_job_process__custom(ma_job* pJob); +static ma_result ma_job_process__resource_manager__load_data_buffer_node(ma_job* pJob); +static ma_result ma_job_process__resource_manager__free_data_buffer_node(ma_job* pJob); +static ma_result ma_job_process__resource_manager__page_data_buffer_node(ma_job* pJob); +static ma_result ma_job_process__resource_manager__load_data_buffer(ma_job* pJob); +static ma_result ma_job_process__resource_manager__free_data_buffer(ma_job* pJob); +static ma_result ma_job_process__resource_manager__load_data_stream(ma_job* pJob); +static ma_result ma_job_process__resource_manager__free_data_stream(ma_job* pJob); +static ma_result ma_job_process__resource_manager__page_data_stream(ma_job* pJob); +static ma_result ma_job_process__resource_manager__seek_data_stream(ma_job* pJob); + +#if !defined(MA_NO_DEVICE_IO) +static ma_result ma_job_process__device__aaudio_reroute(ma_job* pJob); +#endif + +static ma_job_proc g_jobVTable[MA_JOB_TYPE_COUNT] = +{ + /* Miscellaneous. */ + ma_job_process__quit, /* MA_JOB_TYPE_QUIT */ + ma_job_process__custom, /* MA_JOB_TYPE_CUSTOM */ + + /* Resource Manager. */ + ma_job_process__resource_manager__load_data_buffer_node, /* MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER_NODE */ + ma_job_process__resource_manager__free_data_buffer_node, /* MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER_NODE */ + ma_job_process__resource_manager__page_data_buffer_node, /* MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE */ + ma_job_process__resource_manager__load_data_buffer, /* MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER */ + ma_job_process__resource_manager__free_data_buffer, /* MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER */ + ma_job_process__resource_manager__load_data_stream, /* MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_STREAM */ + ma_job_process__resource_manager__free_data_stream, /* MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_STREAM */ + ma_job_process__resource_manager__page_data_stream, /* MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_STREAM */ + ma_job_process__resource_manager__seek_data_stream, /* MA_JOB_TYPE_RESOURCE_MANAGER_SEEK_DATA_STREAM */ + + /* Device. */ +#if !defined(MA_NO_DEVICE_IO) + ma_job_process__device__aaudio_reroute /*MA_JOB_TYPE_DEVICE_AAUDIO_REROUTE*/ +#endif +}; + +MA_API ma_result ma_job_process(ma_job* pJob) +{ + if (pJob == NULL) { + return MA_INVALID_ARGS; + } + + if (pJob->toc.breakup.code >= MA_JOB_TYPE_COUNT) { + return MA_INVALID_OPERATION; + } + + return g_jobVTable[pJob->toc.breakup.code](pJob); +} + +static ma_result ma_job_process__noop(ma_job* pJob) +{ + MA_ASSERT(pJob != NULL); + + /* No-op. */ + (void)pJob; + + return MA_SUCCESS; +} + +static ma_result ma_job_process__quit(ma_job* pJob) +{ + return ma_job_process__noop(pJob); +} + +static ma_result ma_job_process__custom(ma_job* pJob) +{ + MA_ASSERT(pJob != NULL); + + /* No-op if there's no callback. */ + if (pJob->data.custom.proc == NULL) { + return MA_SUCCESS; + } + + return pJob->data.custom.proc(pJob); +} + + + +MA_API ma_job_queue_config ma_job_queue_config_init(ma_uint32 flags, ma_uint32 capacity) +{ + ma_job_queue_config config; + + config.flags = flags; + config.capacity = capacity; + + return config; +} + + +typedef struct +{ + size_t sizeInBytes; + size_t allocatorOffset; + size_t jobsOffset; +} ma_job_queue_heap_layout; + +static ma_result ma_job_queue_get_heap_layout(const ma_job_queue_config* pConfig, ma_job_queue_heap_layout* pHeapLayout) +{ + ma_result result; + + MA_ASSERT(pHeapLayout != NULL); + + MA_ZERO_OBJECT(pHeapLayout); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->capacity == 0) { + return MA_INVALID_ARGS; + } + + pHeapLayout->sizeInBytes = 0; + + /* Allocator. */ + { + ma_slot_allocator_config allocatorConfig; + size_t allocatorHeapSizeInBytes; + + allocatorConfig = ma_slot_allocator_config_init(pConfig->capacity); + result = ma_slot_allocator_get_heap_size(&allocatorConfig, &allocatorHeapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + pHeapLayout->allocatorOffset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += allocatorHeapSizeInBytes; + } + + /* Jobs. */ + pHeapLayout->jobsOffset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += ma_align_64(pConfig->capacity * sizeof(ma_job)); + + return MA_SUCCESS; +} + +MA_API ma_result ma_job_queue_get_heap_size(const ma_job_queue_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_result result; + ma_job_queue_heap_layout layout; + + if (pHeapSizeInBytes == NULL) { + return MA_INVALID_ARGS; + } + + *pHeapSizeInBytes = 0; + + result = ma_job_queue_get_heap_layout(pConfig, &layout); + if (result != MA_SUCCESS) { + return result; + } + + *pHeapSizeInBytes = layout.sizeInBytes; + + return MA_SUCCESS; +} + +MA_API ma_result ma_job_queue_init_preallocated(const ma_job_queue_config* pConfig, void* pHeap, ma_job_queue* pQueue) +{ + ma_result result; + ma_job_queue_heap_layout heapLayout; + ma_slot_allocator_config allocatorConfig; + + if (pQueue == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pQueue); + + result = ma_job_queue_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + pQueue->_pHeap = pHeap; + MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes); + + pQueue->flags = pConfig->flags; + pQueue->capacity = pConfig->capacity; + pQueue->pJobs = (ma_job*)ma_offset_ptr(pHeap, heapLayout.jobsOffset); + + allocatorConfig = ma_slot_allocator_config_init(pConfig->capacity); + result = ma_slot_allocator_init_preallocated(&allocatorConfig, ma_offset_ptr(pHeap, heapLayout.allocatorOffset), &pQueue->allocator); + if (result != MA_SUCCESS) { + return result; + } + + /* We need a semaphore if we're running in non-blocking mode. If threading is disabled we need to return an error. */ + if ((pQueue->flags & MA_JOB_QUEUE_FLAG_NON_BLOCKING) == 0) { + #ifndef MA_NO_THREADING + { + ma_semaphore_init(0, &pQueue->sem); + } + #else + { + /* Threading is disabled and we've requested non-blocking mode. */ + return MA_INVALID_OPERATION; + } + #endif + } + + /* + Our queue needs to be initialized with a free standing node. This should always be slot 0. Required for the lock free algorithm. The first job in the queue is + just a dummy item for giving us the first item in the list which is stored in the "next" member. + */ + ma_slot_allocator_alloc(&pQueue->allocator, &pQueue->head); /* Will never fail. */ + pQueue->pJobs[ma_job_extract_slot(pQueue->head)].next = MA_JOB_ID_NONE; + pQueue->tail = pQueue->head; + + return MA_SUCCESS; +} + +MA_API ma_result ma_job_queue_init(const ma_job_queue_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_job_queue* pQueue) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_job_queue_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_job_queue_init_preallocated(pConfig, pHeap, pQueue); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pQueue->_ownsHeap = MA_TRUE; + return MA_SUCCESS; +} + +MA_API void ma_job_queue_uninit(ma_job_queue* pQueue, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pQueue == NULL) { + return; + } + + /* All we need to do is uninitialize the semaphore. */ + if ((pQueue->flags & MA_JOB_QUEUE_FLAG_NON_BLOCKING) == 0) { + #ifndef MA_NO_THREADING + { + ma_semaphore_uninit(&pQueue->sem); + } + #else + { + MA_ASSERT(MA_FALSE); /* Should never get here. Should have been checked at initialization time. */ + } + #endif + } + + ma_slot_allocator_uninit(&pQueue->allocator, pAllocationCallbacks); + + if (pQueue->_ownsHeap) { + ma_free(pQueue->_pHeap, pAllocationCallbacks); + } +} + +static ma_bool32 ma_job_queue_cas(volatile ma_uint64* dst, ma_uint64 expected, ma_uint64 desired) +{ + /* The new counter is taken from the expected value. */ + return ma_atomic_compare_and_swap_64(dst, expected, ma_job_set_refcount(desired, ma_job_extract_refcount(expected) + 1)) == expected; +} + +MA_API ma_result ma_job_queue_post(ma_job_queue* pQueue, const ma_job* pJob) +{ + /* + Lock free queue implementation based on the paper by Michael and Scott: Nonblocking Algorithms and Preemption-Safe Locking on Multiprogrammed Shared Memory Multiprocessors + */ + ma_result result; + ma_uint64 slot; + ma_uint64 tail; + ma_uint64 next; + + if (pQueue == NULL || pJob == NULL) { + return MA_INVALID_ARGS; + } + + /* We need a new slot. */ + result = ma_slot_allocator_alloc(&pQueue->allocator, &slot); + if (result != MA_SUCCESS) { + return result; /* Probably ran out of slots. If so, MA_OUT_OF_MEMORY will be returned. */ + } + + /* At this point we should have a slot to place the job. */ + MA_ASSERT(ma_job_extract_slot(slot) < pQueue->capacity); + + /* We need to put the job into memory before we do anything. */ + pQueue->pJobs[ma_job_extract_slot(slot)] = *pJob; + pQueue->pJobs[ma_job_extract_slot(slot)].toc.allocation = slot; /* This will overwrite the job code. */ + pQueue->pJobs[ma_job_extract_slot(slot)].toc.breakup.code = pJob->toc.breakup.code; /* The job code needs to be applied again because the line above overwrote it. */ + pQueue->pJobs[ma_job_extract_slot(slot)].next = MA_JOB_ID_NONE; /* Reset for safety. */ + + #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE + ma_spinlock_lock(&pQueue->lock); + #endif + { + /* The job is stored in memory so now we need to add it to our linked list. We only ever add items to the end of the list. */ + for (;;) { + tail = ma_atomic_load_64(&pQueue->tail); + next = ma_atomic_load_64(&pQueue->pJobs[ma_job_extract_slot(tail)].next); + + if (ma_job_toc_to_allocation(tail) == ma_job_toc_to_allocation(ma_atomic_load_64(&pQueue->tail))) { + if (ma_job_extract_slot(next) == 0xFFFF) { + if (ma_job_queue_cas(&pQueue->pJobs[ma_job_extract_slot(tail)].next, next, slot)) { + break; + } + } else { + ma_job_queue_cas(&pQueue->tail, tail, ma_job_extract_slot(next)); + } + } + } + ma_job_queue_cas(&pQueue->tail, tail, slot); + } + #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE + ma_spinlock_unlock(&pQueue->lock); + #endif + + + /* Signal the semaphore as the last step if we're using synchronous mode. */ + if ((pQueue->flags & MA_JOB_QUEUE_FLAG_NON_BLOCKING) == 0) { + #ifndef MA_NO_THREADING + { + ma_semaphore_release(&pQueue->sem); + } + #else + { + MA_ASSERT(MA_FALSE); /* Should never get here. Should have been checked at initialization time. */ + } + #endif + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_job_queue_next(ma_job_queue* pQueue, ma_job* pJob) +{ + ma_uint64 head; + ma_uint64 tail; + ma_uint64 next; + + if (pQueue == NULL || pJob == NULL) { + return MA_INVALID_ARGS; + } + + /* If we're running in synchronous mode we'll need to wait on a semaphore. */ + if ((pQueue->flags & MA_JOB_QUEUE_FLAG_NON_BLOCKING) == 0) { + #ifndef MA_NO_THREADING + { + ma_semaphore_wait(&pQueue->sem); + } + #else + { + MA_ASSERT(MA_FALSE); /* Should never get here. Should have been checked at initialization time. */ + } + #endif + } + + #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE + ma_spinlock_lock(&pQueue->lock); + #endif + { + /* + BUG: In lock-free mode, multiple threads can be in this section of code. The "head" variable in the loop below + is stored. One thread can fall through to the freeing of this item while another is still using "head" for the + retrieval of the "next" variable. + + The slot allocator might need to make use of some reference counting to ensure it's only truely freed when + there are no more references to the item. This must be fixed before removing these locks. + */ + + /* Now we need to remove the root item from the list. */ + for (;;) { + head = ma_atomic_load_64(&pQueue->head); + tail = ma_atomic_load_64(&pQueue->tail); + next = ma_atomic_load_64(&pQueue->pJobs[ma_job_extract_slot(head)].next); + + if (ma_job_toc_to_allocation(head) == ma_job_toc_to_allocation(ma_atomic_load_64(&pQueue->head))) { + if (ma_job_extract_slot(head) == ma_job_extract_slot(tail)) { + if (ma_job_extract_slot(next) == 0xFFFF) { + #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE + ma_spinlock_unlock(&pQueue->lock); + #endif + return MA_NO_DATA_AVAILABLE; + } + ma_job_queue_cas(&pQueue->tail, tail, ma_job_extract_slot(next)); + } else { + *pJob = pQueue->pJobs[ma_job_extract_slot(next)]; + if (ma_job_queue_cas(&pQueue->head, head, ma_job_extract_slot(next))) { + break; + } + } + } + } + } + #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE + ma_spinlock_unlock(&pQueue->lock); + #endif + + ma_slot_allocator_free(&pQueue->allocator, head); + + /* + If it's a quit job make sure it's put back on the queue to ensure other threads have an opportunity to detect it and terminate naturally. We + could instead just leave it on the queue, but that would involve fiddling with the lock-free code above and I want to keep that as simple as + possible. + */ + if (pJob->toc.breakup.code == MA_JOB_TYPE_QUIT) { + ma_job_queue_post(pQueue, pJob); + return MA_CANCELLED; /* Return a cancelled status just in case the thread is checking return codes and not properly checking for a quit job. */ + } + + return MA_SUCCESS; +} + + + +/******************************************************************************* + +Dynamic Linking + +*******************************************************************************/ +#ifdef MA_POSIX + /* No need for dlfcn.h if we're not using runtime linking. */ + #ifndef MA_NO_RUNTIME_LINKING + #include + #endif +#endif + +MA_API ma_handle ma_dlopen(ma_log* pLog, const char* filename) +{ +#ifndef MA_NO_RUNTIME_LINKING + ma_handle handle; + + ma_log_postf(pLog, MA_LOG_LEVEL_DEBUG, "Loading library: %s\n", filename); + + #ifdef MA_WIN32 + /* From MSDN: Desktop applications cannot use LoadPackagedLibrary; if a desktop application calls this function it fails with APPMODEL_ERROR_NO_PACKAGE.*/ + #if !defined(MA_WIN32_UWP) || !(defined(WINAPI_FAMILY) && ((defined(WINAPI_FAMILY_PHONE_APP) && WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP))) + handle = (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) { + handle = NULL; + } else { + handle = (ma_handle)LoadPackagedLibrary(filenameW, 0); + } + #endif + #else + handle = (ma_handle)dlopen(filename, RTLD_NOW); + #endif + + /* + I'm not considering failure to load a library an error nor a warning because seamlessly falling through to a lower-priority + backend is a deliberate design choice. Instead I'm logging it as an informational message. + */ + if (handle == NULL) { + ma_log_postf(pLog, MA_LOG_LEVEL_INFO, "Failed to load library: %s\n", filename); + } + + return handle; +#else + /* Runtime linking is disabled. */ + (void)pLog; + (void)filename; + return NULL; +#endif +} + +MA_API void ma_dlclose(ma_log* pLog, ma_handle handle) +{ +#ifndef MA_NO_RUNTIME_LINKING + #ifdef MA_WIN32 + FreeLibrary((HMODULE)handle); + #else + dlclose((void*)handle); + #endif + + (void)pLog; +#else + /* Runtime linking is disabled. */ + (void)pLog; + (void)handle; +#endif +} + +MA_API ma_proc ma_dlsym(ma_log* pLog, ma_handle handle, const char* symbol) +{ +#ifndef MA_NO_RUNTIME_LINKING + ma_proc proc; + + ma_log_postf(pLog, MA_LOG_LEVEL_DEBUG, "Loading symbol: %s\n", symbol); + +#ifdef _WIN32 + proc = (ma_proc)GetProcAddress((HMODULE)handle, symbol); +#else +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wpedantic" +#endif + proc = (ma_proc)dlsym((void*)handle, symbol); +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)) + #pragma GCC diagnostic pop +#endif +#endif + + if (proc == NULL) { + ma_log_postf(pLog, MA_LOG_LEVEL_WARNING, "Failed to load symbol: %s\n", symbol); + } + + (void)pLog; /* It's possible for pContext to be unused. */ + return proc; +#else + /* Runtime linking is disabled. */ + (void)pLog; + (void)handle; + (void)symbol; + return NULL; +#endif +} + + + +/************************************************************************************************************************************************************ +************************************************************************************************************************************************************* + +DEVICE I/O +========== + +************************************************************************************************************************************************************* +************************************************************************************************************************************************************/ + +/* Disable run-time linking on certain backends and platforms. */ +#ifndef MA_NO_RUNTIME_LINKING + #if defined(MA_EMSCRIPTEN) || defined(MA_ORBIS) || defined(MA_PROSPERO) + #define MA_NO_RUNTIME_LINKING + #endif +#endif + +#ifndef MA_NO_DEVICE_IO + +#if defined(MA_APPLE) && (__MAC_OS_X_VERSION_MIN_REQUIRED < 101200) + #include /* For mach_absolute_time() */ +#endif + +#ifdef MA_POSIX + #include + #include + + /* No need for dlfcn.h if we're not using runtime linking. */ + #ifndef MA_NO_RUNTIME_LINKING + #include + #endif +#endif + + + +MA_API void ma_device_info_add_native_data_format(ma_device_info* pDeviceInfo, ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 flags) +{ + if (pDeviceInfo == NULL) { + return; + } + + if (pDeviceInfo->nativeDataFormatCount < ma_countof(pDeviceInfo->nativeDataFormats)) { + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = format; + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels; + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = sampleRate; + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = flags; + pDeviceInfo->nativeDataFormatCount += 1; + } +} + + +typedef struct +{ + ma_backend backend; + const char* pName; +} ma_backend_info; + +static ma_backend_info gBackendInfo[] = /* Indexed by the backend enum. Must be in the order backends are declared in the ma_backend enum. */ +{ + {ma_backend_wasapi, "WASAPI"}, + {ma_backend_dsound, "DirectSound"}, + {ma_backend_winmm, "WinMM"}, + {ma_backend_coreaudio, "Core Audio"}, + {ma_backend_sndio, "sndio"}, + {ma_backend_audio4, "audio(4)"}, + {ma_backend_oss, "OSS"}, + {ma_backend_pulseaudio, "PulseAudio"}, + {ma_backend_alsa, "ALSA"}, + {ma_backend_jack, "JACK"}, + {ma_backend_aaudio, "AAudio"}, + {ma_backend_opensl, "OpenSL|ES"}, + {ma_backend_webaudio, "Web Audio"}, + {ma_backend_custom, "Custom"}, + {ma_backend_null, "Null"} +}; + +MA_API const char* ma_get_backend_name(ma_backend backend) +{ + if (backend < 0 || backend >= (int)ma_countof(gBackendInfo)) { + return "Unknown"; + } + + return gBackendInfo[backend].pName; +} + +MA_API ma_result ma_get_backend_from_name(const char* pBackendName, ma_backend* pBackend) +{ + size_t iBackend; + + if (pBackendName == NULL) { + return MA_INVALID_ARGS; + } + + for (iBackend = 0; iBackend < ma_countof(gBackendInfo); iBackend += 1) { + if (ma_strcmp(pBackendName, gBackendInfo[iBackend].pName) == 0) { + if (pBackend != NULL) { + *pBackend = gBackendInfo[iBackend].backend; + } + + return MA_SUCCESS; + } + } + + /* Getting here means the backend name is unknown. */ + return MA_INVALID_ARGS; +} + +MA_API ma_bool32 ma_is_backend_enabled(ma_backend backend) +{ + /* + This looks a little bit gross, but we want all backends to be included in the switch to avoid warnings on some compilers + about some enums not being handled by the switch statement. + */ + switch (backend) + { + case ma_backend_wasapi: + #if defined(MA_HAS_WASAPI) + return MA_TRUE; + #else + return MA_FALSE; + #endif + case ma_backend_dsound: + #if defined(MA_HAS_DSOUND) + return MA_TRUE; + #else + return MA_FALSE; + #endif + case ma_backend_winmm: + #if defined(MA_HAS_WINMM) + return MA_TRUE; + #else + return MA_FALSE; + #endif + case ma_backend_coreaudio: + #if defined(MA_HAS_COREAUDIO) + return MA_TRUE; + #else + return MA_FALSE; + #endif + case ma_backend_sndio: + #if defined(MA_HAS_SNDIO) + return MA_TRUE; + #else + return MA_FALSE; + #endif + case ma_backend_audio4: + #if defined(MA_HAS_AUDIO4) + return MA_TRUE; + #else + return MA_FALSE; + #endif + case ma_backend_oss: + #if defined(MA_HAS_OSS) + return MA_TRUE; + #else + return MA_FALSE; + #endif + case ma_backend_pulseaudio: + #if defined(MA_HAS_PULSEAUDIO) + return MA_TRUE; + #else + return MA_FALSE; + #endif + case ma_backend_alsa: + #if defined(MA_HAS_ALSA) + return MA_TRUE; + #else + return MA_FALSE; + #endif + case ma_backend_jack: + #if defined(MA_HAS_JACK) + return MA_TRUE; + #else + return MA_FALSE; + #endif + case ma_backend_aaudio: + #if defined(MA_HAS_AAUDIO) + #if defined(MA_ANDROID) + { + return ma_android_sdk_version() >= 26; + } + #else + return MA_FALSE; + #endif + #else + return MA_FALSE; + #endif + case ma_backend_opensl: + #if defined(MA_HAS_OPENSL) + #if defined(MA_ANDROID) + { + return ma_android_sdk_version() >= 9; + } + #else + return MA_TRUE; + #endif + #else + return MA_FALSE; + #endif + case ma_backend_webaudio: + #if defined(MA_HAS_WEBAUDIO) + return MA_TRUE; + #else + return MA_FALSE; + #endif + case ma_backend_custom: + #if defined(MA_HAS_CUSTOM) + return MA_TRUE; + #else + return MA_FALSE; + #endif + case ma_backend_null: + #if defined(MA_HAS_NULL) + return MA_TRUE; + #else + return MA_FALSE; + #endif + + default: return MA_FALSE; + } +} + +MA_API ma_result ma_get_enabled_backends(ma_backend* pBackends, size_t backendCap, size_t* pBackendCount) +{ + size_t backendCount; + size_t iBackend; + ma_result result = MA_SUCCESS; + + if (pBackendCount == NULL) { + return MA_INVALID_ARGS; + } + + backendCount = 0; + + for (iBackend = 0; iBackend <= ma_backend_null; iBackend += 1) { + ma_backend backend = (ma_backend)iBackend; + + if (ma_is_backend_enabled(backend)) { + /* The backend is enabled. Try adding it to the list. If there's no room, MA_NO_SPACE needs to be returned. */ + if (backendCount == backendCap) { + result = MA_NO_SPACE; + break; + } else { + pBackends[backendCount] = backend; + backendCount += 1; + } + } + } + + if (pBackendCount != NULL) { + *pBackendCount = backendCount; + } + + return result; +} + +MA_API ma_bool32 ma_is_loopback_supported(ma_backend backend) +{ + switch (backend) + { + case ma_backend_wasapi: return MA_TRUE; + case ma_backend_dsound: return MA_FALSE; + case ma_backend_winmm: return MA_FALSE; + case ma_backend_coreaudio: return MA_FALSE; + case ma_backend_sndio: return MA_FALSE; + case ma_backend_audio4: return MA_FALSE; + case ma_backend_oss: return MA_FALSE; + case ma_backend_pulseaudio: return MA_FALSE; + case ma_backend_alsa: return MA_FALSE; + case ma_backend_jack: return MA_FALSE; + case ma_backend_aaudio: return MA_FALSE; + case ma_backend_opensl: return MA_FALSE; + case ma_backend_webaudio: return MA_FALSE; + case ma_backend_custom: return MA_FALSE; /* <-- Will depend on the implementation of the backend. */ + case ma_backend_null: return MA_FALSE; + default: return MA_FALSE; + } +} + + + +#if defined(MA_WIN32) +/* WASAPI error codes. */ +#define MA_AUDCLNT_E_NOT_INITIALIZED ((HRESULT)0x88890001) +#define MA_AUDCLNT_E_ALREADY_INITIALIZED ((HRESULT)0x88890002) +#define MA_AUDCLNT_E_WRONG_ENDPOINT_TYPE ((HRESULT)0x88890003) +#define MA_AUDCLNT_E_DEVICE_INVALIDATED ((HRESULT)0x88890004) +#define MA_AUDCLNT_E_NOT_STOPPED ((HRESULT)0x88890005) +#define MA_AUDCLNT_E_BUFFER_TOO_LARGE ((HRESULT)0x88890006) +#define MA_AUDCLNT_E_OUT_OF_ORDER ((HRESULT)0x88890007) +#define MA_AUDCLNT_E_UNSUPPORTED_FORMAT ((HRESULT)0x88890008) +#define MA_AUDCLNT_E_INVALID_SIZE ((HRESULT)0x88890009) +#define MA_AUDCLNT_E_DEVICE_IN_USE ((HRESULT)0x8889000A) +#define MA_AUDCLNT_E_BUFFER_OPERATION_PENDING ((HRESULT)0x8889000B) +#define MA_AUDCLNT_E_THREAD_NOT_REGISTERED ((HRESULT)0x8889000C) +#define MA_AUDCLNT_E_NO_SINGLE_PROCESS ((HRESULT)0x8889000D) +#define MA_AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED ((HRESULT)0x8889000E) +#define MA_AUDCLNT_E_ENDPOINT_CREATE_FAILED ((HRESULT)0x8889000F) +#define MA_AUDCLNT_E_SERVICE_NOT_RUNNING ((HRESULT)0x88890010) +#define MA_AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED ((HRESULT)0x88890011) +#define MA_AUDCLNT_E_EXCLUSIVE_MODE_ONLY ((HRESULT)0x88890012) +#define MA_AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL ((HRESULT)0x88890013) +#define MA_AUDCLNT_E_EVENTHANDLE_NOT_SET ((HRESULT)0x88890014) +#define MA_AUDCLNT_E_INCORRECT_BUFFER_SIZE ((HRESULT)0x88890015) +#define MA_AUDCLNT_E_BUFFER_SIZE_ERROR ((HRESULT)0x88890016) +#define MA_AUDCLNT_E_CPUUSAGE_EXCEEDED ((HRESULT)0x88890017) +#define MA_AUDCLNT_E_BUFFER_ERROR ((HRESULT)0x88890018) +#define MA_AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED ((HRESULT)0x88890019) +#define MA_AUDCLNT_E_INVALID_DEVICE_PERIOD ((HRESULT)0x88890020) +#define MA_AUDCLNT_E_INVALID_STREAM_FLAG ((HRESULT)0x88890021) +#define MA_AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE ((HRESULT)0x88890022) +#define MA_AUDCLNT_E_OUT_OF_OFFLOAD_RESOURCES ((HRESULT)0x88890023) +#define MA_AUDCLNT_E_OFFLOAD_MODE_ONLY ((HRESULT)0x88890024) +#define MA_AUDCLNT_E_NONOFFLOAD_MODE_ONLY ((HRESULT)0x88890025) +#define MA_AUDCLNT_E_RESOURCES_INVALIDATED ((HRESULT)0x88890026) +#define MA_AUDCLNT_E_RAW_MODE_UNSUPPORTED ((HRESULT)0x88890027) +#define MA_AUDCLNT_E_ENGINE_PERIODICITY_LOCKED ((HRESULT)0x88890028) +#define MA_AUDCLNT_E_ENGINE_FORMAT_LOCKED ((HRESULT)0x88890029) +#define MA_AUDCLNT_E_HEADTRACKING_ENABLED ((HRESULT)0x88890030) +#define MA_AUDCLNT_E_HEADTRACKING_UNSUPPORTED ((HRESULT)0x88890040) +#define MA_AUDCLNT_S_BUFFER_EMPTY ((HRESULT)0x08890001) +#define MA_AUDCLNT_S_THREAD_ALREADY_REGISTERED ((HRESULT)0x08890002) +#define MA_AUDCLNT_S_POSITION_STALLED ((HRESULT)0x08890003) + +#define MA_DS_OK ((HRESULT)0) +#define MA_DS_NO_VIRTUALIZATION ((HRESULT)0x0878000A) +#define MA_DSERR_ALLOCATED ((HRESULT)0x8878000A) +#define MA_DSERR_CONTROLUNAVAIL ((HRESULT)0x8878001E) +#define MA_DSERR_INVALIDPARAM ((HRESULT)0x80070057) /*E_INVALIDARG*/ +#define MA_DSERR_INVALIDCALL ((HRESULT)0x88780032) +#define MA_DSERR_GENERIC ((HRESULT)0x80004005) /*E_FAIL*/ +#define MA_DSERR_PRIOLEVELNEEDED ((HRESULT)0x88780046) +#define MA_DSERR_OUTOFMEMORY ((HRESULT)0x8007000E) /*E_OUTOFMEMORY*/ +#define MA_DSERR_BADFORMAT ((HRESULT)0x88780064) +#define MA_DSERR_UNSUPPORTED ((HRESULT)0x80004001) /*E_NOTIMPL*/ +#define MA_DSERR_NODRIVER ((HRESULT)0x88780078) +#define MA_DSERR_ALREADYINITIALIZED ((HRESULT)0x88780082) +#define MA_DSERR_NOAGGREGATION ((HRESULT)0x80040110) /*CLASS_E_NOAGGREGATION*/ +#define MA_DSERR_BUFFERLOST ((HRESULT)0x88780096) +#define MA_DSERR_OTHERAPPHASPRIO ((HRESULT)0x887800A0) +#define MA_DSERR_UNINITIALIZED ((HRESULT)0x887800AA) +#define MA_DSERR_NOINTERFACE ((HRESULT)0x80004002) /*E_NOINTERFACE*/ +#define MA_DSERR_ACCESSDENIED ((HRESULT)0x80070005) /*E_ACCESSDENIED*/ +#define MA_DSERR_BUFFERTOOSMALL ((HRESULT)0x887800B4) +#define MA_DSERR_DS8_REQUIRED ((HRESULT)0x887800BE) +#define MA_DSERR_SENDLOOP ((HRESULT)0x887800C8) +#define MA_DSERR_BADSENDBUFFERGUID ((HRESULT)0x887800D2) +#define MA_DSERR_OBJECTNOTFOUND ((HRESULT)0x88781161) +#define MA_DSERR_FXUNAVAILABLE ((HRESULT)0x887800DC) + +static ma_result ma_result_from_HRESULT(HRESULT hr) +{ + switch (hr) + { + case NOERROR: return MA_SUCCESS; + /*case S_OK: return MA_SUCCESS;*/ + + case E_POINTER: return MA_INVALID_ARGS; + case E_UNEXPECTED: return MA_ERROR; + case E_NOTIMPL: return MA_NOT_IMPLEMENTED; + case E_OUTOFMEMORY: return MA_OUT_OF_MEMORY; + case E_INVALIDARG: return MA_INVALID_ARGS; + case E_NOINTERFACE: return MA_API_NOT_FOUND; + case E_HANDLE: return MA_INVALID_ARGS; + case E_ABORT: return MA_ERROR; + case E_FAIL: return MA_ERROR; + case E_ACCESSDENIED: return MA_ACCESS_DENIED; + + /* WASAPI */ + case MA_AUDCLNT_E_NOT_INITIALIZED: return MA_DEVICE_NOT_INITIALIZED; + case MA_AUDCLNT_E_ALREADY_INITIALIZED: return MA_DEVICE_ALREADY_INITIALIZED; + case MA_AUDCLNT_E_WRONG_ENDPOINT_TYPE: return MA_INVALID_ARGS; + case MA_AUDCLNT_E_DEVICE_INVALIDATED: return MA_UNAVAILABLE; + case MA_AUDCLNT_E_NOT_STOPPED: return MA_DEVICE_NOT_STOPPED; + case MA_AUDCLNT_E_BUFFER_TOO_LARGE: return MA_TOO_BIG; + case MA_AUDCLNT_E_OUT_OF_ORDER: return MA_INVALID_OPERATION; + case MA_AUDCLNT_E_UNSUPPORTED_FORMAT: return MA_FORMAT_NOT_SUPPORTED; + case MA_AUDCLNT_E_INVALID_SIZE: return MA_INVALID_ARGS; + case MA_AUDCLNT_E_DEVICE_IN_USE: return MA_BUSY; + case MA_AUDCLNT_E_BUFFER_OPERATION_PENDING: return MA_INVALID_OPERATION; + case MA_AUDCLNT_E_THREAD_NOT_REGISTERED: return MA_DOES_NOT_EXIST; + case MA_AUDCLNT_E_NO_SINGLE_PROCESS: return MA_INVALID_OPERATION; + case MA_AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: return MA_SHARE_MODE_NOT_SUPPORTED; + case MA_AUDCLNT_E_ENDPOINT_CREATE_FAILED: return MA_FAILED_TO_OPEN_BACKEND_DEVICE; + case MA_AUDCLNT_E_SERVICE_NOT_RUNNING: return MA_NOT_CONNECTED; + case MA_AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: return MA_INVALID_ARGS; + case MA_AUDCLNT_E_EXCLUSIVE_MODE_ONLY: return MA_SHARE_MODE_NOT_SUPPORTED; + case MA_AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: return MA_INVALID_ARGS; + case MA_AUDCLNT_E_EVENTHANDLE_NOT_SET: return MA_INVALID_ARGS; + case MA_AUDCLNT_E_INCORRECT_BUFFER_SIZE: return MA_INVALID_ARGS; + case MA_AUDCLNT_E_BUFFER_SIZE_ERROR: return MA_INVALID_ARGS; + case MA_AUDCLNT_E_CPUUSAGE_EXCEEDED: return MA_ERROR; + case MA_AUDCLNT_E_BUFFER_ERROR: return MA_ERROR; + case MA_AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED: return MA_INVALID_ARGS; + case MA_AUDCLNT_E_INVALID_DEVICE_PERIOD: return MA_INVALID_ARGS; + case MA_AUDCLNT_E_INVALID_STREAM_FLAG: return MA_INVALID_ARGS; + case MA_AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE: return MA_INVALID_OPERATION; + case MA_AUDCLNT_E_OUT_OF_OFFLOAD_RESOURCES: return MA_OUT_OF_MEMORY; + case MA_AUDCLNT_E_OFFLOAD_MODE_ONLY: return MA_INVALID_OPERATION; + case MA_AUDCLNT_E_NONOFFLOAD_MODE_ONLY: return MA_INVALID_OPERATION; + case MA_AUDCLNT_E_RESOURCES_INVALIDATED: return MA_INVALID_DATA; + case MA_AUDCLNT_E_RAW_MODE_UNSUPPORTED: return MA_INVALID_OPERATION; + case MA_AUDCLNT_E_ENGINE_PERIODICITY_LOCKED: return MA_INVALID_OPERATION; + case MA_AUDCLNT_E_ENGINE_FORMAT_LOCKED: return MA_INVALID_OPERATION; + case MA_AUDCLNT_E_HEADTRACKING_ENABLED: return MA_INVALID_OPERATION; + case MA_AUDCLNT_E_HEADTRACKING_UNSUPPORTED: return MA_INVALID_OPERATION; + case MA_AUDCLNT_S_BUFFER_EMPTY: return MA_NO_SPACE; + case MA_AUDCLNT_S_THREAD_ALREADY_REGISTERED: return MA_ALREADY_EXISTS; + case MA_AUDCLNT_S_POSITION_STALLED: return MA_ERROR; + + /* DirectSound */ + /*case MA_DS_OK: return MA_SUCCESS;*/ /* S_OK */ + case MA_DS_NO_VIRTUALIZATION: return MA_SUCCESS; + case MA_DSERR_ALLOCATED: return MA_ALREADY_IN_USE; + case MA_DSERR_CONTROLUNAVAIL: return MA_INVALID_OPERATION; + /*case MA_DSERR_INVALIDPARAM: return MA_INVALID_ARGS;*/ /* E_INVALIDARG */ + case MA_DSERR_INVALIDCALL: return MA_INVALID_OPERATION; + /*case MA_DSERR_GENERIC: return MA_ERROR;*/ /* E_FAIL */ + case MA_DSERR_PRIOLEVELNEEDED: return MA_INVALID_OPERATION; + /*case MA_DSERR_OUTOFMEMORY: return MA_OUT_OF_MEMORY;*/ /* E_OUTOFMEMORY */ + case MA_DSERR_BADFORMAT: return MA_FORMAT_NOT_SUPPORTED; + /*case MA_DSERR_UNSUPPORTED: return MA_NOT_IMPLEMENTED;*/ /* E_NOTIMPL */ + case MA_DSERR_NODRIVER: return MA_FAILED_TO_INIT_BACKEND; + case MA_DSERR_ALREADYINITIALIZED: return MA_DEVICE_ALREADY_INITIALIZED; + case MA_DSERR_NOAGGREGATION: return MA_ERROR; + case MA_DSERR_BUFFERLOST: return MA_UNAVAILABLE; + case MA_DSERR_OTHERAPPHASPRIO: return MA_ACCESS_DENIED; + case MA_DSERR_UNINITIALIZED: return MA_DEVICE_NOT_INITIALIZED; + /*case MA_DSERR_NOINTERFACE: return MA_API_NOT_FOUND;*/ /* E_NOINTERFACE */ + /*case MA_DSERR_ACCESSDENIED: return MA_ACCESS_DENIED;*/ /* E_ACCESSDENIED */ + case MA_DSERR_BUFFERTOOSMALL: return MA_NO_SPACE; + case MA_DSERR_DS8_REQUIRED: return MA_INVALID_OPERATION; + case MA_DSERR_SENDLOOP: return MA_DEADLOCK; + case MA_DSERR_BADSENDBUFFERGUID: return MA_INVALID_ARGS; + case MA_DSERR_OBJECTNOTFOUND: return MA_NO_DEVICE; + case MA_DSERR_FXUNAVAILABLE: return MA_UNAVAILABLE; + + default: return MA_ERROR; + } +} + +/* PROPVARIANT */ +#define MA_VT_LPWSTR 31 +#define MA_VT_BLOB 65 + +#if defined(_MSC_VER) && !defined(__clang__) + #pragma warning(push) + #pragma warning(disable:4201) /* nonstandard extension used: nameless struct/union */ +#elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wpedantic" /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */ + #if defined(__clang__) + #pragma GCC diagnostic ignored "-Wc11-extensions" /* anonymous unions are a C11 extension */ + #endif +#endif +typedef struct +{ + WORD vt; + WORD wReserved1; + WORD wReserved2; + WORD wReserved3; + union + { + struct + { + ULONG cbSize; + BYTE* pBlobData; + } blob; + WCHAR* pwszVal; + char pad[16]; /* Just to ensure the size of the struct matches the official version. */ + }; +} MA_PROPVARIANT; +#if defined(_MSC_VER) && !defined(__clang__) + #pragma warning(pop) +#elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))) + #pragma GCC diagnostic pop +#endif + +typedef HRESULT (WINAPI * MA_PFN_CoInitialize)(void* pvReserved); +typedef HRESULT (WINAPI * MA_PFN_CoInitializeEx)(void* pvReserved, DWORD dwCoInit); +typedef void (WINAPI * MA_PFN_CoUninitialize)(void); +typedef HRESULT (WINAPI * MA_PFN_CoCreateInstance)(const IID* rclsid, void* pUnkOuter, DWORD dwClsContext, const IID* riid, void* ppv); +typedef void (WINAPI * MA_PFN_CoTaskMemFree)(void* pv); +typedef HRESULT (WINAPI * MA_PFN_PropVariantClear)(MA_PROPVARIANT *pvar); +typedef int (WINAPI * MA_PFN_StringFromGUID2)(const GUID* const rguid, WCHAR* lpsz, int cchMax); + +typedef HWND (WINAPI * MA_PFN_GetForegroundWindow)(void); +typedef HWND (WINAPI * MA_PFN_GetDesktopWindow)(void); + +#if defined(MA_WIN32_DESKTOP) +/* 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, const char* lpSubKey, DWORD ulOptions, DWORD samDesired, HKEY* phkResult); +typedef LONG (WINAPI * MA_PFN_RegCloseKey)(HKEY hKey); +typedef LONG (WINAPI * MA_PFN_RegQueryValueExA)(HKEY hKey, const char* lpValueName, DWORD* lpReserved, DWORD* lpType, BYTE* lpData, DWORD* lpcbData); +#endif /* MA_WIN32_DESKTOP */ + + +MA_API size_t ma_strlen_WCHAR(const WCHAR* str) +{ + size_t len = 0; + while (str[len] != '\0') { + len += 1; + } + + return len; +} + +MA_API int ma_strcmp_WCHAR(const WCHAR *s1, const WCHAR *s2) +{ + while (*s1 != '\0' && *s1 == *s2) { + s1 += 1; + s2 += 1; + } + + return *s1 - *s2; +} + +MA_API int ma_strcpy_s_WCHAR(WCHAR* dst, size_t dstCap, const WCHAR* src) +{ + size_t i; + + if (dst == 0) { + return 22; + } + if (dstCap == 0) { + return 34; + } + if (src == 0) { + dst[0] = '\0'; + return 22; + } + + for (i = 0; i < dstCap && src[i] != '\0'; ++i) { + dst[i] = src[i]; + } + + if (i < dstCap) { + dst[i] = '\0'; + return 0; + } + + dst[0] = '\0'; + return 34; +} +#endif /* MA_WIN32 */ + + +#define MA_DEFAULT_PLAYBACK_DEVICE_NAME "Default Playback Device" +#define MA_DEFAULT_CAPTURE_DEVICE_NAME "Default Capture Device" + + + + +/******************************************************************************* + +Timing + +*******************************************************************************/ +#if defined(MA_WIN32) && !defined(MA_POSIX) + static LARGE_INTEGER g_ma_TimerFrequency; /* <-- Initialized to zero since it's static. */ + static void ma_timer_init(ma_timer* pTimer) + { + LARGE_INTEGER counter; + + if (g_ma_TimerFrequency.QuadPart == 0) { + QueryPerformanceFrequency(&g_ma_TimerFrequency); + } + + QueryPerformanceCounter(&counter); + pTimer->counter = counter.QuadPart; + } + + static 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) + static ma_uint64 g_ma_TimerFrequency = 0; + static 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(); + } + + static 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) + static MA_INLINE void ma_timer_init(ma_timer* pTimer) + { + pTimer->counterD = emscripten_get_now(); + } + + static MA_INLINE double ma_timer_get_time_in_seconds(ma_timer* pTimer) + { + return (emscripten_get_now() - pTimer->counterD) / 1000; /* Emscripten is in milliseconds. */ + } +#else + #if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309L + #if defined(CLOCK_MONOTONIC) + #define MA_CLOCK_ID CLOCK_MONOTONIC + #else + #define MA_CLOCK_ID CLOCK_REALTIME + #endif + + static 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; + } + + static 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); + + newTimeCounter = (newTime.tv_sec * 1000000000) + newTime.tv_nsec; + oldTimeCounter = pTimer->counter; + + return (newTimeCounter - oldTimeCounter) / 1000000000.0; + } + #else + static void ma_timer_init(ma_timer* pTimer) + { + struct timeval newTime; + gettimeofday(&newTime, NULL); + + pTimer->counter = (newTime.tv_sec * 1000000) + newTime.tv_usec; + } + + static double ma_timer_get_time_in_seconds(ma_timer* pTimer) + { + ma_uint64 newTimeCounter; + ma_uint64 oldTimeCounter; + + struct timeval newTime; + gettimeofday(&newTime, NULL); + + newTimeCounter = (newTime.tv_sec * 1000000) + newTime.tv_usec; + oldTimeCounter = pTimer->counter; + + return (newTimeCounter - oldTimeCounter) / 1000000.0; + } + #endif +#endif + + + +#if 0 +static ma_uint32 ma_get_closest_standard_sample_rate(ma_uint32 sampleRateIn) +{ + ma_uint32 closestRate = 0; + ma_uint32 closestDiff = 0xFFFFFFFF; + size_t 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 { + 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; +} +#endif + + +static MA_INLINE unsigned int ma_device_disable_denormals(ma_device* pDevice) +{ + MA_ASSERT(pDevice != NULL); + + if (!pDevice->noDisableDenormals) { + return ma_disable_denormals(); + } else { + return 0; + } +} + +static MA_INLINE void ma_device_restore_denormals(ma_device* pDevice, unsigned int prevState) +{ + MA_ASSERT(pDevice != NULL); + + if (!pDevice->noDisableDenormals) { + ma_restore_denormals(prevState); + } else { + /* Do nothing. */ + (void)prevState; + } +} + +static ma_device_notification ma_device_notification_init(ma_device* pDevice, ma_device_notification_type type) +{ + ma_device_notification notification; + + MA_ZERO_OBJECT(¬ification); + notification.pDevice = pDevice; + notification.type = type; + + return notification; +} + +static void ma_device__on_notification(ma_device_notification notification) +{ + MA_ASSERT(notification.pDevice != NULL); + + if (notification.pDevice->onNotification != NULL) { + notification.pDevice->onNotification(¬ification); + } + + /* TEMP FOR COMPATIBILITY: If it's a stopped notification, fire the onStop callback as well. This is only for backwards compatibility and will be removed. */ + if (notification.pDevice->onStop != NULL && notification.type == ma_device_notification_type_stopped) { + notification.pDevice->onStop(notification.pDevice); + } +} + +static void ma_device__on_notification_started(ma_device* pDevice) +{ + ma_device__on_notification(ma_device_notification_init(pDevice, ma_device_notification_type_started)); +} + +static void ma_device__on_notification_stopped(ma_device* pDevice) +{ + ma_device__on_notification(ma_device_notification_init(pDevice, ma_device_notification_type_stopped)); +} + +/* Not all platforms support reroute notifications. */ +#if !defined(MA_EMSCRIPTEN) +static void ma_device__on_notification_rerouted(ma_device* pDevice) +{ + ma_device__on_notification(ma_device_notification_init(pDevice, ma_device_notification_type_rerouted)); +} +#endif + +#if defined(MA_EMSCRIPTEN) +EMSCRIPTEN_KEEPALIVE +void ma_device__on_notification_unlocked(ma_device* pDevice) +{ + ma_device__on_notification(ma_device_notification_init(pDevice, ma_device_notification_type_unlocked)); +} +#endif + + +static void ma_device__on_data_inner(ma_device* pDevice, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount) +{ + MA_ASSERT(pDevice != NULL); + MA_ASSERT(pDevice->onData != NULL); + + if (!pDevice->noPreSilencedOutputBuffer && pFramesOut != NULL) { + ma_silence_pcm_frames(pFramesOut, frameCount, pDevice->playback.format, pDevice->playback.channels); + } + + pDevice->onData(pDevice, pFramesOut, pFramesIn, frameCount); +} + +static void ma_device__on_data(ma_device* pDevice, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount) +{ + MA_ASSERT(pDevice != NULL); + + /* Don't read more data from the client if we're in the process of stopping. */ + if (ma_device_get_state(pDevice) == ma_device_state_stopping) { + return; + } + + if (pDevice->noFixedSizedCallback) { + /* Fast path. Not using a fixed sized callback. Process directly from the specified buffers. */ + ma_device__on_data_inner(pDevice, pFramesOut, pFramesIn, frameCount); + } else { + /* Slow path. Using a fixed sized callback. Need to use the intermediary buffer. */ + ma_uint32 totalFramesProcessed = 0; + + while (totalFramesProcessed < frameCount) { + ma_uint32 totalFramesRemaining = frameCount - totalFramesProcessed; + ma_uint32 framesToProcessThisIteration = 0; + + if (pFramesIn != NULL) { + /* Capturing. Write to the intermediary buffer. If there's no room, fire the callback to empty it. */ + if (pDevice->capture.intermediaryBufferLen < pDevice->capture.intermediaryBufferCap) { + /* There's some room left in the intermediary buffer. Write to it without firing the callback. */ + framesToProcessThisIteration = totalFramesRemaining; + if (framesToProcessThisIteration > pDevice->capture.intermediaryBufferCap - pDevice->capture.intermediaryBufferLen) { + framesToProcessThisIteration = pDevice->capture.intermediaryBufferCap - pDevice->capture.intermediaryBufferLen; + } + + ma_copy_pcm_frames( + ma_offset_pcm_frames_ptr(pDevice->capture.pIntermediaryBuffer, pDevice->capture.intermediaryBufferLen, pDevice->capture.format, pDevice->capture.channels), + ma_offset_pcm_frames_const_ptr(pFramesIn, totalFramesProcessed, pDevice->capture.format, pDevice->capture.channels), + framesToProcessThisIteration, + pDevice->capture.format, pDevice->capture.channels); + + pDevice->capture.intermediaryBufferLen += framesToProcessThisIteration; + } + + if (pDevice->capture.intermediaryBufferLen == pDevice->capture.intermediaryBufferCap) { + /* No room left in the intermediary buffer. Fire the data callback. */ + if (pDevice->type == ma_device_type_duplex) { + /* We'll do the duplex data callback later after we've processed the playback data. */ + } else { + ma_device__on_data_inner(pDevice, NULL, pDevice->capture.pIntermediaryBuffer, pDevice->capture.intermediaryBufferCap); + + /* The intermediary buffer has just been drained. */ + pDevice->capture.intermediaryBufferLen = 0; + } + } + } + + if (pFramesOut != NULL) { + /* Playing back. Read from the intermediary buffer. If there's nothing in it, fire the callback to fill it. */ + if (pDevice->playback.intermediaryBufferLen > 0) { + /* There's some content in the intermediary buffer. Read from that without firing the callback. */ + if (pDevice->type == ma_device_type_duplex) { + /* The frames processed this iteration for a duplex device will always be based on the capture side. Leave it unmodified. */ + } else { + framesToProcessThisIteration = totalFramesRemaining; + if (framesToProcessThisIteration > pDevice->playback.intermediaryBufferLen) { + framesToProcessThisIteration = pDevice->playback.intermediaryBufferLen; + } + } + + ma_copy_pcm_frames( + ma_offset_pcm_frames_ptr(pFramesOut, totalFramesProcessed, pDevice->playback.format, pDevice->playback.channels), + ma_offset_pcm_frames_ptr(pDevice->playback.pIntermediaryBuffer, pDevice->playback.intermediaryBufferCap - pDevice->playback.intermediaryBufferLen, pDevice->playback.format, pDevice->playback.channels), + framesToProcessThisIteration, + pDevice->playback.format, pDevice->playback.channels); + + pDevice->playback.intermediaryBufferLen -= framesToProcessThisIteration; + } + + if (pDevice->playback.intermediaryBufferLen == 0) { + /* There's nothing in the intermediary buffer. Fire the data callback to fill it. */ + if (pDevice->type == ma_device_type_duplex) { + /* In duplex mode, the data callback will be fired later. Nothing to do here. */ + } else { + ma_device__on_data_inner(pDevice, pDevice->playback.pIntermediaryBuffer, NULL, pDevice->playback.intermediaryBufferCap); + + /* The intermediary buffer has just been filled. */ + pDevice->playback.intermediaryBufferLen = pDevice->playback.intermediaryBufferCap; + } + } + } + + /* If we're in duplex mode we might need to do a refill of the data. */ + if (pDevice->type == ma_device_type_duplex) { + if (pDevice->capture.intermediaryBufferLen == pDevice->capture.intermediaryBufferCap) { + ma_device__on_data_inner(pDevice, pDevice->playback.pIntermediaryBuffer, pDevice->capture.pIntermediaryBuffer, pDevice->capture.intermediaryBufferCap); + + pDevice->playback.intermediaryBufferLen = pDevice->playback.intermediaryBufferCap; /* The playback buffer will have just been filled. */ + pDevice->capture.intermediaryBufferLen = 0; /* The intermediary buffer has just been drained. */ + } + } + + /* Make sure this is only incremented once in the duplex case. */ + totalFramesProcessed += framesToProcessThisIteration; + } + } +} + +static void ma_device__handle_data_callback(ma_device* pDevice, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount) +{ + float masterVolumeFactor; + + ma_device_get_master_volume(pDevice, &masterVolumeFactor); /* Use ma_device_get_master_volume() to ensure the volume is loaded atomically. */ + + if (pDevice->onData) { + unsigned int prevDenormalState = ma_device_disable_denormals(pDevice); + { + /* Volume control of input makes things a bit awkward because the input buffer is read-only. We'll need to use a temp buffer and loop in this case. */ + if (pFramesIn != NULL && masterVolumeFactor < 1) { + ma_uint8 tempFramesIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; + ma_uint32 bpfCapture = ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels); + ma_uint32 bpfPlayback = ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels); + ma_uint32 totalFramesProcessed = 0; + while (totalFramesProcessed < frameCount) { + ma_uint32 framesToProcessThisIteration = frameCount - totalFramesProcessed; + if (framesToProcessThisIteration > sizeof(tempFramesIn)/bpfCapture) { + framesToProcessThisIteration = sizeof(tempFramesIn)/bpfCapture; + } + + ma_copy_and_apply_volume_factor_pcm_frames(tempFramesIn, ma_offset_ptr(pFramesIn, totalFramesProcessed*bpfCapture), framesToProcessThisIteration, pDevice->capture.format, pDevice->capture.channels, masterVolumeFactor); + + ma_device__on_data(pDevice, ma_offset_ptr(pFramesOut, totalFramesProcessed*bpfPlayback), tempFramesIn, framesToProcessThisIteration); + + totalFramesProcessed += framesToProcessThisIteration; + } + } else { + ma_device__on_data(pDevice, pFramesOut, pFramesIn, frameCount); + } + + /* Volume control and clipping for playback devices. */ + if (pFramesOut != NULL) { + if (masterVolumeFactor < 1) { + if (pFramesIn == NULL) { /* <-- In full-duplex situations, the volume will have been applied to the input samples before the data callback. Applying it again post-callback will incorrectly compound it. */ + ma_apply_volume_factor_pcm_frames(pFramesOut, frameCount, pDevice->playback.format, pDevice->playback.channels, masterVolumeFactor); + } + } + + if (!pDevice->noClip && pDevice->playback.format == ma_format_f32) { + ma_clip_samples_f32((float*)pFramesOut, (const float*)pFramesOut, frameCount * pDevice->playback.channels); /* Intentionally specifying the same pointer for both input and output for in-place processing. */ + } + } + } + ma_device_restore_denormals(pDevice, prevDenormalState); + } +} + + + +/* A helper function for reading sample data from the client. */ +static void ma_device__read_frames_from_client(ma_device* pDevice, ma_uint32 frameCount, void* pFramesOut) +{ + MA_ASSERT(pDevice != NULL); + MA_ASSERT(frameCount > 0); + MA_ASSERT(pFramesOut != NULL); + + if (pDevice->playback.converter.isPassthrough) { + ma_device__handle_data_callback(pDevice, pFramesOut, NULL, frameCount); + } else { + ma_result result; + ma_uint64 totalFramesReadOut; + void* pRunningFramesOut; + + totalFramesReadOut = 0; + pRunningFramesOut = pFramesOut; + + /* + We run slightly different logic depending on whether or not we're using a heap-allocated + buffer for caching input data. This will be the case if the data converter does not have + the ability to retrieve the required input frame count for a given output frame count. + */ + if (pDevice->playback.pInputCache != NULL) { + while (totalFramesReadOut < frameCount) { + ma_uint64 framesToReadThisIterationIn; + ma_uint64 framesToReadThisIterationOut; + + /* If there's any data available in the cache, that needs to get processed first. */ + if (pDevice->playback.inputCacheRemaining > 0) { + framesToReadThisIterationOut = (frameCount - totalFramesReadOut); + framesToReadThisIterationIn = framesToReadThisIterationOut; + if (framesToReadThisIterationIn > pDevice->playback.inputCacheRemaining) { + framesToReadThisIterationIn = pDevice->playback.inputCacheRemaining; + } + + result = ma_data_converter_process_pcm_frames(&pDevice->playback.converter, ma_offset_pcm_frames_ptr(pDevice->playback.pInputCache, pDevice->playback.inputCacheConsumed, pDevice->playback.format, pDevice->playback.channels), &framesToReadThisIterationIn, pRunningFramesOut, &framesToReadThisIterationOut); + if (result != MA_SUCCESS) { + break; + } + + pDevice->playback.inputCacheConsumed += framesToReadThisIterationIn; + pDevice->playback.inputCacheRemaining -= framesToReadThisIterationIn; + + totalFramesReadOut += framesToReadThisIterationOut; + pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesToReadThisIterationOut * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels)); + + if (framesToReadThisIterationIn == 0 && framesToReadThisIterationOut == 0) { + break; /* We're done. */ + } + } + + /* Getting here means there's no data in the cache and we need to fill it up with data from the client. */ + if (pDevice->playback.inputCacheRemaining == 0) { + ma_device__handle_data_callback(pDevice, pDevice->playback.pInputCache, NULL, (ma_uint32)pDevice->playback.inputCacheCap); + + pDevice->playback.inputCacheConsumed = 0; + pDevice->playback.inputCacheRemaining = pDevice->playback.inputCacheCap; + } + } + } else { + while (totalFramesReadOut < frameCount) { + ma_uint8 pIntermediaryBuffer[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In client format. */ + ma_uint64 intermediaryBufferCap = sizeof(pIntermediaryBuffer) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels); + ma_uint64 framesToReadThisIterationIn; + ma_uint64 framesReadThisIterationIn; + ma_uint64 framesToReadThisIterationOut; + ma_uint64 framesReadThisIterationOut; + ma_uint64 requiredInputFrameCount; + + framesToReadThisIterationOut = (frameCount - totalFramesReadOut); + framesToReadThisIterationIn = framesToReadThisIterationOut; + if (framesToReadThisIterationIn > intermediaryBufferCap) { + framesToReadThisIterationIn = intermediaryBufferCap; + } + + ma_data_converter_get_required_input_frame_count(&pDevice->playback.converter, framesToReadThisIterationOut, &requiredInputFrameCount); + if (framesToReadThisIterationIn > requiredInputFrameCount) { + framesToReadThisIterationIn = requiredInputFrameCount; + } + + if (framesToReadThisIterationIn > 0) { + ma_device__handle_data_callback(pDevice, pIntermediaryBuffer, NULL, (ma_uint32)framesToReadThisIterationIn); + } + + /* + At this point we have our decoded data in input format and now we need to convert to output format. Note that even if we didn't read any + input frames, we still want to try processing frames because there may some output frames generated from cached input data. + */ + framesReadThisIterationIn = framesToReadThisIterationIn; + framesReadThisIterationOut = framesToReadThisIterationOut; + result = ma_data_converter_process_pcm_frames(&pDevice->playback.converter, pIntermediaryBuffer, &framesReadThisIterationIn, pRunningFramesOut, &framesReadThisIterationOut); + if (result != MA_SUCCESS) { + break; + } + + totalFramesReadOut += framesReadThisIterationOut; + pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesReadThisIterationOut * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels)); + + if (framesReadThisIterationIn == 0 && framesReadThisIterationOut == 0) { + break; /* We're done. */ + } + } + } + } +} + +/* A helper for sending sample data to the client. */ +static void ma_device__send_frames_to_client(ma_device* pDevice, ma_uint32 frameCountInDeviceFormat, const void* pFramesInDeviceFormat) +{ + MA_ASSERT(pDevice != NULL); + MA_ASSERT(frameCountInDeviceFormat > 0); + MA_ASSERT(pFramesInDeviceFormat != NULL); + + if (pDevice->capture.converter.isPassthrough) { + ma_device__handle_data_callback(pDevice, NULL, pFramesInDeviceFormat, frameCountInDeviceFormat); + } else { + ma_result result; + ma_uint8 pFramesInClientFormat[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; + ma_uint64 framesInClientFormatCap = sizeof(pFramesInClientFormat) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels); + ma_uint64 totalDeviceFramesProcessed = 0; + ma_uint64 totalClientFramesProcessed = 0; + const void* pRunningFramesInDeviceFormat = pFramesInDeviceFormat; + + /* We just keep going until we've exhaused all of our input frames and cannot generate any more output frames. */ + for (;;) { + ma_uint64 deviceFramesProcessedThisIteration; + ma_uint64 clientFramesProcessedThisIteration; + + deviceFramesProcessedThisIteration = (frameCountInDeviceFormat - totalDeviceFramesProcessed); + clientFramesProcessedThisIteration = framesInClientFormatCap; + + result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningFramesInDeviceFormat, &deviceFramesProcessedThisIteration, pFramesInClientFormat, &clientFramesProcessedThisIteration); + if (result != MA_SUCCESS) { + break; + } + + if (clientFramesProcessedThisIteration > 0) { + ma_device__handle_data_callback(pDevice, NULL, pFramesInClientFormat, (ma_uint32)clientFramesProcessedThisIteration); /* Safe cast. */ + } + + pRunningFramesInDeviceFormat = ma_offset_ptr(pRunningFramesInDeviceFormat, deviceFramesProcessedThisIteration * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels)); + totalDeviceFramesProcessed += deviceFramesProcessedThisIteration; + totalClientFramesProcessed += clientFramesProcessedThisIteration; + + /* This is just to silence a warning. I might want to use this variable later so leaving in place for now. */ + (void)totalClientFramesProcessed; + + if (deviceFramesProcessedThisIteration == 0 && clientFramesProcessedThisIteration == 0) { + break; /* We're done. */ + } + } + } +} + +static ma_result ma_device__handle_duplex_callback_capture(ma_device* pDevice, ma_uint32 frameCountInDeviceFormat, const void* pFramesInDeviceFormat, ma_pcm_rb* pRB) +{ + ma_result result; + ma_uint32 totalDeviceFramesProcessed = 0; + const void* pRunningFramesInDeviceFormat = pFramesInDeviceFormat; + + MA_ASSERT(pDevice != NULL); + MA_ASSERT(frameCountInDeviceFormat > 0); + MA_ASSERT(pFramesInDeviceFormat != NULL); + MA_ASSERT(pRB != NULL); + + /* Write to the ring buffer. The ring buffer is in the client format which means we need to convert. */ + for (;;) { + ma_uint32 framesToProcessInDeviceFormat = (frameCountInDeviceFormat - totalDeviceFramesProcessed); + ma_uint32 framesToProcessInClientFormat = MA_DATA_CONVERTER_STACK_BUFFER_SIZE / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels); + ma_uint64 framesProcessedInDeviceFormat; + ma_uint64 framesProcessedInClientFormat; + void* pFramesInClientFormat; + + result = ma_pcm_rb_acquire_write(pRB, &framesToProcessInClientFormat, &pFramesInClientFormat); + if (result != MA_SUCCESS) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "Failed to acquire capture PCM frames from ring buffer."); + break; + } + + if (framesToProcessInClientFormat == 0) { + if (ma_pcm_rb_pointer_distance(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. */ + framesProcessedInDeviceFormat = framesToProcessInDeviceFormat; + framesProcessedInClientFormat = framesToProcessInClientFormat; + result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningFramesInDeviceFormat, &framesProcessedInDeviceFormat, pFramesInClientFormat, &framesProcessedInClientFormat); + if (result != MA_SUCCESS) { + break; + } + + result = ma_pcm_rb_commit_write(pRB, (ma_uint32)framesProcessedInClientFormat); /* Safe cast. */ + if (result != MA_SUCCESS) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "Failed to commit capture PCM frames to ring buffer."); + break; + } + + pRunningFramesInDeviceFormat = ma_offset_ptr(pRunningFramesInDeviceFormat, framesProcessedInDeviceFormat * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels)); + totalDeviceFramesProcessed += (ma_uint32)framesProcessedInDeviceFormat; /* Safe cast. */ + + /* We're done when we're unable to process any client nor device frames. */ + if (framesProcessedInClientFormat == 0 && framesProcessedInDeviceFormat == 0) { + break; /* Done. */ + } + } + + return MA_SUCCESS; +} + +static 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 silentInputFrames[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; + ma_uint32 totalFramesReadOut = 0; + + MA_ASSERT(pDevice != NULL); + MA_ASSERT(frameCount > 0); + MA_ASSERT(pFramesInInternalFormat != NULL); + MA_ASSERT(pRB != NULL); + MA_ASSERT(pDevice->playback.pInputCache != 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_ZERO_MEMORY(silentInputFrames, sizeof(silentInputFrames)); + + while (totalFramesReadOut < frameCount && ma_device_is_started(pDevice)) { + /* + We should have a buffer allocated on the heap. Any playback frames still sitting in there + need to be sent to the internal device before we process any more data from the client. + */ + if (pDevice->playback.inputCacheRemaining > 0) { + ma_uint64 framesConvertedIn = pDevice->playback.inputCacheRemaining; + ma_uint64 framesConvertedOut = (frameCount - totalFramesReadOut); + ma_data_converter_process_pcm_frames(&pDevice->playback.converter, ma_offset_pcm_frames_ptr(pDevice->playback.pInputCache, pDevice->playback.inputCacheConsumed, pDevice->playback.format, pDevice->playback.channels), &framesConvertedIn, pFramesInInternalFormat, &framesConvertedOut); + + pDevice->playback.inputCacheConsumed += framesConvertedIn; + pDevice->playback.inputCacheRemaining -= framesConvertedIn; + + totalFramesReadOut += (ma_uint32)framesConvertedOut; /* Safe cast. */ + pFramesInInternalFormat = ma_offset_ptr(pFramesInInternalFormat, framesConvertedOut * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels)); + } + + /* If there's no more data in the cache we'll need to fill it with some. */ + if (totalFramesReadOut < frameCount && pDevice->playback.inputCacheRemaining == 0) { + ma_uint32 inputFrameCount; + void* pInputFrames; + + inputFrameCount = (ma_uint32)pDevice->playback.inputCacheCap; + result = ma_pcm_rb_acquire_read(pRB, &inputFrameCount, &pInputFrames); + if (result == MA_SUCCESS) { + if (inputFrameCount > 0) { + ma_device__handle_data_callback(pDevice, pDevice->playback.pInputCache, pInputFrames, inputFrameCount); + } else { + if (ma_pcm_rb_pointer_distance(pRB) == 0) { + break; /* Underrun. */ + } + } + } else { + /* No capture data available. Feed in silence. */ + inputFrameCount = (ma_uint32)ma_min(pDevice->playback.inputCacheCap, sizeof(silentInputFrames) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels)); + ma_device__handle_data_callback(pDevice, pDevice->playback.pInputCache, silentInputFrames, inputFrameCount); + } + + pDevice->playback.inputCacheConsumed = 0; + pDevice->playback.inputCacheRemaining = inputFrameCount; + + result = ma_pcm_rb_commit_read(pRB, inputFrameCount); + if (result != MA_SUCCESS) { + return result; /* Should never happen. */ + } + } + } + + return MA_SUCCESS; +} + +/* A helper for changing the state of the device. */ +static MA_INLINE void ma_device__set_state(ma_device* pDevice, ma_device_state newState) +{ + ma_atomic_device_state_set(&pDevice->state, newState); +} + + +#if defined(MA_WIN32) + static GUID MA_GUID_KSDATAFORMAT_SUBTYPE_PCM = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}}; + static GUID MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = {0x00000003, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}}; + /*static GUID MA_GUID_KSDATAFORMAT_SUBTYPE_ALAW = {0x00000006, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};*/ + /*static GUID MA_GUID_KSDATAFORMAT_SUBTYPE_MULAW = {0x00000007, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};*/ +#endif + + + +MA_API ma_uint32 ma_get_format_priority_index(ma_format format) /* Lower = better. */ +{ + 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. */ + return (ma_uint32)-1; +} + +static ma_result ma_device__post_init_setup(ma_device* pDevice, ma_device_type deviceType); + +static ma_bool32 ma_device_descriptor_is_valid(const ma_device_descriptor* pDeviceDescriptor) +{ + if (pDeviceDescriptor == NULL) { + return MA_FALSE; + } + + if (pDeviceDescriptor->format == ma_format_unknown) { + return MA_FALSE; + } + + if (pDeviceDescriptor->channels == 0 || pDeviceDescriptor->channels > MA_MAX_CHANNELS) { + return MA_FALSE; + } + + if (pDeviceDescriptor->sampleRate == 0) { + return MA_FALSE; + } + + return MA_TRUE; +} + + +static ma_result ma_device_audio_thread__default_read_write(ma_device* pDevice) +{ + ma_result result = MA_SUCCESS; + ma_bool32 exitLoop = MA_FALSE; + ma_uint8 capturedDeviceData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; + ma_uint8 playbackDeviceData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; + ma_uint32 capturedDeviceDataCapInFrames = 0; + ma_uint32 playbackDeviceDataCapInFrames = 0; + + MA_ASSERT(pDevice != NULL); + + /* Just some quick validation on the device type and the available callbacks. */ + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) { + if (pDevice->pContext->callbacks.onDeviceRead == NULL) { + return MA_NOT_IMPLEMENTED; + } + + capturedDeviceDataCapInFrames = sizeof(capturedDeviceData) / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + if (pDevice->pContext->callbacks.onDeviceWrite == NULL) { + return MA_NOT_IMPLEMENTED; + } + + playbackDeviceDataCapInFrames = sizeof(playbackDeviceData) / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + } + + /* NOTE: The device was started outside of this function, in the worker thread. */ + + while (ma_device_get_state(pDevice) == ma_device_state_started && !exitLoop) { + switch (pDevice->type) { + case ma_device_type_duplex: + { + /* The process is: onDeviceRead() -> convert -> callback -> convert -> onDeviceWrite() */ + ma_uint32 totalCapturedDeviceFramesProcessed = 0; + ma_uint32 capturedDevicePeriodSizeInFrames = ma_min(pDevice->capture.internalPeriodSizeInFrames, pDevice->playback.internalPeriodSizeInFrames); + + while (totalCapturedDeviceFramesProcessed < capturedDevicePeriodSizeInFrames) { + ma_uint32 capturedDeviceFramesRemaining; + ma_uint32 capturedDeviceFramesProcessed; + ma_uint32 capturedDeviceFramesToProcess; + ma_uint32 capturedDeviceFramesToTryProcessing = capturedDevicePeriodSizeInFrames - totalCapturedDeviceFramesProcessed; + if (capturedDeviceFramesToTryProcessing > capturedDeviceDataCapInFrames) { + capturedDeviceFramesToTryProcessing = capturedDeviceDataCapInFrames; + } + + result = pDevice->pContext->callbacks.onDeviceRead(pDevice, capturedDeviceData, capturedDeviceFramesToTryProcessing, &capturedDeviceFramesToProcess); + if (result != MA_SUCCESS) { + exitLoop = MA_TRUE; + break; + } + + capturedDeviceFramesRemaining = capturedDeviceFramesToProcess; + capturedDeviceFramesProcessed = 0; + + /* At this point we have our captured data in device format and we now need to convert it to client format. */ + for (;;) { + ma_uint8 capturedClientData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; + ma_uint8 playbackClientData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; + ma_uint32 capturedClientDataCapInFrames = sizeof(capturedClientData) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels); + ma_uint32 playbackClientDataCapInFrames = sizeof(playbackClientData) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels); + ma_uint64 capturedClientFramesToProcessThisIteration = ma_min(capturedClientDataCapInFrames, playbackClientDataCapInFrames); + ma_uint64 capturedDeviceFramesToProcessThisIteration = capturedDeviceFramesRemaining; + ma_uint8* pRunningCapturedDeviceFrames = ma_offset_ptr(capturedDeviceData, capturedDeviceFramesProcessed * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels)); + + /* Convert capture data from device format to client format. */ + result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningCapturedDeviceFrames, &capturedDeviceFramesToProcessThisIteration, capturedClientData, &capturedClientFramesToProcessThisIteration); + if (result != MA_SUCCESS) { + break; + } + + /* + If we weren't able to generate any output frames it must mean we've exhaused all of our input. The only time this would not be the case is if capturedClientData was too small + which should never be the case when it's of the size MA_DATA_CONVERTER_STACK_BUFFER_SIZE. + */ + if (capturedClientFramesToProcessThisIteration == 0) { + break; + } + + ma_device__handle_data_callback(pDevice, playbackClientData, capturedClientData, (ma_uint32)capturedClientFramesToProcessThisIteration); /* Safe cast .*/ + + capturedDeviceFramesProcessed += (ma_uint32)capturedDeviceFramesToProcessThisIteration; /* Safe cast. */ + capturedDeviceFramesRemaining -= (ma_uint32)capturedDeviceFramesToProcessThisIteration; /* Safe cast. */ + + /* At this point the playbackClientData buffer should be holding data that needs to be written to the device. */ + for (;;) { + ma_uint64 convertedClientFrameCount = capturedClientFramesToProcessThisIteration; + ma_uint64 convertedDeviceFrameCount = playbackDeviceDataCapInFrames; + result = ma_data_converter_process_pcm_frames(&pDevice->playback.converter, playbackClientData, &convertedClientFrameCount, playbackDeviceData, &convertedDeviceFrameCount); + if (result != MA_SUCCESS) { + break; + } + + result = pDevice->pContext->callbacks.onDeviceWrite(pDevice, playbackDeviceData, (ma_uint32)convertedDeviceFrameCount, NULL); /* Safe cast. */ + if (result != MA_SUCCESS) { + exitLoop = MA_TRUE; + break; + } + + capturedClientFramesToProcessThisIteration -= (ma_uint32)convertedClientFrameCount; /* Safe cast. */ + if (capturedClientFramesToProcessThisIteration == 0) { + break; + } + } + + /* In case an error happened from ma_device_write__null()... */ + if (result != MA_SUCCESS) { + exitLoop = MA_TRUE; + break; + } + } + + /* Make sure we don't get stuck in the inner loop. */ + if (capturedDeviceFramesProcessed == 0) { + break; + } + + totalCapturedDeviceFramesProcessed += capturedDeviceFramesProcessed; + } + } break; + + case ma_device_type_capture: + case ma_device_type_loopback: + { + ma_uint32 periodSizeInFrames = pDevice->capture.internalPeriodSizeInFrames; + ma_uint32 framesReadThisPeriod = 0; + while (framesReadThisPeriod < periodSizeInFrames) { + ma_uint32 framesRemainingInPeriod = periodSizeInFrames - framesReadThisPeriod; + ma_uint32 framesProcessed; + ma_uint32 framesToReadThisIteration = framesRemainingInPeriod; + if (framesToReadThisIteration > capturedDeviceDataCapInFrames) { + framesToReadThisIteration = capturedDeviceDataCapInFrames; + } + + result = pDevice->pContext->callbacks.onDeviceRead(pDevice, capturedDeviceData, framesToReadThisIteration, &framesProcessed); + if (result != MA_SUCCESS) { + exitLoop = MA_TRUE; + break; + } + + /* Make sure we don't get stuck in the inner loop. */ + if (framesProcessed == 0) { + break; + } + + ma_device__send_frames_to_client(pDevice, framesProcessed, capturedDeviceData); + + framesReadThisPeriod += framesProcessed; + } + } break; + + case ma_device_type_playback: + { + /* We write in chunks of the period size, but use a stack allocated buffer for the intermediary. */ + ma_uint32 periodSizeInFrames = pDevice->playback.internalPeriodSizeInFrames; + ma_uint32 framesWrittenThisPeriod = 0; + while (framesWrittenThisPeriod < periodSizeInFrames) { + ma_uint32 framesRemainingInPeriod = periodSizeInFrames - framesWrittenThisPeriod; + ma_uint32 framesProcessed; + ma_uint32 framesToWriteThisIteration = framesRemainingInPeriod; + if (framesToWriteThisIteration > playbackDeviceDataCapInFrames) { + framesToWriteThisIteration = playbackDeviceDataCapInFrames; + } + + ma_device__read_frames_from_client(pDevice, framesToWriteThisIteration, playbackDeviceData); + + result = pDevice->pContext->callbacks.onDeviceWrite(pDevice, playbackDeviceData, framesToWriteThisIteration, &framesProcessed); + if (result != MA_SUCCESS) { + exitLoop = MA_TRUE; + break; + } + + /* Make sure we don't get stuck in the inner loop. */ + if (framesProcessed == 0) { + break; + } + + framesWrittenThisPeriod += framesProcessed; + } + } break; + + /* Should never get here. */ + default: break; + } + } + + return result; +} + + + +/******************************************************************************* + +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 + +static 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. */ + ma_uint32 operation; + + /* Wait for an operation to be requested. */ + ma_event_wait(&pDevice->null_device.operationEvent); + + /* At this point an event should have been triggered. */ + operation = pDevice->null_device.operation; + + /* Starting the device needs to put the thread into a loop. */ + if (operation == MA_DEVICE_OP_START__NULL) { + /* Reset the timer just in case. */ + ma_timer_init(&pDevice->null_device.timer); + + /* Getting here means a suspend or kill operation has been requested. */ + pDevice->null_device.operationResult = MA_SUCCESS; + ma_event_signal(&pDevice->null_device.operationCompletionEvent); + ma_semaphore_release(&pDevice->null_device.operationSemaphore); + continue; + } + + /* Suspending the device means we need to stop the timer and just continue the loop. */ + if (operation == MA_DEVICE_OP_SUSPEND__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. */ + pDevice->null_device.operationResult = MA_SUCCESS; + ma_event_signal(&pDevice->null_device.operationCompletionEvent); + ma_semaphore_release(&pDevice->null_device.operationSemaphore); + continue; + } + + /* Killing the device means we need to get out of this loop so that this thread can terminate. */ + if (operation == MA_DEVICE_OP_KILL__NULL) { + pDevice->null_device.operationResult = MA_SUCCESS; + ma_event_signal(&pDevice->null_device.operationCompletionEvent); + ma_semaphore_release(&pDevice->null_device.operationSemaphore); + break; + } + + /* Getting a signal on a "none" operation probably means an error. Return invalid operation. */ + if (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). */ + pDevice->null_device.operationResult = MA_INVALID_OPERATION; + ma_event_signal(&pDevice->null_device.operationCompletionEvent); + ma_semaphore_release(&pDevice->null_device.operationSemaphore); + continue; /* Continue the loop. Don't terminate. */ + } + } + + return (ma_thread_result)0; +} + +static ma_result ma_device_do_operation__null(ma_device* pDevice, ma_uint32 operation) +{ + ma_result result; + + /* + TODO: Need to review this and consider just using mutual exclusion. I think the original motivation + for this was to just post the event to a queue and return immediately, but that has since changed + and now this function is synchronous. I think this can be simplified to just use a mutex. + */ + + /* + The first thing to do is wait for an operation slot to become available. We only have a single slot for this, but we could extend this later + to support queing of operations. + */ + result = ma_semaphore_wait(&pDevice->null_device.operationSemaphore); + if (result != MA_SUCCESS) { + return result; /* Failed to wait for the event. */ + } + + /* + When we get here it means the background thread is not referencing the operation code and it can be changed. After changing this we need to + signal an event to the worker thread to let it know that it can start work. + */ + pDevice->null_device.operation = operation; + + /* Once the operation code has been set, the worker thread can start work. */ + if (ma_event_signal(&pDevice->null_device.operationEvent) != MA_SUCCESS) { + return MA_ERROR; + } + + /* We want everything to be synchronous so we're going to wait for the worker thread to complete it's operation. */ + if (ma_event_wait(&pDevice->null_device.operationCompletionEvent) != MA_SUCCESS) { + return MA_ERROR; + } + + return pDevice->null_device.operationResult; +} + +static 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); +} + +static 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); + + /* 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); + deviceInfo.isDefault = MA_TRUE; /* Only one playback and capture device for the null backend, so might as well mark as default. */ + 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); + deviceInfo.isDefault = MA_TRUE; /* Only one playback and capture device for the null backend, so might as well mark as default. */ + cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData); + } + + (void)cbResult; /* Silence a static analysis warning. */ + + return MA_SUCCESS; +} + +static ma_result ma_context_get_device_info__null(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo) +{ + MA_ASSERT(pContext != NULL); + + 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); + } + + pDeviceInfo->isDefault = MA_TRUE; /* Only one playback and capture device for the null backend, so might as well mark as default. */ + + /* Support everything on the null backend. */ + pDeviceInfo->nativeDataFormats[0].format = ma_format_unknown; + pDeviceInfo->nativeDataFormats[0].channels = 0; + pDeviceInfo->nativeDataFormats[0].sampleRate = 0; + pDeviceInfo->nativeDataFormats[0].flags = 0; + pDeviceInfo->nativeDataFormatCount = 1; + + (void)pContext; + return MA_SUCCESS; +} + + +static ma_result 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); + + /* Wait for the thread to finish before continuing. */ + ma_thread_wait(&pDevice->null_device.deviceThread); + + /* At this point the loop in the device thread is as good as terminated so we can uninitialize our events. */ + ma_semaphore_uninit(&pDevice->null_device.operationSemaphore); + ma_event_uninit(&pDevice->null_device.operationCompletionEvent); + ma_event_uninit(&pDevice->null_device.operationEvent); + + return MA_SUCCESS; +} + +static ma_result ma_device_init__null(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture) +{ + ma_result result; + + MA_ASSERT(pDevice != NULL); + + MA_ZERO_OBJECT(&pDevice->null_device); + + if (pConfig->deviceType == ma_device_type_loopback) { + return MA_DEVICE_TYPE_NOT_SUPPORTED; + } + + /* The null backend supports everything exactly as we specify it. */ + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + pDescriptorCapture->format = (pDescriptorCapture->format != ma_format_unknown) ? pDescriptorCapture->format : MA_DEFAULT_FORMAT; + pDescriptorCapture->channels = (pDescriptorCapture->channels != 0) ? pDescriptorCapture->channels : MA_DEFAULT_CHANNELS; + pDescriptorCapture->sampleRate = (pDescriptorCapture->sampleRate != 0) ? pDescriptorCapture->sampleRate : MA_DEFAULT_SAMPLE_RATE; + + if (pDescriptorCapture->channelMap[0] == MA_CHANNEL_NONE) { + ma_channel_map_init_standard(ma_standard_channel_map_default, pDescriptorCapture->channelMap, ma_countof(pDescriptorCapture->channelMap), pDescriptorCapture->channels); + } + + pDescriptorCapture->periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptorCapture, pDescriptorCapture->sampleRate, pConfig->performanceProfile); + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + pDescriptorPlayback->format = (pDescriptorPlayback->format != ma_format_unknown) ? pDescriptorPlayback->format : MA_DEFAULT_FORMAT; + pDescriptorPlayback->channels = (pDescriptorPlayback->channels != 0) ? pDescriptorPlayback->channels : MA_DEFAULT_CHANNELS; + pDescriptorPlayback->sampleRate = (pDescriptorPlayback->sampleRate != 0) ? pDescriptorPlayback->sampleRate : MA_DEFAULT_SAMPLE_RATE; + + if (pDescriptorPlayback->channelMap[0] == MA_CHANNEL_NONE) { + ma_channel_map_init_standard(ma_standard_channel_map_default, pDescriptorPlayback->channelMap, ma_countof(pDescriptorCapture->channelMap), pDescriptorPlayback->channels); + } + + pDescriptorPlayback->periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptorPlayback, pDescriptorPlayback->sampleRate, pConfig->performanceProfile); + } + + /* + 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(&pDevice->null_device.operationEvent); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_event_init(&pDevice->null_device.operationCompletionEvent); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_semaphore_init(1, &pDevice->null_device.operationSemaphore); /* <-- It's important that the initial value is set to 1. */ + if (result != MA_SUCCESS) { + return result; + } + + result = ma_thread_create(&pDevice->null_device.deviceThread, pDevice->pContext->threadPriority, 0, ma_device_thread__null, pDevice, &pDevice->pContext->allocationCallbacks); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +static 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_bool32_set(&pDevice->null_device.isStarted, MA_TRUE); + return MA_SUCCESS; +} + +static 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_bool32_set(&pDevice->null_device.isStarted, MA_FALSE); + return MA_SUCCESS; +} + +static ma_bool32 ma_device_is_started__null(ma_device* pDevice) +{ + MA_ASSERT(pDevice != NULL); + + return ma_atomic_bool32_get(&pDevice->null_device.isStarted); +} + +static ma_result ma_device_write__null(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten) +{ + ma_result result = MA_SUCCESS; + ma_uint32 totalPCMFramesProcessed; + ma_bool32 wasStartedOnEntry; + + if (pFramesWritten != NULL) { + *pFramesWritten = 0; + } + + wasStartedOnEntry = ma_device_is_started__null(pDevice); + + /* 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); + 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 (!ma_device_is_started__null(pDevice) && !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. */ + targetFrame = pDevice->null_device.lastProcessedFramePlayback; + for (;;) { + ma_uint64 currentFrame; + + /* Stop waiting if the device has been stopped. */ + if (!ma_device_is_started__null(pDevice)) { + break; + } + + 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.internalPeriodSizeInFrames; + pDevice->null_device.currentPeriodFramesRemainingPlayback = pDevice->playback.internalPeriodSizeInFrames; + } + + if (pFramesWritten != NULL) { + *pFramesWritten = totalPCMFramesProcessed; + } + + return result; +} + +static ma_result ma_device_read__null(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead) +{ + ma_result result = MA_SUCCESS; + ma_uint32 totalPCMFramesProcessed; + + if (pFramesRead != NULL) { + *pFramesRead = 0; + } + + /* 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); + ma_uint32 framesRemaining = (frameCount - totalPCMFramesProcessed); + ma_uint32 framesToProcess = pDevice->null_device.currentPeriodFramesRemainingCapture; + if (framesToProcess > framesRemaining) { + framesToProcess = framesRemaining; + } + + /* We need to ensure 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. */ + targetFrame = pDevice->null_device.lastProcessedFrameCapture + pDevice->capture.internalPeriodSizeInFrames; + for (;;) { + ma_uint64 currentFrame; + + /* Stop waiting if the device has been stopped. */ + if (!ma_device_is_started__null(pDevice)) { + break; + } + + 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.internalPeriodSizeInFrames; + pDevice->null_device.currentPeriodFramesRemainingCapture = pDevice->capture.internalPeriodSizeInFrames; + } + + if (pFramesRead != NULL) { + *pFramesRead = totalPCMFramesProcessed; + } + + return result; +} + +static 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; +} + +static ma_result ma_context_init__null(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks) +{ + MA_ASSERT(pContext != NULL); + + (void)pConfig; + (void)pContext; + + pCallbacks->onContextInit = ma_context_init__null; + pCallbacks->onContextUninit = ma_context_uninit__null; + pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__null; + pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__null; + pCallbacks->onDeviceInit = ma_device_init__null; + pCallbacks->onDeviceUninit = ma_device_uninit__null; + pCallbacks->onDeviceStart = ma_device_start__null; + pCallbacks->onDeviceStop = ma_device_stop__null; + pCallbacks->onDeviceRead = ma_device_read__null; + pCallbacks->onDeviceWrite = ma_device_write__null; + pCallbacks->onDeviceDataLoop = NULL; /* Our backend is asynchronous with a blocking read-write API which means we can get miniaudio to deal with the audio thread. */ + + /* The null backend always works. */ + return MA_SUCCESS; +} +#endif + + + +/******************************************************************************* + +WIN32 COMMON + +*******************************************************************************/ +#if defined(MA_WIN32) +#if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK) + #define ma_CoInitializeEx(pContext, pvReserved, dwCoInit) ((pContext->win32.CoInitializeEx) ? ((MA_PFN_CoInitializeEx)pContext->win32.CoInitializeEx)(pvReserved, dwCoInit) : ((MA_PFN_CoInitialize)pContext->win32.CoInitialize)(pvReserved)) + #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) && !defined(__WATCOMC__) +typedef size_t DWORD_PTR; +#endif + +#if !defined(WAVE_FORMAT_1M08) +#define WAVE_FORMAT_1M08 0x00000001 +#define WAVE_FORMAT_1S08 0x00000002 +#define WAVE_FORMAT_1M16 0x00000004 +#define WAVE_FORMAT_1S16 0x00000008 +#define WAVE_FORMAT_2M08 0x00000010 +#define WAVE_FORMAT_2S08 0x00000020 +#define WAVE_FORMAT_2M16 0x00000040 +#define WAVE_FORMAT_2S16 0x00000080 +#define WAVE_FORMAT_4M08 0x00000100 +#define WAVE_FORMAT_4S08 0x00000200 +#define WAVE_FORMAT_4M16 0x00000400 +#define WAVE_FORMAT_4S16 0x00000800 +#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 + +/* +Implement our own version of MA_WAVEFORMATEXTENSIBLE so we can avoid a header. Be careful with this +because MA_WAVEFORMATEX has an extra two bytes over standard WAVEFORMATEX due to padding. The +standard version uses tight packing, but for compiler compatibility we're not doing that with ours. +*/ +typedef struct +{ + WORD wFormatTag; + WORD nChannels; + DWORD nSamplesPerSec; + DWORD nAvgBytesPerSec; + WORD nBlockAlign; + WORD wBitsPerSample; + WORD cbSize; +} MA_WAVEFORMATEX; + +typedef struct +{ + WORD wFormatTag; + WORD nChannels; + DWORD nSamplesPerSec; + DWORD nAvgBytesPerSec; + WORD nBlockAlign; + WORD wBitsPerSample; + WORD cbSize; + union + { + WORD wValidBitsPerSample; + WORD wSamplesPerBlock; + WORD wReserved; + } Samples; + DWORD dwChannelMask; + GUID SubFormat; +} MA_WAVEFORMATEXTENSIBLE; + + + +#ifndef WAVE_FORMAT_EXTENSIBLE +#define WAVE_FORMAT_EXTENSIBLE 0xFFFE +#endif + +#ifndef WAVE_FORMAT_PCM +#define WAVE_FORMAT_PCM 1 +#endif + +#ifndef WAVE_FORMAT_IEEE_FLOAT +#define WAVE_FORMAT_IEEE_FLOAT 0x0003 +#endif + +/* Converts an individual Win32-style channel identifier (SPEAKER_FRONT_LEFT, etc.) to miniaudio. */ +static 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. */ +static 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. */ +static DWORD ma_channel_map_to_channel_mask__win32(const ma_channel* pChannelMap, ma_uint32 channels) +{ + DWORD dwChannelMask = 0; + ma_uint32 iChannel; + + for (iChannel = 0; iChannel < channels; ++iChannel) { + dwChannelMask |= ma_channel_id_to_win32(pChannelMap[iChannel]); + } + + return dwChannelMask; +} + +/* Converts a Win32-style channel mask to a miniaudio channel map. */ +static void ma_channel_mask_to_channel_map__win32(DWORD dwChannelMask, ma_uint32 channels, ma_channel* pChannelMap) +{ + /* If the channel mask is set to 0, just assume a default Win32 channel map. */ + if (dwChannelMask == 0) { + ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pChannelMap, channels, channels); + } else { + if (channels == 1 && (dwChannelMask & SPEAKER_FRONT_CENTER) != 0) { + pChannelMap[0] = MA_CHANNEL_MONO; + } else { + /* Just iterate over each bit. */ + ma_uint32 iChannel = 0; + ma_uint32 iBit; + + for (iBit = 0; iBit < 32 && iChannel < channels; ++iBit) { + DWORD bitValue = (dwChannelMask & (1UL << iBit)); + if (bitValue != 0) { + /* The bit is set. */ + pChannelMap[iChannel] = ma_channel_id_to_ma__win32(bitValue); + iChannel += 1; + } + } + } + } +} + +#ifdef __cplusplus +static 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 + +static MA_INLINE ma_bool32 ma_is_guid_null(const void* guid) +{ + static GUID nullguid = {0x00000000, 0x0000, 0x0000, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}; + return ma_is_guid_equal(guid, &nullguid); +} + +static ma_format ma_format_from_WAVEFORMATEX(const MA_WAVEFORMATEX* pWF) +{ + MA_ASSERT(pWF != NULL); + + if (pWF->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { + const MA_WAVEFORMATEXTENSIBLE* pWFEX = (const MA_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->wBitsPerSample == 32) { + return ma_format_s32; + } + if (pWFEX->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 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 */ + +static ma_result ma_device_reroute__wasapi(ma_device* pDevice, ma_device_type deviceType); + +/* 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; + DWORD dwMajorVersion; + DWORD dwMinorVersion; + DWORD dwBuildNumber; + DWORD dwPlatformId; + WCHAR szCSDVersion[128]; + WORD wServicePackMajor; + WORD wServicePackMinor; + WORD wSuiteMask; + BYTE wProductType; + BYTE wReserved; +} ma_OSVERSIONINFOEXW; + +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 +#define PROPERTYKEY_DEFINED +#ifndef __WATCOMC__ +typedef struct +{ + GUID fmtid; + DWORD pid; +} PROPERTYKEY; +#endif +#endif + +/* Some compilers don't define PropVariantInit(). We just do this ourselves since it's just a memset(). */ +static MA_INLINE void ma_PropVariantInit(MA_PROPVARIANT* pProp) +{ + MA_ZERO_OBJECT(pProp); +} + + +static const PROPERTYKEY MA_PKEY_Device_FriendlyName = {{0xA45C254E, 0xDF1C, 0x4EFD, {0x80, 0x20, 0x67, 0xD1, 0x46, 0xA8, 0x50, 0xE0}}, 14}; +static const PROPERTYKEY MA_PKEY_AudioEngine_DeviceFormat = {{0xF19F064D, 0x82C, 0x4E27, {0xBC, 0x73, 0x68, 0x82, 0xA1, 0xBB, 0x8E, 0x4C}}, 0}; + +static const IID MA_IID_IUnknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; /* 00000000-0000-0000-C000-000000000046 */ +#if !defined(MA_WIN32_DESKTOP) && !defined(MA_WIN32_GDK) +static const IID MA_IID_IAgileObject = {0x94EA2B94, 0xE9CC, 0x49E0, {0xC0, 0xFF, 0xEE, 0x64, 0xCA, 0x8F, 0x5B, 0x90}}; /* 94EA2B94-E9CC-49E0-C0FF-EE64CA8F5B90 */ +#endif + +static const IID MA_IID_IAudioClient = {0x1CB9AD4C, 0xDBFA, 0x4C32, {0xB1, 0x78, 0xC2, 0xF5, 0x68, 0xA7, 0x03, 0xB2}}; /* 1CB9AD4C-DBFA-4C32-B178-C2F568A703B2 = __uuidof(IAudioClient) */ +static const IID MA_IID_IAudioClient2 = {0x726778CD, 0xF60A, 0x4EDA, {0x82, 0xDE, 0xE4, 0x76, 0x10, 0xCD, 0x78, 0xAA}}; /* 726778CD-F60A-4EDA-82DE-E47610CD78AA = __uuidof(IAudioClient2) */ +static const IID MA_IID_IAudioClient3 = {0x7ED4EE07, 0x8E67, 0x4CD4, {0x8C, 0x1A, 0x2B, 0x7A, 0x59, 0x87, 0xAD, 0x42}}; /* 7ED4EE07-8E67-4CD4-8C1A-2B7A5987AD42 = __uuidof(IAudioClient3) */ +static const IID MA_IID_IAudioRenderClient = {0xF294ACFC, 0x3146, 0x4483, {0xA7, 0xBF, 0xAD, 0xDC, 0xA7, 0xC2, 0x60, 0xE2}}; /* F294ACFC-3146-4483-A7BF-ADDCA7C260E2 = __uuidof(IAudioRenderClient) */ +static const IID MA_IID_IAudioCaptureClient = {0xC8ADBD64, 0xE71E, 0x48A0, {0xA4, 0xDE, 0x18, 0x5C, 0x39, 0x5C, 0xD3, 0x17}}; /* C8ADBD64-E71E-48A0-A4DE-185C395CD317 = __uuidof(IAudioCaptureClient) */ +static const IID MA_IID_IMMNotificationClient = {0x7991EEC9, 0x7E89, 0x4D85, {0x83, 0x90, 0x6C, 0x70, 0x3C, 0xEC, 0x60, 0xC0}}; /* 7991EEC9-7E89-4D85-8390-6C703CEC60C0 = __uuidof(IMMNotificationClient) */ +#if !defined(MA_WIN32_DESKTOP) && !defined(MA_WIN32_GDK) +static const IID MA_IID_DEVINTERFACE_AUDIO_RENDER = {0xE6327CAD, 0xDCEC, 0x4949, {0xAE, 0x8A, 0x99, 0x1E, 0x97, 0x6A, 0x79, 0xD2}}; /* E6327CAD-DCEC-4949-AE8A-991E976A79D2 */ +static const IID MA_IID_DEVINTERFACE_AUDIO_CAPTURE = {0x2EEF81BE, 0x33FA, 0x4800, {0x96, 0x70, 0x1C, 0xD4, 0x74, 0x97, 0x2C, 0x3F}}; /* 2EEF81BE-33FA-4800-9670-1CD474972C3F */ +static const IID MA_IID_IActivateAudioInterfaceCompletionHandler = {0x41D949AB, 0x9862, 0x444A, {0x80, 0xF6, 0xC2, 0x61, 0x33, 0x4D, 0xA5, 0xEB}}; /* 41D949AB-9862-444A-80F6-C261334DA5EB */ +#endif + +static const IID MA_CLSID_MMDeviceEnumerator = {0xBCDE0395, 0xE52F, 0x467C, {0x8E, 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E}}; /* BCDE0395-E52F-467C-8E3D-C4579291692E = __uuidof(MMDeviceEnumerator) */ +static const IID MA_IID_IMMDeviceEnumerator = {0xA95664D2, 0x9614, 0x4F35, {0xA7, 0x46, 0xDE, 0x8D, 0xB6, 0x36, 0x17, 0xE6}}; /* A95664D2-9614-4F35-A746-DE8DB63617E6 = __uuidof(IMMDeviceEnumerator) */ + +#if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK) +#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 + +/* Buffer flags. */ +#define MA_AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY 1 +#define MA_AUDCLNT_BUFFERFLAGS_SILENT 2 +#define MA_AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR 4 + +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 +{ + ma_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; +}; +static MA_INLINE HRESULT ma_IUnknown_QueryInterface(ma_IUnknown* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +static MA_INLINE ULONG ma_IUnknown_AddRef(ma_IUnknown* pThis) { return pThis->lpVtbl->AddRef(pThis); } +static MA_INLINE ULONG ma_IUnknown_Release(ma_IUnknown* pThis) { return pThis->lpVtbl->Release(pThis); } + +#if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK) + /* 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, const WCHAR* pDeviceID, DWORD dwNewState); + HRESULT (STDMETHODCALLTYPE * OnDeviceAdded) (ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID); + HRESULT (STDMETHODCALLTYPE * OnDeviceRemoved) (ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID); + HRESULT (STDMETHODCALLTYPE * OnDefaultDeviceChanged)(ma_IMMNotificationClient* pThis, ma_EDataFlow dataFlow, ma_ERole role, const WCHAR* pDefaultDeviceID); + HRESULT (STDMETHODCALLTYPE * OnPropertyValueChanged)(ma_IMMNotificationClient* pThis, const WCHAR* 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, const WCHAR* 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; + }; + static MA_INLINE HRESULT ma_IMMDeviceEnumerator_QueryInterface(ma_IMMDeviceEnumerator* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } + static MA_INLINE ULONG ma_IMMDeviceEnumerator_AddRef(ma_IMMDeviceEnumerator* pThis) { return pThis->lpVtbl->AddRef(pThis); } + static MA_INLINE ULONG ma_IMMDeviceEnumerator_Release(ma_IMMDeviceEnumerator* pThis) { return pThis->lpVtbl->Release(pThis); } + static MA_INLINE HRESULT ma_IMMDeviceEnumerator_EnumAudioEndpoints(ma_IMMDeviceEnumerator* pThis, ma_EDataFlow dataFlow, DWORD dwStateMask, ma_IMMDeviceCollection** ppDevices) { return pThis->lpVtbl->EnumAudioEndpoints(pThis, dataFlow, dwStateMask, ppDevices); } + static MA_INLINE HRESULT ma_IMMDeviceEnumerator_GetDefaultAudioEndpoint(ma_IMMDeviceEnumerator* pThis, ma_EDataFlow dataFlow, ma_ERole role, ma_IMMDevice** ppEndpoint) { return pThis->lpVtbl->GetDefaultAudioEndpoint(pThis, dataFlow, role, ppEndpoint); } + static MA_INLINE HRESULT ma_IMMDeviceEnumerator_GetDevice(ma_IMMDeviceEnumerator* pThis, const WCHAR* pID, ma_IMMDevice** ppDevice) { return pThis->lpVtbl->GetDevice(pThis, pID, ppDevice); } + static MA_INLINE HRESULT ma_IMMDeviceEnumerator_RegisterEndpointNotificationCallback(ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient) { return pThis->lpVtbl->RegisterEndpointNotificationCallback(pThis, pClient); } + static MA_INLINE 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; + }; + static MA_INLINE HRESULT ma_IMMDeviceCollection_QueryInterface(ma_IMMDeviceCollection* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } + static MA_INLINE ULONG ma_IMMDeviceCollection_AddRef(ma_IMMDeviceCollection* pThis) { return pThis->lpVtbl->AddRef(pThis); } + static MA_INLINE ULONG ma_IMMDeviceCollection_Release(ma_IMMDeviceCollection* pThis) { return pThis->lpVtbl->Release(pThis); } + static MA_INLINE HRESULT ma_IMMDeviceCollection_GetCount(ma_IMMDeviceCollection* pThis, UINT* pDevices) { return pThis->lpVtbl->GetCount(pThis, pDevices); } + static MA_INLINE 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, MA_PROPVARIANT* pActivationParams, void** ppInterface); + HRESULT (STDMETHODCALLTYPE * OpenPropertyStore)(ma_IMMDevice* pThis, DWORD stgmAccess, ma_IPropertyStore** ppProperties); + HRESULT (STDMETHODCALLTYPE * GetId) (ma_IMMDevice* pThis, WCHAR** pID); + HRESULT (STDMETHODCALLTYPE * GetState) (ma_IMMDevice* pThis, DWORD *pState); + } ma_IMMDeviceVtbl; + struct ma_IMMDevice + { + ma_IMMDeviceVtbl* lpVtbl; + }; + static MA_INLINE HRESULT ma_IMMDevice_QueryInterface(ma_IMMDevice* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } + static MA_INLINE ULONG ma_IMMDevice_AddRef(ma_IMMDevice* pThis) { return pThis->lpVtbl->AddRef(pThis); } + static MA_INLINE ULONG ma_IMMDevice_Release(ma_IMMDevice* pThis) { return pThis->lpVtbl->Release(pThis); } + static MA_INLINE HRESULT ma_IMMDevice_Activate(ma_IMMDevice* pThis, const IID* const iid, DWORD dwClsCtx, MA_PROPVARIANT* pActivationParams, void** ppInterface) { return pThis->lpVtbl->Activate(pThis, iid, dwClsCtx, pActivationParams, ppInterface); } + static MA_INLINE HRESULT ma_IMMDevice_OpenPropertyStore(ma_IMMDevice* pThis, DWORD stgmAccess, ma_IPropertyStore** ppProperties) { return pThis->lpVtbl->OpenPropertyStore(pThis, stgmAccess, ppProperties); } + static MA_INLINE HRESULT ma_IMMDevice_GetId(ma_IMMDevice* pThis, WCHAR** pID) { return pThis->lpVtbl->GetId(pThis, pID); } + static MA_INLINE 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; + }; + static MA_INLINE HRESULT ma_IActivateAudioInterfaceAsyncOperation_QueryInterface(ma_IActivateAudioInterfaceAsyncOperation* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } + static MA_INLINE ULONG ma_IActivateAudioInterfaceAsyncOperation_AddRef(ma_IActivateAudioInterfaceAsyncOperation* pThis) { return pThis->lpVtbl->AddRef(pThis); } + static MA_INLINE ULONG ma_IActivateAudioInterfaceAsyncOperation_Release(ma_IActivateAudioInterfaceAsyncOperation* pThis) { return pThis->lpVtbl->Release(pThis); } + static MA_INLINE 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, MA_PROPVARIANT* pPropVar); + HRESULT (STDMETHODCALLTYPE * SetValue)(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, const MA_PROPVARIANT* const pPropVar); + HRESULT (STDMETHODCALLTYPE * Commit) (ma_IPropertyStore* pThis); +} ma_IPropertyStoreVtbl; +struct ma_IPropertyStore +{ + ma_IPropertyStoreVtbl* lpVtbl; +}; +static MA_INLINE HRESULT ma_IPropertyStore_QueryInterface(ma_IPropertyStore* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +static MA_INLINE ULONG ma_IPropertyStore_AddRef(ma_IPropertyStore* pThis) { return pThis->lpVtbl->AddRef(pThis); } +static MA_INLINE ULONG ma_IPropertyStore_Release(ma_IPropertyStore* pThis) { return pThis->lpVtbl->Release(pThis); } +static MA_INLINE HRESULT ma_IPropertyStore_GetCount(ma_IPropertyStore* pThis, DWORD* pPropCount) { return pThis->lpVtbl->GetCount(pThis, pPropCount); } +static MA_INLINE HRESULT ma_IPropertyStore_GetAt(ma_IPropertyStore* pThis, DWORD propIndex, PROPERTYKEY* pPropKey) { return pThis->lpVtbl->GetAt(pThis, propIndex, pPropKey); } +static MA_INLINE HRESULT ma_IPropertyStore_GetValue(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, MA_PROPVARIANT* pPropVar) { return pThis->lpVtbl->GetValue(pThis, pKey, pPropVar); } +static MA_INLINE HRESULT ma_IPropertyStore_SetValue(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, const MA_PROPVARIANT* const pPropVar) { return pThis->lpVtbl->SetValue(pThis, pKey, pPropVar); } +static MA_INLINE 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 MA_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 MA_WAVEFORMATEX* pFormat, MA_WAVEFORMATEX** ppClosestMatch); + HRESULT (STDMETHODCALLTYPE * GetMixFormat) (ma_IAudioClient* pThis, MA_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; +}; +static MA_INLINE HRESULT ma_IAudioClient_QueryInterface(ma_IAudioClient* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +static MA_INLINE ULONG ma_IAudioClient_AddRef(ma_IAudioClient* pThis) { return pThis->lpVtbl->AddRef(pThis); } +static MA_INLINE ULONG ma_IAudioClient_Release(ma_IAudioClient* pThis) { return pThis->lpVtbl->Release(pThis); } +static MA_INLINE HRESULT ma_IAudioClient_Initialize(ma_IAudioClient* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const MA_WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid) { return pThis->lpVtbl->Initialize(pThis, shareMode, streamFlags, bufferDuration, periodicity, pFormat, pAudioSessionGuid); } +static MA_INLINE HRESULT ma_IAudioClient_GetBufferSize(ma_IAudioClient* pThis, ma_uint32* pNumBufferFrames) { return pThis->lpVtbl->GetBufferSize(pThis, pNumBufferFrames); } +static MA_INLINE HRESULT ma_IAudioClient_GetStreamLatency(ma_IAudioClient* pThis, MA_REFERENCE_TIME* pLatency) { return pThis->lpVtbl->GetStreamLatency(pThis, pLatency); } +static MA_INLINE HRESULT ma_IAudioClient_GetCurrentPadding(ma_IAudioClient* pThis, ma_uint32* pNumPaddingFrames) { return pThis->lpVtbl->GetCurrentPadding(pThis, pNumPaddingFrames); } +static MA_INLINE HRESULT ma_IAudioClient_IsFormatSupported(ma_IAudioClient* pThis, MA_AUDCLNT_SHAREMODE shareMode, const MA_WAVEFORMATEX* pFormat, MA_WAVEFORMATEX** ppClosestMatch) { return pThis->lpVtbl->IsFormatSupported(pThis, shareMode, pFormat, ppClosestMatch); } +static MA_INLINE HRESULT ma_IAudioClient_GetMixFormat(ma_IAudioClient* pThis, MA_WAVEFORMATEX** ppDeviceFormat) { return pThis->lpVtbl->GetMixFormat(pThis, ppDeviceFormat); } +static MA_INLINE HRESULT ma_IAudioClient_GetDevicePeriod(ma_IAudioClient* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod) { return pThis->lpVtbl->GetDevicePeriod(pThis, pDefaultDevicePeriod, pMinimumDevicePeriod); } +static MA_INLINE HRESULT ma_IAudioClient_Start(ma_IAudioClient* pThis) { return pThis->lpVtbl->Start(pThis); } +static MA_INLINE HRESULT ma_IAudioClient_Stop(ma_IAudioClient* pThis) { return pThis->lpVtbl->Stop(pThis); } +static MA_INLINE HRESULT ma_IAudioClient_Reset(ma_IAudioClient* pThis) { return pThis->lpVtbl->Reset(pThis); } +static MA_INLINE HRESULT ma_IAudioClient_SetEventHandle(ma_IAudioClient* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); } +static MA_INLINE 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 MA_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 MA_WAVEFORMATEX* pFormat, MA_WAVEFORMATEX** ppClosestMatch); + HRESULT (STDMETHODCALLTYPE * GetMixFormat) (ma_IAudioClient2* pThis, MA_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 MA_WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration); +} ma_IAudioClient2Vtbl; +struct ma_IAudioClient2 +{ + ma_IAudioClient2Vtbl* lpVtbl; +}; +static MA_INLINE HRESULT ma_IAudioClient2_QueryInterface(ma_IAudioClient2* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +static MA_INLINE ULONG ma_IAudioClient2_AddRef(ma_IAudioClient2* pThis) { return pThis->lpVtbl->AddRef(pThis); } +static MA_INLINE ULONG ma_IAudioClient2_Release(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Release(pThis); } +static MA_INLINE HRESULT ma_IAudioClient2_Initialize(ma_IAudioClient2* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const MA_WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid) { return pThis->lpVtbl->Initialize(pThis, shareMode, streamFlags, bufferDuration, periodicity, pFormat, pAudioSessionGuid); } +static MA_INLINE HRESULT ma_IAudioClient2_GetBufferSize(ma_IAudioClient2* pThis, ma_uint32* pNumBufferFrames) { return pThis->lpVtbl->GetBufferSize(pThis, pNumBufferFrames); } +static MA_INLINE HRESULT ma_IAudioClient2_GetStreamLatency(ma_IAudioClient2* pThis, MA_REFERENCE_TIME* pLatency) { return pThis->lpVtbl->GetStreamLatency(pThis, pLatency); } +static MA_INLINE HRESULT ma_IAudioClient2_GetCurrentPadding(ma_IAudioClient2* pThis, ma_uint32* pNumPaddingFrames) { return pThis->lpVtbl->GetCurrentPadding(pThis, pNumPaddingFrames); } +static MA_INLINE HRESULT ma_IAudioClient2_IsFormatSupported(ma_IAudioClient2* pThis, MA_AUDCLNT_SHAREMODE shareMode, const MA_WAVEFORMATEX* pFormat, MA_WAVEFORMATEX** ppClosestMatch) { return pThis->lpVtbl->IsFormatSupported(pThis, shareMode, pFormat, ppClosestMatch); } +static MA_INLINE HRESULT ma_IAudioClient2_GetMixFormat(ma_IAudioClient2* pThis, MA_WAVEFORMATEX** ppDeviceFormat) { return pThis->lpVtbl->GetMixFormat(pThis, ppDeviceFormat); } +static MA_INLINE HRESULT ma_IAudioClient2_GetDevicePeriod(ma_IAudioClient2* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod) { return pThis->lpVtbl->GetDevicePeriod(pThis, pDefaultDevicePeriod, pMinimumDevicePeriod); } +static MA_INLINE HRESULT ma_IAudioClient2_Start(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Start(pThis); } +static MA_INLINE HRESULT ma_IAudioClient2_Stop(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Stop(pThis); } +static MA_INLINE HRESULT ma_IAudioClient2_Reset(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Reset(pThis); } +static MA_INLINE HRESULT ma_IAudioClient2_SetEventHandle(ma_IAudioClient2* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); } +static MA_INLINE HRESULT ma_IAudioClient2_GetService(ma_IAudioClient2* pThis, const IID* const riid, void** pp) { return pThis->lpVtbl->GetService(pThis, riid, pp); } +static MA_INLINE HRESULT ma_IAudioClient2_IsOffloadCapable(ma_IAudioClient2* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable) { return pThis->lpVtbl->IsOffloadCapable(pThis, category, pOffloadCapable); } +static MA_INLINE HRESULT ma_IAudioClient2_SetClientProperties(ma_IAudioClient2* pThis, const ma_AudioClientProperties* pProperties) { return pThis->lpVtbl->SetClientProperties(pThis, pProperties); } +static MA_INLINE HRESULT ma_IAudioClient2_GetBufferSizeLimits(ma_IAudioClient2* pThis, const MA_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 MA_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 MA_WAVEFORMATEX* pFormat, MA_WAVEFORMATEX** ppClosestMatch); + HRESULT (STDMETHODCALLTYPE * GetMixFormat) (ma_IAudioClient3* pThis, MA_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 MA_WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration); + + /* IAudioClient3 */ + HRESULT (STDMETHODCALLTYPE * GetSharedModeEnginePeriod) (ma_IAudioClient3* pThis, const MA_WAVEFORMATEX* pFormat, ma_uint32* pDefaultPeriodInFrames, ma_uint32* pFundamentalPeriodInFrames, ma_uint32* pMinPeriodInFrames, ma_uint32* pMaxPeriodInFrames); + HRESULT (STDMETHODCALLTYPE * GetCurrentSharedModeEnginePeriod)(ma_IAudioClient3* pThis, MA_WAVEFORMATEX** ppFormat, ma_uint32* pCurrentPeriodInFrames); + HRESULT (STDMETHODCALLTYPE * InitializeSharedAudioStream) (ma_IAudioClient3* pThis, DWORD streamFlags, ma_uint32 periodInFrames, const MA_WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid); +} ma_IAudioClient3Vtbl; +struct ma_IAudioClient3 +{ + ma_IAudioClient3Vtbl* lpVtbl; +}; +static MA_INLINE HRESULT ma_IAudioClient3_QueryInterface(ma_IAudioClient3* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +static MA_INLINE ULONG ma_IAudioClient3_AddRef(ma_IAudioClient3* pThis) { return pThis->lpVtbl->AddRef(pThis); } +static MA_INLINE ULONG ma_IAudioClient3_Release(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Release(pThis); } +static MA_INLINE HRESULT ma_IAudioClient3_Initialize(ma_IAudioClient3* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const MA_WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid) { return pThis->lpVtbl->Initialize(pThis, shareMode, streamFlags, bufferDuration, periodicity, pFormat, pAudioSessionGuid); } +static MA_INLINE HRESULT ma_IAudioClient3_GetBufferSize(ma_IAudioClient3* pThis, ma_uint32* pNumBufferFrames) { return pThis->lpVtbl->GetBufferSize(pThis, pNumBufferFrames); } +static MA_INLINE HRESULT ma_IAudioClient3_GetStreamLatency(ma_IAudioClient3* pThis, MA_REFERENCE_TIME* pLatency) { return pThis->lpVtbl->GetStreamLatency(pThis, pLatency); } +static MA_INLINE HRESULT ma_IAudioClient3_GetCurrentPadding(ma_IAudioClient3* pThis, ma_uint32* pNumPaddingFrames) { return pThis->lpVtbl->GetCurrentPadding(pThis, pNumPaddingFrames); } +static MA_INLINE HRESULT ma_IAudioClient3_IsFormatSupported(ma_IAudioClient3* pThis, MA_AUDCLNT_SHAREMODE shareMode, const MA_WAVEFORMATEX* pFormat, MA_WAVEFORMATEX** ppClosestMatch) { return pThis->lpVtbl->IsFormatSupported(pThis, shareMode, pFormat, ppClosestMatch); } +static MA_INLINE HRESULT ma_IAudioClient3_GetMixFormat(ma_IAudioClient3* pThis, MA_WAVEFORMATEX** ppDeviceFormat) { return pThis->lpVtbl->GetMixFormat(pThis, ppDeviceFormat); } +static MA_INLINE HRESULT ma_IAudioClient3_GetDevicePeriod(ma_IAudioClient3* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod) { return pThis->lpVtbl->GetDevicePeriod(pThis, pDefaultDevicePeriod, pMinimumDevicePeriod); } +static MA_INLINE HRESULT ma_IAudioClient3_Start(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Start(pThis); } +static MA_INLINE HRESULT ma_IAudioClient3_Stop(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Stop(pThis); } +static MA_INLINE HRESULT ma_IAudioClient3_Reset(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Reset(pThis); } +static MA_INLINE HRESULT ma_IAudioClient3_SetEventHandle(ma_IAudioClient3* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); } +static MA_INLINE HRESULT ma_IAudioClient3_GetService(ma_IAudioClient3* pThis, const IID* const riid, void** pp) { return pThis->lpVtbl->GetService(pThis, riid, pp); } +static MA_INLINE HRESULT ma_IAudioClient3_IsOffloadCapable(ma_IAudioClient3* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable) { return pThis->lpVtbl->IsOffloadCapable(pThis, category, pOffloadCapable); } +static MA_INLINE HRESULT ma_IAudioClient3_SetClientProperties(ma_IAudioClient3* pThis, const ma_AudioClientProperties* pProperties) { return pThis->lpVtbl->SetClientProperties(pThis, pProperties); } +static MA_INLINE HRESULT ma_IAudioClient3_GetBufferSizeLimits(ma_IAudioClient3* pThis, const MA_WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration) { return pThis->lpVtbl->GetBufferSizeLimits(pThis, pFormat, eventDriven, pMinBufferDuration, pMaxBufferDuration); } +static MA_INLINE HRESULT ma_IAudioClient3_GetSharedModeEnginePeriod(ma_IAudioClient3* pThis, const MA_WAVEFORMATEX* pFormat, ma_uint32* pDefaultPeriodInFrames, ma_uint32* pFundamentalPeriodInFrames, ma_uint32* pMinPeriodInFrames, ma_uint32* pMaxPeriodInFrames) { return pThis->lpVtbl->GetSharedModeEnginePeriod(pThis, pFormat, pDefaultPeriodInFrames, pFundamentalPeriodInFrames, pMinPeriodInFrames, pMaxPeriodInFrames); } +static MA_INLINE HRESULT ma_IAudioClient3_GetCurrentSharedModeEnginePeriod(ma_IAudioClient3* pThis, MA_WAVEFORMATEX** ppFormat, ma_uint32* pCurrentPeriodInFrames) { return pThis->lpVtbl->GetCurrentSharedModeEnginePeriod(pThis, ppFormat, pCurrentPeriodInFrames); } +static MA_INLINE HRESULT ma_IAudioClient3_InitializeSharedAudioStream(ma_IAudioClient3* pThis, DWORD streamFlags, ma_uint32 periodInFrames, const MA_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; +}; +static MA_INLINE HRESULT ma_IAudioRenderClient_QueryInterface(ma_IAudioRenderClient* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +static MA_INLINE ULONG ma_IAudioRenderClient_AddRef(ma_IAudioRenderClient* pThis) { return pThis->lpVtbl->AddRef(pThis); } +static MA_INLINE ULONG ma_IAudioRenderClient_Release(ma_IAudioRenderClient* pThis) { return pThis->lpVtbl->Release(pThis); } +static MA_INLINE HRESULT ma_IAudioRenderClient_GetBuffer(ma_IAudioRenderClient* pThis, ma_uint32 numFramesRequested, BYTE** ppData) { return pThis->lpVtbl->GetBuffer(pThis, numFramesRequested, ppData); } +static MA_INLINE 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; +}; +static MA_INLINE HRESULT ma_IAudioCaptureClient_QueryInterface(ma_IAudioCaptureClient* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +static MA_INLINE ULONG ma_IAudioCaptureClient_AddRef(ma_IAudioCaptureClient* pThis) { return pThis->lpVtbl->AddRef(pThis); } +static MA_INLINE ULONG ma_IAudioCaptureClient_Release(ma_IAudioCaptureClient* pThis) { return pThis->lpVtbl->Release(pThis); } +static MA_INLINE 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); } +static MA_INLINE HRESULT ma_IAudioCaptureClient_ReleaseBuffer(ma_IAudioCaptureClient* pThis, ma_uint32 numFramesRead) { return pThis->lpVtbl->ReleaseBuffer(pThis, numFramesRead); } +static MA_INLINE HRESULT ma_IAudioCaptureClient_GetNextPacketSize(ma_IAudioCaptureClient* pThis, ma_uint32* pNumFramesInNextPacket) { return pThis->lpVtbl->GetNextPacketSize(pThis, pNumFramesInNextPacket); } + +#if defined(MA_WIN32_UWP) +/* mmdevapi Functions */ +typedef HRESULT (WINAPI * MA_PFN_ActivateAudioInterfaceAsync)(const wchar_t* deviceInterfacePath, const IID* riid, MA_PROPVARIANT* activationParams, ma_IActivateAudioInterfaceCompletionHandler* completionHandler, ma_IActivateAudioInterfaceAsyncOperation** activationOperation); +#endif + +/* Avrt Functions */ +typedef HANDLE (WINAPI * MA_PFN_AvSetMmThreadCharacteristicsA)(const char* TaskName, DWORD* TaskIndex); +typedef BOOL (WINAPI * MA_PFN_AvRevertMmThreadCharacteristics)(HANDLE AvrtHandle); + +#if !defined(MA_WIN32_DESKTOP) && !defined(MA_WIN32_GDK) +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_ATOMIC(4, ma_uint32) counter; + HANDLE hEvent; +}; + +static 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; +} + +static ULONG STDMETHODCALLTYPE ma_completion_handler_uwp_AddRef(ma_completion_handler_uwp* pThis) +{ + return (ULONG)ma_atomic_fetch_add_32(&pThis->counter, 1) + 1; +} + +static ULONG STDMETHODCALLTYPE ma_completion_handler_uwp_Release(ma_completion_handler_uwp* pThis) +{ + ma_uint32 newRefCount = ma_atomic_fetch_sub_32(&pThis->counter, 1) - 1; + if (newRefCount == 0) { + return 0; /* We don't free anything here because we never allocate the object on the heap. */ + } + + return (ULONG)newRefCount; +} + +static 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 +}; + +static 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_result_from_GetLastError(GetLastError()); + } + + return MA_SUCCESS; +} + +static void ma_completion_handler_uwp_uninit(ma_completion_handler_uwp* pHandler) +{ + if (pHandler->hEvent != NULL) { + CloseHandle(pHandler->hEvent); + } +} + +static void ma_completion_handler_uwp_wait(ma_completion_handler_uwp* pHandler) +{ + WaitForSingleObject((HANDLE)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. */ +#if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK) +static 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; +} + +static ULONG STDMETHODCALLTYPE ma_IMMNotificationClient_AddRef(ma_IMMNotificationClient* pThis) +{ + return (ULONG)ma_atomic_fetch_add_32(&pThis->counter, 1) + 1; +} + +static ULONG STDMETHODCALLTYPE ma_IMMNotificationClient_Release(ma_IMMNotificationClient* pThis) +{ + ma_uint32 newRefCount = ma_atomic_fetch_sub_32(&pThis->counter, 1) - 1; + if (newRefCount == 0) { + return 0; /* We don't free anything here because we never allocate the object on the heap. */ + } + + return (ULONG)newRefCount; +} + +static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDeviceStateChanged(ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID, DWORD dwNewState) +{ + ma_bool32 isThisDevice = MA_FALSE; + ma_bool32 isCapture = MA_FALSE; + ma_bool32 isPlayback = MA_FALSE; + +#ifdef MA_DEBUG_OUTPUT + /*ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "IMMNotificationClient_OnDeviceStateChanged(pDeviceID=%S, dwNewState=%u)\n", (pDeviceID != NULL) ? pDeviceID : L"(NULL)", (unsigned int)dwNewState);*/ +#endif + + /* + There have been reports of a hang when a playback device is disconnected. The idea with this code is to explicitly stop the device if we detect + that the device is disabled or has been unplugged. + */ + if (pThis->pDevice->wasapi.allowCaptureAutoStreamRouting && (pThis->pDevice->type == ma_device_type_capture || pThis->pDevice->type == ma_device_type_duplex || pThis->pDevice->type == ma_device_type_loopback)) { + isCapture = MA_TRUE; + if (ma_strcmp_WCHAR(pThis->pDevice->capture.id.wasapi, pDeviceID) == 0) { + isThisDevice = MA_TRUE; + } + } + + if (pThis->pDevice->wasapi.allowPlaybackAutoStreamRouting && (pThis->pDevice->type == ma_device_type_playback || pThis->pDevice->type == ma_device_type_duplex)) { + isPlayback = MA_TRUE; + if (ma_strcmp_WCHAR(pThis->pDevice->playback.id.wasapi, pDeviceID) == 0) { + isThisDevice = MA_TRUE; + } + } + + + /* + If the device ID matches our device we need to mark our device as detached and stop it. When a + device is added in OnDeviceAdded(), we'll restart it. We only mark it as detached if the device + was started at the time of being removed. + */ + if (isThisDevice) { + if ((dwNewState & MA_MM_DEVICE_STATE_ACTIVE) == 0) { + /* + Unplugged or otherwise unavailable. Mark as detached if we were in a playing state. We'll + use this to determine whether or not we need to automatically start the device when it's + plugged back in again. + */ + if (ma_device_get_state(pThis->pDevice) == ma_device_state_started) { + if (isPlayback) { + pThis->pDevice->wasapi.isDetachedPlayback = MA_TRUE; + } + if (isCapture) { + pThis->pDevice->wasapi.isDetachedCapture = MA_TRUE; + } + + ma_device_stop(pThis->pDevice); + } + } + + if ((dwNewState & MA_MM_DEVICE_STATE_ACTIVE) != 0) { + /* The device was activated. If we were detached, we need to start it again. */ + ma_bool8 tryRestartingDevice = MA_FALSE; + + if (isPlayback) { + if (pThis->pDevice->wasapi.isDetachedPlayback) { + pThis->pDevice->wasapi.isDetachedPlayback = MA_FALSE; + ma_device_reroute__wasapi(pThis->pDevice, ma_device_type_playback); + tryRestartingDevice = MA_TRUE; + } + } + + if (isCapture) { + if (pThis->pDevice->wasapi.isDetachedCapture) { + pThis->pDevice->wasapi.isDetachedCapture = MA_FALSE; + ma_device_reroute__wasapi(pThis->pDevice, (pThis->pDevice->type == ma_device_type_loopback) ? ma_device_type_loopback : ma_device_type_capture); + tryRestartingDevice = MA_TRUE; + } + } + + if (tryRestartingDevice) { + if (pThis->pDevice->wasapi.isDetachedPlayback == MA_FALSE && pThis->pDevice->wasapi.isDetachedCapture == MA_FALSE) { + ma_device_start(pThis->pDevice); + } + } + } + } + + return S_OK; +} + +static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDeviceAdded(ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID) +{ +#ifdef MA_DEBUG_OUTPUT + /*ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "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; +} + +static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDeviceRemoved(ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID) +{ +#ifdef MA_DEBUG_OUTPUT + /*ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "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; +} + +static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDefaultDeviceChanged(ma_IMMNotificationClient* pThis, ma_EDataFlow dataFlow, ma_ERole role, const WCHAR* pDefaultDeviceID) +{ +#ifdef MA_DEBUG_OUTPUT + /*ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "IMMNotificationClient_OnDefaultDeviceChanged(dataFlow=%d, role=%d, pDefaultDeviceID=%S)\n", dataFlow, role, (pDefaultDeviceID != NULL) ? pDefaultDeviceID : L"(NULL)");*/ +#endif + + (void)role; + + /* We only care about devices with the same data flow 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) || + (pThis->pDevice->type == ma_device_type_loopback && dataFlow != ma_eRender)) { + ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Stream rerouting abandoned because dataFlow does match device type.\n"); + return S_OK; + } + + /* We need to consider dataFlow as ma_eCapture if device is ma_device_type_loopback */ + if (pThis->pDevice->type == ma_device_type_loopback) { + dataFlow = ma_eCapture; + } + + /* Don't do automatic stream routing if we're not allowed. */ + if ((dataFlow == ma_eRender && pThis->pDevice->wasapi.allowPlaybackAutoStreamRouting == MA_FALSE) || + (dataFlow == ma_eCapture && pThis->pDevice->wasapi.allowCaptureAutoStreamRouting == MA_FALSE)) { + ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Stream rerouting abandoned because automatic stream routing has been disabled by the device config.\n"); + 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)) { + ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Stream rerouting abandoned because the device shared mode is exclusive.\n"); + return S_OK; + } + + + + /* + Second attempt at device rerouting. We're going to retrieve the device's state at the time of + the route change. We're then going to stop the device, reinitialize the device, and then start + it again if the state before stopping was ma_device_state_started. + */ + { + ma_uint32 previousState = ma_device_get_state(pThis->pDevice); + ma_bool8 restartDevice = MA_FALSE; + + if (previousState == ma_device_state_uninitialized || previousState == ma_device_state_starting) { + ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Stream rerouting abandoned because the device is in the process of starting.\n"); + return S_OK; + } + + if (previousState == ma_device_state_started) { + ma_device_stop(pThis->pDevice); + restartDevice = MA_TRUE; + } + + if (pDefaultDeviceID != NULL) { /* <-- The input device ID will be null if there's no other device available. */ + ma_mutex_lock(&pThis->pDevice->wasapi.rerouteLock); + { + if (dataFlow == ma_eRender) { + ma_device_reroute__wasapi(pThis->pDevice, ma_device_type_playback); + + if (pThis->pDevice->wasapi.isDetachedPlayback) { + pThis->pDevice->wasapi.isDetachedPlayback = MA_FALSE; + + if (pThis->pDevice->type == ma_device_type_duplex && pThis->pDevice->wasapi.isDetachedCapture) { + restartDevice = MA_FALSE; /* It's a duplex device and the capture side is detached. We cannot be restarting the device just yet. */ + } + else { + restartDevice = MA_TRUE; /* It's not a duplex device, or the capture side is also attached so we can go ahead and restart the device. */ + } + } + } + else { + ma_device_reroute__wasapi(pThis->pDevice, (pThis->pDevice->type == ma_device_type_loopback) ? ma_device_type_loopback : ma_device_type_capture); + + if (pThis->pDevice->wasapi.isDetachedCapture) { + pThis->pDevice->wasapi.isDetachedCapture = MA_FALSE; + + if (pThis->pDevice->type == ma_device_type_duplex && pThis->pDevice->wasapi.isDetachedPlayback) { + restartDevice = MA_FALSE; /* It's a duplex device and the playback side is detached. We cannot be restarting the device just yet. */ + } + else { + restartDevice = MA_TRUE; /* It's not a duplex device, or the playback side is also attached so we can go ahead and restart the device. */ + } + } + } + } + ma_mutex_unlock(&pThis->pDevice->wasapi.rerouteLock); + + if (restartDevice) { + ma_device_start(pThis->pDevice); + } + } + } + + return S_OK; +} + +static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnPropertyValueChanged(ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID, const PROPERTYKEY key) +{ +#ifdef MA_DEBUG_OUTPUT + /*ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "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 */ + +static const char* ma_to_usage_string__wasapi(ma_wasapi_usage usage) +{ + switch (usage) + { + case ma_wasapi_usage_default: return NULL; + case ma_wasapi_usage_games: return "Games"; + case ma_wasapi_usage_pro_audio: return "Pro Audio"; + default: break; + } + + return NULL; +} + +#if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK) +typedef ma_IMMDevice ma_WASAPIDeviceInterface; +#else +typedef ma_IUnknown ma_WASAPIDeviceInterface; +#endif + + +#define MA_CONTEXT_COMMAND_QUIT__WASAPI 1 +#define MA_CONTEXT_COMMAND_CREATE_IAUDIOCLIENT__WASAPI 2 +#define MA_CONTEXT_COMMAND_RELEASE_IAUDIOCLIENT__WASAPI 3 + +static ma_context_command__wasapi ma_context_init_command__wasapi(int code) +{ + ma_context_command__wasapi cmd; + + MA_ZERO_OBJECT(&cmd); + cmd.code = code; + + return cmd; +} + +static ma_result ma_context_post_command__wasapi(ma_context* pContext, const ma_context_command__wasapi* pCmd) +{ + /* For now we are doing everything synchronously, but I might relax this later if the need arises. */ + ma_result result; + ma_bool32 isUsingLocalEvent = MA_FALSE; + ma_event localEvent; + + MA_ASSERT(pContext != NULL); + MA_ASSERT(pCmd != NULL); + + if (pCmd->pEvent == NULL) { + isUsingLocalEvent = MA_TRUE; + + result = ma_event_init(&localEvent); + if (result != MA_SUCCESS) { + return result; /* Failed to create the event for this command. */ + } + } + + /* Here is where we add the command to the list. If there's not enough room we'll spin until there is. */ + ma_mutex_lock(&pContext->wasapi.commandLock); + { + ma_uint32 index; + + /* Spin until we've got some space available. */ + while (pContext->wasapi.commandCount == ma_countof(pContext->wasapi.commands)) { + ma_yield(); + } + + /* Space is now available. Can safely add to the list. */ + index = (pContext->wasapi.commandIndex + pContext->wasapi.commandCount) % ma_countof(pContext->wasapi.commands); + pContext->wasapi.commands[index] = *pCmd; + pContext->wasapi.commands[index].pEvent = &localEvent; + pContext->wasapi.commandCount += 1; + + /* Now that the command has been added, release the semaphore so ma_context_next_command__wasapi() can return. */ + ma_semaphore_release(&pContext->wasapi.commandSem); + } + ma_mutex_unlock(&pContext->wasapi.commandLock); + + if (isUsingLocalEvent) { + ma_event_wait(&localEvent); + ma_event_uninit(&localEvent); + } + + return MA_SUCCESS; +} + +static ma_result ma_context_next_command__wasapi(ma_context* pContext, ma_context_command__wasapi* pCmd) +{ + ma_result result = MA_SUCCESS; + + MA_ASSERT(pContext != NULL); + MA_ASSERT(pCmd != NULL); + + result = ma_semaphore_wait(&pContext->wasapi.commandSem); + if (result == MA_SUCCESS) { + ma_mutex_lock(&pContext->wasapi.commandLock); + { + *pCmd = pContext->wasapi.commands[pContext->wasapi.commandIndex]; + pContext->wasapi.commandIndex = (pContext->wasapi.commandIndex + 1) % ma_countof(pContext->wasapi.commands); + pContext->wasapi.commandCount -= 1; + } + ma_mutex_unlock(&pContext->wasapi.commandLock); + } + + return result; +} + +static ma_thread_result MA_THREADCALL ma_context_command_thread__wasapi(void* pUserData) +{ + ma_result result; + ma_context* pContext = (ma_context*)pUserData; + MA_ASSERT(pContext != NULL); + + for (;;) { + ma_context_command__wasapi cmd; + result = ma_context_next_command__wasapi(pContext, &cmd); + if (result != MA_SUCCESS) { + break; + } + + switch (cmd.code) + { + case MA_CONTEXT_COMMAND_QUIT__WASAPI: + { + /* Do nothing. Handled after the switch. */ + } break; + + case MA_CONTEXT_COMMAND_CREATE_IAUDIOCLIENT__WASAPI: + { + if (cmd.data.createAudioClient.deviceType == ma_device_type_playback) { + *cmd.data.createAudioClient.pResult = ma_result_from_HRESULT(ma_IAudioClient_GetService((ma_IAudioClient*)cmd.data.createAudioClient.pAudioClient, &MA_IID_IAudioRenderClient, cmd.data.createAudioClient.ppAudioClientService)); + } else { + *cmd.data.createAudioClient.pResult = ma_result_from_HRESULT(ma_IAudioClient_GetService((ma_IAudioClient*)cmd.data.createAudioClient.pAudioClient, &MA_IID_IAudioCaptureClient, cmd.data.createAudioClient.ppAudioClientService)); + } + } break; + + case MA_CONTEXT_COMMAND_RELEASE_IAUDIOCLIENT__WASAPI: + { + if (cmd.data.releaseAudioClient.deviceType == ma_device_type_playback) { + if (cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientPlayback != NULL) { + ma_IAudioClient_Release((ma_IAudioClient*)cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientPlayback); + cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientPlayback = NULL; + } + } + + if (cmd.data.releaseAudioClient.deviceType == ma_device_type_capture) { + if (cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientCapture != NULL) { + ma_IAudioClient_Release((ma_IAudioClient*)cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientCapture); + cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientCapture = NULL; + } + } + } break; + + default: + { + /* Unknown command. Ignore it, but trigger an assert in debug mode so we're aware of it. */ + MA_ASSERT(MA_FALSE); + } break; + } + + if (cmd.pEvent != NULL) { + ma_event_signal(cmd.pEvent); + } + + if (cmd.code == MA_CONTEXT_COMMAND_QUIT__WASAPI) { + break; /* Received a quit message. Get out of here. */ + } + } + + return (ma_thread_result)0; +} + +static ma_result ma_device_create_IAudioClient_service__wasapi(ma_context* pContext, ma_device_type deviceType, ma_IAudioClient* pAudioClient, void** ppAudioClientService) +{ + ma_result result; + ma_result cmdResult; + ma_context_command__wasapi cmd = ma_context_init_command__wasapi(MA_CONTEXT_COMMAND_CREATE_IAUDIOCLIENT__WASAPI); + cmd.data.createAudioClient.deviceType = deviceType; + cmd.data.createAudioClient.pAudioClient = (void*)pAudioClient; + cmd.data.createAudioClient.ppAudioClientService = ppAudioClientService; + cmd.data.createAudioClient.pResult = &cmdResult; /* Declared locally, but won't be dereferenced after this function returns since execution of the command will wait here. */ + + result = ma_context_post_command__wasapi(pContext, &cmd); /* This will not return until the command has actually been run. */ + if (result != MA_SUCCESS) { + return result; + } + + return *cmd.data.createAudioClient.pResult; +} + +#if 0 /* Not used at the moment, but leaving here for future use. */ +static ma_result ma_device_release_IAudioClient_service__wasapi(ma_device* pDevice, ma_device_type deviceType) +{ + ma_result result; + ma_context_command__wasapi cmd = ma_context_init_command__wasapi(MA_CONTEXT_COMMAND_RELEASE_IAUDIOCLIENT__WASAPI); + cmd.data.releaseAudioClient.pDevice = pDevice; + cmd.data.releaseAudioClient.deviceType = deviceType; + + result = ma_context_post_command__wasapi(pDevice->pContext, &cmd); /* This will not return until the command has actually been run. */ + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} +#endif + + +static void ma_add_native_data_format_to_device_info_from_WAVEFORMATEX(const MA_WAVEFORMATEX* pWF, ma_share_mode shareMode, ma_device_info* pInfo) +{ + MA_ASSERT(pWF != NULL); + MA_ASSERT(pInfo != NULL); + + if (pInfo->nativeDataFormatCount >= ma_countof(pInfo->nativeDataFormats)) { + return; /* Too many data formats. Need to ignore this one. Don't think this should ever happen with WASAPI. */ + } + + pInfo->nativeDataFormats[pInfo->nativeDataFormatCount].format = ma_format_from_WAVEFORMATEX(pWF); + pInfo->nativeDataFormats[pInfo->nativeDataFormatCount].channels = pWF->nChannels; + pInfo->nativeDataFormats[pInfo->nativeDataFormatCount].sampleRate = pWF->nSamplesPerSec; + pInfo->nativeDataFormats[pInfo->nativeDataFormatCount].flags = (shareMode == ma_share_mode_exclusive) ? MA_DATA_FORMAT_FLAG_EXCLUSIVE_MODE : 0; + pInfo->nativeDataFormatCount += 1; +} + +static ma_result ma_context_get_device_info_from_IAudioClient__wasapi(ma_context* pContext, /*ma_IMMDevice**/void* pMMDevice, ma_IAudioClient* pAudioClient, ma_device_info* pInfo) +{ + HRESULT hr; + MA_WAVEFORMATEX* pWF = NULL; + + MA_ASSERT(pAudioClient != NULL); + MA_ASSERT(pInfo != NULL); + + /* Shared Mode. We use GetMixFormat() here. */ + hr = ma_IAudioClient_GetMixFormat((ma_IAudioClient*)pAudioClient, (MA_WAVEFORMATEX**)&pWF); + if (SUCCEEDED(hr)) { + ma_add_native_data_format_to_device_info_from_WAVEFORMATEX(pWF, ma_share_mode_shared, pInfo); + } else { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve mix format for device info retrieval."); + return ma_result_from_HRESULT(hr); + } + + /* + Exlcusive Mode. We repeatedly call IsFormatSupported() here. This is not currently supported on + UWP. Failure to retrieve the exclusive mode format is not considered an error, so from here on + out, MA_SUCCESS is guaranteed to be returned. + */ + #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK) + { + ma_IPropertyStore *pProperties; + + /* + 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. + */ + hr = ma_IMMDevice_OpenPropertyStore((ma_IMMDevice*)pMMDevice, STGM_READ, &pProperties); + if (SUCCEEDED(hr)) { + MA_PROPVARIANT var; + ma_PropVariantInit(&var); + + hr = ma_IPropertyStore_GetValue(pProperties, &MA_PKEY_AudioEngine_DeviceFormat, &var); + if (SUCCEEDED(hr)) { + pWF = (MA_WAVEFORMATEX*)var.blob.pBlobData; + + /* + 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); + if (SUCCEEDED(hr)) { + /* The format returned by PKEY_AudioEngine_DeviceFormat is supported. */ + ma_add_native_data_format_to_device_info_from_WAVEFORMATEX(pWF, ma_share_mode_exclusive, pInfo); + } else { + /* + 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 = pWF->nChannels; + ma_channel defaultChannelMap[MA_MAX_CHANNELS]; + MA_WAVEFORMATEXTENSIBLE wf; + ma_bool32 found; + ma_uint32 iFormat; + + /* Make sure we don't overflow the channel map. */ + if (channels > MA_MAX_CHANNELS) { + channels = MA_MAX_CHANNELS; + } + + ma_channel_map_init_standard(ma_standard_channel_map_microsoft, defaultChannelMap, ma_countof(defaultChannelMap), channels); + + MA_ZERO_OBJECT(&wf); + wf.cbSize = sizeof(wf); + wf.wFormatTag = WAVE_FORMAT_EXTENSIBLE; + wf.nChannels = (WORD)channels; + wf.dwChannelMask = ma_channel_map_to_channel_mask__win32(defaultChannelMap, channels); + + found = MA_FALSE; + for (iFormat = 0; iFormat < ma_countof(g_maFormatPriorities); ++iFormat) { + ma_format format = g_maFormatPriorities[iFormat]; + ma_uint32 iSampleRate; + + wf.wBitsPerSample = (WORD)(ma_get_bytes_per_sample(format)*8); + wf.nBlockAlign = (WORD)(wf.nChannels * wf.wBitsPerSample / 8); + wf.nAvgBytesPerSec = wf.nBlockAlign * wf.nSamplesPerSec; + wf.Samples.wValidBitsPerSample = /*(format == ma_format_s24_32) ? 24 :*/ wf.wBitsPerSample; + if (format == ma_format_f32) { + wf.SubFormat = MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; + } else { + wf.SubFormat = MA_GUID_KSDATAFORMAT_SUBTYPE_PCM; + } + + for (iSampleRate = 0; iSampleRate < ma_countof(g_maStandardSampleRatePriorities); ++iSampleRate) { + wf.nSamplesPerSec = g_maStandardSampleRatePriorities[iSampleRate]; + + hr = ma_IAudioClient_IsFormatSupported((ma_IAudioClient*)pAudioClient, MA_AUDCLNT_SHAREMODE_EXCLUSIVE, (MA_WAVEFORMATEX*)&wf, NULL); + if (SUCCEEDED(hr)) { + ma_add_native_data_format_to_device_info_from_WAVEFORMATEX((MA_WAVEFORMATEX*)&wf, ma_share_mode_exclusive, pInfo); + found = MA_TRUE; + break; + } + } + + if (found) { + break; + } + } + + ma_PropVariantClear(pContext, &var); + + if (!found) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "[WASAPI] Failed to find suitable device format for device info retrieval."); + } + } + } else { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "[WASAPI] Failed to retrieve device format for device info retrieval."); + } + + ma_IPropertyStore_Release(pProperties); + } else { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "[WASAPI] Failed to open property store for device info retrieval."); + } + } + #else + { + (void)pMMDevice; /* Unused. */ + } + #endif + + return MA_SUCCESS; +} + +#if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK) +static ma_EDataFlow ma_device_type_to_EDataFlow(ma_device_type deviceType) +{ + if (deviceType == ma_device_type_playback) { + return ma_eRender; + } else if (deviceType == ma_device_type_capture) { + return ma_eCapture; + } else { + MA_ASSERT(MA_FALSE); + return ma_eRender; /* Should never hit this. */ + } +} + +static ma_result ma_context_create_IMMDeviceEnumerator__wasapi(ma_context* pContext, ma_IMMDeviceEnumerator** ppDeviceEnumerator) +{ + HRESULT hr; + ma_IMMDeviceEnumerator* pDeviceEnumerator; + + MA_ASSERT(pContext != NULL); + MA_ASSERT(ppDeviceEnumerator != NULL); + + *ppDeviceEnumerator = NULL; /* Safety. */ + + hr = ma_CoCreateInstance(pContext, &MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator); + if (FAILED(hr)) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create device enumerator."); + return ma_result_from_HRESULT(hr); + } + + *ppDeviceEnumerator = pDeviceEnumerator; + + return MA_SUCCESS; +} + +static WCHAR* ma_context_get_default_device_id_from_IMMDeviceEnumerator__wasapi(ma_context* pContext, ma_IMMDeviceEnumerator* pDeviceEnumerator, ma_device_type deviceType) +{ + HRESULT hr; + ma_IMMDevice* pMMDefaultDevice = NULL; + WCHAR* pDefaultDeviceID = NULL; + ma_EDataFlow dataFlow; + ma_ERole role; + + MA_ASSERT(pContext != NULL); + MA_ASSERT(pDeviceEnumerator != NULL); + + (void)pContext; + + /* Grab the EDataFlow type from the device type. */ + dataFlow = ma_device_type_to_EDataFlow(deviceType); + + /* The role is always eConsole, but we may make this configurable later. */ + role = ma_eConsole; + + hr = ma_IMMDeviceEnumerator_GetDefaultAudioEndpoint(pDeviceEnumerator, dataFlow, role, &pMMDefaultDevice); + if (FAILED(hr)) { + return NULL; + } + + hr = ma_IMMDevice_GetId(pMMDefaultDevice, &pDefaultDeviceID); + + ma_IMMDevice_Release(pMMDefaultDevice); + pMMDefaultDevice = NULL; + + if (FAILED(hr)) { + return NULL; + } + + return pDefaultDeviceID; +} + +static WCHAR* ma_context_get_default_device_id__wasapi(ma_context* pContext, ma_device_type deviceType) /* Free the returned pointer with ma_CoTaskMemFree() */ +{ + ma_result result; + ma_IMMDeviceEnumerator* pDeviceEnumerator; + WCHAR* pDefaultDeviceID = NULL; + + MA_ASSERT(pContext != NULL); + + result = ma_context_create_IMMDeviceEnumerator__wasapi(pContext, &pDeviceEnumerator); + if (result != MA_SUCCESS) { + return NULL; + } + + pDefaultDeviceID = ma_context_get_default_device_id_from_IMMDeviceEnumerator__wasapi(pContext, pDeviceEnumerator, deviceType); + + ma_IMMDeviceEnumerator_Release(pDeviceEnumerator); + return pDefaultDeviceID; +} + +static 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); + + hr = ma_CoCreateInstance(pContext, &MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator); + if (FAILED(hr)) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create IMMDeviceEnumerator.\n"); + return ma_result_from_HRESULT(hr); + } + + if (pDeviceID == NULL) { + hr = ma_IMMDeviceEnumerator_GetDefaultAudioEndpoint(pDeviceEnumerator, (deviceType == ma_device_type_capture) ? ma_eCapture : ma_eRender, ma_eConsole, ppMMDevice); + } else { + hr = ma_IMMDeviceEnumerator_GetDevice(pDeviceEnumerator, pDeviceID->wasapi, ppMMDevice); + } + + ma_IMMDeviceEnumerator_Release(pDeviceEnumerator); + if (FAILED(hr)) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve IMMDevice.\n"); + return ma_result_from_HRESULT(hr); + } + + return MA_SUCCESS; +} + +static ma_result ma_context_get_device_id_from_MMDevice__wasapi(ma_context* pContext, ma_IMMDevice* pMMDevice, ma_device_id* pDeviceID) +{ + WCHAR* pDeviceIDString; + HRESULT hr; + + MA_ASSERT(pDeviceID != NULL); + + hr = ma_IMMDevice_GetId(pMMDevice, &pDeviceIDString); + if (SUCCEEDED(hr)) { + size_t idlen = ma_strlen_WCHAR(pDeviceIDString); + if (idlen+1 > ma_countof(pDeviceID->wasapi)) { + ma_CoTaskMemFree(pContext, pDeviceIDString); + 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(pDeviceID->wasapi, pDeviceIDString, idlen * sizeof(wchar_t)); + pDeviceID->wasapi[idlen] = '\0'; + + ma_CoTaskMemFree(pContext, pDeviceIDString); + + return MA_SUCCESS; + } + + return MA_ERROR; +} + +static ma_result ma_context_get_device_info_from_MMDevice__wasapi(ma_context* pContext, ma_IMMDevice* pMMDevice, WCHAR* pDefaultDeviceID, ma_bool32 onlySimpleInfo, ma_device_info* pInfo) +{ + ma_result result; + HRESULT hr; + + MA_ASSERT(pContext != NULL); + MA_ASSERT(pMMDevice != NULL); + MA_ASSERT(pInfo != NULL); + + /* ID. */ + result = ma_context_get_device_id_from_MMDevice__wasapi(pContext, pMMDevice, &pInfo->id); + if (result == MA_SUCCESS) { + if (pDefaultDeviceID != NULL) { + if (ma_strcmp_WCHAR(pInfo->id.wasapi, pDefaultDeviceID) == 0) { + pInfo->isDefault = MA_TRUE; + } + } + } + + /* Description / Friendly Name */ + { + ma_IPropertyStore *pProperties; + hr = ma_IMMDevice_OpenPropertyStore(pMMDevice, STGM_READ, &pProperties); + if (SUCCEEDED(hr)) { + MA_PROPVARIANT var; + + 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)) { + result = ma_context_get_device_info_from_IAudioClient__wasapi(pContext, pMMDevice, pAudioClient, pInfo); + + ma_IAudioClient_Release(pAudioClient); + return result; + } else { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to activate audio client for device info retrieval."); + return ma_result_from_HRESULT(hr); + } + } + + return MA_SUCCESS; +} + +static ma_result ma_context_enumerate_devices_by_type__wasapi(ma_context* pContext, ma_IMMDeviceEnumerator* pDeviceEnumerator, ma_device_type deviceType, ma_enum_devices_callback_proc callback, void* pUserData) +{ + ma_result result = MA_SUCCESS; + UINT deviceCount; + HRESULT hr; + ma_uint32 iDevice; + WCHAR* pDefaultDeviceID = NULL; + ma_IMMDeviceCollection* pDeviceCollection = NULL; + + MA_ASSERT(pContext != NULL); + MA_ASSERT(callback != NULL); + + /* Grab the default device. We use this to know whether or not flag the returned device info as being the default. */ + pDefaultDeviceID = ma_context_get_default_device_id_from_IMMDeviceEnumerator__wasapi(pContext, pDeviceEnumerator, deviceType); + + /* We need to enumerate the devices which returns a device collection. */ + hr = ma_IMMDeviceEnumerator_EnumAudioEndpoints(pDeviceEnumerator, ma_device_type_to_EDataFlow(deviceType), MA_MM_DEVICE_STATE_ACTIVE, &pDeviceCollection); + if (SUCCEEDED(hr)) { + hr = ma_IMMDeviceCollection_GetCount(pDeviceCollection, &deviceCount); + if (FAILED(hr)) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to get device count.\n"); + result = ma_result_from_HRESULT(hr); + goto done; + } + + for (iDevice = 0; iDevice < deviceCount; ++iDevice) { + ma_device_info deviceInfo; + ma_IMMDevice* pMMDevice; + + MA_ZERO_OBJECT(&deviceInfo); + + hr = ma_IMMDeviceCollection_Item(pDeviceCollection, iDevice, &pMMDevice); + if (SUCCEEDED(hr)) { + result = ma_context_get_device_info_from_MMDevice__wasapi(pContext, pMMDevice, pDefaultDeviceID, 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; + } + } + } + } + } + +done: + if (pDefaultDeviceID != NULL) { + ma_CoTaskMemFree(pContext, pDefaultDeviceID); + pDefaultDeviceID = NULL; + } + + if (pDeviceCollection != NULL) { + ma_IMMDeviceCollection_Release(pDeviceCollection); + pDeviceCollection = NULL; + } + + return result; +} + +static ma_result ma_context_get_IAudioClient_Desktop__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, MA_PROPVARIANT* pActivationParams, 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, pActivationParams, (void**)ppAudioClient); + if (FAILED(hr)) { + return ma_result_from_HRESULT(hr); + } + + return MA_SUCCESS; +} +#else +static ma_result ma_context_get_IAudioClient_UWP__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, MA_PROPVARIANT* pActivationParams, ma_IAudioClient** ppAudioClient, ma_IUnknown** ppActivatedInterface) +{ + ma_IActivateAudioInterfaceAsyncOperation *pAsyncOp = NULL; + ma_completion_handler_uwp completionHandler; + IID iid; + WCHAR* iidStr; + HRESULT hr; + ma_result result; + HRESULT activateResult; + ma_IUnknown* pActivatedInterface; + + MA_ASSERT(pContext != NULL); + MA_ASSERT(ppAudioClient != NULL); + + if (pDeviceID != NULL) { + iidStr = (WCHAR*)pDeviceID->wasapi; + } else { + if (deviceType == ma_device_type_capture) { + iid = MA_IID_DEVINTERFACE_AUDIO_CAPTURE; + } else { + iid = MA_IID_DEVINTERFACE_AUDIO_RENDER; + } + + #if defined(__cplusplus) + hr = StringFromIID(iid, &iidStr); + #else + hr = StringFromIID(&iid, &iidStr); + #endif + if (FAILED(hr)) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to convert device IID to string for ActivateAudioInterfaceAsync(). Out of memory.\n"); + return ma_result_from_HRESULT(hr); + } + } + + result = ma_completion_handler_uwp_init(&completionHandler); + if (result != MA_SUCCESS) { + ma_CoTaskMemFree(pContext, iidStr); + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create event for waiting for ActivateAudioInterfaceAsync().\n"); + return result; + } + + hr = ((MA_PFN_ActivateAudioInterfaceAsync)pContext->wasapi.ActivateAudioInterfaceAsync)(iidStr, &MA_IID_IAudioClient, pActivationParams, (ma_IActivateAudioInterfaceCompletionHandler*)&completionHandler, (ma_IActivateAudioInterfaceAsyncOperation**)&pAsyncOp); + if (FAILED(hr)) { + ma_completion_handler_uwp_uninit(&completionHandler); + ma_CoTaskMemFree(pContext, iidStr); + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] ActivateAudioInterfaceAsync() failed.\n"); + return ma_result_from_HRESULT(hr); + } + + if (pDeviceID == NULL) { + ma_CoTaskMemFree(pContext, iidStr); + } + + /* Wait for the async operation for finish. */ + ma_completion_handler_uwp_wait(&completionHandler); + ma_completion_handler_uwp_uninit(&completionHandler); + + hr = ma_IActivateAudioInterfaceAsyncOperation_GetActivateResult(pAsyncOp, &activateResult, &pActivatedInterface); + ma_IActivateAudioInterfaceAsyncOperation_Release(pAsyncOp); + + if (FAILED(hr) || FAILED(activateResult)) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to activate device.\n"); + return FAILED(hr) ? ma_result_from_HRESULT(hr) : ma_result_from_HRESULT(activateResult); + } + + /* Here is where we grab the IAudioClient interface. */ + hr = ma_IUnknown_QueryInterface(pActivatedInterface, &MA_IID_IAudioClient, (void**)ppAudioClient); + if (FAILED(hr)) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to query IAudioClient interface.\n"); + return ma_result_from_HRESULT(hr); + } + + if (ppActivatedInterface) { + *ppActivatedInterface = pActivatedInterface; + } else { + ma_IUnknown_Release(pActivatedInterface); + } + + return MA_SUCCESS; +} +#endif + + +/* https://docs.microsoft.com/en-us/windows/win32/api/audioclientactivationparams/ne-audioclientactivationparams-audioclient_activation_type */ +typedef enum +{ + MA_AUDIOCLIENT_ACTIVATION_TYPE_DEFAULT, + MA_AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK +} MA_AUDIOCLIENT_ACTIVATION_TYPE; + +/* https://docs.microsoft.com/en-us/windows/win32/api/audioclientactivationparams/ne-audioclientactivationparams-process_loopback_mode */ +typedef enum +{ + MA_PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE, + MA_PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE +} MA_PROCESS_LOOPBACK_MODE; + +/* https://docs.microsoft.com/en-us/windows/win32/api/audioclientactivationparams/ns-audioclientactivationparams-audioclient_process_loopback_params */ +typedef struct +{ + DWORD TargetProcessId; + MA_PROCESS_LOOPBACK_MODE ProcessLoopbackMode; +} MA_AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS; + +#if defined(_MSC_VER) && !defined(__clang__) + #pragma warning(push) + #pragma warning(disable:4201) /* nonstandard extension used: nameless struct/union */ +#elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wpedantic" /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */ + #if defined(__clang__) + #pragma GCC diagnostic ignored "-Wc11-extensions" /* anonymous unions are a C11 extension */ + #endif +#endif +/* https://docs.microsoft.com/en-us/windows/win32/api/audioclientactivationparams/ns-audioclientactivationparams-audioclient_activation_params */ +typedef struct +{ + MA_AUDIOCLIENT_ACTIVATION_TYPE ActivationType; + union + { + MA_AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS ProcessLoopbackParams; + }; +} MA_AUDIOCLIENT_ACTIVATION_PARAMS; +#if defined(_MSC_VER) && !defined(__clang__) + #pragma warning(pop) +#elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))) + #pragma GCC diagnostic pop +#endif + +#define MA_VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK L"VAD\\Process_Loopback" + +static ma_result ma_context_get_IAudioClient__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_uint32 loopbackProcessID, ma_bool32 loopbackProcessExclude, ma_IAudioClient** ppAudioClient, ma_WASAPIDeviceInterface** ppDeviceInterface) +{ + ma_result result; + ma_bool32 usingProcessLoopback = MA_FALSE; + MA_AUDIOCLIENT_ACTIVATION_PARAMS audioclientActivationParams; + MA_PROPVARIANT activationParams; + MA_PROPVARIANT* pActivationParams = NULL; + ma_device_id virtualDeviceID; + + /* Activation parameters specific to loopback mode. Note that process-specific loopback will only work when a default device ID is specified. */ + if (deviceType == ma_device_type_loopback && loopbackProcessID != 0 && pDeviceID == NULL) { + usingProcessLoopback = MA_TRUE; + } + + if (usingProcessLoopback) { + MA_ZERO_OBJECT(&audioclientActivationParams); + audioclientActivationParams.ActivationType = MA_AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK; + audioclientActivationParams.ProcessLoopbackParams.ProcessLoopbackMode = (loopbackProcessExclude) ? MA_PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE : MA_PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE; + audioclientActivationParams.ProcessLoopbackParams.TargetProcessId = (DWORD)loopbackProcessID; + + ma_PropVariantInit(&activationParams); + activationParams.vt = MA_VT_BLOB; + activationParams.blob.cbSize = sizeof(audioclientActivationParams); + activationParams.blob.pBlobData = (BYTE*)&audioclientActivationParams; + pActivationParams = &activationParams; + + /* When requesting a specific device ID we need to use a special device ID. */ + MA_COPY_MEMORY(virtualDeviceID.wasapi, MA_VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, (wcslen(MA_VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK) + 1) * sizeof(wchar_t)); /* +1 for the null terminator. */ + pDeviceID = &virtualDeviceID; + } else { + pActivationParams = NULL; /* No activation parameters required. */ + } + +#if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK) + result = ma_context_get_IAudioClient_Desktop__wasapi(pContext, deviceType, pDeviceID, pActivationParams, ppAudioClient, ppDeviceInterface); +#else + result = ma_context_get_IAudioClient_UWP__wasapi(pContext, deviceType, pDeviceID, pActivationParams, ppAudioClient, ppDeviceInterface); +#endif + + /* + If loopback mode was requested with a process ID and initialization failed, it could be because it's + trying to run on an older version of Windows where it's not supported. We need to let the caller + know about this with a log message. + */ + if (result != MA_SUCCESS) { + if (usingProcessLoopback) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Loopback mode requested to %s process ID %u, but initialization failed. Support for this feature begins with Windows 10 Build 20348. Confirm your version of Windows or consider not using process-specific loopback.\n", (loopbackProcessExclude) ? "exclude" : "include", loopbackProcessID); + } + } + + return result; +} + + +static ma_result ma_context_enumerate_devices__wasapi(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) +{ + /* Different enumeration for desktop and UWP. */ +#if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK) + /* Desktop */ + HRESULT hr; + ma_IMMDeviceEnumerator* pDeviceEnumerator; + + hr = ma_CoCreateInstance(pContext, &MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator); + if (FAILED(hr)) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create device enumerator."); + return ma_result_from_HRESULT(hr); + } + + ma_context_enumerate_devices_by_type__wasapi(pContext, pDeviceEnumerator, ma_device_type_playback, callback, pUserData); + ma_context_enumerate_devices_by_type__wasapi(pContext, pDeviceEnumerator, ma_device_type_capture, callback, pUserData); + + 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); + deviceInfo.isDefault = MA_TRUE; + 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); + deviceInfo.isDefault = MA_TRUE; + cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData); + } + } +#endif + + return MA_SUCCESS; +} + +static ma_result ma_context_get_device_info__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo) +{ +#if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK) + ma_result result; + ma_IMMDevice* pMMDevice = NULL; + WCHAR* pDefaultDeviceID = NULL; + + result = ma_context_get_MMDevice__wasapi(pContext, deviceType, pDeviceID, &pMMDevice); + if (result != MA_SUCCESS) { + return result; + } + + /* We need the default device ID so we can set the isDefault flag in the device info. */ + pDefaultDeviceID = ma_context_get_default_device_id__wasapi(pContext, deviceType); + + result = ma_context_get_device_info_from_MMDevice__wasapi(pContext, pMMDevice, pDefaultDeviceID, MA_FALSE, pDeviceInfo); /* MA_FALSE = !onlySimpleInfo. */ + + if (pDefaultDeviceID != NULL) { + ma_CoTaskMemFree(pContext, pDefaultDeviceID); + pDefaultDeviceID = NULL; + } + + ma_IMMDevice_Release(pMMDevice); + + return result; +#else + 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); + } + + result = ma_context_get_IAudioClient_UWP__wasapi(pContext, deviceType, pDeviceID, NULL, &pAudioClient, NULL); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_context_get_device_info_from_IAudioClient__wasapi(pContext, NULL, pAudioClient, pDeviceInfo); + + pDeviceInfo->isDefault = MA_TRUE; /* UWP only supports default devices. */ + + ma_IAudioClient_Release(pAudioClient); + return result; +#endif +} + +static ma_result ma_device_uninit__wasapi(ma_device* pDevice) +{ + MA_ASSERT(pDevice != NULL); + +#if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK) + 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) { + if (pDevice->wasapi.pMappedBufferPlayback != NULL) { + ma_IAudioRenderClient_ReleaseBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, pDevice->wasapi.mappedBufferPlaybackCap, 0); + pDevice->wasapi.pMappedBufferPlayback = NULL; + pDevice->wasapi.mappedBufferPlaybackCap = 0; + pDevice->wasapi.mappedBufferPlaybackLen = 0; + } + + ma_IAudioRenderClient_Release((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient); + } + if (pDevice->wasapi.pCaptureClient) { + if (pDevice->wasapi.pMappedBufferCapture != NULL) { + ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, pDevice->wasapi.mappedBufferCaptureCap); + pDevice->wasapi.pMappedBufferCapture = NULL; + pDevice->wasapi.mappedBufferCaptureCap = 0; + pDevice->wasapi.mappedBufferCaptureLen = 0; + } + + 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((HANDLE)pDevice->wasapi.hEventPlayback); + } + if (pDevice->wasapi.hEventCapture) { + CloseHandle((HANDLE)pDevice->wasapi.hEventCapture); + } + + return MA_SUCCESS; +} + + +typedef struct +{ + /* Input. */ + ma_format formatIn; + ma_uint32 channelsIn; + ma_uint32 sampleRateIn; + ma_channel channelMapIn[MA_MAX_CHANNELS]; + ma_uint32 periodSizeInFramesIn; + ma_uint32 periodSizeInMillisecondsIn; + ma_uint32 periodsIn; + ma_share_mode shareMode; + ma_performance_profile performanceProfile; + ma_bool32 noAutoConvertSRC; + ma_bool32 noDefaultQualitySRC; + ma_bool32 noHardwareOffloading; + ma_uint32 loopbackProcessID; + ma_bool32 loopbackProcessExclude; + + /* 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 periodSizeInFramesOut; + ma_uint32 periodsOut; + ma_bool32 usingAudioClient3; + char deviceName[256]; + ma_device_id id; +} ma_device_init_internal_data__wasapi; + +static 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) +{ + HRESULT hr; + ma_result result = MA_SUCCESS; + const char* errorMsg = ""; + MA_AUDCLNT_SHAREMODE shareMode = MA_AUDCLNT_SHAREMODE_SHARED; + DWORD streamFlags = 0; + MA_REFERENCE_TIME periodDurationInMicroseconds; + ma_bool32 wasInitializedUsingIAudioClient3 = MA_FALSE; + MA_WAVEFORMATEXTENSIBLE wf; + ma_WASAPIDeviceInterface* pDeviceInterface = NULL; + ma_IAudioClient2* pAudioClient2; + ma_uint32 nativeSampleRate; + ma_bool32 usingProcessLoopback = MA_FALSE; + + MA_ASSERT(pContext != NULL); + MA_ASSERT(pData != NULL); + + /* This function is only used to initialize one device type: either playback, capture or loopback. Never full-duplex. */ + if (deviceType == ma_device_type_duplex) { + return MA_INVALID_ARGS; + } + + usingProcessLoopback = deviceType == ma_device_type_loopback && pData->loopbackProcessID != 0 && pDeviceID == NULL; + + pData->pAudioClient = NULL; + pData->pRenderClient = NULL; + pData->pCaptureClient = NULL; + + streamFlags = MA_AUDCLNT_STREAMFLAGS_EVENTCALLBACK; + if (!pData->noAutoConvertSRC && pData->sampleRateIn != 0 && pData->shareMode != ma_share_mode_exclusive) { /* <-- Exclusive streams must use the native sample rate. */ + streamFlags |= MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM; + } + if (!pData->noDefaultQualitySRC && pData->sampleRateIn != 0 && (streamFlags & MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM) != 0) { + streamFlags |= MA_AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY; + } + if (deviceType == ma_device_type_loopback) { + streamFlags |= MA_AUDCLNT_STREAMFLAGS_LOOPBACK; + } + + result = ma_context_get_IAudioClient__wasapi(pContext, deviceType, pDeviceID, pData->loopbackProcessID, pData->loopbackProcessExclude, &pData->pAudioClient, &pDeviceInterface); + if (result != MA_SUCCESS) { + goto done; + } + + MA_ZERO_OBJECT(&wf); + + /* Try enabling hardware offloading. */ + if (!pData->noHardwareOffloading) { + 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); + } + + pAudioClient2->lpVtbl->Release(pAudioClient2); + } + } + + /* 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) { + #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK) + /* 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)) { + MA_PROPVARIANT prop; + ma_PropVariantInit(&prop); + hr = ma_IPropertyStore_GetValue(pStore, &MA_PKEY_AudioEngine_DeviceFormat, &prop); + if (SUCCEEDED(hr)) { + MA_WAVEFORMATEX* pActualFormat = (MA_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(MA_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. */ + MA_WAVEFORMATEXTENSIBLE* pNativeFormat = NULL; + hr = ma_IAudioClient_GetMixFormat((ma_IAudioClient*)pData->pAudioClient, (MA_WAVEFORMATEX**)&pNativeFormat); + if (hr != S_OK) { + /* When using process-specific loopback, GetMixFormat() seems to always fail. */ + if (usingProcessLoopback) { + wf.wFormatTag = WAVE_FORMAT_IEEE_FLOAT; + wf.nChannels = 2; + wf.nSamplesPerSec = 44100; + wf.wBitsPerSample = 32; + wf.nBlockAlign = wf.nChannels * wf.wBitsPerSample / 8; + wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign; + wf.cbSize = sizeof(MA_WAVEFORMATEX); + + result = MA_SUCCESS; + } else { + result = MA_FORMAT_NOT_SUPPORTED; + } + } else { + /* + I've seen cases where cbSize will be set to sizeof(WAVEFORMATEX) even though the structure itself + is given the format tag of WAVE_FORMAT_EXTENSIBLE. If the format tag is WAVE_FORMAT_EXTENSIBLE + want to make sure we copy the whole WAVEFORMATEXTENSIBLE structure. Otherwise we'll have to be + safe and only copy the WAVEFORMATEX part. + */ + if (pNativeFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { + MA_COPY_MEMORY(&wf, pNativeFormat, sizeof(MA_WAVEFORMATEXTENSIBLE)); + } else { + /* I've seen a case where cbSize was set to 0. Assume sizeof(WAVEFORMATEX) in this case. */ + size_t cbSize = pNativeFormat->cbSize; + if (cbSize == 0) { + cbSize = sizeof(MA_WAVEFORMATEX); + } + + /* Make sure we don't copy more than the capacity of `wf`. */ + if (cbSize > sizeof(wf)) { + cbSize = sizeof(wf); + } + + MA_COPY_MEMORY(&wf, pNativeFormat, cbSize); + } + + 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; + } + + /* + Override the native sample rate with the one requested by the caller, but only if we're not using the default sample rate. We'll use + WASAPI to perform the sample rate conversion. + */ + nativeSampleRate = wf.nSamplesPerSec; + if (streamFlags & MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM) { + wf.nSamplesPerSec = (pData->sampleRateIn != 0) ? pData->sampleRateIn : MA_DEFAULT_SAMPLE_RATE; + wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign; + } + + pData->formatOut = ma_format_from_WAVEFORMATEX((MA_WAVEFORMATEX*)&wf); + if (pData->formatOut == ma_format_unknown) { + /* + The format isn't supported. This is almost certainly because the exclusive mode format isn't supported by miniaudio. We need to return MA_SHARE_MODE_NOT_SUPPORTED + in this case so that the caller can detect it and fall back to shared mode if desired. We should never get here if shared mode was requested, but just for + completeness we'll check for it and return MA_FORMAT_NOT_SUPPORTED. + */ + if (shareMode == MA_AUDCLNT_SHAREMODE_EXCLUSIVE) { + result = MA_SHARE_MODE_NOT_SUPPORTED; + } else { + result = MA_FORMAT_NOT_SUPPORTED; + } + + errorMsg = "[WASAPI] Native format not supported."; + goto done; + } + + pData->channelsOut = wf.nChannels; + pData->sampleRateOut = wf.nSamplesPerSec; + + /* + Get the internal channel map based on the channel mask. There is a possibility that GetMixFormat() returns + a WAVEFORMATEX instead of a WAVEFORMATEXTENSIBLE, in which case the channel mask will be undefined. In this + case we'll just use the default channel map. + */ + if (wf.wFormatTag == WAVE_FORMAT_EXTENSIBLE || wf.cbSize >= sizeof(MA_WAVEFORMATEXTENSIBLE)) { + ma_channel_mask_to_channel_map__win32(wf.dwChannelMask, pData->channelsOut, pData->channelMapOut); + } else { + ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pData->channelMapOut, ma_countof(pData->channelMapOut), pData->channelsOut); + } + + /* Period size. */ + pData->periodsOut = (pData->periodsIn != 0) ? pData->periodsIn : MA_DEFAULT_PERIODS; + pData->periodSizeInFramesOut = pData->periodSizeInFramesIn; + if (pData->periodSizeInFramesOut == 0) { + if (pData->periodSizeInMillisecondsIn == 0) { + if (pData->performanceProfile == ma_performance_profile_low_latency) { + pData->periodSizeInFramesOut = ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY, wf.nSamplesPerSec); + } else { + pData->periodSizeInFramesOut = ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE, wf.nSamplesPerSec); + } + } else { + pData->periodSizeInFramesOut = ma_calculate_buffer_size_in_frames_from_milliseconds(pData->periodSizeInMillisecondsIn, wf.nSamplesPerSec); + } + } + + periodDurationInMicroseconds = ((ma_uint64)pData->periodSizeInFramesOut * 1000 * 1000) / wf.nSamplesPerSec; + + + /* 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 = periodDurationInMicroseconds * 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, streamFlags, bufferDuration, bufferDuration, (MA_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) { + ma_uint32 bufferSizeInFrames; + hr = ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pData->pAudioClient, &bufferSizeInFrames); + if (SUCCEEDED(hr)) { + bufferDuration = (MA_REFERENCE_TIME)((10000.0 * 1000 / wf.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); + + #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK) + 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, streamFlags, bufferDuration, bufferDuration, (MA_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_BUSY; + } else { + errorMsg = "[WASAPI] Failed to initialize device in exclusive mode."; result = ma_result_from_HRESULT(hr); + } + goto done; + } + } + + if (shareMode == MA_AUDCLNT_SHAREMODE_SHARED) { + /* + Low latency shared mode via IAudioClient3. + + NOTE + ==== + Contrary to the documentation on MSDN (https://docs.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient3-initializesharedaudiostream), the + use of AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM and AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY with IAudioClient3_InitializeSharedAudioStream() absolutely does not work. Using + any of these flags will result in HRESULT code 0x88890021. The other problem is that calling IAudioClient3_GetSharedModeEnginePeriod() with a sample rate different to + that returned by IAudioClient_GetMixFormat() also results in an error. I'm therefore disabling low-latency shared mode with AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM. + */ + #ifndef MA_WASAPI_NO_LOW_LATENCY_SHARED_MODE + { + if ((streamFlags & MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM) == 0 || nativeSampleRate == wf.nSamplesPerSec) { + ma_IAudioClient3* pAudioClient3 = NULL; + hr = ma_IAudioClient_QueryInterface(pData->pAudioClient, &MA_IID_IAudioClient3, (void**)&pAudioClient3); + if (SUCCEEDED(hr)) { + ma_uint32 defaultPeriodInFrames; + ma_uint32 fundamentalPeriodInFrames; + ma_uint32 minPeriodInFrames; + ma_uint32 maxPeriodInFrames; + hr = ma_IAudioClient3_GetSharedModeEnginePeriod(pAudioClient3, (MA_WAVEFORMATEX*)&wf, &defaultPeriodInFrames, &fundamentalPeriodInFrames, &minPeriodInFrames, &maxPeriodInFrames); + if (SUCCEEDED(hr)) { + ma_uint32 desiredPeriodInFrames = pData->periodSizeInFramesOut; + ma_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); + + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[WASAPI] Trying IAudioClient3_InitializeSharedAudioStream(actualPeriodInFrames=%d)\n", actualPeriodInFrames); + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " defaultPeriodInFrames=%d\n", defaultPeriodInFrames); + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " fundamentalPeriodInFrames=%d\n", fundamentalPeriodInFrames); + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " minPeriodInFrames=%d\n", minPeriodInFrames); + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " maxPeriodInFrames=%d\n", 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) { + /* + MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | MA_AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY must not be in the stream flags. If either of these are specified, + IAudioClient3_InitializeSharedAudioStream() will fail. + */ + hr = ma_IAudioClient3_InitializeSharedAudioStream(pAudioClient3, streamFlags & ~(MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | MA_AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY), actualPeriodInFrames, (MA_WAVEFORMATEX*)&wf, NULL); + if (SUCCEEDED(hr)) { + wasInitializedUsingIAudioClient3 = MA_TRUE; + pData->periodSizeInFramesOut = actualPeriodInFrames; + + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[WASAPI] Using IAudioClient3\n"); + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " periodSizeInFramesOut=%d\n", pData->periodSizeInFramesOut); + } else { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[WASAPI] IAudioClient3_InitializeSharedAudioStream failed. Falling back to IAudioClient.\n"); + } + } else { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[WASAPI] Not using IAudioClient3 because the desired period size is larger than the maximum supported by IAudioClient3.\n"); + } + } else { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[WASAPI] IAudioClient3_GetSharedModeEnginePeriod failed. Falling back to IAudioClient.\n"); + } + + ma_IAudioClient3_Release(pAudioClient3); + pAudioClient3 = NULL; + } + } + } + #else + { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[WASAPI] Not using IAudioClient3 because MA_WASAPI_NO_LOW_LATENCY_SHARED_MODE is enabled.\n"); + } + #endif + + /* If we don't have an IAudioClient3 then we need to use the normal initialization routine. */ + if (!wasInitializedUsingIAudioClient3) { + MA_REFERENCE_TIME bufferDuration = periodDurationInMicroseconds * pData->periodsOut * 10; /* <-- Multiply by 10 for microseconds to 100-nanoseconds. */ + hr = ma_IAudioClient_Initialize((ma_IAudioClient*)pData->pAudioClient, shareMode, streamFlags, bufferDuration, 0, (const MA_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_BUSY; + } else { + errorMsg = "[WASAPI] Failed to initialize device.", result = ma_result_from_HRESULT(hr); + } + + goto done; + } + } + } + + if (!wasInitializedUsingIAudioClient3) { + ma_uint32 bufferSizeInFrames = 0; + hr = ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pData->pAudioClient, &bufferSizeInFrames); + if (FAILED(hr)) { + errorMsg = "[WASAPI] Failed to get audio client's actual buffer size.", result = ma_result_from_HRESULT(hr); + goto done; + } + + /* + When using process loopback mode, retrieval of the buffer size seems to result in totally + incorrect values. In this case we'll just assume it's the same size as what we requested + when we initialized the client. + */ + if (usingProcessLoopback) { + bufferSizeInFrames = (ma_uint32)((periodDurationInMicroseconds * pData->periodsOut) * pData->sampleRateOut / 1000000); + } + + pData->periodSizeInFramesOut = bufferSizeInFrames / pData->periodsOut; + } + + pData->usingAudioClient3 = wasInitializedUsingIAudioClient3; + + + if (deviceType == ma_device_type_playback) { + result = ma_device_create_IAudioClient_service__wasapi(pContext, deviceType, (ma_IAudioClient*)pData->pAudioClient, (void**)&pData->pRenderClient); + } else { + result = ma_device_create_IAudioClient_service__wasapi(pContext, deviceType, (ma_IAudioClient*)pData->pAudioClient, (void**)&pData->pCaptureClient); + } + + /*if (FAILED(hr)) {*/ + if (result != MA_SUCCESS) { + errorMsg = "[WASAPI] Failed to get audio client service."; + goto done; + } + + + /* Grab the name of the device. */ + #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK) + { + ma_IPropertyStore *pProperties; + hr = ma_IMMDevice_OpenPropertyStore(pDeviceInterface, STGM_READ, &pProperties); + if (SUCCEEDED(hr)) { + MA_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 + + /* + For the WASAPI backend we need to know the actual IDs of the device in order to do automatic + stream routing so that IDs can be compared and we can determine which device has been detached + and whether or not it matches with our ma_device. + */ + #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK) + { + /* Desktop */ + ma_context_get_device_id_from_MMDevice__wasapi(pContext, pDeviceInterface, &pData->id); + } + #else + { + /* UWP */ + /* TODO: Implement me. Need to figure out how to get the ID of the default device. */ + } + #endif + +done: + /* Clean up. */ +#if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK) + 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; + } + + if (errorMsg != NULL && errorMsg[0] != '\0') { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "%s\n", errorMsg); + } + + return result; + } else { + return MA_SUCCESS; + } +} + +static 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. */ + if (deviceType == ma_device_type_duplex) { + return MA_INVALID_ARGS; + } + + + /* + Before reinitializing the device we need to free the previous audio clients. + + There's a known memory leak here. We will be calling this from the routing change callback that + is fired by WASAPI. If we attempt to release the IAudioClient we will deadlock. In my opinion + this is a bug. I'm not sure what I need to do to handle this cleanly, but I think we'll probably + need some system where we post an event, but delay the execution of it until the callback has + returned. I'm not sure how to do this reliably, however. I have set up some infrastructure for + a command thread which might be useful for this. + */ + if (deviceType == ma_device_type_capture || deviceType == ma_device_type_loopback) { + if (pDevice->wasapi.pCaptureClient) { + ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient); + pDevice->wasapi.pCaptureClient = NULL; + } + + if (pDevice->wasapi.pAudioClientCapture) { + /*ma_device_release_IAudioClient_service__wasapi(pDevice, ma_device_type_capture);*/ + pDevice->wasapi.pAudioClientCapture = NULL; + } + } + + 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_device_release_IAudioClient_service__wasapi(pDevice, ma_device_type_playback);*/ + pDevice->wasapi.pAudioClientPlayback = NULL; + } + } + + + if (deviceType == ma_device_type_playback) { + 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; + } else { + 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.sampleRateIn = pDevice->sampleRate; + data.periodSizeInFramesIn = pDevice->wasapi.originalPeriodSizeInFrames; + data.periodSizeInMillisecondsIn = pDevice->wasapi.originalPeriodSizeInMilliseconds; + data.periodsIn = pDevice->wasapi.originalPeriods; + data.performanceProfile = pDevice->wasapi.originalPerformanceProfile; + data.noAutoConvertSRC = pDevice->wasapi.noAutoConvertSRC; + data.noDefaultQualitySRC = pDevice->wasapi.noDefaultQualitySRC; + data.noHardwareOffloading = pDevice->wasapi.noHardwareOffloading; + data.loopbackProcessID = pDevice->wasapi.loopbackProcessID; + data.loopbackProcessExclude = pDevice->wasapi.loopbackProcessExclude; + 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 || deviceType == ma_device_type_loopback) { + 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.internalPeriodSizeInFrames = data.periodSizeInFramesOut; + 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, (HANDLE)pDevice->wasapi.hEventCapture); + + pDevice->wasapi.periodSizeInFramesCapture = data.periodSizeInFramesOut; + ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, &pDevice->wasapi.actualBufferSizeInFramesCapture); + + /* We must always have a valid ID. */ + ma_strcpy_s_WCHAR(pDevice->capture.id.wasapi, sizeof(pDevice->capture.id.wasapi), data.id.wasapi); + } + + if (deviceType == ma_device_type_playback) { + 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.internalPeriodSizeInFrames = data.periodSizeInFramesOut; + 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, (HANDLE)pDevice->wasapi.hEventPlayback); + + pDevice->wasapi.periodSizeInFramesPlayback = data.periodSizeInFramesOut; + ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &pDevice->wasapi.actualBufferSizeInFramesPlayback); + + /* We must always have a valid ID because rerouting will look at it. */ + ma_strcpy_s_WCHAR(pDevice->playback.id.wasapi, sizeof(pDevice->playback.id.wasapi), data.id.wasapi); + } + + return MA_SUCCESS; +} + +static ma_result ma_device_init__wasapi(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture) +{ + ma_result result = MA_SUCCESS; + +#if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK) + HRESULT hr; + ma_IMMDeviceEnumerator* pDeviceEnumerator; +#endif + + MA_ASSERT(pDevice != NULL); + + MA_ZERO_OBJECT(&pDevice->wasapi); + pDevice->wasapi.usage = pConfig->wasapi.usage; + pDevice->wasapi.noAutoConvertSRC = pConfig->wasapi.noAutoConvertSRC; + pDevice->wasapi.noDefaultQualitySRC = pConfig->wasapi.noDefaultQualitySRC; + pDevice->wasapi.noHardwareOffloading = pConfig->wasapi.noHardwareOffloading; + pDevice->wasapi.loopbackProcessID = pConfig->wasapi.loopbackProcessID; + pDevice->wasapi.loopbackProcessExclude = pConfig->wasapi.loopbackProcessExclude; + + /* Exclusive mode is not allowed with loopback. */ + if (pConfig->deviceType == ma_device_type_loopback && pConfig->playback.shareMode == ma_share_mode_exclusive) { + return MA_INVALID_DEVICE_CONFIG; + } + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) { + ma_device_init_internal_data__wasapi data; + data.formatIn = pDescriptorCapture->format; + data.channelsIn = pDescriptorCapture->channels; + data.sampleRateIn = pDescriptorCapture->sampleRate; + MA_COPY_MEMORY(data.channelMapIn, pDescriptorCapture->channelMap, sizeof(pDescriptorCapture->channelMap)); + data.periodSizeInFramesIn = pDescriptorCapture->periodSizeInFrames; + data.periodSizeInMillisecondsIn = pDescriptorCapture->periodSizeInMilliseconds; + data.periodsIn = pDescriptorCapture->periodCount; + data.shareMode = pDescriptorCapture->shareMode; + data.performanceProfile = pConfig->performanceProfile; + data.noAutoConvertSRC = pConfig->wasapi.noAutoConvertSRC; + data.noDefaultQualitySRC = pConfig->wasapi.noDefaultQualitySRC; + data.noHardwareOffloading = pConfig->wasapi.noHardwareOffloading; + data.loopbackProcessID = pConfig->wasapi.loopbackProcessID; + data.loopbackProcessExclude = pConfig->wasapi.loopbackProcessExclude; + + result = ma_device_init_internal__wasapi(pDevice->pContext, (pConfig->deviceType == ma_device_type_loopback) ? ma_device_type_loopback : ma_device_type_capture, pDescriptorCapture->pDeviceID, &data); + if (result != MA_SUCCESS) { + return result; + } + + pDevice->wasapi.pAudioClientCapture = data.pAudioClient; + pDevice->wasapi.pCaptureClient = data.pCaptureClient; + pDevice->wasapi.originalPeriodSizeInMilliseconds = pDescriptorCapture->periodSizeInMilliseconds; + pDevice->wasapi.originalPeriodSizeInFrames = pDescriptorCapture->periodSizeInFrames; + pDevice->wasapi.originalPeriods = pDescriptorCapture->periodCount; + pDevice->wasapi.originalPerformanceProfile = pConfig->performanceProfile; + + /* + 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 = (ma_handle)CreateEventA(NULL, FALSE, FALSE, NULL); /* Auto reset, unsignaled by default. */ + if (pDevice->wasapi.hEventCapture == NULL) { + result = ma_result_from_GetLastError(GetLastError()); + + 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; + } + + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create event for capture."); + return result; + } + ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, (HANDLE)pDevice->wasapi.hEventCapture); + + pDevice->wasapi.periodSizeInFramesCapture = data.periodSizeInFramesOut; + ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, &pDevice->wasapi.actualBufferSizeInFramesCapture); + + /* We must always have a valid ID. */ + ma_strcpy_s_WCHAR(pDevice->capture.id.wasapi, sizeof(pDevice->capture.id.wasapi), data.id.wasapi); + + /* The descriptor needs to be updated with actual values. */ + pDescriptorCapture->format = data.formatOut; + pDescriptorCapture->channels = data.channelsOut; + pDescriptorCapture->sampleRate = data.sampleRateOut; + MA_COPY_MEMORY(pDescriptorCapture->channelMap, data.channelMapOut, sizeof(data.channelMapOut)); + pDescriptorCapture->periodSizeInFrames = data.periodSizeInFramesOut; + pDescriptorCapture->periodCount = data.periodsOut; + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + ma_device_init_internal_data__wasapi data; + data.formatIn = pDescriptorPlayback->format; + data.channelsIn = pDescriptorPlayback->channels; + data.sampleRateIn = pDescriptorPlayback->sampleRate; + MA_COPY_MEMORY(data.channelMapIn, pDescriptorPlayback->channelMap, sizeof(pDescriptorPlayback->channelMap)); + data.periodSizeInFramesIn = pDescriptorPlayback->periodSizeInFrames; + data.periodSizeInMillisecondsIn = pDescriptorPlayback->periodSizeInMilliseconds; + data.periodsIn = pDescriptorPlayback->periodCount; + data.shareMode = pDescriptorPlayback->shareMode; + data.performanceProfile = pConfig->performanceProfile; + data.noAutoConvertSRC = pConfig->wasapi.noAutoConvertSRC; + data.noDefaultQualitySRC = pConfig->wasapi.noDefaultQualitySRC; + data.noHardwareOffloading = pConfig->wasapi.noHardwareOffloading; + data.loopbackProcessID = pConfig->wasapi.loopbackProcessID; + data.loopbackProcessExclude = pConfig->wasapi.loopbackProcessExclude; + + result = ma_device_init_internal__wasapi(pDevice->pContext, ma_device_type_playback, pDescriptorPlayback->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((HANDLE)pDevice->wasapi.hEventCapture); + pDevice->wasapi.hEventCapture = NULL; + } + return result; + } + + pDevice->wasapi.pAudioClientPlayback = data.pAudioClient; + pDevice->wasapi.pRenderClient = data.pRenderClient; + pDevice->wasapi.originalPeriodSizeInMilliseconds = pDescriptorPlayback->periodSizeInMilliseconds; + pDevice->wasapi.originalPeriodSizeInFrames = pDescriptorPlayback->periodSizeInFrames; + pDevice->wasapi.originalPeriods = pDescriptorPlayback->periodCount; + pDevice->wasapi.originalPerformanceProfile = pConfig->performanceProfile; + + /* + 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 = (ma_handle)CreateEventA(NULL, FALSE, TRUE, NULL); /* Auto reset, signaled by default. */ + if (pDevice->wasapi.hEventPlayback == NULL) { + result = ma_result_from_GetLastError(GetLastError()); + + 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((HANDLE)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; + } + + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create event for playback."); + return result; + } + ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, (HANDLE)pDevice->wasapi.hEventPlayback); + + pDevice->wasapi.periodSizeInFramesPlayback = data.periodSizeInFramesOut; + ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &pDevice->wasapi.actualBufferSizeInFramesPlayback); + + /* We must always have a valid ID because rerouting will look at it. */ + ma_strcpy_s_WCHAR(pDevice->playback.id.wasapi, sizeof(pDevice->playback.id.wasapi), data.id.wasapi); + + /* The descriptor needs to be updated with actual values. */ + pDescriptorPlayback->format = data.formatOut; + pDescriptorPlayback->channels = data.channelsOut; + pDescriptorPlayback->sampleRate = data.sampleRateOut; + MA_COPY_MEMORY(pDescriptorPlayback->channelMap, data.channelMapOut, sizeof(data.channelMapOut)); + pDescriptorPlayback->periodSizeInFrames = data.periodSizeInFramesOut; + pDescriptorPlayback->periodCount = data.periodsOut; + } + + /* + We need to register a notification client to detect when the device has been disabled, unplugged or re-routed (when the default device changes). When + we are connecting to the default device we want to do automatic stream routing when the device is disabled or unplugged. Otherwise we want to just + stop the device outright and let the application handle it. + */ +#if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK) + if (pConfig->wasapi.noAutoStreamRouting == MA_FALSE) { + if ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) && pConfig->capture.pDeviceID == NULL) { + pDevice->wasapi.allowCaptureAutoStreamRouting = MA_TRUE; + } + if ((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.pDeviceID == NULL) { + pDevice->wasapi.allowPlaybackAutoStreamRouting = MA_TRUE; + } + } + + ma_mutex_init(&pDevice->wasapi.rerouteLock); + + hr = ma_CoCreateInstance(pDevice->pContext, &MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator); + if (FAILED(hr)) { + ma_device_uninit__wasapi(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create device enumerator."); + return ma_result_from_HRESULT(hr); + } + + 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_bool32_set(&pDevice->wasapi.isStartedCapture, MA_FALSE); + ma_atomic_bool32_set(&pDevice->wasapi.isStartedPlayback, MA_FALSE); + + return MA_SUCCESS; +} + +static 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); + + *pFrameCount = 0; + + if ((ma_ptr)pAudioClient != pDevice->wasapi.pAudioClientPlayback && (ma_ptr)pAudioClient != pDevice->wasapi.pAudioClientCapture) { + return MA_INVALID_OPERATION; + } + + /* + I've had a report that GetCurrentPadding() is returning a frame count of 0 which is preventing + higher level function calls from doing anything because it thinks nothing is available. I have + taken a look at the documentation and it looks like this is unnecessary in exclusive mode. + + From Microsoft's documentation: + + For an exclusive-mode rendering or capture stream that was initialized with the + AUDCLNT_STREAMFLAGS_EVENTCALLBACK flag, the client typically has no use for the padding + value reported by GetCurrentPadding. Instead, the client accesses an entire buffer during + each processing pass. + + Considering this, I'm going to skip GetCurrentPadding() for exclusive mode and just report the + entire buffer. This depends on the caller making sure they wait on the event handler. + */ + shareMode = ((ma_ptr)pAudioClient == pDevice->wasapi.pAudioClientPlayback) ? pDevice->playback.shareMode : pDevice->capture.shareMode; + if (shareMode == ma_share_mode_shared) { + /* Shared mode. */ + hr = ma_IAudioClient_GetCurrentPadding(pAudioClient, &paddingFramesCount); + if (FAILED(hr)) { + return ma_result_from_HRESULT(hr); + } + + if ((ma_ptr)pAudioClient == pDevice->wasapi.pAudioClientPlayback) { + *pFrameCount = pDevice->wasapi.actualBufferSizeInFramesPlayback - paddingFramesCount; + } else { + *pFrameCount = paddingFramesCount; + } + } else { + /* Exclusive mode. */ + if ((ma_ptr)pAudioClient == pDevice->wasapi.pAudioClientPlayback) { + *pFrameCount = pDevice->wasapi.actualBufferSizeInFramesPlayback; + } else { + *pFrameCount = pDevice->wasapi.actualBufferSizeInFramesCapture; + } + } + + return MA_SUCCESS; +} + + +static 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; + } + + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "=== CHANGING DEVICE ===\n"); + + result = ma_device_reinit__wasapi(pDevice, deviceType); + if (result != MA_SUCCESS) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[WASAPI] Reinitializing device after route change failed.\n"); + return result; + } + + ma_device__post_init_setup(pDevice, deviceType); + ma_device__on_notification_rerouted(pDevice); + + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "=== DEVICE CHANGED ===\n"); + + return MA_SUCCESS; +} + +static ma_result ma_device_start__wasapi_nolock(ma_device* pDevice) +{ + HRESULT hr; + + if (pDevice->pContext->wasapi.hAvrt) { + const char* pTaskName = ma_to_usage_string__wasapi(pDevice->wasapi.usage); + if (pTaskName) { + DWORD idx = 0; + pDevice->wasapi.hAvrtHandle = (ma_handle)((MA_PFN_AvSetMmThreadCharacteristicsA)pDevice->pContext->wasapi.AvSetMmThreadCharacteristicsA)(pTaskName, &idx); + } + } + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) { + hr = ma_IAudioClient_Start((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture); + if (FAILED(hr)) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to start internal capture device. HRESULT = %d.", (int)hr); + return ma_result_from_HRESULT(hr); + } + + ma_atomic_bool32_set(&pDevice->wasapi.isStartedCapture, MA_TRUE); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + hr = ma_IAudioClient_Start((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback); + if (FAILED(hr)) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to start internal playback device. HRESULT = %d.", (int)hr); + return ma_result_from_HRESULT(hr); + } + + ma_atomic_bool32_set(&pDevice->wasapi.isStartedPlayback, MA_TRUE); + } + + return MA_SUCCESS; +} + +static ma_result ma_device_start__wasapi(ma_device* pDevice) +{ + ma_result result; + + MA_ASSERT(pDevice != NULL); + + /* Wait for any rerouting to finish before attempting to start the device. */ + ma_mutex_lock(&pDevice->wasapi.rerouteLock); + { + result = ma_device_start__wasapi_nolock(pDevice); + } + ma_mutex_unlock(&pDevice->wasapi.rerouteLock); + + return result; +} + +static ma_result ma_device_stop__wasapi_nolock(ma_device* pDevice) +{ + ma_result result; + HRESULT hr; + + MA_ASSERT(pDevice != NULL); + + if (pDevice->wasapi.hAvrtHandle) { + ((MA_PFN_AvRevertMmThreadCharacteristics)pDevice->pContext->wasapi.AvRevertMmThreadcharacteristics)((HANDLE)pDevice->wasapi.hAvrtHandle); + pDevice->wasapi.hAvrtHandle = NULL; + } + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) { + hr = ma_IAudioClient_Stop((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture); + if (FAILED(hr)) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to stop internal capture device."); + return ma_result_from_HRESULT(hr); + } + + /* The audio client needs to be reset otherwise restarting will fail. */ + hr = ma_IAudioClient_Reset((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture); + if (FAILED(hr)) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to reset internal capture device."); + return ma_result_from_HRESULT(hr); + } + + /* If we have a mapped buffer we need to release it. */ + if (pDevice->wasapi.pMappedBufferCapture != NULL) { + ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, pDevice->wasapi.mappedBufferCaptureCap); + pDevice->wasapi.pMappedBufferCapture = NULL; + pDevice->wasapi.mappedBufferCaptureCap = 0; + pDevice->wasapi.mappedBufferCaptureLen = 0; + } + + ma_atomic_bool32_set(&pDevice->wasapi.isStartedCapture, MA_FALSE); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + /* + 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 portion of it not getting played. + */ + if (ma_atomic_bool32_get(&pDevice->wasapi.isStartedPlayback)) { + /* We need to make sure we put a timeout here or else we'll risk getting stuck in a deadlock in some cases. */ + DWORD waitTime = pDevice->wasapi.actualBufferSizeInFramesPlayback / pDevice->playback.internalSampleRate; + + if (pDevice->playback.shareMode == ma_share_mode_exclusive) { + WaitForSingleObject((HANDLE)pDevice->wasapi.hEventPlayback, waitTime); + } + else { + ma_uint32 prevFramesAvaialablePlayback = (ma_uint32)-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((HANDLE)pDevice->wasapi.hEventPlayback, waitTime * 1000); + ResetEvent((HANDLE)pDevice->wasapi.hEventPlayback); /* Manual reset. */ + } + } + } + + hr = ma_IAudioClient_Stop((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback); + if (FAILED(hr)) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to stop internal playback device."); + return ma_result_from_HRESULT(hr); + } + + /* The audio client needs to be reset otherwise restarting will fail. */ + hr = ma_IAudioClient_Reset((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback); + if (FAILED(hr)) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to reset internal playback device."); + return ma_result_from_HRESULT(hr); + } + + if (pDevice->wasapi.pMappedBufferPlayback != NULL) { + ma_IAudioRenderClient_ReleaseBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, pDevice->wasapi.mappedBufferPlaybackCap, 0); + pDevice->wasapi.pMappedBufferPlayback = NULL; + pDevice->wasapi.mappedBufferPlaybackCap = 0; + pDevice->wasapi.mappedBufferPlaybackLen = 0; + } + + ma_atomic_bool32_set(&pDevice->wasapi.isStartedPlayback, MA_FALSE); + } + + return MA_SUCCESS; +} + +static ma_result ma_device_stop__wasapi(ma_device* pDevice) +{ + ma_result result; + + MA_ASSERT(pDevice != NULL); + + /* Wait for any rerouting to finish before attempting to stop the device. */ + ma_mutex_lock(&pDevice->wasapi.rerouteLock); + { + result = ma_device_stop__wasapi_nolock(pDevice); + } + ma_mutex_unlock(&pDevice->wasapi.rerouteLock); + + return result; +} + + +#ifndef MA_WASAPI_WAIT_TIMEOUT_MILLISECONDS +#define MA_WASAPI_WAIT_TIMEOUT_MILLISECONDS 5000 +#endif + +static ma_result ma_device_read__wasapi(ma_device* pDevice, void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesRead) +{ + ma_result result = MA_SUCCESS; + ma_uint32 totalFramesProcessed = 0; + + /* + When reading, we need to get a buffer and process all of it before releasing it. Because the + frame count (frameCount) can be different to the size of the buffer, we'll need to cache the + pointer to the buffer. + */ + + /* Keep running until we've processed the requested number of frames. */ + while (ma_device_get_state(pDevice) == ma_device_state_started && totalFramesProcessed < frameCount) { + ma_uint32 framesRemaining = frameCount - totalFramesProcessed; + + /* If we have a mapped data buffer, consume that first. */ + if (pDevice->wasapi.pMappedBufferCapture != NULL) { + /* We have a cached data pointer so consume that before grabbing another one from WASAPI. */ + ma_uint32 framesToProcessNow = framesRemaining; + if (framesToProcessNow > pDevice->wasapi.mappedBufferCaptureLen) { + framesToProcessNow = pDevice->wasapi.mappedBufferCaptureLen; + } + + /* Now just copy the data over to the output buffer. */ + ma_copy_pcm_frames( + ma_offset_pcm_frames_ptr(pFrames, totalFramesProcessed, pDevice->capture.internalFormat, pDevice->capture.internalChannels), + ma_offset_pcm_frames_const_ptr(pDevice->wasapi.pMappedBufferCapture, pDevice->wasapi.mappedBufferCaptureCap - pDevice->wasapi.mappedBufferCaptureLen, pDevice->capture.internalFormat, pDevice->capture.internalChannels), + framesToProcessNow, + pDevice->capture.internalFormat, pDevice->capture.internalChannels + ); + + totalFramesProcessed += framesToProcessNow; + pDevice->wasapi.mappedBufferCaptureLen -= framesToProcessNow; + + /* If the data buffer has been fully consumed we need to release it. */ + if (pDevice->wasapi.mappedBufferCaptureLen == 0) { + ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, pDevice->wasapi.mappedBufferCaptureCap); + pDevice->wasapi.pMappedBufferCapture = NULL; + pDevice->wasapi.mappedBufferCaptureCap = 0; + } + } else { + /* We don't have any cached data pointer, so grab another one. */ + HRESULT hr; + DWORD flags = 0; + + /* First just ask WASAPI for a data buffer. If it's not available, we'll wait for more. */ + hr = ma_IAudioCaptureClient_GetBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, (BYTE**)&pDevice->wasapi.pMappedBufferCapture, &pDevice->wasapi.mappedBufferCaptureCap, &flags, NULL, NULL); + if (hr == S_OK) { + /* We got a data buffer. Continue to the next loop iteration which will then read from the mapped pointer. */ + pDevice->wasapi.mappedBufferCaptureLen = pDevice->wasapi.mappedBufferCaptureCap; + + /* + There have been reports that indicate that at times the AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY is reported for every + call to IAudioCaptureClient_GetBuffer() above which results in spamming of the debug messages below. To partially + work around this, I'm only outputting these messages when MA_DEBUG_OUTPUT is explicitly defined. The better solution + would be to figure out why the flag is always getting reported. + */ + #if defined(MA_DEBUG_OUTPUT) + { + if (flags != 0) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Capture Flags: %ld\n", flags); + + if ((flags & MA_AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) != 0) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Data discontinuity (possible overrun). Attempting recovery. mappedBufferCaptureCap=%d\n", pDevice->wasapi.mappedBufferCaptureCap); + } + } + } + #endif + + /* Overrun detection. */ + if ((flags & MA_AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) != 0) { + /* Glitched. Probably due to an overrun. */ + + /* + If we got an overrun it probably means we're straddling the end of the buffer. In normal capture + mode this is the fault of the client application because they're responsible for ensuring data is + processed fast enough. In duplex mode, however, the processing of audio is tied to the playback + device, so this can possibly be the result of a timing de-sync. + + In capture mode we're not going to do any kind of recovery because the real fix is for the client + application to process faster. In duplex mode, we'll treat this as a desync and reset the buffers + to prevent a never-ending sequence of glitches due to straddling the end of the buffer. + */ + if (pDevice->type == ma_device_type_duplex) { + /* + Experiment: + + If we empty out the *entire* buffer we may end up putting ourselves into an underrun position + which isn't really any better than the overrun we're probably in right now. Instead we'll just + empty out about half. + */ + ma_uint32 i; + ma_uint32 periodCount = (pDevice->wasapi.actualBufferSizeInFramesCapture / pDevice->wasapi.periodSizeInFramesCapture); + ma_uint32 iterationCount = periodCount / 2; + if ((periodCount % 2) > 0) { + iterationCount += 1; + } + + for (i = 0; i < iterationCount; i += 1) { + hr = ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, pDevice->wasapi.mappedBufferCaptureCap); + if (FAILED(hr)) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Data discontinuity recovery: IAudioCaptureClient_ReleaseBuffer() failed with %ld.\n", hr); + break; + } + + flags = 0; + hr = ma_IAudioCaptureClient_GetBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, (BYTE**)&pDevice->wasapi.pMappedBufferCapture, &pDevice->wasapi.mappedBufferCaptureCap, &flags, NULL, NULL); + if (hr == MA_AUDCLNT_S_BUFFER_EMPTY || FAILED(hr)) { + /* + The buffer has been completely emptied or an error occurred. In this case we'll need + to reset the state of the mapped buffer which will trigger the next iteration to get + a fresh buffer from WASAPI. + */ + pDevice->wasapi.pMappedBufferCapture = NULL; + pDevice->wasapi.mappedBufferCaptureCap = 0; + pDevice->wasapi.mappedBufferCaptureLen = 0; + + if (hr == MA_AUDCLNT_S_BUFFER_EMPTY) { + if ((flags & MA_AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) != 0) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Data discontinuity recovery: Buffer emptied, and data discontinuity still reported.\n"); + } else { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Data discontinuity recovery: Buffer emptied.\n"); + } + } + + if (FAILED(hr)) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Data discontinuity recovery: IAudioCaptureClient_GetBuffer() failed with %ld.\n", hr); + } + + break; + } + } + + /* If at this point we have a valid buffer mapped, make sure the buffer length is set appropriately. */ + if (pDevice->wasapi.pMappedBufferCapture != NULL) { + pDevice->wasapi.mappedBufferCaptureLen = pDevice->wasapi.mappedBufferCaptureCap; + } + } + } + + continue; + } else { + if (hr == MA_AUDCLNT_S_BUFFER_EMPTY || hr == MA_AUDCLNT_E_BUFFER_ERROR) { + /* + No data is available. We need to wait for more. There's two situations to consider + here. The first is normal capture mode. If this times out it probably means the + microphone isn't delivering data for whatever reason. In this case we'll just + abort the read and return whatever we were able to get. The other situations is + loopback mode, in which case a timeout probably just means the nothing is playing + through the speakers. + */ + + /* Experiment: Use a shorter timeout for loopback mode. */ + DWORD timeoutInMilliseconds = MA_WASAPI_WAIT_TIMEOUT_MILLISECONDS; + if (pDevice->type == ma_device_type_loopback) { + timeoutInMilliseconds = 10; + } + + if (WaitForSingleObject((HANDLE)pDevice->wasapi.hEventCapture, timeoutInMilliseconds) != WAIT_OBJECT_0) { + if (pDevice->type == ma_device_type_loopback) { + continue; /* Keep waiting in loopback mode. */ + } else { + result = MA_ERROR; + break; /* Wait failed. */ + } + } + + /* At this point we should be able to loop back to the start of the loop and try retrieving a data buffer again. */ + } else { + /* An error occurred and we need to abort. */ + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve internal buffer from capture device in preparation for reading from the device. HRESULT = %d. Stopping device.\n", (int)hr); + result = ma_result_from_HRESULT(hr); + break; + } + } + } + } + + /* + If we were unable to process the entire requested frame count, but we still have a mapped buffer, + there's a good chance either an error occurred or the device was stopped mid-read. In this case + we'll need to make sure the buffer is released. + */ + if (totalFramesProcessed < frameCount && pDevice->wasapi.pMappedBufferCapture != NULL) { + ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, pDevice->wasapi.mappedBufferCaptureCap); + pDevice->wasapi.pMappedBufferCapture = NULL; + pDevice->wasapi.mappedBufferCaptureCap = 0; + pDevice->wasapi.mappedBufferCaptureLen = 0; + } + + if (pFramesRead != NULL) { + *pFramesRead = totalFramesProcessed; + } + + return result; +} + +static ma_result ma_device_write__wasapi(ma_device* pDevice, const void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten) +{ + ma_result result = MA_SUCCESS; + ma_uint32 totalFramesProcessed = 0; + + /* Keep writing to the device until it's stopped or we've consumed all of our input. */ + while (ma_device_get_state(pDevice) == ma_device_state_started && totalFramesProcessed < frameCount) { + ma_uint32 framesRemaining = frameCount - totalFramesProcessed; + + /* + We're going to do this in a similar way to capture. We'll first check if the cached data pointer + is valid, and if so, read from that. Otherwise We will call IAudioRenderClient_GetBuffer() with + a requested buffer size equal to our actual period size. If it returns AUDCLNT_E_BUFFER_TOO_LARGE + it means we need to wait for some data to become available. + */ + if (pDevice->wasapi.pMappedBufferPlayback != NULL) { + /* We still have some space available in the mapped data buffer. Write to it. */ + ma_uint32 framesToProcessNow = framesRemaining; + if (framesToProcessNow > (pDevice->wasapi.mappedBufferPlaybackCap - pDevice->wasapi.mappedBufferPlaybackLen)) { + framesToProcessNow = (pDevice->wasapi.mappedBufferPlaybackCap - pDevice->wasapi.mappedBufferPlaybackLen); + } + + /* Now just copy the data over to the output buffer. */ + ma_copy_pcm_frames( + ma_offset_pcm_frames_ptr(pDevice->wasapi.pMappedBufferPlayback, pDevice->wasapi.mappedBufferPlaybackLen, pDevice->playback.internalFormat, pDevice->playback.internalChannels), + ma_offset_pcm_frames_const_ptr(pFrames, totalFramesProcessed, pDevice->playback.internalFormat, pDevice->playback.internalChannels), + framesToProcessNow, + pDevice->playback.internalFormat, pDevice->playback.internalChannels + ); + + totalFramesProcessed += framesToProcessNow; + pDevice->wasapi.mappedBufferPlaybackLen += framesToProcessNow; + + /* If the data buffer has been fully consumed we need to release it. */ + if (pDevice->wasapi.mappedBufferPlaybackLen == pDevice->wasapi.mappedBufferPlaybackCap) { + ma_IAudioRenderClient_ReleaseBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, pDevice->wasapi.mappedBufferPlaybackCap, 0); + pDevice->wasapi.pMappedBufferPlayback = NULL; + pDevice->wasapi.mappedBufferPlaybackCap = 0; + pDevice->wasapi.mappedBufferPlaybackLen = 0; + + /* + In exclusive mode we need to wait here. Exclusive mode is weird because GetBuffer() never + seems to return AUDCLNT_E_BUFFER_TOO_LARGE, which is what we normally use to determine + whether or not we need to wait for more data. + */ + if (pDevice->playback.shareMode == ma_share_mode_exclusive) { + if (WaitForSingleObject((HANDLE)pDevice->wasapi.hEventPlayback, MA_WASAPI_WAIT_TIMEOUT_MILLISECONDS) != WAIT_OBJECT_0) { + result = MA_ERROR; + break; /* Wait failed. Probably timed out. */ + } + } + } + } else { + /* We don't have a mapped data buffer so we'll need to get one. */ + HRESULT hr; + ma_uint32 bufferSizeInFrames; + + /* Special rules for exclusive mode. */ + if (pDevice->playback.shareMode == ma_share_mode_exclusive) { + bufferSizeInFrames = pDevice->wasapi.actualBufferSizeInFramesPlayback; + } else { + bufferSizeInFrames = pDevice->wasapi.periodSizeInFramesPlayback; + } + + hr = ma_IAudioRenderClient_GetBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, bufferSizeInFrames, (BYTE**)&pDevice->wasapi.pMappedBufferPlayback); + if (hr == S_OK) { + /* We have data available. */ + pDevice->wasapi.mappedBufferPlaybackCap = bufferSizeInFrames; + pDevice->wasapi.mappedBufferPlaybackLen = 0; + } else { + if (hr == MA_AUDCLNT_E_BUFFER_TOO_LARGE || hr == MA_AUDCLNT_E_BUFFER_ERROR) { + /* Not enough data available. We need to wait for more. */ + if (WaitForSingleObject((HANDLE)pDevice->wasapi.hEventPlayback, MA_WASAPI_WAIT_TIMEOUT_MILLISECONDS) != WAIT_OBJECT_0) { + result = MA_ERROR; + break; /* Wait failed. Probably timed out. */ + } + } else { + /* Some error occurred. We'll need to abort. */ + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve internal buffer from playback device in preparation for writing to the device. HRESULT = %d. Stopping device.\n", (int)hr); + result = ma_result_from_HRESULT(hr); + break; + } + } + } + } + + if (pFramesWritten != NULL) { + *pFramesWritten = totalFramesProcessed; + } + + return result; +} + +static ma_result ma_device_data_loop_wakeup__wasapi(ma_device* pDevice) +{ + MA_ASSERT(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) { + SetEvent((HANDLE)pDevice->wasapi.hEventCapture); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + SetEvent((HANDLE)pDevice->wasapi.hEventPlayback); + } + + return MA_SUCCESS; +} + + +static ma_result ma_context_uninit__wasapi(ma_context* pContext) +{ + ma_context_command__wasapi cmd = ma_context_init_command__wasapi(MA_CONTEXT_COMMAND_QUIT__WASAPI); + + MA_ASSERT(pContext != NULL); + MA_ASSERT(pContext->backend == ma_backend_wasapi); + + ma_context_post_command__wasapi(pContext, &cmd); + ma_thread_wait(&pContext->wasapi.commandThread); + + if (pContext->wasapi.hAvrt) { + ma_dlclose(ma_context_get_log(pContext), pContext->wasapi.hAvrt); + pContext->wasapi.hAvrt = NULL; + } + + #if defined(MA_WIN32_UWP) + { + if (pContext->wasapi.hMMDevapi) { + ma_dlclose(ma_context_get_log(pContext), pContext->wasapi.hMMDevapi); + pContext->wasapi.hMMDevapi = NULL; + } + } + #endif + + /* Only after the thread has been terminated can we uninitialize the sync objects for the command thread. */ + ma_semaphore_uninit(&pContext->wasapi.commandSem); + ma_mutex_uninit(&pContext->wasapi.commandLock); + + return MA_SUCCESS; +} + +static ma_result ma_context_init__wasapi(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks) +{ + ma_result result = MA_SUCCESS; + + MA_ASSERT(pContext != NULL); + + (void)pConfig; + +#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. + + Unfortunately older compilers don't define these functions so we need to dynamically load them in order to avoid a link error. + */ + { + ma_OSVERSIONINFOEXW osvi; + ma_handle kernel32DLL; + ma_PFNVerifyVersionInfoW _VerifyVersionInfoW; + ma_PFNVerSetConditionMask _VerSetConditionMask; + + kernel32DLL = ma_dlopen(ma_context_get_log(pContext), "kernel32.dll"); + if (kernel32DLL == NULL) { + return MA_NO_BACKEND; + } + + _VerifyVersionInfoW = (ma_PFNVerifyVersionInfoW )ma_dlsym(ma_context_get_log(pContext), kernel32DLL, "VerifyVersionInfoW"); + _VerSetConditionMask = (ma_PFNVerSetConditionMask)ma_dlsym(ma_context_get_log(pContext), kernel32DLL, "VerSetConditionMask"); + if (_VerifyVersionInfoW == NULL || _VerSetConditionMask == NULL) { + ma_dlclose(ma_context_get_log(pContext), kernel32DLL); + return MA_NO_BACKEND; + } + + MA_ZERO_OBJECT(&osvi); + osvi.dwOSVersionInfoSize = sizeof(osvi); + osvi.dwMajorVersion = ((MA_WIN32_WINNT_VISTA >> 8) & 0xFF); + osvi.dwMinorVersion = ((MA_WIN32_WINNT_VISTA >> 0) & 0xFF); + 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(ma_context_get_log(pContext), kernel32DLL); + } +#endif + + if (result != MA_SUCCESS) { + return result; + } + + MA_ZERO_OBJECT(&pContext->wasapi); + + + #if defined(MA_WIN32_UWP) + { + /* Link to mmdevapi so we can get access to ActivateAudioInterfaceAsync(). */ + pContext->wasapi.hMMDevapi = ma_dlopen(ma_context_get_log(pContext), "mmdevapi.dll"); + if (pContext->wasapi.hMMDevapi) { + pContext->wasapi.ActivateAudioInterfaceAsync = ma_dlsym(ma_context_get_log(pContext), pContext->wasapi.hMMDevapi, "ActivateAudioInterfaceAsync"); + if (pContext->wasapi.ActivateAudioInterfaceAsync == NULL) { + ma_dlclose(ma_context_get_log(pContext), pContext->wasapi.hMMDevapi); + return MA_NO_BACKEND; /* ActivateAudioInterfaceAsync() could not be loaded. */ + } + } else { + return MA_NO_BACKEND; /* Failed to load mmdevapi.dll which is required for ActivateAudioInterfaceAsync() */ + } + } + #endif + + /* Optionally use the Avrt API to specify the audio thread's latency sensitivity requirements */ + pContext->wasapi.hAvrt = ma_dlopen(ma_context_get_log(pContext), "avrt.dll"); + if (pContext->wasapi.hAvrt) { + pContext->wasapi.AvSetMmThreadCharacteristicsA = ma_dlsym(ma_context_get_log(pContext), pContext->wasapi.hAvrt, "AvSetMmThreadCharacteristicsA"); + pContext->wasapi.AvRevertMmThreadcharacteristics = ma_dlsym(ma_context_get_log(pContext), pContext->wasapi.hAvrt, "AvRevertMmThreadCharacteristics"); + + /* If either function could not be found, disable use of avrt entirely. */ + if (!pContext->wasapi.AvSetMmThreadCharacteristicsA || !pContext->wasapi.AvRevertMmThreadcharacteristics) { + pContext->wasapi.AvSetMmThreadCharacteristicsA = NULL; + pContext->wasapi.AvRevertMmThreadcharacteristics = NULL; + ma_dlclose(ma_context_get_log(pContext), pContext->wasapi.hAvrt); + pContext->wasapi.hAvrt = NULL; + } + } + + + /* + Annoyingly, WASAPI does not allow you to release an IAudioClient object from a different thread + than the one that retrieved it with GetService(). This can result in a deadlock in two + situations: + + 1) When calling ma_device_uninit() from a different thread to ma_device_init(); and + 2) When uninitializing and reinitializing the internal IAudioClient object in response to + automatic stream routing. + + We could define ma_device_uninit() such that it must be called on the same thread as + ma_device_init(). We could also just not release the IAudioClient when performing automatic + stream routing to avoid the deadlock. Neither of these are acceptable solutions in my view so + we're going to have to work around this with a worker thread. This is not ideal, but I can't + think of a better way to do this. + + More information about this can be found here: + + https://docs.microsoft.com/en-us/windows/win32/api/audioclient/nn-audioclient-iaudiorenderclient + + Note this section: + + When releasing an IAudioRenderClient interface instance, the client must call the interface's + Release method from the same thread as the call to IAudioClient::GetService that created the + object. + */ + { + result = ma_mutex_init(&pContext->wasapi.commandLock); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_semaphore_init(0, &pContext->wasapi.commandSem); + if (result != MA_SUCCESS) { + ma_mutex_uninit(&pContext->wasapi.commandLock); + return result; + } + + result = ma_thread_create(&pContext->wasapi.commandThread, ma_thread_priority_normal, 0, ma_context_command_thread__wasapi, pContext, &pContext->allocationCallbacks); + if (result != MA_SUCCESS) { + ma_semaphore_uninit(&pContext->wasapi.commandSem); + ma_mutex_uninit(&pContext->wasapi.commandLock); + return result; + } + } + + + pCallbacks->onContextInit = ma_context_init__wasapi; + pCallbacks->onContextUninit = ma_context_uninit__wasapi; + pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__wasapi; + pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__wasapi; + pCallbacks->onDeviceInit = ma_device_init__wasapi; + pCallbacks->onDeviceUninit = ma_device_uninit__wasapi; + pCallbacks->onDeviceStart = ma_device_start__wasapi; + pCallbacks->onDeviceStop = ma_device_stop__wasapi; + pCallbacks->onDeviceRead = ma_device_read__wasapi; + pCallbacks->onDeviceWrite = ma_device_write__wasapi; + pCallbacks->onDeviceDataLoop = NULL; + pCallbacks->onDeviceDataLoopWakeup = ma_device_data_loop_wakeup__wasapi; + + return MA_SUCCESS; +} +#endif + +/****************************************************************************** + +DirectSound Backend + +******************************************************************************/ +#ifdef MA_HAS_DSOUND +/*#include */ + +/*static const 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; + MA_WAVEFORMATEX* lpwfxFormat; + GUID guid3DAlgorithm; +} MA_DSBUFFERDESC; + +typedef struct +{ + DWORD dwSize; + DWORD dwFlags; + DWORD dwBufferBytes; + DWORD dwReserved; + MA_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; +}; +static MA_INLINE HRESULT ma_IDirectSound_QueryInterface(ma_IDirectSound* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +static MA_INLINE ULONG ma_IDirectSound_AddRef(ma_IDirectSound* pThis) { return pThis->lpVtbl->AddRef(pThis); } +static MA_INLINE ULONG ma_IDirectSound_Release(ma_IDirectSound* pThis) { return pThis->lpVtbl->Release(pThis); } +static MA_INLINE HRESULT ma_IDirectSound_CreateSoundBuffer(ma_IDirectSound* pThis, const MA_DSBUFFERDESC* pDSBufferDesc, ma_IDirectSoundBuffer** ppDSBuffer, void* pUnkOuter) { return pThis->lpVtbl->CreateSoundBuffer(pThis, pDSBufferDesc, ppDSBuffer, pUnkOuter); } +static MA_INLINE HRESULT ma_IDirectSound_GetCaps(ma_IDirectSound* pThis, MA_DSCAPS* pDSCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSCaps); } +static MA_INLINE HRESULT ma_IDirectSound_DuplicateSoundBuffer(ma_IDirectSound* pThis, ma_IDirectSoundBuffer* pDSBufferOriginal, ma_IDirectSoundBuffer** ppDSBufferDuplicate) { return pThis->lpVtbl->DuplicateSoundBuffer(pThis, pDSBufferOriginal, ppDSBufferDuplicate); } +static MA_INLINE HRESULT ma_IDirectSound_SetCooperativeLevel(ma_IDirectSound* pThis, HWND hwnd, DWORD dwLevel) { return pThis->lpVtbl->SetCooperativeLevel(pThis, hwnd, dwLevel); } +static MA_INLINE HRESULT ma_IDirectSound_Compact(ma_IDirectSound* pThis) { return pThis->lpVtbl->Compact(pThis); } +static MA_INLINE HRESULT ma_IDirectSound_GetSpeakerConfig(ma_IDirectSound* pThis, DWORD* pSpeakerConfig) { return pThis->lpVtbl->GetSpeakerConfig(pThis, pSpeakerConfig); } +static MA_INLINE HRESULT ma_IDirectSound_SetSpeakerConfig(ma_IDirectSound* pThis, DWORD dwSpeakerConfig) { return pThis->lpVtbl->SetSpeakerConfig(pThis, dwSpeakerConfig); } +static MA_INLINE 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, MA_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 MA_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; +}; +static MA_INLINE HRESULT ma_IDirectSoundBuffer_QueryInterface(ma_IDirectSoundBuffer* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +static MA_INLINE ULONG ma_IDirectSoundBuffer_AddRef(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->AddRef(pThis); } +static MA_INLINE ULONG ma_IDirectSoundBuffer_Release(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->Release(pThis); } +static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetCaps(ma_IDirectSoundBuffer* pThis, MA_DSBCAPS* pDSBufferCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSBufferCaps); } +static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetCurrentPosition(ma_IDirectSoundBuffer* pThis, DWORD* pCurrentPlayCursor, DWORD* pCurrentWriteCursor) { return pThis->lpVtbl->GetCurrentPosition(pThis, pCurrentPlayCursor, pCurrentWriteCursor); } +static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetFormat(ma_IDirectSoundBuffer* pThis, MA_WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten) { return pThis->lpVtbl->GetFormat(pThis, pFormat, dwSizeAllocated, pSizeWritten); } +static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetVolume(ma_IDirectSoundBuffer* pThis, LONG* pVolume) { return pThis->lpVtbl->GetVolume(pThis, pVolume); } +static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetPan(ma_IDirectSoundBuffer* pThis, LONG* pPan) { return pThis->lpVtbl->GetPan(pThis, pPan); } +static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetFrequency(ma_IDirectSoundBuffer* pThis, DWORD* pFrequency) { return pThis->lpVtbl->GetFrequency(pThis, pFrequency); } +static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetStatus(ma_IDirectSoundBuffer* pThis, DWORD* pStatus) { return pThis->lpVtbl->GetStatus(pThis, pStatus); } +static MA_INLINE HRESULT ma_IDirectSoundBuffer_Initialize(ma_IDirectSoundBuffer* pThis, ma_IDirectSound* pDirectSound, const MA_DSBUFFERDESC* pDSBufferDesc) { return pThis->lpVtbl->Initialize(pThis, pDirectSound, pDSBufferDesc); } +static MA_INLINE 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); } +static MA_INLINE HRESULT ma_IDirectSoundBuffer_Play(ma_IDirectSoundBuffer* pThis, DWORD dwReserved1, DWORD dwPriority, DWORD dwFlags) { return pThis->lpVtbl->Play(pThis, dwReserved1, dwPriority, dwFlags); } +static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetCurrentPosition(ma_IDirectSoundBuffer* pThis, DWORD dwNewPosition) { return pThis->lpVtbl->SetCurrentPosition(pThis, dwNewPosition); } +static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetFormat(ma_IDirectSoundBuffer* pThis, const MA_WAVEFORMATEX* pFormat) { return pThis->lpVtbl->SetFormat(pThis, pFormat); } +static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetVolume(ma_IDirectSoundBuffer* pThis, LONG volume) { return pThis->lpVtbl->SetVolume(pThis, volume); } +static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetPan(ma_IDirectSoundBuffer* pThis, LONG pan) { return pThis->lpVtbl->SetPan(pThis, pan); } +static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetFrequency(ma_IDirectSoundBuffer* pThis, DWORD dwFrequency) { return pThis->lpVtbl->SetFrequency(pThis, dwFrequency); } +static MA_INLINE HRESULT ma_IDirectSoundBuffer_Stop(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->Stop(pThis); } +static MA_INLINE HRESULT ma_IDirectSoundBuffer_Unlock(ma_IDirectSoundBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2) { return pThis->lpVtbl->Unlock(pThis, pAudioPtr1, dwAudioBytes1, pAudioPtr2, dwAudioBytes2); } +static MA_INLINE 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; +}; +static MA_INLINE HRESULT ma_IDirectSoundCapture_QueryInterface (ma_IDirectSoundCapture* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +static MA_INLINE ULONG ma_IDirectSoundCapture_AddRef (ma_IDirectSoundCapture* pThis) { return pThis->lpVtbl->AddRef(pThis); } +static MA_INLINE ULONG ma_IDirectSoundCapture_Release (ma_IDirectSoundCapture* pThis) { return pThis->lpVtbl->Release(pThis); } +static MA_INLINE HRESULT ma_IDirectSoundCapture_CreateCaptureBuffer(ma_IDirectSoundCapture* pThis, const MA_DSCBUFFERDESC* pDSCBufferDesc, ma_IDirectSoundCaptureBuffer** ppDSCBuffer, void* pUnkOuter) { return pThis->lpVtbl->CreateCaptureBuffer(pThis, pDSCBufferDesc, ppDSCBuffer, pUnkOuter); } +static MA_INLINE HRESULT ma_IDirectSoundCapture_GetCaps (ma_IDirectSoundCapture* pThis, MA_DSCCAPS* pDSCCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSCCaps); } +static MA_INLINE 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, MA_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; +}; +static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_QueryInterface(ma_IDirectSoundCaptureBuffer* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +static MA_INLINE ULONG ma_IDirectSoundCaptureBuffer_AddRef(ma_IDirectSoundCaptureBuffer* pThis) { return pThis->lpVtbl->AddRef(pThis); } +static MA_INLINE ULONG ma_IDirectSoundCaptureBuffer_Release(ma_IDirectSoundCaptureBuffer* pThis) { return pThis->lpVtbl->Release(pThis); } +static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_GetCaps(ma_IDirectSoundCaptureBuffer* pThis, MA_DSCBCAPS* pDSCBCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSCBCaps); } +static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_GetCurrentPosition(ma_IDirectSoundCaptureBuffer* pThis, DWORD* pCapturePosition, DWORD* pReadPosition) { return pThis->lpVtbl->GetCurrentPosition(pThis, pCapturePosition, pReadPosition); } +static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_GetFormat(ma_IDirectSoundCaptureBuffer* pThis, MA_WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten) { return pThis->lpVtbl->GetFormat(pThis, pFormat, dwSizeAllocated, pSizeWritten); } +static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_GetStatus(ma_IDirectSoundCaptureBuffer* pThis, DWORD* pStatus) { return pThis->lpVtbl->GetStatus(pThis, pStatus); } +static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_Initialize(ma_IDirectSoundCaptureBuffer* pThis, ma_IDirectSoundCapture* pDirectSoundCapture, const MA_DSCBUFFERDESC* pDSCBufferDesc) { return pThis->lpVtbl->Initialize(pThis, pDirectSoundCapture, pDSCBufferDesc); } +static MA_INLINE 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); } +static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_Start(ma_IDirectSoundCaptureBuffer* pThis, DWORD dwFlags) { return pThis->lpVtbl->Start(pThis, dwFlags); } +static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_Stop(ma_IDirectSoundCaptureBuffer* pThis) { return pThis->lpVtbl->Stop(pThis); } +static MA_INLINE 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; +}; +static MA_INLINE HRESULT ma_IDirectSoundNotify_QueryInterface(ma_IDirectSoundNotify* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +static MA_INLINE ULONG ma_IDirectSoundNotify_AddRef(ma_IDirectSoundNotify* pThis) { return pThis->lpVtbl->AddRef(pThis); } +static MA_INLINE ULONG ma_IDirectSoundNotify_Release(ma_IDirectSoundNotify* pThis) { return pThis->lpVtbl->Release(pThis); } +static MA_INLINE 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) (GUID* pDeviceGUID, const char* pDeviceDescription, const char* pModule, void* pContext); +typedef HRESULT (WINAPI * ma_DirectSoundCreateProc) (const GUID* pcGuidDevice, ma_IDirectSound** ppDS8, ma_IUnknown* pUnkOuter); +typedef HRESULT (WINAPI * ma_DirectSoundEnumerateAProc) (ma_DSEnumCallbackAProc pDSEnumCallback, void* pContext); +typedef HRESULT (WINAPI * ma_DirectSoundCaptureCreateProc) (const GUID* pcGuidDevice, ma_IDirectSoundCapture** ppDSC8, ma_IUnknown* pUnkOuter); +typedef HRESULT (WINAPI * ma_DirectSoundCaptureEnumerateAProc)(ma_DSEnumCallbackAProc pDSEnumCallback, void* pContext); + +static 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_uint32)ma_standard_sample_rate_min) { + sampleRateMin = (ma_uint32)ma_standard_sample_rate_min; + } + if (sampleRateMax > (ma_uint32)ma_standard_sample_rate_max) { + sampleRateMax = (ma_uint32)ma_standard_sample_rate_max; + } + if (sampleRateMin > sampleRateMax) { + sampleRateMin = sampleRateMax; + } + + if (sampleRateMin == sampleRateMax) { + return sampleRateMax; + } else { + 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; + } + } + } + + /* Should never get here. */ + MA_ASSERT(MA_FALSE); + return 0; +} + +/* +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. +*/ +static void ma_get_channels_from_speaker_config__dsound(DWORD speakerConfig, WORD* pChannelsOut, DWORD* pChannelMapOut) +{ + WORD channels; + DWORD channelMap; + + channels = 0; + if (pChannelsOut != NULL) { + channels = *pChannelsOut; + } + + 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; + } +} + + +static 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; + HRESULT hr; + + MA_ASSERT(pContext != NULL); + MA_ASSERT(ppDirectSound != NULL); + + *ppDirectSound = NULL; + pDirectSound = NULL; + + if (FAILED(((ma_DirectSoundCreateProc)pContext->dsound.DirectSoundCreate)((pDeviceID == NULL) ? NULL : (const GUID*)pDeviceID->dsound, &pDirectSound, NULL))) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[DirectSound] DirectSoundCreate() failed for playback device."); + return MA_FAILED_TO_OPEN_BACKEND_DEVICE; + } + + /* The cooperative level must be set before doing anything else. */ + hWnd = ((MA_PFN_GetForegroundWindow)pContext->win32.GetForegroundWindow)(); + if (hWnd == 0) { + hWnd = ((MA_PFN_GetDesktopWindow)pContext->win32.GetDesktopWindow)(); + } + + hr = ma_IDirectSound_SetCooperativeLevel(pDirectSound, hWnd, (shareMode == ma_share_mode_exclusive) ? MA_DSSCL_EXCLUSIVE : MA_DSSCL_PRIORITY); + if (FAILED(hr)) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_SetCooperateiveLevel() failed for playback device."); + return ma_result_from_HRESULT(hr); + } + + *ppDirectSound = pDirectSound; + return MA_SUCCESS; +} + +static 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; + HRESULT hr; + + 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; + pDirectSoundCapture = NULL; + + hr = ((ma_DirectSoundCaptureCreateProc)pContext->dsound.DirectSoundCaptureCreate)((pDeviceID == NULL) ? NULL : (const GUID*)pDeviceID->dsound, &pDirectSoundCapture, NULL); + if (FAILED(hr)) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[DirectSound] DirectSoundCaptureCreate() failed for capture device."); + return ma_result_from_HRESULT(hr); + } + + *ppDirectSoundCapture = pDirectSoundCapture; + return MA_SUCCESS; +} + +static ma_result ma_context_get_format_info_for_IDirectSoundCapture__dsound(ma_context* pContext, ma_IDirectSoundCapture* pDirectSoundCapture, WORD* pChannels, WORD* pBitsPerSample, DWORD* pSampleRate) +{ + HRESULT hr; + MA_DSCCAPS caps; + WORD bitsPerSample; + DWORD sampleRate; + + MA_ASSERT(pContext != NULL); + MA_ASSERT(pDirectSoundCapture != NULL); + + if (pChannels) { + *pChannels = 0; + } + if (pBitsPerSample) { + *pBitsPerSample = 0; + } + if (pSampleRate) { + *pSampleRate = 0; + } + + MA_ZERO_OBJECT(&caps); + caps.dwSize = sizeof(caps); + hr = ma_IDirectSoundCapture_GetCaps(pDirectSoundCapture, &caps); + if (FAILED(hr)) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCapture_GetCaps() failed for capture device."); + return ma_result_from_HRESULT(hr); + } + + 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. */ + bitsPerSample = 16; + 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; +} + + +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; + +static BOOL CALLBACK ma_context_enumerate_devices_callback__dsound(GUID* lpGuid, const char* lpcstrDescription, const char* lpcstrModule, void* lpContext) +{ + ma_context_enumerate_devices_callback_data__dsound* pData = (ma_context_enumerate_devices_callback_data__dsound*)lpContext; + ma_device_info deviceInfo; + + (void)lpcstrModule; + + MA_ZERO_OBJECT(&deviceInfo); + + /* ID. */ + if (lpGuid != NULL) { + MA_COPY_MEMORY(deviceInfo.id.dsound, lpGuid, 16); + } else { + MA_ZERO_MEMORY(deviceInfo.id.dsound, 16); + deviceInfo.isDefault = MA_TRUE; + } + + /* 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. */ + MA_ASSERT(pData != NULL); + pData->terminated = (pData->callback(pData->pContext, pData->deviceType, &deviceInfo, pData->pUserData) == MA_FALSE); + if (pData->terminated) { + return FALSE; /* Stop enumeration. */ + } else { + return TRUE; /* Continue enumeration. */ + } +} + +static 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); + + 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; + +static BOOL CALLBACK ma_context_get_device_info_callback__dsound(GUID* lpGuid, const char* lpcstrDescription, const char* lpcstrModule, void* lpContext) +{ + 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_null(pData->pDeviceID->dsound)) && (lpGuid == NULL || ma_is_guid_null(lpGuid))) { + /* Default device. */ + ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), lpcstrDescription, (size_t)-1); + pData->pDeviceInfo->isDefault = MA_TRUE; + pData->found = MA_TRUE; + return FALSE; /* Stop enumeration. */ + } else { + /* Not the default device. */ + if (lpGuid != NULL && pData->pDeviceID != 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. */ + } + } + } + + (void)lpcstrModule; + return TRUE; +} + +static ma_result ma_context_get_device_info__dsound(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo) +{ + ma_result result; + HRESULT hr; + + if (pDeviceID != NULL) { + 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. */ + 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); + } + + pDeviceInfo->isDefault = MA_TRUE; + } + + /* Retrieving detailed information is slightly different depending on the device type. */ + if (deviceType == ma_device_type_playback) { + /* Playback. */ + ma_IDirectSound* pDirectSound; + MA_DSCAPS caps; + WORD channels; + + result = ma_context_create_IDirectSound__dsound(pContext, ma_share_mode_shared, pDeviceID, &pDirectSound); + if (result != MA_SUCCESS) { + return result; + } + + MA_ZERO_OBJECT(&caps); + caps.dwSize = sizeof(caps); + hr = ma_IDirectSound_GetCaps(pDirectSound, &caps); + if (FAILED(hr)) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_GetCaps() failed for playback device."); + return ma_result_from_HRESULT(hr); + } + + + /* Channels. Only a single channel count is reported for DirectSound. */ + if ((caps.dwFlags & MA_DSCAPS_PRIMARYSTEREO) != 0) { + /* It supports at least stereo, but could support more. */ + DWORD speakerConfig; + + channels = 2; + + /* Look at the speaker configuration to get a better idea on the channel count. */ + hr = ma_IDirectSound_GetSpeakerConfig(pDirectSound, &speakerConfig); + if (SUCCEEDED(hr)) { + ma_get_channels_from_speaker_config__dsound(speakerConfig, &channels, NULL); + } + } else { + /* It does not support stereo, which means we are stuck with mono. */ + channels = 1; + } + + + /* + In DirectSound, our native formats are centered around sample rates. All formats are supported, and we're only reporting a single channel + count. However, DirectSound can report a range of supported sample rates. We're only going to include standard rates known by miniaudio + in order to keep the size of this within reason. + */ + if ((caps.dwFlags & MA_DSCAPS_CONTINUOUSRATE) != 0) { + /* Multiple sample rates are supported. We'll report in order of our preferred sample rates. */ + size_t iStandardSampleRate; + for (iStandardSampleRate = 0; iStandardSampleRate < ma_countof(g_maStandardSampleRatePriorities); iStandardSampleRate += 1) { + ma_uint32 sampleRate = g_maStandardSampleRatePriorities[iStandardSampleRate]; + if (sampleRate >= caps.dwMinSecondarySampleRate && sampleRate <= caps.dwMaxSecondarySampleRate) { + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = ma_format_unknown; + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels; + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = sampleRate; + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = 0; + pDeviceInfo->nativeDataFormatCount += 1; + } + } + } else { + /* Only a single sample rate is supported. */ + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = ma_format_unknown; + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels; + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = caps.dwMaxSecondarySampleRate; + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = 0; + pDeviceInfo->nativeDataFormatCount += 1; + } + + 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; + WORD channels; + WORD bitsPerSample; + DWORD sampleRate; + + result = ma_context_create_IDirectSoundCapture__dsound(pContext, ma_share_mode_shared, pDeviceID, &pDirectSoundCapture); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_context_get_format_info_for_IDirectSoundCapture__dsound(pContext, pDirectSoundCapture, &channels, &bitsPerSample, &sampleRate); + if (result != MA_SUCCESS) { + ma_IDirectSoundCapture_Release(pDirectSoundCapture); + return result; + } + + ma_IDirectSoundCapture_Release(pDirectSoundCapture); + + /* The format is always an integer format and is based on the bits per sample. */ + if (bitsPerSample == 8) { + pDeviceInfo->nativeDataFormats[0].format = ma_format_u8; + } else if (bitsPerSample == 16) { + pDeviceInfo->nativeDataFormats[0].format = ma_format_s16; + } else if (bitsPerSample == 24) { + pDeviceInfo->nativeDataFormats[0].format = ma_format_s24; + } else if (bitsPerSample == 32) { + pDeviceInfo->nativeDataFormats[0].format = ma_format_s32; + } else { + return MA_FORMAT_NOT_SUPPORTED; + } + + pDeviceInfo->nativeDataFormats[0].channels = channels; + pDeviceInfo->nativeDataFormats[0].sampleRate = sampleRate; + pDeviceInfo->nativeDataFormats[0].flags = 0; + pDeviceInfo->nativeDataFormatCount = 1; + } + + return MA_SUCCESS; +} + + + +static ma_result 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); + } + + return MA_SUCCESS; +} + +static ma_result ma_config_to_WAVEFORMATEXTENSIBLE(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, const ma_channel* pChannelMap, MA_WAVEFORMATEXTENSIBLE* pWF) +{ + GUID subformat; + + if (format == ma_format_unknown) { + format = MA_DEFAULT_FORMAT; + } + + if (channels == 0) { + channels = MA_DEFAULT_CHANNELS; + } + + if (sampleRate == 0) { + sampleRate = MA_DEFAULT_SAMPLE_RATE; + } + + 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->cbSize = sizeof(*pWF); + pWF->wFormatTag = WAVE_FORMAT_EXTENSIBLE; + pWF->nChannels = (WORD)channels; + pWF->nSamplesPerSec = (DWORD)sampleRate; + pWF->wBitsPerSample = (WORD)(ma_get_bytes_per_sample(format)*8); + pWF->nBlockAlign = (WORD)(pWF->nChannels * pWF->wBitsPerSample / 8); + pWF->nAvgBytesPerSec = pWF->nBlockAlign * pWF->nSamplesPerSec; + pWF->Samples.wValidBitsPerSample = pWF->wBitsPerSample; + pWF->dwChannelMask = ma_channel_map_to_channel_mask__win32(pChannelMap, channels); + pWF->SubFormat = subformat; + + return MA_SUCCESS; +} + +static ma_uint32 ma_calculate_period_size_in_frames_from_descriptor__dsound(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile) +{ + /* + DirectSound has a minimum period size of 20ms. In practice, this doesn't seem to be enough for + reliable glitch-free processing so going to use 30ms instead. + */ + ma_uint32 minPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(30, nativeSampleRate); + ma_uint32 periodSizeInFrames; + + periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, nativeSampleRate, performanceProfile); + if (periodSizeInFrames < minPeriodSizeInFrames) { + periodSizeInFrames = minPeriodSizeInFrames; + } + + return periodSizeInFrames; +} + +static ma_result ma_device_init__dsound(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture) +{ + ma_result result; + HRESULT hr; + + MA_ASSERT(pDevice != NULL); + + MA_ZERO_OBJECT(&pDevice->dsound); + + if (pConfig->deviceType == ma_device_type_loopback) { + return MA_DEVICE_TYPE_NOT_SUPPORTED; + } + + /* + 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) { + MA_WAVEFORMATEXTENSIBLE wf; + MA_DSCBUFFERDESC descDS; + ma_uint32 periodSizeInFrames; + ma_uint32 periodCount; + char rawdata[1024]; /* <-- Ugly hack to avoid a malloc() due to a crappy DirectSound API. */ + MA_WAVEFORMATEXTENSIBLE* pActualFormat; + + result = ma_config_to_WAVEFORMATEXTENSIBLE(pDescriptorCapture->format, pDescriptorCapture->channels, pDescriptorCapture->sampleRate, pDescriptorCapture->channelMap, &wf); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_context_create_IDirectSoundCapture__dsound(pDevice->pContext, pDescriptorCapture->shareMode, pDescriptorCapture->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(pDevice->pContext, (ma_IDirectSoundCapture*)pDevice->dsound.pCapture, &wf.nChannels, &wf.wBitsPerSample, &wf.nSamplesPerSec); + if (result != MA_SUCCESS) { + ma_device_uninit__dsound(pDevice); + return result; + } + + wf.nBlockAlign = (WORD)(wf.nChannels * wf.wBitsPerSample / 8); + wf.nAvgBytesPerSec = wf.nBlockAlign * wf.nSamplesPerSec; + wf.Samples.wValidBitsPerSample = wf.wBitsPerSample; + wf.SubFormat = MA_GUID_KSDATAFORMAT_SUBTYPE_PCM; + + /* The size of the buffer must be a clean multiple of the period count. */ + periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__dsound(pDescriptorCapture, wf.nSamplesPerSec, pConfig->performanceProfile); + periodCount = (pDescriptorCapture->periodCount > 0) ? pDescriptorCapture->periodCount : MA_DEFAULT_PERIODS; + + MA_ZERO_OBJECT(&descDS); + descDS.dwSize = sizeof(descDS); + descDS.dwFlags = 0; + descDS.dwBufferBytes = periodSizeInFrames * periodCount * wf.nBlockAlign; + descDS.lpwfxFormat = (MA_WAVEFORMATEX*)&wf; + hr = ma_IDirectSoundCapture_CreateCaptureBuffer((ma_IDirectSoundCapture*)pDevice->dsound.pCapture, &descDS, (ma_IDirectSoundCaptureBuffer**)&pDevice->dsound.pCaptureBuffer, NULL); + if (FAILED(hr)) { + ma_device_uninit__dsound(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCapture_CreateCaptureBuffer() failed for capture device."); + return ma_result_from_HRESULT(hr); + } + + /* Get the _actual_ properties of the buffer. */ + pActualFormat = (MA_WAVEFORMATEXTENSIBLE*)rawdata; + hr = ma_IDirectSoundCaptureBuffer_GetFormat((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, (MA_WAVEFORMATEX*)pActualFormat, sizeof(rawdata), NULL); + if (FAILED(hr)) { + ma_device_uninit__dsound(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to retrieve the actual format of the capture device's buffer."); + return ma_result_from_HRESULT(hr); + } + + /* We can now start setting the output data formats. */ + pDescriptorCapture->format = ma_format_from_WAVEFORMATEX((MA_WAVEFORMATEX*)pActualFormat); + pDescriptorCapture->channels = pActualFormat->nChannels; + pDescriptorCapture->sampleRate = pActualFormat->nSamplesPerSec; + + /* Get the native channel map based on the channel mask. */ + if (pActualFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { + ma_channel_mask_to_channel_map__win32(pActualFormat->dwChannelMask, pDescriptorCapture->channels, pDescriptorCapture->channelMap); + } else { + ma_channel_mask_to_channel_map__win32(wf.dwChannelMask, pDescriptorCapture->channels, pDescriptorCapture->channelMap); + } + + /* + 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 (periodSizeInFrames != (descDS.dwBufferBytes / ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels) / periodCount)) { + descDS.dwBufferBytes = periodSizeInFrames * ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels) * periodCount; + ma_IDirectSoundCaptureBuffer_Release((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer); + + hr = ma_IDirectSoundCapture_CreateCaptureBuffer((ma_IDirectSoundCapture*)pDevice->dsound.pCapture, &descDS, (ma_IDirectSoundCaptureBuffer**)&pDevice->dsound.pCaptureBuffer, NULL); + if (FAILED(hr)) { + ma_device_uninit__dsound(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Second attempt at IDirectSoundCapture_CreateCaptureBuffer() failed for capture device."); + return ma_result_from_HRESULT(hr); + } + } + + /* DirectSound should give us a buffer exactly the size we asked for. */ + pDescriptorCapture->periodSizeInFrames = periodSizeInFrames; + pDescriptorCapture->periodCount = periodCount; + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + MA_WAVEFORMATEXTENSIBLE wf; + MA_DSBUFFERDESC descDSPrimary; + MA_DSCAPS caps; + char rawdata[1024]; /* <-- Ugly hack to avoid a malloc() due to a crappy DirectSound API. */ + MA_WAVEFORMATEXTENSIBLE* pActualFormat; + ma_uint32 periodSizeInFrames; + ma_uint32 periodCount; + MA_DSBUFFERDESC descDS; + WORD nativeChannelCount; + DWORD nativeChannelMask = 0; + + result = ma_config_to_WAVEFORMATEXTENSIBLE(pDescriptorPlayback->format, pDescriptorPlayback->channels, pDescriptorPlayback->sampleRate, pDescriptorPlayback->channelMap, &wf); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_context_create_IDirectSound__dsound(pDevice->pContext, pDescriptorPlayback->shareMode, pDescriptorPlayback->pDeviceID, (ma_IDirectSound**)&pDevice->dsound.pPlayback); + if (result != MA_SUCCESS) { + ma_device_uninit__dsound(pDevice); + return result; + } + + MA_ZERO_OBJECT(&descDSPrimary); + descDSPrimary.dwSize = sizeof(MA_DSBUFFERDESC); + descDSPrimary.dwFlags = MA_DSBCAPS_PRIMARYBUFFER | MA_DSBCAPS_CTRLVOLUME; + hr = ma_IDirectSound_CreateSoundBuffer((ma_IDirectSound*)pDevice->dsound.pPlayback, &descDSPrimary, (ma_IDirectSoundBuffer**)&pDevice->dsound.pPlaybackPrimaryBuffer, NULL); + if (FAILED(hr)) { + ma_device_uninit__dsound(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_CreateSoundBuffer() failed for playback device's primary buffer."); + return ma_result_from_HRESULT(hr); + } + + + /* We may want to make some adjustments to the format if we are using defaults. */ + MA_ZERO_OBJECT(&caps); + caps.dwSize = sizeof(caps); + hr = ma_IDirectSound_GetCaps((ma_IDirectSound*)pDevice->dsound.pPlayback, &caps); + if (FAILED(hr)) { + ma_device_uninit__dsound(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_GetCaps() failed for playback device."); + return ma_result_from_HRESULT(hr); + } + + if ((caps.dwFlags & MA_DSCAPS_PRIMARYSTEREO) != 0) { + DWORD speakerConfig; + + /* It supports at least stereo, but could support more. */ + nativeChannelCount = 2; + + /* 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, &nativeChannelCount, &nativeChannelMask); + } + } else { + /* It does not support stereo, which means we are stuck with mono. */ + nativeChannelCount = 1; + nativeChannelMask = 0x00000001; + } + + if (pDescriptorPlayback->channels == 0) { + wf.nChannels = nativeChannelCount; + wf.dwChannelMask = nativeChannelMask; + } + + if (pDescriptorPlayback->sampleRate == 0) { + /* We base the sample rate on the values returned by GetCaps(). */ + if ((caps.dwFlags & MA_DSCAPS_CONTINUOUSRATE) != 0) { + wf.nSamplesPerSec = ma_get_best_sample_rate_within_range(caps.dwMinSecondarySampleRate, caps.dwMaxSecondarySampleRate); + } else { + wf.nSamplesPerSec = caps.dwMaxSecondarySampleRate; + } + } + + wf.nBlockAlign = (WORD)(wf.nChannels * wf.wBitsPerSample / 8); + wf.nAvgBytesPerSec = wf.nBlockAlign * wf.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. + */ + hr = ma_IDirectSoundBuffer_SetFormat((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer, (MA_WAVEFORMATEX*)&wf); + if (FAILED(hr)) { + /* + If setting of the format failed we'll try again with some fallback settings. On Windows 98 I have + observed that IEEE_FLOAT does not work. We'll therefore enforce PCM. I also had issues where a + sample rate of 48000 did not work correctly. Not sure if it was a driver issue or not, but will + use 44100 for the sample rate. + */ + wf.cbSize = 18; /* NOTE: Don't use sizeof(MA_WAVEFORMATEX) here because it's got an extra 2 bytes due to padding. */ + wf.wFormatTag = WAVE_FORMAT_PCM; + wf.wBitsPerSample = 16; + wf.nChannels = nativeChannelCount; + wf.nSamplesPerSec = 44100; + wf.nBlockAlign = wf.nChannels * (wf.wBitsPerSample / 8); + wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign; + + hr = ma_IDirectSoundBuffer_SetFormat((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer, (MA_WAVEFORMATEX*)&wf); + if (FAILED(hr)) { + ma_device_uninit__dsound(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to set format of playback device's primary buffer."); + return ma_result_from_HRESULT(hr); + } + } + + /* Get the _actual_ properties of the buffer. */ + pActualFormat = (MA_WAVEFORMATEXTENSIBLE*)rawdata; + hr = ma_IDirectSoundBuffer_GetFormat((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer, (MA_WAVEFORMATEX*)pActualFormat, sizeof(rawdata), NULL); + if (FAILED(hr)) { + ma_device_uninit__dsound(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to retrieve the actual format of the playback device's primary buffer."); + return ma_result_from_HRESULT(hr); + } + + /* We now have enough information to start setting some output properties. */ + pDescriptorPlayback->format = ma_format_from_WAVEFORMATEX((MA_WAVEFORMATEX*)pActualFormat); + pDescriptorPlayback->channels = pActualFormat->nChannels; + pDescriptorPlayback->sampleRate = pActualFormat->nSamplesPerSec; + + /* Get the internal channel map based on the channel mask. */ + if (pActualFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { + ma_channel_mask_to_channel_map__win32(pActualFormat->dwChannelMask, pDescriptorPlayback->channels, pDescriptorPlayback->channelMap); + } else { + ma_channel_mask_to_channel_map__win32(wf.dwChannelMask, pDescriptorPlayback->channels, pDescriptorPlayback->channelMap); + } + + /* The size of the buffer must be a clean multiple of the period count. */ + periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__dsound(pDescriptorPlayback, pDescriptorPlayback->sampleRate, pConfig->performanceProfile); + periodCount = (pDescriptorPlayback->periodCount > 0) ? pDescriptorPlayback->periodCount : MA_DEFAULT_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; + descDS.dwBufferBytes = periodSizeInFrames * periodCount * ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels); + descDS.lpwfxFormat = (MA_WAVEFORMATEX*)pActualFormat; + hr = ma_IDirectSound_CreateSoundBuffer((ma_IDirectSound*)pDevice->dsound.pPlayback, &descDS, (ma_IDirectSoundBuffer**)&pDevice->dsound.pPlaybackBuffer, NULL); + if (FAILED(hr)) { + ma_device_uninit__dsound(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_CreateSoundBuffer() failed for playback device's secondary buffer."); + return ma_result_from_HRESULT(hr); + } + + /* DirectSound should give us a buffer exactly the size we asked for. */ + pDescriptorPlayback->periodSizeInFrames = periodSizeInFrames; + pDescriptorPlayback->periodCount = periodCount; + } + + return MA_SUCCESS; +} + + +static ma_result ma_device_data_loop__dsound(ma_device* pDevice) +{ + ma_result result = MA_SUCCESS; + ma_uint32 bpfDeviceCapture = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + ma_uint32 bpfDevicePlayback = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + HRESULT hr; + DWORD lockOffsetInBytesCapture; + DWORD lockSizeInBytesCapture; + DWORD mappedSizeInBytesCapture; + DWORD mappedDeviceFramesProcessedCapture; + void* pMappedDeviceBufferCapture; + DWORD lockOffsetInBytesPlayback; + DWORD lockSizeInBytesPlayback; + DWORD mappedSizeInBytesPlayback; + void* pMappedDeviceBufferPlayback; + 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) { + hr = ma_IDirectSoundCaptureBuffer_Start((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, MA_DSCBSTART_LOOPING); + if (FAILED(hr)) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCaptureBuffer_Start() failed."); + return ma_result_from_HRESULT(hr); + } + } + + while (ma_device_get_state(pDevice) == ma_device_state_started) { + switch (pDevice->type) + { + case ma_device_type_duplex: + { + DWORD physicalCaptureCursorInBytes; + DWORD physicalReadCursorInBytes; + hr = ma_IDirectSoundCaptureBuffer_GetCurrentPosition((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, &physicalCaptureCursorInBytes, &physicalReadCursorInBytes); + if (FAILED(hr)) { + return ma_result_from_HRESULT(hr); + } + + /* 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.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture) { + /* Lock up to the end of the buffer. */ + lockOffsetInBytesCapture = prevReadCursorInBytesCapture; + lockSizeInBytesCapture = (pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture) - 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, &pMappedDeviceBufferCapture, &mappedSizeInBytesCapture, NULL, NULL, 0); + if (FAILED(hr)) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to map buffer from capture device in preparation for writing to the device."); + return ma_result_from_HRESULT(hr); + } + + + /* 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. */ + mappedDeviceFramesProcessedCapture = 0; + + for (;;) { /* Keep writing to the playback device. */ + ma_uint8 inputFramesInClientFormat[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; + ma_uint32 inputFramesInClientFormatCap = sizeof(inputFramesInClientFormat) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels); + ma_uint8 outputFramesInClientFormat[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; + ma_uint32 outputFramesInClientFormatCap = sizeof(outputFramesInClientFormat) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels); + ma_uint32 outputFramesInClientFormatCount; + ma_uint32 outputFramesInClientFormatConsumed = 0; + ma_uint64 clientCapturedFramesToProcess = ma_min(inputFramesInClientFormatCap, outputFramesInClientFormatCap); + ma_uint64 deviceCapturedFramesToProcess = (mappedSizeInBytesCapture / bpfDeviceCapture) - mappedDeviceFramesProcessedCapture; + void* pRunningMappedDeviceBufferCapture = ma_offset_ptr(pMappedDeviceBufferCapture, mappedDeviceFramesProcessedCapture * bpfDeviceCapture); + + result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningMappedDeviceBufferCapture, &deviceCapturedFramesToProcess, inputFramesInClientFormat, &clientCapturedFramesToProcess); + if (result != MA_SUCCESS) { + break; + } + + outputFramesInClientFormatCount = (ma_uint32)clientCapturedFramesToProcess; + mappedDeviceFramesProcessedCapture += (ma_uint32)deviceCapturedFramesToProcess; + + ma_device__handle_data_callback(pDevice, outputFramesInClientFormat, inputFramesInClientFormat, (ma_uint32)clientCapturedFramesToProcess); + + /* At this point we have input and output data in client format. All we need to do now is convert it to the output device format. This may take a few passes. */ + 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.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback; + availableBytesPlayback += physicalPlayCursorInBytes; /* Wrap around. */ + } else { + /* This is an error. */ + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[DirectSound] (Duplex/Playback): Play cursor has moved in front of the write cursor (same loop iteration). physicalPlayCursorInBytes=%ld, virtualWriteCursorInBytes=%ld.\n", physicalPlayCursorInBytes, virtualWriteCursorInBytesPlayback); + 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. */ + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[DirectSound] (Duplex/Playback): Write cursor has moved behind the play cursor (different loop iterations). physicalPlayCursorInBytes=%ld, virtualWriteCursorInBytes=%ld.\n", physicalPlayCursorInBytes, virtualWriteCursorInBytesPlayback); + availableBytesPlayback = 0; + } + } + + /* 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) { + hr = ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING); + if (FAILED(hr)) { + ma_IDirectSoundCaptureBuffer_Stop((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed."); + return ma_result_from_HRESULT(hr); + } + 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.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - 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, &pMappedDeviceBufferPlayback, &mappedSizeInBytesPlayback, NULL, NULL, 0); + if (FAILED(hr)) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to map buffer from playback device in preparation for writing to the device."); + result = ma_result_from_HRESULT(hr); + 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.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - availableBytesPlayback; + if (bytesQueuedForPlayback < (pDevice->playback.internalPeriodSizeInFrames*bpfDevicePlayback)) { + silentPaddingInBytes = (pDevice->playback.internalPeriodSizeInFrames*2*bpfDevicePlayback) - bytesQueuedForPlayback; + if (silentPaddingInBytes > lockSizeInBytesPlayback) { + silentPaddingInBytes = lockSizeInBytesPlayback; + } + + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[DirectSound] (Duplex/Playback) Playback buffer starved. availableBytesPlayback=%ld, silentPaddingInBytes=%ld\n", availableBytesPlayback, silentPaddingInBytes); + } + } + + /* At this point we have a buffer for output. */ + if (silentPaddingInBytes > 0) { + MA_ZERO_MEMORY(pMappedDeviceBufferPlayback, silentPaddingInBytes); + framesWrittenThisIteration = silentPaddingInBytes/bpfDevicePlayback; + } else { + ma_uint64 convertedFrameCountIn = (outputFramesInClientFormatCount - outputFramesInClientFormatConsumed); + ma_uint64 convertedFrameCountOut = mappedSizeInBytesPlayback/bpfDevicePlayback; + void* pConvertedFramesIn = ma_offset_ptr(outputFramesInClientFormat, outputFramesInClientFormatConsumed * bpfDevicePlayback); + void* pConvertedFramesOut = pMappedDeviceBufferPlayback; + + result = ma_data_converter_process_pcm_frames(&pDevice->playback.converter, pConvertedFramesIn, &convertedFrameCountIn, pConvertedFramesOut, &convertedFrameCountOut); + if (result != MA_SUCCESS) { + break; + } + + outputFramesInClientFormatConsumed += (ma_uint32)convertedFrameCountOut; + framesWrittenThisIteration = (ma_uint32)convertedFrameCountOut; + } + + + hr = ma_IDirectSoundBuffer_Unlock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, pMappedDeviceBufferPlayback, framesWrittenThisIteration*bpfDevicePlayback, NULL, 0); + if (FAILED(hr)) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to unlock internal buffer from playback device after writing to the device."); + result = ma_result_from_HRESULT(hr); + break; + } + + virtualWriteCursorInBytesPlayback += framesWrittenThisIteration*bpfDevicePlayback; + if ((virtualWriteCursorInBytesPlayback/bpfDevicePlayback) == pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods) { + 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.internalPeriodSizeInFrames*2)) { + hr = ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING); + if (FAILED(hr)) { + ma_IDirectSoundCaptureBuffer_Stop((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed."); + return ma_result_from_HRESULT(hr); + } + isPlaybackDeviceStarted = MA_TRUE; + } + + if (framesWrittenThisIteration < mappedSizeInBytesPlayback/bpfDevicePlayback) { + break; /* We're finished with the output data.*/ + } + } + + if (clientCapturedFramesToProcess == 0) { + 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, pMappedDeviceBufferCapture, mappedSizeInBytesCapture, NULL, 0); + if (FAILED(hr)) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to unlock internal buffer from capture device after reading from the device."); + return ma_result_from_HRESULT(hr); + } + prevReadCursorInBytesCapture = (lockOffsetInBytesCapture + mappedSizeInBytesCapture); + } break; + + + + case ma_device_type_capture: + { + DWORD physicalCaptureCursorInBytes; + DWORD physicalReadCursorInBytes; + hr = ma_IDirectSoundCaptureBuffer_GetCurrentPosition((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, &physicalCaptureCursorInBytes, &physicalReadCursorInBytes); + if (FAILED(hr)) { + 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.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture) { + /* Lock up to the end of the buffer. */ + lockOffsetInBytesCapture = prevReadCursorInBytesCapture; + lockSizeInBytesCapture = (pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture) - prevReadCursorInBytesCapture; + } else { + /* Lock starting from the start of the buffer. */ + lockOffsetInBytesCapture = 0; + lockSizeInBytesCapture = physicalReadCursorInBytes; + } + } + + if (lockSizeInBytesCapture < pDevice->capture.internalPeriodSizeInFrames) { + ma_sleep(waitTimeInMilliseconds); + continue; /* Nothing is available in the capture buffer. */ + } + + hr = ma_IDirectSoundCaptureBuffer_Lock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, lockOffsetInBytesCapture, lockSizeInBytesCapture, &pMappedDeviceBufferCapture, &mappedSizeInBytesCapture, NULL, NULL, 0); + if (FAILED(hr)) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to map buffer from capture device in preparation for writing to the device."); + result = ma_result_from_HRESULT(hr); + } + + if (lockSizeInBytesCapture != mappedSizeInBytesCapture) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[DirectSound] (Capture) lockSizeInBytesCapture=%ld != mappedSizeInBytesCapture=%ld\n", lockSizeInBytesCapture, mappedSizeInBytesCapture); + } + + ma_device__send_frames_to_client(pDevice, mappedSizeInBytesCapture/bpfDeviceCapture, pMappedDeviceBufferCapture); + + hr = ma_IDirectSoundCaptureBuffer_Unlock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, pMappedDeviceBufferCapture, mappedSizeInBytesCapture, NULL, 0); + if (FAILED(hr)) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to unlock internal buffer from capture device after reading from the device."); + return ma_result_from_HRESULT(hr); + } + prevReadCursorInBytesCapture = lockOffsetInBytesCapture + mappedSizeInBytesCapture; + + if (prevReadCursorInBytesCapture == (pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture)) { + prevReadCursorInBytesCapture = 0; + } + } break; + + + + case ma_device_type_playback: + { + DWORD availableBytesPlayback; + DWORD physicalPlayCursorInBytes; + DWORD physicalWriteCursorInBytes; + hr = ma_IDirectSoundBuffer_GetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, &physicalPlayCursorInBytes, &physicalWriteCursorInBytes); + if (FAILED(hr)) { + 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.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback; + availableBytesPlayback += physicalPlayCursorInBytes; /* Wrap around. */ + } else { + /* This is an error. */ + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[DirectSound] (Playback): Play cursor has moved in front of the write cursor (same loop iterations). physicalPlayCursorInBytes=%ld, virtualWriteCursorInBytes=%ld.\n", physicalPlayCursorInBytes, virtualWriteCursorInBytesPlayback); + 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. */ + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[DirectSound] (Playback): Write cursor has moved behind the play cursor (different loop iterations). physicalPlayCursorInBytes=%ld, virtualWriteCursorInBytes=%ld.\n", physicalPlayCursorInBytes, virtualWriteCursorInBytesPlayback); + availableBytesPlayback = 0; + } + } + + /* If there's no room available for writing we need to wait for more. */ + if (availableBytesPlayback < pDevice->playback.internalPeriodSizeInFrames) { + /* 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) { + hr = ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING); + if (FAILED(hr)) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed."); + return ma_result_from_HRESULT(hr); + } + 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.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - 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, &pMappedDeviceBufferPlayback, &mappedSizeInBytesPlayback, NULL, NULL, 0); + if (FAILED(hr)) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to map buffer from playback device in preparation for writing to the device."); + result = ma_result_from_HRESULT(hr); + break; + } + + /* At this point we have a buffer for output. */ + ma_device__read_frames_from_client(pDevice, (mappedSizeInBytesPlayback/bpfDevicePlayback), pMappedDeviceBufferPlayback); + + hr = ma_IDirectSoundBuffer_Unlock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, pMappedDeviceBufferPlayback, mappedSizeInBytesPlayback, NULL, 0); + if (FAILED(hr)) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to unlock internal buffer from playback device after writing to the device."); + result = ma_result_from_HRESULT(hr); + break; + } + + virtualWriteCursorInBytesPlayback += mappedSizeInBytesPlayback; + if (virtualWriteCursorInBytesPlayback == pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) { + 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/bpfDevicePlayback; + if (!isPlaybackDeviceStarted && framesWrittenToPlaybackDevice >= pDevice->playback.internalPeriodSizeInFrames) { + hr = ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING); + if (FAILED(hr)) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed."); + return ma_result_from_HRESULT(hr); + } + 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) { + hr = ma_IDirectSoundCaptureBuffer_Stop((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer); + if (FAILED(hr)) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCaptureBuffer_Stop() failed."); + return ma_result_from_HRESULT(hr); + } + } + + 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; + hr = ma_IDirectSoundBuffer_GetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, &physicalPlayCursorInBytes, &physicalWriteCursorInBytes); + if (FAILED(hr)) { + 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.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - 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.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback)) { + break; + } + + ma_sleep(waitTimeInMilliseconds); + } + } + + hr = ma_IDirectSoundBuffer_Stop((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer); + if (FAILED(hr)) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Stop() failed."); + return ma_result_from_HRESULT(hr); + } + + ma_IDirectSoundBuffer_SetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0); + } + + return MA_SUCCESS; +} + +static ma_result ma_context_uninit__dsound(ma_context* pContext) +{ + MA_ASSERT(pContext != NULL); + MA_ASSERT(pContext->backend == ma_backend_dsound); + + ma_dlclose(ma_context_get_log(pContext), pContext->dsound.hDSoundDLL); + + return MA_SUCCESS; +} + +static ma_result ma_context_init__dsound(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks) +{ + MA_ASSERT(pContext != NULL); + + (void)pConfig; + + pContext->dsound.hDSoundDLL = ma_dlopen(ma_context_get_log(pContext), "dsound.dll"); + if (pContext->dsound.hDSoundDLL == NULL) { + return MA_API_NOT_FOUND; + } + + pContext->dsound.DirectSoundCreate = ma_dlsym(ma_context_get_log(pContext), pContext->dsound.hDSoundDLL, "DirectSoundCreate"); + pContext->dsound.DirectSoundEnumerateA = ma_dlsym(ma_context_get_log(pContext), pContext->dsound.hDSoundDLL, "DirectSoundEnumerateA"); + pContext->dsound.DirectSoundCaptureCreate = ma_dlsym(ma_context_get_log(pContext), pContext->dsound.hDSoundDLL, "DirectSoundCaptureCreate"); + pContext->dsound.DirectSoundCaptureEnumerateA = ma_dlsym(ma_context_get_log(pContext), pContext->dsound.hDSoundDLL, "DirectSoundCaptureEnumerateA"); + + /* + We need to support all functions or nothing. DirectSound with Windows 95 seems to not work too + well in my testing. For example, it's missing DirectSoundCaptureEnumerateA(). This is a convenient + place to just disable the DirectSound backend for Windows 95. + */ + if (pContext->dsound.DirectSoundCreate == NULL || + pContext->dsound.DirectSoundEnumerateA == NULL || + pContext->dsound.DirectSoundCaptureCreate == NULL || + pContext->dsound.DirectSoundCaptureEnumerateA == NULL) { + return MA_API_NOT_FOUND; + } + + pCallbacks->onContextInit = ma_context_init__dsound; + pCallbacks->onContextUninit = ma_context_uninit__dsound; + pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__dsound; + pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__dsound; + pCallbacks->onDeviceInit = ma_device_init__dsound; + pCallbacks->onDeviceUninit = ma_device_uninit__dsound; + pCallbacks->onDeviceStart = NULL; /* Not used. Started in onDeviceDataLoop. */ + pCallbacks->onDeviceStop = NULL; /* Not used. Stopped in onDeviceDataLoop. */ + pCallbacks->onDeviceRead = NULL; /* Not used. Data is read directly in onDeviceDataLoop. */ + pCallbacks->onDeviceWrite = NULL; /* Not used. Data is written directly in onDeviceDataLoop. */ + pCallbacks->onDeviceDataLoop = ma_device_data_loop__dsound; + + return MA_SUCCESS; +} +#endif + + + +/****************************************************************************** + +WinMM Backend + +******************************************************************************/ +#ifdef MA_HAS_WINMM + +/* +Some build configurations will exclude the WinMM API. An example is when WIN32_LEAN_AND_MEAN +is defined. We need to define the types and functions we need manually. +*/ +#define MA_MMSYSERR_NOERROR 0 +#define MA_MMSYSERR_ERROR 1 +#define MA_MMSYSERR_BADDEVICEID 2 +#define MA_MMSYSERR_INVALHANDLE 5 +#define MA_MMSYSERR_NOMEM 7 +#define MA_MMSYSERR_INVALFLAG 10 +#define MA_MMSYSERR_INVALPARAM 11 +#define MA_MMSYSERR_HANDLEBUSY 12 + +#define MA_CALLBACK_EVENT 0x00050000 +#define MA_WAVE_ALLOWSYNC 0x0002 + +#define MA_WHDR_DONE 0x00000001 +#define MA_WHDR_PREPARED 0x00000002 +#define MA_WHDR_BEGINLOOP 0x00000004 +#define MA_WHDR_ENDLOOP 0x00000008 +#define MA_WHDR_INQUEUE 0x00000010 + +#define MA_MAXPNAMELEN 32 + +typedef void* MA_HWAVEIN; +typedef void* MA_HWAVEOUT; +typedef UINT MA_MMRESULT; +typedef UINT MA_MMVERSION; + +typedef struct +{ + WORD wMid; + WORD wPid; + MA_MMVERSION vDriverVersion; + CHAR szPname[MA_MAXPNAMELEN]; + DWORD dwFormats; + WORD wChannels; + WORD wReserved1; +} MA_WAVEINCAPSA; + +typedef struct +{ + WORD wMid; + WORD wPid; + MA_MMVERSION vDriverVersion; + CHAR szPname[MA_MAXPNAMELEN]; + DWORD dwFormats; + WORD wChannels; + WORD wReserved1; + DWORD dwSupport; +} MA_WAVEOUTCAPSA; + +typedef struct tagWAVEHDR +{ + char* lpData; + DWORD dwBufferLength; + DWORD dwBytesRecorded; + DWORD_PTR dwUser; + DWORD dwFlags; + DWORD dwLoops; + struct tagWAVEHDR* lpNext; + DWORD_PTR reserved; +} MA_WAVEHDR; + +typedef struct +{ + WORD wMid; + WORD wPid; + MA_MMVERSION vDriverVersion; + CHAR szPname[MA_MAXPNAMELEN]; + DWORD dwFormats; + WORD wChannels; + WORD wReserved1; + DWORD dwSupport; + GUID ManufacturerGuid; + GUID ProductGuid; + GUID NameGuid; +} MA_WAVEOUTCAPS2A; + +typedef struct +{ + WORD wMid; + WORD wPid; + MA_MMVERSION vDriverVersion; + CHAR szPname[MA_MAXPNAMELEN]; + DWORD dwFormats; + WORD wChannels; + WORD wReserved1; + GUID ManufacturerGuid; + GUID ProductGuid; + GUID NameGuid; +} MA_WAVEINCAPS2A; + +typedef UINT (WINAPI * MA_PFN_waveOutGetNumDevs)(void); +typedef MA_MMRESULT (WINAPI * MA_PFN_waveOutGetDevCapsA)(ma_uintptr uDeviceID, MA_WAVEOUTCAPSA* pwoc, UINT cbwoc); +typedef MA_MMRESULT (WINAPI * MA_PFN_waveOutOpen)(MA_HWAVEOUT* phwo, UINT uDeviceID, const MA_WAVEFORMATEX* pwfx, DWORD_PTR dwCallback, DWORD_PTR dwInstance, DWORD fdwOpen); +typedef MA_MMRESULT (WINAPI * MA_PFN_waveOutClose)(MA_HWAVEOUT hwo); +typedef MA_MMRESULT (WINAPI * MA_PFN_waveOutPrepareHeader)(MA_HWAVEOUT hwo, MA_WAVEHDR* pwh, UINT cbwh); +typedef MA_MMRESULT (WINAPI * MA_PFN_waveOutUnprepareHeader)(MA_HWAVEOUT hwo, MA_WAVEHDR* pwh, UINT cbwh); +typedef MA_MMRESULT (WINAPI * MA_PFN_waveOutWrite)(MA_HWAVEOUT hwo, MA_WAVEHDR* pwh, UINT cbwh); +typedef MA_MMRESULT (WINAPI * MA_PFN_waveOutReset)(MA_HWAVEOUT hwo); +typedef UINT (WINAPI * MA_PFN_waveInGetNumDevs)(void); +typedef MA_MMRESULT (WINAPI * MA_PFN_waveInGetDevCapsA)(ma_uintptr uDeviceID, MA_WAVEINCAPSA* pwic, UINT cbwic); +typedef MA_MMRESULT (WINAPI * MA_PFN_waveInOpen)(MA_HWAVEIN* phwi, UINT uDeviceID, const MA_WAVEFORMATEX* pwfx, DWORD_PTR dwCallback, DWORD_PTR dwInstance, DWORD fdwOpen); +typedef MA_MMRESULT (WINAPI * MA_PFN_waveInClose)(MA_HWAVEIN hwi); +typedef MA_MMRESULT (WINAPI * MA_PFN_waveInPrepareHeader)(MA_HWAVEIN hwi, MA_WAVEHDR* pwh, UINT cbwh); +typedef MA_MMRESULT (WINAPI * MA_PFN_waveInUnprepareHeader)(MA_HWAVEIN hwi, MA_WAVEHDR* pwh, UINT cbwh); +typedef MA_MMRESULT (WINAPI * MA_PFN_waveInAddBuffer)(MA_HWAVEIN hwi, MA_WAVEHDR* pwh, UINT cbwh); +typedef MA_MMRESULT (WINAPI * MA_PFN_waveInStart)(MA_HWAVEIN hwi); +typedef MA_MMRESULT (WINAPI * MA_PFN_waveInReset)(MA_HWAVEIN hwi); + +static ma_result ma_result_from_MMRESULT(MA_MMRESULT resultMM) +{ + switch (resultMM) + { + case MA_MMSYSERR_NOERROR: return MA_SUCCESS; + case MA_MMSYSERR_BADDEVICEID: return MA_INVALID_ARGS; + case MA_MMSYSERR_INVALHANDLE: return MA_INVALID_ARGS; + case MA_MMSYSERR_NOMEM: return MA_OUT_OF_MEMORY; + case MA_MMSYSERR_INVALFLAG: return MA_INVALID_ARGS; + case MA_MMSYSERR_INVALPARAM: return MA_INVALID_ARGS; + case MA_MMSYSERR_HANDLEBUSY: return MA_BUSY; + case MA_MMSYSERR_ERROR: return MA_ERROR; + default: return MA_ERROR; + } +} + +static char* ma_find_last_character(char* str, char ch) +{ + char* last; + + if (str == NULL) { + return NULL; + } + + last = NULL; + while (*str != '\0') { + if (*str == ch) { + last = str; + } + + str += 1; + } + + return last; +} + +static ma_uint32 ma_get_period_size_in_bytes(ma_uint32 periodSizeInFrames, ma_format format, ma_uint32 channels) +{ + return periodSizeInFrames * ma_get_bytes_per_frame(format, channels); +} + + +/* +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[MA_MAXPNAMELEN]; + DWORD dwFormats; + WORD wChannels; + GUID NameGuid; +} MA_WAVECAPSA; + +static 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; + } + if (pSampleRate) { + *pSampleRate = 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; +} + +static ma_result ma_formats_flags_to_WAVEFORMATEX__winmm(DWORD dwFormats, WORD channels, MA_WAVEFORMATEX* pWF) +{ + ma_result result; + + 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; + } + + result = ma_get_best_info_from_formats_flags__winmm(dwFormats, channels, &pWF->wBitsPerSample, &pWF->nSamplesPerSec); + if (result != MA_SUCCESS) { + return result; + } + + pWF->nBlockAlign = (WORD)(pWF->nChannels * pWF->wBitsPerSample / 8); + pWF->nAvgBytesPerSec = pWF->nBlockAlign * pWF->nSamplesPerSec; + + return MA_SUCCESS; +} + +static 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. + */ + + /* 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_null(&pCaps->NameGuid)) { + WCHAR 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); + + ma_strcpy_s(keyStr, sizeof(keyStr), "SYSTEM\\CurrentControlSet\\Control\\MediaCategories\\"); + ma_strcat_s(keyStr, sizeof(keyStr), guidStr); + + if (((MA_PFN_RegOpenKeyExA)pContext->win32.RegOpenKeyExA)(HKEY_LOCAL_MACHINE, keyStr, 0, KEY_READ, &hKey) == ERROR_SUCCESS) { + BYTE nameFromReg[512]; + DWORD nameFromRegSize = sizeof(nameFromReg); + LONG resultWin32 = ((MA_PFN_RegQueryValueExA)pContext->win32.RegQueryValueExA)(hKey, "Name", 0, NULL, (BYTE*)nameFromReg, (DWORD*)&nameFromRegSize); + ((MA_PFN_RegCloseKey)pContext->win32.RegCloseKey)(hKey); + + if (resultWin32 == 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); + } + } + } + } + } + } + + + result = ma_get_best_info_from_formats_flags__winmm(pCaps->dwFormats, pCaps->wChannels, &bitsPerSample, &sampleRate); + if (result != MA_SUCCESS) { + return result; + } + + if (bitsPerSample == 8) { + pDeviceInfo->nativeDataFormats[0].format = ma_format_u8; + } else if (bitsPerSample == 16) { + pDeviceInfo->nativeDataFormats[0].format = ma_format_s16; + } else if (bitsPerSample == 24) { + pDeviceInfo->nativeDataFormats[0].format = ma_format_s24; + } else if (bitsPerSample == 32) { + pDeviceInfo->nativeDataFormats[0].format = ma_format_s32; + } else { + return MA_FORMAT_NOT_SUPPORTED; + } + pDeviceInfo->nativeDataFormats[0].channels = pCaps->wChannels; + pDeviceInfo->nativeDataFormats[0].sampleRate = sampleRate; + pDeviceInfo->nativeDataFormats[0].flags = 0; + pDeviceInfo->nativeDataFormatCount = 1; + + return MA_SUCCESS; +} + +static 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_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); +} + +static 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_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); +} + + +static 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. */ + playbackDeviceCount = ((MA_PFN_waveOutGetNumDevs)pContext->winmm.waveOutGetNumDevs)(); + for (iPlaybackDevice = 0; iPlaybackDevice < playbackDeviceCount; ++iPlaybackDevice) { + MA_MMRESULT result; + MA_WAVEOUTCAPS2A caps; + + MA_ZERO_OBJECT(&caps); + + result = ((MA_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(iPlaybackDevice, (MA_WAVEOUTCAPSA*)&caps, sizeof(caps)); + if (result == MA_MMSYSERR_NOERROR) { + ma_device_info deviceInfo; + + MA_ZERO_OBJECT(&deviceInfo); + deviceInfo.id.winmm = iPlaybackDevice; + + /* The first enumerated device is the default device. */ + if (iPlaybackDevice == 0) { + deviceInfo.isDefault = MA_TRUE; + } + + 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. */ + captureDeviceCount = ((MA_PFN_waveInGetNumDevs)pContext->winmm.waveInGetNumDevs)(); + for (iCaptureDevice = 0; iCaptureDevice < captureDeviceCount; ++iCaptureDevice) { + MA_MMRESULT result; + MA_WAVEINCAPS2A caps; + + MA_ZERO_OBJECT(&caps); + + result = ((MA_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(iCaptureDevice, (MA_WAVEINCAPSA*)&caps, sizeof(caps)); + if (result == MA_MMSYSERR_NOERROR) { + ma_device_info deviceInfo; + + MA_ZERO_OBJECT(&deviceInfo); + deviceInfo.id.winmm = iCaptureDevice; + + /* The first enumerated device is the default device. */ + if (iCaptureDevice == 0) { + deviceInfo.isDefault = MA_TRUE; + } + + 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; +} + +static ma_result ma_context_get_device_info__winmm(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo) +{ + UINT winMMDeviceID; + + MA_ASSERT(pContext != NULL); + + winMMDeviceID = 0; + if (pDeviceID != NULL) { + winMMDeviceID = (UINT)pDeviceID->winmm; + } + + pDeviceInfo->id.winmm = winMMDeviceID; + + /* The first ID is the default device. */ + if (winMMDeviceID == 0) { + pDeviceInfo->isDefault = MA_TRUE; + } + + if (deviceType == ma_device_type_playback) { + MA_MMRESULT result; + MA_WAVEOUTCAPS2A caps; + + MA_ZERO_OBJECT(&caps); + + result = ((MA_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(winMMDeviceID, (MA_WAVEOUTCAPSA*)&caps, sizeof(caps)); + if (result == MA_MMSYSERR_NOERROR) { + return ma_context_get_device_info_from_WAVEOUTCAPS2(pContext, &caps, pDeviceInfo); + } + } else { + MA_MMRESULT result; + MA_WAVEINCAPS2A caps; + + MA_ZERO_OBJECT(&caps); + + result = ((MA_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(winMMDeviceID, (MA_WAVEINCAPSA*)&caps, sizeof(caps)); + if (result == MA_MMSYSERR_NOERROR) { + return ma_context_get_device_info_from_WAVEINCAPS2(pContext, &caps, pDeviceInfo); + } + } + + return MA_NO_DEVICE; +} + + +static ma_result 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)((MA_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)((MA_HWAVEOUT)pDevice->winmm.hDevicePlayback); + ((MA_PFN_waveOutClose)pDevice->pContext->winmm.waveOutClose)((MA_HWAVEOUT)pDevice->winmm.hDevicePlayback); + CloseHandle((HANDLE)pDevice->winmm.hEventPlayback); + } + + ma_free(pDevice->winmm._pHeapData, &pDevice->pContext->allocationCallbacks); + + MA_ZERO_OBJECT(&pDevice->winmm); /* Safety. */ + + return MA_SUCCESS; +} + +static ma_uint32 ma_calculate_period_size_in_frames_from_descriptor__winmm(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile) +{ + /* WinMM has a minimum period size of 40ms. */ + ma_uint32 minPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(40, nativeSampleRate); + ma_uint32 periodSizeInFrames; + + periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, nativeSampleRate, performanceProfile); + if (periodSizeInFrames < minPeriodSizeInFrames) { + periodSizeInFrames = minPeriodSizeInFrames; + } + + return periodSizeInFrames; +} + +static ma_result ma_device_init__winmm(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture) +{ + 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); + + if (pConfig->deviceType == ma_device_type_loopback) { + return MA_DEVICE_TYPE_NOT_SUPPORTED; + } + + /* No exlusive mode with WinMM. */ + if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive) || + ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive)) { + return MA_SHARE_MODE_NOT_SUPPORTED; + } + + if (pDescriptorPlayback->pDeviceID != NULL) { + winMMDeviceIDPlayback = (UINT)pDescriptorPlayback->pDeviceID->winmm; + } + if (pDescriptorCapture->pDeviceID != NULL) { + winMMDeviceIDCapture = (UINT)pDescriptorCapture->pDeviceID->winmm; + } + + /* The capture device needs to be initialized first. */ + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + MA_WAVEINCAPSA caps; + MA_WAVEFORMATEX wf; + MA_MMRESULT resultMM; + + /* We use an event to know when a new fragment needs to be enqueued. */ + pDevice->winmm.hEventCapture = (ma_handle)CreateEventA(NULL, TRUE, TRUE, NULL); + if (pDevice->winmm.hEventCapture == NULL) { + errorMsg = "[WinMM] Failed to create event for fragment enqueing for the capture device.", errorCode = ma_result_from_GetLastError(GetLastError()); + goto on_error; + } + + /* The format should be based on the device's actual format. */ + if (((MA_PFN_waveInGetDevCapsA)pDevice->pContext->winmm.waveInGetDevCapsA)(winMMDeviceIDCapture, &caps, sizeof(caps)) != MA_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)((MA_HWAVEIN*)&pDevice->winmm.hDeviceCapture, winMMDeviceIDCapture, &wf, (DWORD_PTR)pDevice->winmm.hEventCapture, (DWORD_PTR)pDevice, MA_CALLBACK_EVENT | MA_WAVE_ALLOWSYNC); + if (resultMM != MA_MMSYSERR_NOERROR) { + errorMsg = "[WinMM] Failed to open capture device.", errorCode = MA_FAILED_TO_OPEN_BACKEND_DEVICE; + goto on_error; + } + + pDescriptorCapture->format = ma_format_from_WAVEFORMATEX(&wf); + pDescriptorCapture->channels = wf.nChannels; + pDescriptorCapture->sampleRate = wf.nSamplesPerSec; + ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pDescriptorCapture->channelMap, ma_countof(pDescriptorCapture->channelMap), pDescriptorCapture->channels); + pDescriptorCapture->periodCount = pDescriptorCapture->periodCount; + pDescriptorCapture->periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__winmm(pDescriptorCapture, pDescriptorCapture->sampleRate, pConfig->performanceProfile); + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + MA_WAVEOUTCAPSA caps; + MA_WAVEFORMATEX wf; + MA_MMRESULT resultMM; + + /* We use an event to know when a new fragment needs to be enqueued. */ + pDevice->winmm.hEventPlayback = (ma_handle)CreateEventA(NULL, TRUE, TRUE, NULL); + if (pDevice->winmm.hEventPlayback == NULL) { + errorMsg = "[WinMM] Failed to create event for fragment enqueing for the playback device.", errorCode = ma_result_from_GetLastError(GetLastError()); + goto on_error; + } + + /* The format should be based on the device's actual format. */ + if (((MA_PFN_waveOutGetDevCapsA)pDevice->pContext->winmm.waveOutGetDevCapsA)(winMMDeviceIDPlayback, &caps, sizeof(caps)) != MA_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)pDevice->pContext->winmm.waveOutOpen)((MA_HWAVEOUT*)&pDevice->winmm.hDevicePlayback, winMMDeviceIDPlayback, &wf, (DWORD_PTR)pDevice->winmm.hEventPlayback, (DWORD_PTR)pDevice, MA_CALLBACK_EVENT | MA_WAVE_ALLOWSYNC); + if (resultMM != MA_MMSYSERR_NOERROR) { + errorMsg = "[WinMM] Failed to open playback device.", errorCode = MA_FAILED_TO_OPEN_BACKEND_DEVICE; + goto on_error; + } + + pDescriptorPlayback->format = ma_format_from_WAVEFORMATEX(&wf); + pDescriptorPlayback->channels = wf.nChannels; + pDescriptorPlayback->sampleRate = wf.nSamplesPerSec; + ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pDescriptorPlayback->channelMap, ma_countof(pDescriptorPlayback->channelMap), pDescriptorPlayback->channels); + pDescriptorPlayback->periodCount = pDescriptorPlayback->periodCount; + pDescriptorPlayback->periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__winmm(pDescriptorPlayback, pDescriptorPlayback->sampleRate, pConfig->performanceProfile); + } + + /* + 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(MA_WAVEHDR)*pDescriptorCapture->periodCount + (pDescriptorCapture->periodSizeInFrames * pDescriptorCapture->periodCount * ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels)); + } + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + heapSize += sizeof(MA_WAVEHDR)*pDescriptorPlayback->periodCount + (pDescriptorPlayback->periodSizeInFrames * pDescriptorPlayback->periodCount * ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels)); + } + + pDevice->winmm._pHeapData = (ma_uint8*)ma_calloc(heapSize, &pDevice->pContext->allocationCallbacks); + 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) { + ma_uint32 iPeriod; + + if (pConfig->deviceType == ma_device_type_capture) { + pDevice->winmm.pWAVEHDRCapture = pDevice->winmm._pHeapData; + pDevice->winmm.pIntermediaryBufferCapture = pDevice->winmm._pHeapData + (sizeof(MA_WAVEHDR)*(pDescriptorCapture->periodCount)); + } else { + pDevice->winmm.pWAVEHDRCapture = pDevice->winmm._pHeapData; + pDevice->winmm.pIntermediaryBufferCapture = pDevice->winmm._pHeapData + (sizeof(MA_WAVEHDR)*(pDescriptorCapture->periodCount + pDescriptorPlayback->periodCount)); + } + + /* Prepare headers. */ + for (iPeriod = 0; iPeriod < pDescriptorCapture->periodCount; ++iPeriod) { + ma_uint32 periodSizeInBytes = ma_get_period_size_in_bytes(pDescriptorCapture->periodSizeInFrames, pDescriptorCapture->format, pDescriptorCapture->channels); + + ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].lpData = (char*)(pDevice->winmm.pIntermediaryBufferCapture + (periodSizeInBytes*iPeriod)); + ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwBufferLength = periodSizeInBytes; + ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwFlags = 0L; + ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwLoops = 0L; + ((MA_PFN_waveInPrepareHeader)pDevice->pContext->winmm.waveInPrepareHeader)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture, &((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod], sizeof(MA_WAVEHDR)); + + /* + The user data of the MA_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. + */ + ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwUser = 0; + } + } + + 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(MA_WAVEHDR)*pDescriptorPlayback->periodCount); + } else { + pDevice->winmm.pWAVEHDRPlayback = pDevice->winmm._pHeapData + (sizeof(MA_WAVEHDR)*(pDescriptorCapture->periodCount)); + pDevice->winmm.pIntermediaryBufferPlayback = pDevice->winmm._pHeapData + (sizeof(MA_WAVEHDR)*(pDescriptorCapture->periodCount + pDescriptorPlayback->periodCount)) + (pDescriptorCapture->periodSizeInFrames*pDescriptorCapture->periodCount*ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels)); + } + + /* Prepare headers. */ + for (iPeriod = 0; iPeriod < pDescriptorPlayback->periodCount; ++iPeriod) { + ma_uint32 periodSizeInBytes = ma_get_period_size_in_bytes(pDescriptorPlayback->periodSizeInFrames, pDescriptorPlayback->format, pDescriptorPlayback->channels); + + ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].lpData = (char*)(pDevice->winmm.pIntermediaryBufferPlayback + (periodSizeInBytes*iPeriod)); + ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwBufferLength = periodSizeInBytes; + ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwFlags = 0L; + ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwLoops = 0L; + ((MA_PFN_waveOutPrepareHeader)pDevice->pContext->winmm.waveOutPrepareHeader)((MA_HWAVEOUT)pDevice->winmm.hDevicePlayback, &((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod], sizeof(MA_WAVEHDR)); + + /* + The user data of the MA_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. + */ + ((MA_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) { + ma_uint32 iPeriod; + for (iPeriod = 0; iPeriod < pDescriptorCapture->periodCount; ++iPeriod) { + ((MA_PFN_waveInUnprepareHeader)pDevice->pContext->winmm.waveInUnprepareHeader)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture, &((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod], sizeof(MA_WAVEHDR)); + } + } + + ((MA_PFN_waveInClose)pDevice->pContext->winmm.waveInClose)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + if (pDevice->winmm.pWAVEHDRCapture != NULL) { + ma_uint32 iPeriod; + for (iPeriod = 0; iPeriod < pDescriptorPlayback->periodCount; ++iPeriod) { + ((MA_PFN_waveOutUnprepareHeader)pDevice->pContext->winmm.waveOutUnprepareHeader)((MA_HWAVEOUT)pDevice->winmm.hDevicePlayback, &((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod], sizeof(MA_WAVEHDR)); + } + } + + ((MA_PFN_waveOutClose)pDevice->pContext->winmm.waveOutClose)((MA_HWAVEOUT)pDevice->winmm.hDevicePlayback); + } + + ma_free(pDevice->winmm._pHeapData, &pDevice->pContext->allocationCallbacks); + + if (errorMsg != NULL && errorMsg[0] != '\0') { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "%s", errorMsg); + } + + return errorCode; +} + +static ma_result ma_device_start__winmm(ma_device* pDevice) +{ + MA_ASSERT(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + MA_MMRESULT resultMM; + MA_WAVEHDR* pWAVEHDR; + ma_uint32 iPeriod; + + pWAVEHDR = (MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture; + + /* 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 (iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) { + resultMM = ((MA_PFN_waveInAddBuffer)pDevice->pContext->winmm.waveInAddBuffer)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture, &((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod], sizeof(MA_WAVEHDR)); + if (resultMM != MA_MMSYSERR_NOERROR) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WinMM] Failed to attach input buffers to capture device in preparation for capture."); + return 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)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture); + if (resultMM != MA_MMSYSERR_NOERROR) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WinMM] Failed to start backend device."); + return ma_result_from_MMRESULT(resultMM); + } + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + /* Don't need to do anything for playback. It'll be started automatically in ma_device_start__winmm(). */ + } + + return MA_SUCCESS; +} + +static ma_result ma_device_stop__winmm(ma_device* pDevice) +{ + MA_MMRESULT resultMM; + + 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; + } + + resultMM = ((MA_PFN_waveInReset)pDevice->pContext->winmm.waveInReset)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture); + if (resultMM != MA_MMSYSERR_NOERROR) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[WinMM] WARNING: Failed to reset capture device."); + } + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + ma_uint32 iPeriod; + MA_WAVEHDR* pWAVEHDR; + + if (pDevice->winmm.hDevicePlayback == NULL) { + return MA_INVALID_ARGS; + } + + /* We need to drain the device. To do this we just loop over each header and if it's locked just wait for the event. */ + pWAVEHDR = (MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback; + for (iPeriod = 0; iPeriod < pDevice->playback.internalPeriods; iPeriod += 1) { + if (pWAVEHDR[iPeriod].dwUser == 1) { /* 1 = locked. */ + if (WaitForSingleObject((HANDLE)pDevice->winmm.hEventPlayback, INFINITE) != WAIT_OBJECT_0) { + break; /* An error occurred so just abandon ship and stop the device without draining. */ + } + + pWAVEHDR[iPeriod].dwUser = 0; + } + } + + resultMM = ((MA_PFN_waveOutReset)pDevice->pContext->winmm.waveOutReset)((MA_HWAVEOUT)pDevice->winmm.hDevicePlayback); + if (resultMM != MA_MMSYSERR_NOERROR) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[WinMM] WARNING: Failed to reset playback device."); + } + } + + return MA_SUCCESS; +} + +static ma_result ma_device_write__winmm(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten) +{ + ma_result result = MA_SUCCESS; + MA_MMRESULT resultMM; + ma_uint32 totalFramesWritten; + MA_WAVEHDR* pWAVEHDR; + + MA_ASSERT(pDevice != NULL); + MA_ASSERT(pPCMFrames != NULL); + + if (pFramesWritten != NULL) { + *pFramesWritten = 0; + } + + pWAVEHDR = (MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback; + + /* 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 &= ~MA_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)((MA_HWAVEOUT)pDevice->winmm.hDevicePlayback, &pWAVEHDR[pDevice->winmm.iNextHeaderPlayback], sizeof(MA_WAVEHDR)); + if (resultMM != MA_MMSYSERR_NOERROR) { + result = ma_result_from_MMRESULT(resultMM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WinMM] waveOutWrite() failed."); + break; + } + + /* 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 & MA_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 (ma_device_get_state(pDevice) != ma_device_state_started) { + break; + } + } + + if (pFramesWritten != NULL) { + *pFramesWritten = totalFramesWritten; + } + + return result; +} + +static ma_result ma_device_read__winmm(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead) +{ + ma_result result = MA_SUCCESS; + MA_MMRESULT resultMM; + ma_uint32 totalFramesRead; + MA_WAVEHDR* pWAVEHDR; + + MA_ASSERT(pDevice != NULL); + MA_ASSERT(pPCMFrames != NULL); + + if (pFramesRead != NULL) { + *pFramesRead = 0; + } + + pWAVEHDR = (MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture; + + /* 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 &= ~MA_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)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture, &((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[pDevice->winmm.iNextHeaderCapture], sizeof(MA_WAVEHDR)); + if (resultMM != MA_MMSYSERR_NOERROR) { + result = ma_result_from_MMRESULT(resultMM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WinMM] waveInAddBuffer() failed."); + 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 & MA_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 (ma_device_get_state(pDevice) != ma_device_state_started) { + break; + } + } + + if (pFramesRead != NULL) { + *pFramesRead = totalFramesRead; + } + + return result; +} + +static ma_result ma_context_uninit__winmm(ma_context* pContext) +{ + MA_ASSERT(pContext != NULL); + MA_ASSERT(pContext->backend == ma_backend_winmm); + + ma_dlclose(ma_context_get_log(pContext), pContext->winmm.hWinMM); + return MA_SUCCESS; +} + +static ma_result ma_context_init__winmm(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks) +{ + MA_ASSERT(pContext != NULL); + + (void)pConfig; + + pContext->winmm.hWinMM = ma_dlopen(ma_context_get_log(pContext), "winmm.dll"); + if (pContext->winmm.hWinMM == NULL) { + return MA_NO_BACKEND; + } + + pContext->winmm.waveOutGetNumDevs = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveOutGetNumDevs"); + pContext->winmm.waveOutGetDevCapsA = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveOutGetDevCapsA"); + pContext->winmm.waveOutOpen = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveOutOpen"); + pContext->winmm.waveOutClose = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveOutClose"); + pContext->winmm.waveOutPrepareHeader = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveOutPrepareHeader"); + pContext->winmm.waveOutUnprepareHeader = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveOutUnprepareHeader"); + pContext->winmm.waveOutWrite = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveOutWrite"); + pContext->winmm.waveOutReset = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveOutReset"); + pContext->winmm.waveInGetNumDevs = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveInGetNumDevs"); + pContext->winmm.waveInGetDevCapsA = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveInGetDevCapsA"); + pContext->winmm.waveInOpen = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveInOpen"); + pContext->winmm.waveInClose = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveInClose"); + pContext->winmm.waveInPrepareHeader = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveInPrepareHeader"); + pContext->winmm.waveInUnprepareHeader = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveInUnprepareHeader"); + pContext->winmm.waveInAddBuffer = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveInAddBuffer"); + pContext->winmm.waveInStart = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveInStart"); + pContext->winmm.waveInReset = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveInReset"); + + pCallbacks->onContextInit = ma_context_init__winmm; + pCallbacks->onContextUninit = ma_context_uninit__winmm; + pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__winmm; + pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__winmm; + pCallbacks->onDeviceInit = ma_device_init__winmm; + pCallbacks->onDeviceUninit = ma_device_uninit__winmm; + pCallbacks->onDeviceStart = ma_device_start__winmm; + pCallbacks->onDeviceStop = ma_device_stop__winmm; + pCallbacks->onDeviceRead = ma_device_read__winmm; + pCallbacks->onDeviceWrite = ma_device_write__winmm; + pCallbacks->onDeviceDataLoop = NULL; /* This is a blocking read-write API, so this can be NULL since miniaudio will manage the audio thread for us. */ + + return MA_SUCCESS; +} +#endif + + + + +/****************************************************************************** + +ALSA Backend + +******************************************************************************/ +#ifdef MA_HAS_ALSA + +#include /* poll(), struct pollfd */ +#include /* eventfd() */ + +#ifdef MA_NO_RUNTIME_LINKING + +/* asoundlib.h marks some functions with "inline" which isn't always supported. Need to emulate it. */ +#if !defined(__cplusplus) + #if defined(__STRICT_ANSI__) + #if !defined(inline) + #define inline __inline__ __attribute__((always_inline)) + #define MA_INLINE_DEFINED + #endif + #endif +#endif +#include +#if defined(MA_INLINE_DEFINED) + #undef inline + #undef MA_INLINE_DEFINED +#endif + +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; +typedef snd_pcm_state_t ma_snd_pcm_state_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 int ma_snd_pcm_state_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[1]; +} 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_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int val); +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_channels_minmax_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int *minimum, unsigned int *maximum); +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_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_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_test_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_test_channels_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int val); +typedef int (* ma_snd_pcm_hw_params_test_rate_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_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) (const 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 ma_snd_pcm_state_t (* 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_pcm_reset_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_nonblock_proc) (ma_snd_pcm_t *pcm, int nonblock); +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) (void); +typedef const char* (* ma_snd_pcm_info_get_name_proc) (const ma_snd_pcm_info_t* info); +typedef int (* ma_snd_pcm_poll_descriptors_proc) (ma_snd_pcm_t *pcm, struct pollfd *pfds, unsigned int space); +typedef int (* ma_snd_pcm_poll_descriptors_count_proc) (ma_snd_pcm_t *pcm); +typedef int (* ma_snd_pcm_poll_descriptors_revents_proc) (ma_snd_pcm_t *pcm, struct pollfd *pfds, unsigned int nfds, unsigned short *revents); +typedef int (* ma_snd_config_update_free_global_proc) (void); + +/* This array specifies each of the common devices that can be used for both playback and capture. */ +static const char* g_maCommonDeviceNamesALSA[] = { + "default", + "null", + "pulse", + "jack" +}; + +/* This array allows us to blacklist specific playback devices. */ +static const char* g_maBlacklistedPlaybackDeviceNamesALSA[] = { + "" +}; + +/* This array allows us to blacklist specific capture devices. */ +static const char* g_maBlacklistedCaptureDeviceNamesALSA[] = { + "" +}; + + +static 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]; +} + +static ma_format ma_format_from_alsa(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; + } +} + +static 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; +} + +static ma_bool32 ma_is_common_device_name__alsa(const char* name) +{ + size_t iName; + for (iName = 0; iName < ma_countof(g_maCommonDeviceNamesALSA); ++iName) { + if (ma_strcmp(name, g_maCommonDeviceNamesALSA[iName]) == 0) { + return MA_TRUE; + } + } + + return MA_FALSE; +} + + +static ma_bool32 ma_is_playback_device_blacklisted__alsa(const char* name) +{ + size_t iName; + for (iName = 0; iName < ma_countof(g_maBlacklistedPlaybackDeviceNamesALSA); ++iName) { + if (ma_strcmp(name, g_maBlacklistedPlaybackDeviceNamesALSA[iName]) == 0) { + return MA_TRUE; + } + } + + return MA_FALSE; +} + +static ma_bool32 ma_is_capture_device_blacklisted__alsa(const char* name) +{ + size_t iName; + for (iName = 0; iName < ma_countof(g_maBlacklistedCaptureDeviceNamesALSA); ++iName) { + if (ma_strcmp(name, g_maBlacklistedCaptureDeviceNamesALSA[iName]) == 0) { + return MA_TRUE; + } + } + + return MA_FALSE; +} + +static 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); + } +} + + +static 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; +} + +static 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. */ + + int commaPos; + const char* dev; + int i; + + if (hwid == NULL) { + return MA_FALSE; + } + + if (hwid[0] != 'h' || hwid[1] != 'w' || hwid[2] != ':') { + return MA_FALSE; + } + + hwid += 3; + + 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 (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. */ + i = 0; + while (dev[i] != '\0') { + if (dev[i] < '0' || dev[i] > '9') { + return MA_FALSE; + } + i += 1; + } + + return MA_TRUE; +} + +static 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" */ + + 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. */ + } + + *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); + } + + src = ma_find_char(src, ':', &colonPos); + if (src == NULL) { + return -1; /* Couldn't find a colon */ + } + + 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=" */ + } + + 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. */ + } + + + /* 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; +} + +static 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 (i = 0; i < count; ++i) { + if (ma_strcmp(pUniqueIDs[i].alsa, pHWID) == 0) { + return MA_TRUE; + } + } + + return MA_FALSE; +} + + +static ma_result ma_context_open_pcm__alsa(ma_context* pContext, ma_share_mode shareMode, ma_device_type deviceType, const ma_device_id* pDeviceID, int openMode, ma_snd_pcm_t** ppPCM) +{ + ma_snd_pcm_t* pPCM; + ma_snd_pcm_stream_t stream; + + MA_ASSERT(pContext != NULL); + MA_ASSERT(ppPCM != NULL); + + *ppPCM = NULL; + pPCM = NULL; + + stream = (deviceType == ma_device_type_playback) ? MA_SND_PCM_STREAM_PLAYBACK : MA_SND_PCM_STREAM_CAPTURE; + + if (pDeviceID == NULL) { + 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, + 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"; + } + + 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; + break; + } + } + } + + if (!isDeviceOpen) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_open() failed when trying to open an appropriate default device."); + return 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; + int resultALSA = -ENODEV; + + if (deviceID.alsa[0] != ':') { + /* The ID is not in ":0,0" format. Use the ID exactly as-is. */ + resultALSA = ((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, deviceID.alsa, stream, openMode); + } else { + 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 "". */ + } + + 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) { + resultALSA = ((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, hwid, stream, openMode); + } + } + + /* 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 (resultALSA != 0) { + ma_strcpy_s(hwid, sizeof(hwid), "hw"); + if (ma_strcat_s(hwid, sizeof(hwid), deviceID.alsa) == 0) { + resultALSA = ((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, hwid, stream, openMode); + } + } + } + + if (resultALSA < 0) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_open() failed."); + return ma_result_from_errno(-resultALSA); + } + } + + *ppPCM = pPCM; + return MA_SUCCESS; +} + + +static ma_result ma_context_enumerate_devices__alsa(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) +{ + int resultALSA; + 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_mutex_lock(&pContext->alsa.internalDeviceEnumLock); + + resultALSA = ((ma_snd_device_name_hint_proc)pContext->alsa.snd_device_name_hint)(-1, "pcm", (void***)&ppDeviceHints); + if (resultALSA < 0) { + ma_mutex_unlock(&pContext->alsa.internalDeviceEnumLock); + return ma_result_from_errno(-resultALSA); + } + + 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; + } + if ((IOID != NULL && ma_strcmp(IOID, "Input" ) == 0)) { + deviceType = ma_device_type_capture; + } + + if (NAME != NULL) { + if (pContext->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. */ + size_t newCapacity = sizeof(*pUniqueIDs) * (uniqueIDCount + 1); + ma_device_id* pNewUniqueIDs = (ma_device_id*)ma_realloc(pUniqueIDs, newCapacity, &pContext->allocationCallbacks); + 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_ZERO_OBJECT(&deviceInfo); + ma_strncpy_s(deviceInfo.id.alsa, sizeof(deviceInfo.id.alsa), hwid, (size_t)-1); + + /* + There's no good way to determine whether or not a device is the default on Linux. We're just going to do something simple and + just use the name of "default" as the indicator. + */ + if (ma_strcmp(deviceInfo.id.alsa, "default") == 0) { + deviceInfo.isDefault = MA_TRUE; + } + + + /* + 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->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 and where the IOID hint is NULL, which + means both Input and Output. + */ + if (cbResult) { + if (ma_is_common_device_name__alsa(NAME) || IOID == NULL) { + 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, &pContext->allocationCallbacks); + ((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; + +static 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); + + (void)pContext; + + 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 && (pData->pDeviceID != NULL && ma_strcmp(pData->pDeviceID->alsa, pDeviceInfo->id.alsa) == 0)) { + 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; +} + +static void ma_context_test_rate_and_add_native_data_format__alsa(ma_context* pContext, ma_snd_pcm_t* pPCM, ma_snd_pcm_hw_params_t* pHWParams, ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 flags, ma_device_info* pDeviceInfo) +{ + MA_ASSERT(pPCM != NULL); + MA_ASSERT(pHWParams != NULL); + MA_ASSERT(pDeviceInfo != NULL); + + if (pDeviceInfo->nativeDataFormatCount < ma_countof(pDeviceInfo->nativeDataFormats) && ((ma_snd_pcm_hw_params_test_rate_proc)pContext->alsa.snd_pcm_hw_params_test_rate)(pPCM, pHWParams, sampleRate, 0) == 0) { + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = format; + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels; + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = sampleRate; + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = flags; + pDeviceInfo->nativeDataFormatCount += 1; + } +} + +static void ma_context_iterate_rates_and_add_native_data_format__alsa(ma_context* pContext, ma_snd_pcm_t* pPCM, ma_snd_pcm_hw_params_t* pHWParams, ma_format format, ma_uint32 channels, ma_uint32 flags, ma_device_info* pDeviceInfo) +{ + ma_uint32 iSampleRate; + unsigned int minSampleRate; + unsigned int maxSampleRate; + int sampleRateDir; /* Not used. Just passed into snd_pcm_hw_params_get_rate_min/max(). */ + + /* There could be a range. */ + ((ma_snd_pcm_hw_params_get_rate_min_proc)pContext->alsa.snd_pcm_hw_params_get_rate_min)(pHWParams, &minSampleRate, &sampleRateDir); + ((ma_snd_pcm_hw_params_get_rate_max_proc)pContext->alsa.snd_pcm_hw_params_get_rate_max)(pHWParams, &maxSampleRate, &sampleRateDir); + + /* Make sure our sample rates are clamped to sane values. Stupid devices like "pulse" will reports rates like "1" which is ridiculus. */ + minSampleRate = ma_clamp(minSampleRate, (unsigned int)ma_standard_sample_rate_min, (unsigned int)ma_standard_sample_rate_max); + maxSampleRate = ma_clamp(maxSampleRate, (unsigned int)ma_standard_sample_rate_min, (unsigned int)ma_standard_sample_rate_max); + + for (iSampleRate = 0; iSampleRate < ma_countof(g_maStandardSampleRatePriorities); iSampleRate += 1) { + ma_uint32 standardSampleRate = g_maStandardSampleRatePriorities[iSampleRate]; + + if (standardSampleRate >= minSampleRate && standardSampleRate <= maxSampleRate) { + ma_context_test_rate_and_add_native_data_format__alsa(pContext, pPCM, pHWParams, format, channels, standardSampleRate, flags, pDeviceInfo); + } + } + + /* Now make sure our min and max rates are included just in case they aren't in the range of our standard rates. */ + if (!ma_is_standard_sample_rate(minSampleRate)) { + ma_context_test_rate_and_add_native_data_format__alsa(pContext, pPCM, pHWParams, format, channels, minSampleRate, flags, pDeviceInfo); + } + + if (!ma_is_standard_sample_rate(maxSampleRate) && maxSampleRate != minSampleRate) { + ma_context_test_rate_and_add_native_data_format__alsa(pContext, pPCM, pHWParams, format, channels, maxSampleRate, flags, pDeviceInfo); + } +} + +static ma_result ma_context_get_device_info__alsa(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo) +{ + ma_context_get_device_info_enum_callback_data__alsa data; + ma_result result; + int resultALSA; + ma_snd_pcm_t* pPCM; + ma_snd_pcm_hw_params_t* pHWParams; + ma_uint32 iFormat; + ma_uint32 iChannel; + + MA_ASSERT(pContext != NULL); + + /* We just enumerate to find basic information about the device. */ + data.deviceType = deviceType; + data.pDeviceID = pDeviceID; + data.pDeviceInfo = pDeviceInfo; + data.foundDevice = MA_FALSE; + 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; + } + + if (ma_strcmp(pDeviceInfo->id.alsa, "default") == 0) { + pDeviceInfo->isDefault = MA_TRUE; + } + + /* For detailed info we need to open the device. */ + result = ma_context_open_pcm__alsa(pContext, ma_share_mode_shared, deviceType, pDeviceID, 0, &pPCM); + if (result != MA_SUCCESS) { + return result; + } + + /* We need to initialize a HW parameters object in order to know what formats are supported. */ + pHWParams = (ma_snd_pcm_hw_params_t*)ma_calloc(((ma_snd_pcm_hw_params_sizeof_proc)pContext->alsa.snd_pcm_hw_params_sizeof)(), &pContext->allocationCallbacks); + if (pHWParams == NULL) { + ((ma_snd_pcm_close_proc)pContext->alsa.snd_pcm_close)(pPCM); + return MA_OUT_OF_MEMORY; + } + + resultALSA = ((ma_snd_pcm_hw_params_any_proc)pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams); + if (resultALSA < 0) { + ma_free(pHWParams, &pContext->allocationCallbacks); + ((ma_snd_pcm_close_proc)pContext->alsa.snd_pcm_close)(pPCM); + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize hardware parameters. snd_pcm_hw_params_any() failed."); + return ma_result_from_errno(-resultALSA); + } + + /* + Some ALSA devices can support many permutations of formats, channels and rates. We only support + a fixed number of permutations which means we need to employ some strategies to ensure the best + combinations are returned. An example is the "pulse" device which can do it's own data conversion + in software and as a result can support any combination of format, channels and rate. + + We want to ensure the the first data formats are the best. We have a list of favored sample + formats and sample rates, so these will be the basis of our iteration. + */ + + /* Formats. We just iterate over our standard formats and test them, making sure we reset the configuration space each iteration. */ + for (iFormat = 0; iFormat < ma_countof(g_maFormatPriorities); iFormat += 1) { + ma_format format = g_maFormatPriorities[iFormat]; + + /* + For each format we need to make sure we reset the configuration space so we don't return + channel counts and rates that aren't compatible with a format. + */ + ((ma_snd_pcm_hw_params_any_proc)pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams); + + /* Test the format first. If this fails it means the format is not supported and we can skip it. */ + if (((ma_snd_pcm_hw_params_test_format_proc)pContext->alsa.snd_pcm_hw_params_test_format)(pPCM, pHWParams, ma_convert_ma_format_to_alsa_format(format)) == 0) { + /* The format is supported. */ + unsigned int minChannels; + unsigned int maxChannels; + + /* + The configuration space needs to be restricted to this format so we can get an accurate + picture of which sample rates and channel counts are support with this format. + */ + ((ma_snd_pcm_hw_params_set_format_proc)pContext->alsa.snd_pcm_hw_params_set_format)(pPCM, pHWParams, ma_convert_ma_format_to_alsa_format(format)); + + /* Now we need to check for supported channels. */ + ((ma_snd_pcm_hw_params_get_channels_min_proc)pContext->alsa.snd_pcm_hw_params_get_channels_min)(pHWParams, &minChannels); + ((ma_snd_pcm_hw_params_get_channels_max_proc)pContext->alsa.snd_pcm_hw_params_get_channels_max)(pHWParams, &maxChannels); + + if (minChannels > MA_MAX_CHANNELS) { + continue; /* Too many channels. */ + } + if (maxChannels < MA_MIN_CHANNELS) { + continue; /* Not enough channels. */ + } + + /* + Make sure the channel count is clamped. This is mainly intended for the max channels + because some devices can report an unbound maximum. + */ + minChannels = ma_clamp(minChannels, MA_MIN_CHANNELS, MA_MAX_CHANNELS); + maxChannels = ma_clamp(maxChannels, MA_MIN_CHANNELS, MA_MAX_CHANNELS); + + if (minChannels == MA_MIN_CHANNELS && maxChannels == MA_MAX_CHANNELS) { + /* The device supports all channels. Don't iterate over every single one. Instead just set the channels to 0 which means all channels are supported. */ + ma_context_iterate_rates_and_add_native_data_format__alsa(pContext, pPCM, pHWParams, format, 0, 0, pDeviceInfo); /* Intentionally setting the channel count to 0 as that means all channels are supported. */ + } else { + /* The device only supports a specific set of channels. We need to iterate over all of them. */ + for (iChannel = minChannels; iChannel <= maxChannels; iChannel += 1) { + /* Test the channel before applying it to the configuration space. */ + unsigned int channels = iChannel; + + /* Make sure our channel range is reset before testing again or else we'll always fail the test. */ + ((ma_snd_pcm_hw_params_any_proc)pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams); + ((ma_snd_pcm_hw_params_set_format_proc)pContext->alsa.snd_pcm_hw_params_set_format)(pPCM, pHWParams, ma_convert_ma_format_to_alsa_format(format)); + + if (((ma_snd_pcm_hw_params_test_channels_proc)pContext->alsa.snd_pcm_hw_params_test_channels)(pPCM, pHWParams, channels) == 0) { + /* The channel count is supported. */ + + /* The configuration space now needs to be restricted to the channel count before extracting the sample rate. */ + ((ma_snd_pcm_hw_params_set_channels_proc)pContext->alsa.snd_pcm_hw_params_set_channels)(pPCM, pHWParams, channels); + + /* Only after the configuration space has been restricted to the specific channel count should we iterate over our sample rates. */ + ma_context_iterate_rates_and_add_native_data_format__alsa(pContext, pPCM, pHWParams, format, channels, 0, pDeviceInfo); + } else { + /* The channel count is not supported. Skip. */ + } + } + } + } else { + /* The format is not supported. Skip. */ + } + } + + ma_free(pHWParams, &pContext->allocationCallbacks); + + ((ma_snd_pcm_close_proc)pContext->alsa.snd_pcm_close)(pPCM); + return MA_SUCCESS; +} + +static ma_result 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); + close(pDevice->alsa.wakeupfdCapture); + ma_free(pDevice->alsa.pPollDescriptorsCapture, &pDevice->pContext->allocationCallbacks); + } + + 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); + close(pDevice->alsa.wakeupfdPlayback); + ma_free(pDevice->alsa.pPollDescriptorsPlayback, &pDevice->pContext->allocationCallbacks); + } + + return MA_SUCCESS; +} + +static ma_result ma_device_init_by_type__alsa(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptor, ma_device_type deviceType) +{ + ma_result result; + int resultALSA; + ma_snd_pcm_t* pPCM; + ma_bool32 isUsingMMap; + ma_snd_pcm_format_t formatALSA; + ma_format internalFormat; + ma_uint32 internalChannels; + ma_uint32 internalSampleRate; + ma_channel internalChannelMap[MA_MAX_CHANNELS]; + ma_uint32 internalPeriodSizeInFrames; + ma_uint32 internalPeriods; + int openMode; + ma_snd_pcm_hw_params_t* pHWParams; + ma_snd_pcm_sw_params_t* pSWParams; + ma_snd_pcm_uframes_t bufferBoundary; + int pollDescriptorCount; + struct pollfd* pPollDescriptors; + int wakeupfd; + + 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(pDescriptor->format); + + openMode = 0; + if (pConfig->alsa.noAutoResample) { + openMode |= MA_SND_PCM_NO_AUTO_RESAMPLE; + } + if (pConfig->alsa.noAutoChannels) { + openMode |= MA_SND_PCM_NO_AUTO_CHANNELS; + } + if (pConfig->alsa.noAutoFormat) { + openMode |= MA_SND_PCM_NO_AUTO_FORMAT; + } + + result = ma_context_open_pcm__alsa(pDevice->pContext, pDescriptor->shareMode, deviceType, pDescriptor->pDeviceID, openMode, &pPCM); + if (result != MA_SUCCESS) { + return result; + } + + + /* Hardware parameters. */ + pHWParams = (ma_snd_pcm_hw_params_t*)ma_calloc(((ma_snd_pcm_hw_params_sizeof_proc)pDevice->pContext->alsa.snd_pcm_hw_params_sizeof)(), &pDevice->pContext->allocationCallbacks); + if (pHWParams == NULL) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to allocate memory for hardware parameters."); + return MA_OUT_OF_MEMORY; + } + + resultALSA = ((ma_snd_pcm_hw_params_any_proc)pDevice->pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams); + if (resultALSA < 0) { + ma_free(pHWParams, &pDevice->pContext->allocationCallbacks); + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize hardware parameters. snd_pcm_hw_params_any() failed."); + return ma_result_from_errno(-resultALSA); + } + + /* 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) { + if (((ma_snd_pcm_hw_params_set_access_proc)pDevice->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) { + resultALSA = ((ma_snd_pcm_hw_params_set_access_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_access)(pPCM, pHWParams, MA_SND_PCM_ACCESS_RW_INTERLEAVED); + if (resultALSA < 0) { + ma_free(pHWParams, &pDevice->pContext->allocationCallbacks); + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(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."); + return ma_result_from_errno(-resultALSA); + } + } + + /* + 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. */ + { + /* + 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 (formatALSA == MA_SND_PCM_FORMAT_UNKNOWN || ((ma_snd_pcm_hw_params_test_format_proc)pDevice->pContext->alsa.snd_pcm_hw_params_test_format)(pPCM, pHWParams, formatALSA) != 0) { + /* We're either requesting the native format or the specified format is not supported. */ + size_t iFormat; + + formatALSA = MA_SND_PCM_FORMAT_UNKNOWN; + for (iFormat = 0; iFormat < ma_countof(g_maFormatPriorities); ++iFormat) { + if (((ma_snd_pcm_hw_params_test_format_proc)pDevice->pContext->alsa.snd_pcm_hw_params_test_format)(pPCM, pHWParams, ma_convert_ma_format_to_alsa_format(g_maFormatPriorities[iFormat])) == 0) { + formatALSA = ma_convert_ma_format_to_alsa_format(g_maFormatPriorities[iFormat]); + break; + } + } + + if (formatALSA == MA_SND_PCM_FORMAT_UNKNOWN) { + ma_free(pHWParams, &pDevice->pContext->allocationCallbacks); + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Format not supported. The device does not support any miniaudio formats."); + return MA_FORMAT_NOT_SUPPORTED; + } + } + + resultALSA = ((ma_snd_pcm_hw_params_set_format_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_format)(pPCM, pHWParams, formatALSA); + if (resultALSA < 0) { + ma_free(pHWParams, &pDevice->pContext->allocationCallbacks); + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Format not supported. snd_pcm_hw_params_set_format() failed."); + return ma_result_from_errno(-resultALSA); + } + + internalFormat = ma_format_from_alsa(formatALSA); + if (internalFormat == ma_format_unknown) { + ma_free(pHWParams, &pDevice->pContext->allocationCallbacks); + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] The chosen format is not supported by miniaudio."); + return MA_FORMAT_NOT_SUPPORTED; + } + } + + /* Channels. */ + { + unsigned int channels = pDescriptor->channels; + if (channels == 0) { + channels = MA_DEFAULT_CHANNELS; + } + + resultALSA = ((ma_snd_pcm_hw_params_set_channels_near_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_channels_near)(pPCM, pHWParams, &channels); + if (resultALSA < 0) { + ma_free(pHWParams, &pDevice->pContext->allocationCallbacks); + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set channel count. snd_pcm_hw_params_set_channels_near() failed."); + return ma_result_from_errno(-resultALSA); + } + + 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)pDevice->pContext->alsa.snd_pcm_hw_params_set_rate_resample)(pPCM, pHWParams, 0); + + sampleRate = pDescriptor->sampleRate; + if (sampleRate == 0) { + sampleRate = MA_DEFAULT_SAMPLE_RATE; + } + + resultALSA = ((ma_snd_pcm_hw_params_set_rate_near_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_rate_near)(pPCM, pHWParams, &sampleRate, 0); + if (resultALSA < 0) { + ma_free(pHWParams, &pDevice->pContext->allocationCallbacks); + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Sample rate not supported. snd_pcm_hw_params_set_rate_near() failed."); + return ma_result_from_errno(-resultALSA); + } + + internalSampleRate = (ma_uint32)sampleRate; + } + + /* Periods. */ + { + ma_uint32 periods = pDescriptor->periodCount; + + resultALSA = ((ma_snd_pcm_hw_params_set_periods_near_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_periods_near)(pPCM, pHWParams, &periods, NULL); + if (resultALSA < 0) { + ma_free(pHWParams, &pDevice->pContext->allocationCallbacks); + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set period count. snd_pcm_hw_params_set_periods_near() failed."); + return ma_result_from_errno(-resultALSA); + } + + internalPeriods = periods; + } + + /* Buffer Size */ + { + ma_snd_pcm_uframes_t actualBufferSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, internalSampleRate, pConfig->performanceProfile) * internalPeriods; + + resultALSA = ((ma_snd_pcm_hw_params_set_buffer_size_near_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_buffer_size_near)(pPCM, pHWParams, &actualBufferSizeInFrames); + if (resultALSA < 0) { + ma_free(pHWParams, &pDevice->pContext->allocationCallbacks); + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set buffer size for device. snd_pcm_hw_params_set_buffer_size() failed."); + return ma_result_from_errno(-resultALSA); + } + + internalPeriodSizeInFrames = actualBufferSizeInFrames / internalPeriods; + } + + /* Apply hardware parameters. */ + resultALSA = ((ma_snd_pcm_hw_params_proc)pDevice->pContext->alsa.snd_pcm_hw_params)(pPCM, pHWParams); + if (resultALSA < 0) { + ma_free(pHWParams, &pDevice->pContext->allocationCallbacks); + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set hardware parameters. snd_pcm_hw_params() failed."); + return ma_result_from_errno(-resultALSA); + } + + ma_free(pHWParams, &pDevice->pContext->allocationCallbacks); + pHWParams = NULL; + + + /* Software parameters. */ + pSWParams = (ma_snd_pcm_sw_params_t*)ma_calloc(((ma_snd_pcm_sw_params_sizeof_proc)pDevice->pContext->alsa.snd_pcm_sw_params_sizeof)(), &pDevice->pContext->allocationCallbacks); + if (pSWParams == NULL) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to allocate memory for software parameters."); + return MA_OUT_OF_MEMORY; + } + + resultALSA = ((ma_snd_pcm_sw_params_current_proc)pDevice->pContext->alsa.snd_pcm_sw_params_current)(pPCM, pSWParams); + if (resultALSA < 0) { + ma_free(pSWParams, &pDevice->pContext->allocationCallbacks); + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize software parameters. snd_pcm_sw_params_current() failed."); + return ma_result_from_errno(-resultALSA); + } + + resultALSA = ((ma_snd_pcm_sw_params_set_avail_min_proc)pDevice->pContext->alsa.snd_pcm_sw_params_set_avail_min)(pPCM, pSWParams, ma_prev_power_of_2(internalPeriodSizeInFrames)); + if (resultALSA < 0) { + ma_free(pSWParams, &pDevice->pContext->allocationCallbacks); + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_sw_params_set_avail_min() failed."); + return ma_result_from_errno(-resultALSA); + } + + resultALSA = ((ma_snd_pcm_sw_params_get_boundary_proc)pDevice->pContext->alsa.snd_pcm_sw_params_get_boundary)(pSWParams, &bufferBoundary); + if (resultALSA < 0) { + bufferBoundary = internalPeriodSizeInFrames * internalPeriods; + } + + 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. + */ + resultALSA = ((ma_snd_pcm_sw_params_set_start_threshold_proc)pDevice->pContext->alsa.snd_pcm_sw_params_set_start_threshold)(pPCM, pSWParams, internalPeriodSizeInFrames*2); + if (resultALSA < 0) { + ma_free(pSWParams, &pDevice->pContext->allocationCallbacks); + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set start threshold for playback device. snd_pcm_sw_params_set_start_threshold() failed."); + return ma_result_from_errno(-resultALSA); + } + + resultALSA = ((ma_snd_pcm_sw_params_set_stop_threshold_proc)pDevice->pContext->alsa.snd_pcm_sw_params_set_stop_threshold)(pPCM, pSWParams, bufferBoundary); + if (resultALSA < 0) { /* Set to boundary to loop instead of stop in the event of an xrun. */ + ma_free(pSWParams, &pDevice->pContext->allocationCallbacks); + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set stop threshold for playback device. snd_pcm_sw_params_set_stop_threshold() failed."); + return ma_result_from_errno(-resultALSA); + } + } + + resultALSA = ((ma_snd_pcm_sw_params_proc)pDevice->pContext->alsa.snd_pcm_sw_params)(pPCM, pSWParams); + if (resultALSA < 0) { + ma_free(pSWParams, &pDevice->pContext->allocationCallbacks); + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set software parameters. snd_pcm_sw_params() failed."); + return ma_result_from_errno(-resultALSA); + } + + ma_free(pSWParams, &pDevice->pContext->allocationCallbacks); + 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. */ + { + ma_snd_pcm_chmap_t* pChmap = NULL; + if (pDevice->pContext->alsa.snd_pcm_get_chmap != NULL) { + pChmap = ((ma_snd_pcm_get_chmap_proc)pDevice->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 (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. + */ + ma_bool32 isValid = MA_TRUE; + + /* Fill with defaults. */ + ma_channel_map_init_standard(ma_standard_channel_map_alsa, internalChannelMap, ma_countof(internalChannelMap), internalChannels); + + /* Overwrite first pChmap->channels channels. */ + for (iChannel = 0; iChannel < pChmap->channels; ++iChannel) { + internalChannelMap[iChannel] = ma_convert_alsa_channel_position_to_ma_channel(pChmap->pos[iChannel]); + } + + /* Validate. */ + 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; + } + } + } + + /* If our channel map is invalid, fall back to defaults. */ + if (!isValid) { + ma_channel_map_init_standard(ma_standard_channel_map_alsa, internalChannelMap, ma_countof(internalChannelMap), internalChannels); + } + } + + free(pChmap); + pChmap = NULL; + } else { + /* Could not retrieve the channel map. Fall back to a hard-coded assumption. */ + ma_channel_map_init_standard(ma_standard_channel_map_alsa, internalChannelMap, ma_countof(internalChannelMap), internalChannels); + } + } + + + /* + We need to retrieve the poll descriptors so we can use poll() to wait for data to become + available for reading or writing. There's no well defined maximum for this so we're just going + to allocate this on the heap. + */ + pollDescriptorCount = ((ma_snd_pcm_poll_descriptors_count_proc)pDevice->pContext->alsa.snd_pcm_poll_descriptors_count)(pPCM); + if (pollDescriptorCount <= 0) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to retrieve poll descriptors count."); + return MA_ERROR; + } + + pPollDescriptors = (struct pollfd*)ma_malloc(sizeof(*pPollDescriptors) * (pollDescriptorCount + 1), &pDevice->pContext->allocationCallbacks); /* +1 because we want room for the wakeup descriptor. */ + if (pPollDescriptors == NULL) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to allocate memory for poll descriptors."); + return MA_OUT_OF_MEMORY; + } + + /* + We need an eventfd to wakeup from poll() and avoid a deadlock in situations where the driver + never returns from writei() and readi(). This has been observed with the "pulse" device. + */ + wakeupfd = eventfd(0, 0); + if (wakeupfd < 0) { + ma_free(pPollDescriptors, &pDevice->pContext->allocationCallbacks); + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to create eventfd for poll wakeup."); + return ma_result_from_errno(errno); + } + + /* We'll place the wakeup fd at the start of the buffer. */ + pPollDescriptors[0].fd = wakeupfd; + pPollDescriptors[0].events = POLLIN; /* We only care about waiting to read from the wakeup file descriptor. */ + pPollDescriptors[0].revents = 0; + + /* We can now extract the PCM poll descriptors which we place after the wakeup descriptor. */ + pollDescriptorCount = ((ma_snd_pcm_poll_descriptors_proc)pDevice->pContext->alsa.snd_pcm_poll_descriptors)(pPCM, pPollDescriptors + 1, pollDescriptorCount); /* +1 because we want to place these descriptors after the wakeup descriptor. */ + if (pollDescriptorCount <= 0) { + close(wakeupfd); + ma_free(pPollDescriptors, &pDevice->pContext->allocationCallbacks); + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to retrieve poll descriptors."); + return MA_ERROR; + } + + if (deviceType == ma_device_type_capture) { + pDevice->alsa.pollDescriptorCountCapture = pollDescriptorCount; + pDevice->alsa.pPollDescriptorsCapture = pPollDescriptors; + pDevice->alsa.wakeupfdCapture = wakeupfd; + } else { + pDevice->alsa.pollDescriptorCountPlayback = pollDescriptorCount; + pDevice->alsa.pPollDescriptorsPlayback = pPollDescriptors; + pDevice->alsa.wakeupfdPlayback = wakeupfd; + } + + + /* We're done. Prepare the device. */ + resultALSA = ((ma_snd_pcm_prepare_proc)pDevice->pContext->alsa.snd_pcm_prepare)(pPCM); + if (resultALSA < 0) { + close(wakeupfd); + ma_free(pPollDescriptors, &pDevice->pContext->allocationCallbacks); + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to prepare device."); + return ma_result_from_errno(-resultALSA); + } + + + if (deviceType == ma_device_type_capture) { + pDevice->alsa.pPCMCapture = (ma_ptr)pPCM; + pDevice->alsa.isUsingMMapCapture = isUsingMMap; + } else { + pDevice->alsa.pPCMPlayback = (ma_ptr)pPCM; + pDevice->alsa.isUsingMMapPlayback = isUsingMMap; + } + + pDescriptor->format = internalFormat; + pDescriptor->channels = internalChannels; + pDescriptor->sampleRate = internalSampleRate; + ma_channel_map_copy(pDescriptor->channelMap, internalChannelMap, ma_min(internalChannels, MA_MAX_CHANNELS)); + pDescriptor->periodSizeInFrames = internalPeriodSizeInFrames; + pDescriptor->periodCount = internalPeriods; + + return MA_SUCCESS; +} + +static ma_result ma_device_init__alsa(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture) +{ + MA_ASSERT(pDevice != NULL); + + MA_ZERO_OBJECT(&pDevice->alsa); + + if (pConfig->deviceType == ma_device_type_loopback) { + return MA_DEVICE_TYPE_NOT_SUPPORTED; + } + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + ma_result result = ma_device_init_by_type__alsa(pDevice, pConfig, pDescriptorCapture, ma_device_type_capture); + 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(pDevice, pConfig, pDescriptorPlayback, ma_device_type_playback); + if (result != MA_SUCCESS) { + return result; + } + } + + return MA_SUCCESS; +} + +static ma_result ma_device_start__alsa(ma_device* pDevice) +{ + int resultALSA; + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + resultALSA = ((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture); + if (resultALSA < 0) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to start capture device."); + return ma_result_from_errno(-resultALSA); + } + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + /* Don't need to do anything for playback because it'll be started automatically when enough data has been written. */ + } + + return MA_SUCCESS; +} + +static ma_result ma_device_stop__alsa(ma_device* pDevice) +{ + /* + The stop callback will get called on the worker thread after read/write__alsa() has returned. At this point there is + a small chance that our wakeupfd has not been cleared. We'll clear that out now if applicable. + */ + int resultPoll; + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Dropping capture device...\n"); + ((ma_snd_pcm_drop_proc)pDevice->pContext->alsa.snd_pcm_drop)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Dropping capture device successful.\n"); + + /* We need to prepare the device again, otherwise we won't be able to restart the device. */ + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing capture device...\n"); + if (((ma_snd_pcm_prepare_proc)pDevice->pContext->alsa.snd_pcm_prepare)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture) < 0) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing capture device failed.\n"); + } else { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing capture device successful.\n"); + } + + /* Clear the wakeupfd. */ + resultPoll = poll((struct pollfd*)pDevice->alsa.pPollDescriptorsCapture, 1, 0); + if (resultPoll > 0) { + ma_uint64 t; + read(((struct pollfd*)pDevice->alsa.pPollDescriptorsCapture)[0].fd, &t, sizeof(t)); + } + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Dropping playback device...\n"); + ((ma_snd_pcm_drop_proc)pDevice->pContext->alsa.snd_pcm_drop)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Dropping playback device successful.\n"); + + /* We need to prepare the device again, otherwise we won't be able to restart the device. */ + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing playback device...\n"); + if (((ma_snd_pcm_prepare_proc)pDevice->pContext->alsa.snd_pcm_prepare)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback) < 0) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing playback device failed.\n"); + } else { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing playback device successful.\n"); + } + + /* Clear the wakeupfd. */ + resultPoll = poll((struct pollfd*)pDevice->alsa.pPollDescriptorsPlayback, 1, 0); + if (resultPoll > 0) { + ma_uint64 t; + read(((struct pollfd*)pDevice->alsa.pPollDescriptorsPlayback)[0].fd, &t, sizeof(t)); + } + + } + + return MA_SUCCESS; +} + +static ma_result ma_device_wait__alsa(ma_device* pDevice, ma_snd_pcm_t* pPCM, struct pollfd* pPollDescriptors, int pollDescriptorCount, short requiredEvent) +{ + for (;;) { + unsigned short revents; + int resultALSA; + int resultPoll = poll(pPollDescriptors, pollDescriptorCount, -1); + if (resultPoll < 0) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] poll() failed.\n"); + return ma_result_from_errno(errno); + } + + /* + Before checking the ALSA poll descriptor flag we need to check if the wakeup descriptor + has had it's POLLIN flag set. If so, we need to actually read the data and then exit + function. The wakeup descriptor will be the first item in the descriptors buffer. + */ + if ((pPollDescriptors[0].revents & POLLIN) != 0) { + ma_uint64 t; + int resultRead = read(pPollDescriptors[0].fd, &t, sizeof(t)); /* <-- Important that we read here so that the next write() does not block. */ + if (resultRead < 0) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] read() failed.\n"); + return ma_result_from_errno(errno); + } + + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] POLLIN set for wakeupfd\n"); + return MA_DEVICE_NOT_STARTED; + } + + /* + Getting here means that some data should be able to be read. We need to use ALSA to + translate the revents flags for us. + */ + resultALSA = ((ma_snd_pcm_poll_descriptors_revents_proc)pDevice->pContext->alsa.snd_pcm_poll_descriptors_revents)(pPCM, pPollDescriptors + 1, pollDescriptorCount - 1, &revents); /* +1, -1 to ignore the wakeup descriptor. */ + if (resultALSA < 0) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_poll_descriptors_revents() failed.\n"); + return ma_result_from_errno(-resultALSA); + } + + if ((revents & POLLERR) != 0) { + ma_snd_pcm_state_t state = ((ma_snd_pcm_state_proc)pDevice->pContext->alsa.snd_pcm_state)(pPCM); + if (state == MA_SND_PCM_STATE_XRUN) { + /* The PCM is in a xrun state. This will be recovered from at a higher level. We can disregard this. */ + } else { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[ALSA] POLLERR detected. status = %d\n", ((ma_snd_pcm_state_proc)pDevice->pContext->alsa.snd_pcm_state)(pPCM)); + } + } + + if ((revents & requiredEvent) == requiredEvent) { + break; /* We're done. Data available for reading or writing. */ + } + } + + return MA_SUCCESS; +} + +static ma_result ma_device_wait_read__alsa(ma_device* pDevice) +{ + return ma_device_wait__alsa(pDevice, (ma_snd_pcm_t*)pDevice->alsa.pPCMCapture, (struct pollfd*)pDevice->alsa.pPollDescriptorsCapture, pDevice->alsa.pollDescriptorCountCapture + 1, POLLIN); /* +1 to account for the wakeup descriptor. */ +} + +static ma_result ma_device_wait_write__alsa(ma_device* pDevice) +{ + return ma_device_wait__alsa(pDevice, (ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback, (struct pollfd*)pDevice->alsa.pPollDescriptorsPlayback, pDevice->alsa.pollDescriptorCountPlayback + 1, POLLOUT); /* +1 to account for the wakeup descriptor. */ +} + +static ma_result ma_device_read__alsa(ma_device* pDevice, void* pFramesOut, ma_uint32 frameCount, ma_uint32* pFramesRead) +{ + ma_snd_pcm_sframes_t resultALSA = 0; + + MA_ASSERT(pDevice != NULL); + MA_ASSERT(pFramesOut != NULL); + + if (pFramesRead != NULL) { + *pFramesRead = 0; + } + + while (ma_device_get_state(pDevice) == ma_device_state_started) { + ma_result result; + + /* The first thing to do is wait for data to become available for reading. This will return an error code if the device has been stopped. */ + result = ma_device_wait_read__alsa(pDevice); + if (result != MA_SUCCESS) { + return result; + } + + /* Getting here means we should have data available. */ + resultALSA = ((ma_snd_pcm_readi_proc)pDevice->pContext->alsa.snd_pcm_readi)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture, pFramesOut, frameCount); + if (resultALSA >= 0) { + break; /* Success. */ + } else { + if (resultALSA == -EAGAIN) { + /*ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "EGAIN (read)\n");*/ + continue; /* Try again. */ + } else if (resultALSA == -EPIPE) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "EPIPE (read)\n"); + + /* Overrun. Recover and try again. If this fails we need to return an error. */ + resultALSA = ((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture, resultALSA, MA_TRUE); + if (resultALSA < 0) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to recover device after overrun."); + return ma_result_from_errno((int)-resultALSA); + } + + resultALSA = ((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture); + if (resultALSA < 0) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to start device after underrun."); + return ma_result_from_errno((int)-resultALSA); + } + + continue; /* Try reading again. */ + } + } + } + + if (pFramesRead != NULL) { + *pFramesRead = resultALSA; + } + + return MA_SUCCESS; +} + +static ma_result ma_device_write__alsa(ma_device* pDevice, const void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten) +{ + ma_snd_pcm_sframes_t resultALSA = 0; + + MA_ASSERT(pDevice != NULL); + MA_ASSERT(pFrames != NULL); + + if (pFramesWritten != NULL) { + *pFramesWritten = 0; + } + + while (ma_device_get_state(pDevice) == ma_device_state_started) { + ma_result result; + + /* The first thing to do is wait for space to become available for writing. This will return an error code if the device has been stopped. */ + result = ma_device_wait_write__alsa(pDevice); + if (result != MA_SUCCESS) { + return result; + } + + resultALSA = ((ma_snd_pcm_writei_proc)pDevice->pContext->alsa.snd_pcm_writei)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback, pFrames, frameCount); + if (resultALSA >= 0) { + break; /* Success. */ + } else { + if (resultALSA == -EAGAIN) { + /*ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "EGAIN (write)\n");*/ + continue; /* Try again. */ + } else if (resultALSA == -EPIPE) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "EPIPE (write)\n"); + + /* Underrun. Recover and try again. If this fails we need to return an error. */ + resultALSA = ((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback, resultALSA, MA_TRUE); /* MA_TRUE=silent (don't print anything on error). */ + if (resultALSA < 0) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to recover device after underrun."); + return ma_result_from_errno((int)-resultALSA); + } + + /* + 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. + */ + resultALSA = ((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback); + if (resultALSA < 0) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to start device after underrun."); + return ma_result_from_errno((int)-resultALSA); + } + + continue; /* Try writing again. */ + } + } + } + + if (pFramesWritten != NULL) { + *pFramesWritten = resultALSA; + } + + return MA_SUCCESS; +} + +static ma_result ma_device_data_loop_wakeup__alsa(ma_device* pDevice) +{ + ma_uint64 t = 1; + int resultWrite = 0; + + MA_ASSERT(pDevice != NULL); + + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Waking up...\n"); + + /* Write to an eventfd to trigger a wakeup from poll() and abort any reading or writing. */ + if (pDevice->alsa.pPollDescriptorsCapture != NULL) { + resultWrite = write(pDevice->alsa.wakeupfdCapture, &t, sizeof(t)); + } + if (pDevice->alsa.pPollDescriptorsPlayback != NULL) { + resultWrite = write(pDevice->alsa.wakeupfdPlayback, &t, sizeof(t)); + } + + if (resultWrite < 0) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] write() failed.\n"); + return ma_result_from_errno(errno); + } + + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Waking up completed successfully.\n"); + + return MA_SUCCESS; +} + +static 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(ma_context_get_log(pContext), pContext->alsa.asoundSO); +#endif + + ma_mutex_uninit(&pContext->alsa.internalDeviceEnumLock); + + return MA_SUCCESS; +} + +static ma_result ma_context_init__alsa(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks) +{ + ma_result result; +#ifndef MA_NO_RUNTIME_LINKING + const char* libasoundNames[] = { + "libasound.so.2", + "libasound.so" + }; + size_t i; + + for (i = 0; i < ma_countof(libasoundNames); ++i) { + pContext->alsa.asoundSO = ma_dlopen(ma_context_get_log(pContext), libasoundNames[i]); + if (pContext->alsa.asoundSO != NULL) { + break; + } + } + + if (pContext->alsa.asoundSO == NULL) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[ALSA] Failed to open shared object.\n"); + return MA_NO_BACKEND; + } + + pContext->alsa.snd_pcm_open = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_open"); + pContext->alsa.snd_pcm_close = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_close"); + pContext->alsa.snd_pcm_hw_params_sizeof = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_sizeof"); + pContext->alsa.snd_pcm_hw_params_any = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_any"); + pContext->alsa.snd_pcm_hw_params_set_format = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_format"); + pContext->alsa.snd_pcm_hw_params_set_format_first = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_format_first"); + pContext->alsa.snd_pcm_hw_params_get_format_mask = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_format_mask"); + pContext->alsa.snd_pcm_hw_params_set_channels = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_channels"); + pContext->alsa.snd_pcm_hw_params_set_channels_near = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_channels_near"); + pContext->alsa.snd_pcm_hw_params_set_channels_minmax = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_channels_minmax"); + pContext->alsa.snd_pcm_hw_params_set_rate_resample = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_rate_resample"); + pContext->alsa.snd_pcm_hw_params_set_rate = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_rate"); + pContext->alsa.snd_pcm_hw_params_set_rate_near = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_rate_near"); + pContext->alsa.snd_pcm_hw_params_set_buffer_size_near = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_buffer_size_near"); + pContext->alsa.snd_pcm_hw_params_set_periods_near = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_periods_near"); + pContext->alsa.snd_pcm_hw_params_set_access = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_access"); + pContext->alsa.snd_pcm_hw_params_get_format = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_format"); + pContext->alsa.snd_pcm_hw_params_get_channels = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_channels"); + pContext->alsa.snd_pcm_hw_params_get_channels_min = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_channels_min"); + pContext->alsa.snd_pcm_hw_params_get_channels_max = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_channels_max"); + pContext->alsa.snd_pcm_hw_params_get_rate = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_rate"); + pContext->alsa.snd_pcm_hw_params_get_rate_min = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_rate_min"); + pContext->alsa.snd_pcm_hw_params_get_rate_max = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_rate_max"); + pContext->alsa.snd_pcm_hw_params_get_buffer_size = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_buffer_size"); + pContext->alsa.snd_pcm_hw_params_get_periods = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_periods"); + pContext->alsa.snd_pcm_hw_params_get_access = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_access"); + pContext->alsa.snd_pcm_hw_params_test_format = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_test_format"); + pContext->alsa.snd_pcm_hw_params_test_channels = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_test_channels"); + pContext->alsa.snd_pcm_hw_params_test_rate = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_test_rate"); + pContext->alsa.snd_pcm_hw_params = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params"); + pContext->alsa.snd_pcm_sw_params_sizeof = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_sw_params_sizeof"); + pContext->alsa.snd_pcm_sw_params_current = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_sw_params_current"); + pContext->alsa.snd_pcm_sw_params_get_boundary = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_sw_params_get_boundary"); + pContext->alsa.snd_pcm_sw_params_set_avail_min = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_sw_params_set_avail_min"); + pContext->alsa.snd_pcm_sw_params_set_start_threshold = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_sw_params_set_start_threshold"); + pContext->alsa.snd_pcm_sw_params_set_stop_threshold = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_sw_params_set_stop_threshold"); + pContext->alsa.snd_pcm_sw_params = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_sw_params"); + pContext->alsa.snd_pcm_format_mask_sizeof = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_format_mask_sizeof"); + pContext->alsa.snd_pcm_format_mask_test = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_format_mask_test"); + pContext->alsa.snd_pcm_get_chmap = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_get_chmap"); + pContext->alsa.snd_pcm_state = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_state"); + pContext->alsa.snd_pcm_prepare = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_prepare"); + pContext->alsa.snd_pcm_start = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_start"); + pContext->alsa.snd_pcm_drop = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_drop"); + pContext->alsa.snd_pcm_drain = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_drain"); + pContext->alsa.snd_pcm_reset = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_reset"); + pContext->alsa.snd_device_name_hint = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_device_name_hint"); + pContext->alsa.snd_device_name_get_hint = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_device_name_get_hint"); + pContext->alsa.snd_card_get_index = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_card_get_index"); + pContext->alsa.snd_device_name_free_hint = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_device_name_free_hint"); + pContext->alsa.snd_pcm_mmap_begin = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_mmap_begin"); + pContext->alsa.snd_pcm_mmap_commit = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_mmap_commit"); + pContext->alsa.snd_pcm_recover = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_recover"); + pContext->alsa.snd_pcm_readi = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_readi"); + pContext->alsa.snd_pcm_writei = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_writei"); + pContext->alsa.snd_pcm_avail = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_avail"); + pContext->alsa.snd_pcm_avail_update = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_avail_update"); + pContext->alsa.snd_pcm_wait = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_wait"); + pContext->alsa.snd_pcm_nonblock = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_nonblock"); + pContext->alsa.snd_pcm_info = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_info"); + pContext->alsa.snd_pcm_info_sizeof = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_info_sizeof"); + pContext->alsa.snd_pcm_info_get_name = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_info_get_name"); + pContext->alsa.snd_pcm_poll_descriptors = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_poll_descriptors"); + pContext->alsa.snd_pcm_poll_descriptors_count = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_poll_descriptors_count"); + pContext->alsa.snd_pcm_poll_descriptors_revents = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_poll_descriptors_revents"); + pContext->alsa.snd_config_update_free_global = (ma_proc)ma_dlsym(ma_context_get_log(pContext), 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_proc _snd_pcm_hw_params_set_channels = snd_pcm_hw_params_set_channels; + 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 _snd_pcm_hw_params_set_rate = snd_pcm_hw_params_set_rate; + 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_rate_minmax_proc _snd_pcm_hw_params_set_rate_minmax = snd_pcm_hw_params_set_rate_minmax; + 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_test_format_proc _snd_pcm_hw_params_test_format = snd_pcm_hw_params_test_format; + ma_snd_pcm_hw_params_test_channels_proc _snd_pcm_hw_params_test_channels = snd_pcm_hw_params_test_channels; + ma_snd_pcm_hw_params_test_rate_proc _snd_pcm_hw_params_test_rate = snd_pcm_hw_params_test_rate; + 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_pcm_reset_proc _snd_pcm_reset = snd_pcm_reset; + 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_nonblock_proc _snd_pcm_nonblock = snd_pcm_nonblock; + 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_pcm_poll_descriptors _snd_pcm_poll_descriptors = snd_pcm_poll_descriptors; + ma_snd_pcm_poll_descriptors_count _snd_pcm_poll_descriptors_count = snd_pcm_poll_descriptors_count; + ma_snd_pcm_poll_descriptors_revents _snd_pcm_poll_descriptors_revents = snd_pcm_poll_descriptors_revents; + 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 = (ma_proc)_snd_pcm_hw_params_set_channels; + 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_channels_minmax = (ma_proc)_snd_pcm_hw_params_set_channels_minmax; + 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 = (ma_proc)_snd_pcm_hw_params_set_rate; + 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_rate_min = (ma_proc)_snd_pcm_hw_params_get_rate_min; + pContext->alsa.snd_pcm_hw_params_get_rate_max = (ma_proc)_snd_pcm_hw_params_get_rate_max; + 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_test_format = (ma_proc)_snd_pcm_hw_params_test_format; + pContext->alsa.snd_pcm_hw_params_test_channels = (ma_proc)_snd_pcm_hw_params_test_channels; + pContext->alsa.snd_pcm_hw_params_test_rate = (ma_proc)_snd_pcm_hw_params_test_rate; + 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_pcm_reset = (ma_proc)_snd_pcm_reset; + 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_nonblock = (ma_proc)_snd_pcm_nonblock; + 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_pcm_poll_descriptors = (ma_proc)_snd_pcm_poll_descriptors; + pContext->alsa.snd_pcm_poll_descriptors_count = (ma_proc)_snd_pcm_poll_descriptors_count; + pContext->alsa.snd_pcm_poll_descriptors_revents = (ma_proc)_snd_pcm_poll_descriptors_revents; + pContext->alsa.snd_config_update_free_global = (ma_proc)_snd_config_update_free_global; +#endif + + pContext->alsa.useVerboseDeviceEnumeration = pConfig->alsa.useVerboseDeviceEnumeration; + + result = ma_mutex_init(&pContext->alsa.internalDeviceEnumLock); + if (result != MA_SUCCESS) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[ALSA] WARNING: Failed to initialize mutex for internal device enumeration."); + return result; + } + + pCallbacks->onContextInit = ma_context_init__alsa; + pCallbacks->onContextUninit = ma_context_uninit__alsa; + pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__alsa; + pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__alsa; + pCallbacks->onDeviceInit = ma_device_init__alsa; + pCallbacks->onDeviceUninit = ma_device_uninit__alsa; + pCallbacks->onDeviceStart = ma_device_start__alsa; + pCallbacks->onDeviceStop = ma_device_stop__alsa; + pCallbacks->onDeviceRead = ma_device_read__alsa; + pCallbacks->onDeviceWrite = ma_device_write__alsa; + pCallbacks->onDeviceDataLoop = NULL; + pCallbacks->onDeviceDataLoopWakeup = ma_device_data_loop_wakeup__alsa; + + return MA_SUCCESS; +} +#endif /* ALSA */ + + + +/****************************************************************************** + +PulseAudio Backend + +******************************************************************************/ +#ifdef MA_HAS_PULSEAUDIO +/* +The PulseAudio API, along with Apple's Core Audio, is the worst of the maintream audio APIs. This is a brief description of what's going on +in the PulseAudio backend. I apologize if this gets a bit ranty for your liking - you might want to skip this discussion. + +PulseAudio has something they call the "Simple API", which unfortunately isn't suitable for miniaudio. I've not seen anywhere where it +allows you to enumerate over devices, nor does it seem to support the ability to stop and start streams. Looking at the documentation, it +appears as though the stream is constantly running and you prevent sound from being emitted or captured by simply not calling the read or +write functions. This is not a professional solution as it would be much better to *actually* stop the underlying stream. Perhaps the +simple API has some smarts to do this automatically, but I'm not sure. Another limitation with the simple API is that it seems inefficient +when you want to have multiple streams to a single context. For these reasons, miniaudio is not using the simple API. + +Since we're not using the simple API, we're left with the asynchronous API as our only other option. And boy, is this where it starts to +get fun, and I don't mean that in a good way... + +The problems start with the very name of the API - "asynchronous". Yes, this is an asynchronous oriented API which means your commands +don't immediately take effect. You instead need to issue your commands, and then wait for them to complete. The waiting mechanism is +enabled through the use of a "main loop". In the asychronous API you cannot get away from the main loop, and the main loop is where almost +all of PulseAudio's problems stem from. + +When you first initialize PulseAudio you need an object referred to as "main loop". You can implement this yourself by defining your own +vtable, but it's much easier to just use one of the built-in main loop implementations. There's two generic implementations called +pa_mainloop and pa_threaded_mainloop, and another implementation specific to GLib called pa_glib_mainloop. We're using pa_threaded_mainloop +because it simplifies management of the worker thread. The idea of the main loop object is pretty self explanatory - you're supposed to use +it to implement a worker thread which runs in a loop. The main loop is where operations are actually executed. + +To initialize the main loop, you just use `pa_threaded_mainloop_new()`. This is the first function you'll call. You can then get a pointer +to the vtable with `pa_threaded_mainloop_get_api()` (the main loop vtable is called `pa_mainloop_api`). Again, you can bypass the threaded +main loop object entirely and just implement `pa_mainloop_api` directly, but there's no need for it unless you're doing something extremely +specialized such as if you want to integrate it into your application's existing main loop infrastructure. + +(EDIT 2021-01-26: miniaudio is no longer using `pa_threaded_mainloop` due to this issue: https://github.com/mackron/miniaudio/issues/262. +It is now using `pa_mainloop` which turns out to be a simpler solution anyway. The rest of this rant still applies, however.) + +Once you have your main loop vtable (the `pa_mainloop_api` object) you can create the PulseAudio context. This is very similar to +miniaudio's context and they map to each other quite well. You have one context to many streams, which is basically the same as miniaudio's +one `ma_context` to many `ma_device`s. Here's where it starts to get annoying, however. When you first create the PulseAudio context, which +is done with `pa_context_new()`, it's not actually connected to anything. When you connect, you call `pa_context_connect()`. However, if +you remember, PulseAudio is an asynchronous API. That means you cannot just assume the context is connected after `pa_context_context()` +has returned. You instead need to wait for it to connect. To do this, you need to either wait for a callback to get fired, which you can +set with `pa_context_set_state_callback()`, or you can continuously poll the context's state. Either way, you need to run this in a loop. +All objects from here out are created from the context, and, I believe, you can't be creating these objects until the context is connected. +This waiting loop is therefore unavoidable. In order for the waiting to ever complete, however, the main loop needs to be running. Before +attempting to connect the context, the main loop needs to be started with `pa_threaded_mainloop_start()`. + +The reason for this asynchronous design is to support cases where you're connecting to a remote server, say through a local network or an +internet connection. However, the *VAST* majority of cases don't involve this at all - they just connect to a local "server" running on the +host machine. The fact that this would be the default rather than making `pa_context_connect()` synchronous tends to boggle the mind. + +Once the context has been created and connected you can start creating a stream. A PulseAudio stream is analogous to miniaudio's device. +The initialization of a stream is fairly standard - you configure some attributes (analogous to miniaudio's device config) and then call +`pa_stream_new()` to actually create it. Here is where we start to get into "operations". When configuring the stream, you can get +information about the source (such as sample format, sample rate, etc.), however it's not synchronous. Instead, a `pa_operation` object +is returned from `pa_context_get_source_info_by_name()` (capture) or `pa_context_get_sink_info_by_name()` (playback). Then, you need to +run a loop (again!) to wait for the operation to complete which you can determine via a callback or polling, just like we did with the +context. Then, as an added bonus, you need to decrement the reference counter of the `pa_operation` object to ensure memory is cleaned up. +All of that just to retrieve basic information about a device! + +Once the basic information about the device has been retrieved, miniaudio can now create the stream with `ma_stream_new()`. Like the +context, this needs to be connected. But we need to be careful here, because we're now about to introduce one of the most horrific design +choices in PulseAudio. + +PulseAudio allows you to specify a callback that is fired when data can be written to or read from a stream. The language is important here +because PulseAudio takes it literally, specifically the "can be". You would think these callbacks would be appropriate as the place for +writing and reading data to and from the stream, and that would be right, except when it's not. When you initialize the stream, you can +set a flag that tells PulseAudio to not start the stream automatically. This is required because miniaudio does not auto-start devices +straight after initialization - you need to call `ma_device_start()` manually. The problem is that even when this flag is specified, +PulseAudio will immediately fire it's write or read callback. This is *technically* correct (based on the wording in the documentation) +because indeed, data *can* be written at this point. The problem is that it's not *practical*. It makes sense that the write/read callback +would be where a program will want to write or read data to or from the stream, but when it's called before the application has even +requested that the stream be started, it's just not practical because the program probably isn't ready for any kind of data delivery at +that point (it may still need to load files or whatnot). Instead, this callback should only be fired when the application requests the +stream be started which is how it works with literally *every* other callback-based audio API. Since miniaudio forbids firing of the data +callback until the device has been started (as it should be with *all* callback based APIs), logic needs to be added to ensure miniaudio +doesn't just blindly fire the application-defined data callback from within the PulseAudio callback before the stream has actually been +started. The device state is used for this - if the state is anything other than `ma_device_state_starting` or `ma_device_state_started`, the main data +callback is not fired. + +This, unfortunately, is not the end of the problems with the PulseAudio write callback. Any normal callback based audio API will +continuously fire the callback at regular intervals based on the size of the internal buffer. This will only ever be fired when the device +is running, and will be fired regardless of whether or not the user actually wrote anything to the device/stream. This not the case in +PulseAudio. In PulseAudio, the data callback will *only* be called if you wrote something to it previously. That means, if you don't call +`pa_stream_write()`, the callback will not get fired. On the surface you wouldn't think this would matter because you should be always +writing data, and if you don't have anything to write, just write silence. That's fine until you want to drain the stream. You see, if +you're continuously writing data to the stream, the stream will never get drained! That means in order to drain the stream, you need to +*not* write data to it! But remember, when you don't write data to the stream, the callback won't get fired again! Why is draining +important? Because that's how we've defined stopping to work in miniaudio. In miniaudio, stopping the device requires it to be drained +before returning from ma_device_stop(). So we've stopped the device, which requires us to drain, but draining requires us to *not* write +data to the stream (or else it won't ever complete draining), but not writing to the stream means the callback won't get fired again! + +This becomes a problem when stopping and then restarting the device. When the device is stopped, it's drained, which requires us to *not* +write anything to the stream. But then, since we didn't write anything to it, the write callback will *never* get called again if we just +resume the stream naively. This means that starting the stream requires us to write data to the stream from outside the callback. This +disconnect is something PulseAudio has got seriously wrong - there should only ever be a single source of data delivery, that being the +callback. (I have tried using `pa_stream_flush()` to trigger the write callback to fire, but this just doesn't work for some reason.) + +Once you've created the stream, you need to connect it which involves the whole waiting procedure. This is the same process as the context, +only this time you'll poll for the state with `pa_stream_get_status()`. The starting and stopping of a streaming is referred to as +"corking" in PulseAudio. The analogy is corking a barrel. To start the stream, you uncork it, to stop it you cork it. Personally I think +it's silly - why would you not just call it "starting" and "stopping" like any other normal audio API? Anyway, the act of corking is, you +guessed it, asynchronous. This means you'll need our waiting loop as usual. Again, why this asynchronous design is the default is +absolutely beyond me. Would it really be that hard to just make it run synchronously? + +Teardown is pretty simple (what?!). It's just a matter of calling the relevant `_unref()` function on each object in reverse order that +they were initialized in. + +That's about it from the PulseAudio side. A bit ranty, I know, but they really need to fix that main loop and callback system. They're +embarrassingly unpractical. The main loop thing is an easy fix - have synchronous versions of all APIs. If an application wants these to +run asynchronously, they can execute them in a separate thread themselves. The desire to run these asynchronously is such a niche +requirement - it makes no sense to make it the default. The stream write callback needs to be change, or an alternative provided, that is +constantly fired, regardless of whether or not `pa_stream_write()` has been called, and it needs to take a pointer to a buffer as a +parameter which the program just writes to directly rather than having to call `pa_stream_writable_size()` and `pa_stream_write()`. These +changes alone will change PulseAudio from one of the worst audio APIs to one of the best. +*/ + + +/* +It is assumed pulseaudio.h is available when linking at compile time. When linking at compile time, we use the declarations in the header +to check for type safety. We cannot do this when linking at run time because the header might not be available. +*/ +#ifdef MA_NO_RUNTIME_LINKING + +/* pulseaudio.h marks some functions with "inline" which isn't always supported. Need to emulate it. */ +#if !defined(__cplusplus) + #if defined(__STRICT_ANSI__) + #if !defined(inline) + #define inline __inline__ __attribute__((always_inline)) + #define MA_INLINE_DEFINED + #endif + #endif +#endif +#include +#if defined(MA_INLINE_DEFINED) + #undef inline + #undef MA_INLINE_DEFINED +#endif + +#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_ERR_NOTSUPPORTED PA_ERR_NOTSUPPORTED + +#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_threaded_mainloop ma_pa_threaded_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_stream_notify_cb_t ma_pa_stream_notify_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_ERR_NOTSUPPORTED 19 + +#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_threaded_mainloop ma_pa_threaded_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_stream_notify_cb_t) (ma_pa_stream* s, void* userdata); +typedef void (* ma_pa_free_cb_t) (void* p); +#endif + + +typedef ma_pa_mainloop* (* ma_pa_mainloop_new_proc) (void); +typedef void (* ma_pa_mainloop_free_proc) (ma_pa_mainloop* m); +typedef void (* ma_pa_mainloop_quit_proc) (ma_pa_mainloop* m, int retval); +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_threaded_mainloop* (* ma_pa_threaded_mainloop_new_proc) (void); +typedef void (* ma_pa_threaded_mainloop_free_proc) (ma_pa_threaded_mainloop* m); +typedef int (* ma_pa_threaded_mainloop_start_proc) (ma_pa_threaded_mainloop* m); +typedef void (* ma_pa_threaded_mainloop_stop_proc) (ma_pa_threaded_mainloop* m); +typedef void (* ma_pa_threaded_mainloop_lock_proc) (ma_pa_threaded_mainloop* m); +typedef void (* ma_pa_threaded_mainloop_unlock_proc) (ma_pa_threaded_mainloop* m); +typedef void (* ma_pa_threaded_mainloop_wait_proc) (ma_pa_threaded_mainloop* m); +typedef void (* ma_pa_threaded_mainloop_signal_proc) (ma_pa_threaded_mainloop* m, int wait_for_accept); +typedef void (* ma_pa_threaded_mainloop_accept_proc) (ma_pa_threaded_mainloop* m); +typedef int (* ma_pa_threaded_mainloop_get_retval_proc) (ma_pa_threaded_mainloop* m); +typedef ma_pa_mainloop_api* (* ma_pa_threaded_mainloop_get_api_proc) (ma_pa_threaded_mainloop* m); +typedef int (* ma_pa_threaded_mainloop_in_thread_proc) (ma_pa_threaded_mainloop* m); +typedef void (* ma_pa_threaded_mainloop_set_name_proc) (ma_pa_threaded_mainloop* m, const char* name); +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 void (* ma_pa_stream_set_suspended_callback_proc) (ma_pa_stream* s, ma_pa_stream_notify_cb_t cb, void* userdata); +typedef void (* ma_pa_stream_set_moved_callback_proc) (ma_pa_stream* s, ma_pa_stream_notify_cb_t cb, void* userdata); +typedef int (* ma_pa_stream_is_suspended_proc) (const ma_pa_stream* s); +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; + +static ma_result ma_result_from_pulse(int result) +{ + if (result < 0) { + return MA_ERROR; + } + + 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 +static 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 + +static 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; + } +} + +static 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 +static 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 + +static ma_result ma_wait_for_operation__pulse(ma_context* pContext, ma_ptr pMainLoop, ma_pa_operation* pOP) +{ + int resultPA; + ma_pa_operation_state_t state; + + MA_ASSERT(pContext != NULL); + MA_ASSERT(pOP != NULL); + + for (;;) { + state = ((ma_pa_operation_get_state_proc)pContext->pulse.pa_operation_get_state)(pOP); + if (state != MA_PA_OPERATION_RUNNING) { + break; /* Done. */ + } + + resultPA = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pMainLoop, 1, NULL); + if (resultPA < 0) { + return ma_result_from_pulse(resultPA); + } + } + + return MA_SUCCESS; +} + +static ma_result ma_wait_for_operation_and_unref__pulse(ma_context* pContext, ma_ptr pMainLoop, ma_pa_operation* pOP) +{ + ma_result result; + + if (pOP == NULL) { + return MA_INVALID_ARGS; + } + + result = ma_wait_for_operation__pulse(pContext, pMainLoop, pOP); + ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); + + return result; +} + +static ma_result ma_wait_for_pa_context_to_connect__pulse(ma_context* pContext, ma_ptr pMainLoop, ma_ptr pPulseContext) +{ + int resultPA; + ma_pa_context_state_t state; + + for (;;) { + state = ((ma_pa_context_get_state_proc)pContext->pulse.pa_context_get_state)((ma_pa_context*)pPulseContext); + if (state == MA_PA_CONTEXT_READY) { + break; /* Done. */ + } + + if (state == MA_PA_CONTEXT_FAILED || state == MA_PA_CONTEXT_TERMINATED) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while connecting the PulseAudio context."); + return MA_ERROR; + } + + resultPA = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pMainLoop, 1, NULL); + if (resultPA < 0) { + return ma_result_from_pulse(resultPA); + } + } + + /* Should never get here. */ + return MA_SUCCESS; +} + +static ma_result ma_wait_for_pa_stream_to_connect__pulse(ma_context* pContext, ma_ptr pMainLoop, ma_ptr pStream) +{ + int resultPA; + ma_pa_stream_state_t state; + + for (;;) { + state = ((ma_pa_stream_get_state_proc)pContext->pulse.pa_stream_get_state)((ma_pa_stream*)pStream); + if (state == MA_PA_STREAM_READY) { + break; /* Done. */ + } + + if (state == MA_PA_STREAM_FAILED || state == MA_PA_STREAM_TERMINATED) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while connecting the PulseAudio stream."); + return MA_ERROR; + } + + resultPA = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pMainLoop, 1, NULL); + if (resultPA < 0) { + return ma_result_from_pulse(resultPA); + } + } + + return MA_SUCCESS; +} + + +static ma_result ma_init_pa_mainloop_and_pa_context__pulse(ma_context* pContext, const char* pApplicationName, const char* pServerName, ma_bool32 tryAutoSpawn, ma_ptr* ppMainLoop, ma_ptr* ppPulseContext) +{ + ma_result result; + ma_ptr pMainLoop; + ma_ptr pPulseContext; + + MA_ASSERT(ppMainLoop != NULL); + MA_ASSERT(ppPulseContext != NULL); + + /* The PulseAudio context maps well to miniaudio's notion of a context. The pa_context object will be initialized as part of the ma_context. */ + pMainLoop = ((ma_pa_mainloop_new_proc)pContext->pulse.pa_mainloop_new)(); + if (pMainLoop == NULL) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create mainloop."); + return MA_FAILED_TO_INIT_BACKEND; + } + + pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)(((ma_pa_mainloop_get_api_proc)pContext->pulse.pa_mainloop_get_api)((ma_pa_mainloop*)pMainLoop), pApplicationName); + if (pPulseContext == NULL) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio context."); + ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)(pMainLoop)); + return MA_FAILED_TO_INIT_BACKEND; + } + + /* Now we need to connect to the context. Everything is asynchronous so we need to wait for it to connect before returning. */ + result = ma_result_from_pulse(((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)((ma_pa_context*)pPulseContext, pServerName, (tryAutoSpawn) ? 0 : MA_PA_CONTEXT_NOAUTOSPAWN, NULL)); + if (result != MA_SUCCESS) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to connect PulseAudio context."); + ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)(pMainLoop)); + return result; + } + + /* Since ma_context_init() runs synchronously we need to wait for the PulseAudio context to connect before we return. */ + result = ma_wait_for_pa_context_to_connect__pulse(pContext, pMainLoop, pPulseContext); + if (result != MA_SUCCESS) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] Waiting for connection failed."); + ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)(pMainLoop)); + return result; + } + + *ppMainLoop = pMainLoop; + *ppPulseContext = pPulseContext; + + return MA_SUCCESS; +} + + +static void ma_device_sink_info_callback(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData) +{ + ma_pa_sink_info* pInfoOut; + + if (endOfList > 0) { + return; + } + + /* + There has been a report that indicates that pInfo can be null which results + in a null pointer dereference below. We'll check for this for safety. + */ + if (pInfo == NULL) { + return; + } + + pInfoOut = (ma_pa_sink_info*)pUserData; + MA_ASSERT(pInfoOut != NULL); + + *pInfoOut = *pInfo; + + (void)pPulseContext; /* Unused. */ +} + +static void ma_device_source_info_callback(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData) +{ + ma_pa_source_info* pInfoOut; + + if (endOfList > 0) { + return; + } + + /* + There has been a report that indicates that pInfo can be null which results + in a null pointer dereference below. We'll check for this for safety. + */ + if (pInfo == NULL) { + return; + } + + pInfoOut = (ma_pa_source_info*)pUserData; + MA_ASSERT(pInfoOut != NULL); + + *pInfoOut = *pInfo; + + (void)pPulseContext; /* Unused. */ +} + +#if 0 +static void ma_device_sink_name_callback(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData) +{ + ma_device* pDevice; + + if (endOfList > 0) { + return; + } + + 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. */ +} + +static void ma_device_source_name_callback(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData) +{ + ma_device* pDevice; + + if (endOfList > 0) { + return; + } + + 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. */ +} +#endif + +static ma_result ma_context_get_sink_info__pulse(ma_context* pContext, const char* pDeviceName, ma_pa_sink_info* pSinkInfo) +{ + ma_pa_operation* pOP; + + pOP = ((ma_pa_context_get_sink_info_by_name_proc)pContext->pulse.pa_context_get_sink_info_by_name)((ma_pa_context*)pContext->pulse.pPulseContext, pDeviceName, ma_device_sink_info_callback, pSinkInfo); + if (pOP == NULL) { + return MA_ERROR; + } + + return ma_wait_for_operation_and_unref__pulse(pContext, pContext->pulse.pMainLoop, pOP); +} + +static ma_result ma_context_get_source_info__pulse(ma_context* pContext, const char* pDeviceName, ma_pa_source_info* pSourceInfo) +{ + ma_pa_operation* pOP; + + pOP = ((ma_pa_context_get_source_info_by_name_proc)pContext->pulse.pa_context_get_source_info_by_name)((ma_pa_context*)pContext->pulse.pPulseContext, pDeviceName, ma_device_source_info_callback, pSourceInfo); + if (pOP == NULL) { + return MA_ERROR; + } + + return ma_wait_for_operation_and_unref__pulse(pContext, pContext->pulse.pMainLoop, pOP); +} + +static ma_result ma_context_get_default_device_index__pulse(ma_context* pContext, ma_device_type deviceType, ma_uint32* pIndex) +{ + ma_result result; + + MA_ASSERT(pContext != NULL); + MA_ASSERT(pIndex != NULL); + + if (pIndex != NULL) { + *pIndex = (ma_uint32)-1; + } + + if (deviceType == ma_device_type_playback) { + ma_pa_sink_info sinkInfo; + result = ma_context_get_sink_info__pulse(pContext, NULL, &sinkInfo); + if (result != MA_SUCCESS) { + return result; + } + + if (pIndex != NULL) { + *pIndex = sinkInfo.index; + } + } + + if (deviceType == ma_device_type_capture) { + ma_pa_source_info sourceInfo; + result = ma_context_get_source_info__pulse(pContext, NULL, &sourceInfo); + if (result != MA_SUCCESS) { + return result; + } + + if (pIndex != NULL) { + *pIndex = sourceInfo.index; + } + } + + return MA_SUCCESS; +} + + +typedef struct +{ + ma_context* pContext; + ma_enum_devices_callback_proc callback; + void* pUserData; + ma_bool32 isTerminated; + ma_uint32 defaultDeviceIndexPlayback; + ma_uint32 defaultDeviceIndexCapture; +} ma_context_enumerate_devices_callback_data__pulse; + +static 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_device_info deviceInfo; + + MA_ASSERT(pData != NULL); + + if (endOfList || pData->isTerminated) { + return; + } + + 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); + } + + if (pSinkInfo->index == pData->defaultDeviceIndexPlayback) { + deviceInfo.isDefault = MA_TRUE; + } + + pData->isTerminated = !pData->callback(pData->pContext, ma_device_type_playback, &deviceInfo, pData->pUserData); + + (void)pPulseContext; /* Unused. */ +} + +static void ma_context_enumerate_devices_source_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_source_info* pSourceInfo, int endOfList, void* pUserData) +{ + 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_ZERO_OBJECT(&deviceInfo); + + /* The name from PulseAudio is the ID for miniaudio. */ + if (pSourceInfo->name != NULL) { + ma_strncpy_s(deviceInfo.id.pulse, sizeof(deviceInfo.id.pulse), pSourceInfo->name, (size_t)-1); + } + + /* The description from PulseAudio is the name for miniaudio. */ + if (pSourceInfo->description != NULL) { + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), pSourceInfo->description, (size_t)-1); + } + + if (pSourceInfo->index == pData->defaultDeviceIndexCapture) { + deviceInfo.isDefault = MA_TRUE; + } + + pData->isTerminated = !pData->callback(pData->pContext, ma_device_type_capture, &deviceInfo, pData->pUserData); + + (void)pPulseContext; /* Unused. */ +} + +static 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_ASSERT(pContext != NULL); + MA_ASSERT(callback != NULL); + + callbackData.pContext = pContext; + callbackData.callback = callback; + callbackData.pUserData = pUserData; + callbackData.isTerminated = MA_FALSE; + callbackData.defaultDeviceIndexPlayback = (ma_uint32)-1; + callbackData.defaultDeviceIndexCapture = (ma_uint32)-1; + + /* We need to get the index of the default devices. */ + ma_context_get_default_device_index__pulse(pContext, ma_device_type_playback, &callbackData.defaultDeviceIndexPlayback); + ma_context_get_default_device_index__pulse(pContext, ma_device_type_capture, &callbackData.defaultDeviceIndexCapture); + + /* Playback. */ + if (!callbackData.isTerminated) { + pOP = ((ma_pa_context_get_sink_info_list_proc)pContext->pulse.pa_context_get_sink_info_list)((ma_pa_context*)(pContext->pulse.pPulseContext), ma_context_enumerate_devices_sink_callback__pulse, &callbackData); + if (pOP == NULL) { + result = MA_ERROR; + goto done; + } + + result = ma_wait_for_operation__pulse(pContext, pContext->pulse.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)((ma_pa_context*)(pContext->pulse.pPulseContext), ma_context_enumerate_devices_source_callback__pulse, &callbackData); + if (pOP == NULL) { + result = MA_ERROR; + goto done; + } + + result = ma_wait_for_operation__pulse(pContext, pContext->pulse.pMainLoop, pOP); + ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); + + if (result != MA_SUCCESS) { + goto done; + } + } + +done: + return result; +} + + +typedef struct +{ + ma_device_info* pDeviceInfo; + ma_uint32 defaultDeviceIndex; + ma_bool32 foundDevice; +} ma_context_get_device_info_callback_data__pulse; + +static void ma_context_get_device_info_sink_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData) +{ + ma_context_get_device_info_callback_data__pulse* pData = (ma_context_get_device_info_callback_data__pulse*)pUserData; + + if (endOfList > 0) { + return; + } + + 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); + } + + /* + We're just reporting a single data format here. I think technically PulseAudio might support + all formats, but I don't trust that PulseAudio will do *anything* right, so I'm just going to + report the "native" device format. + */ + pData->pDeviceInfo->nativeDataFormats[0].format = ma_format_from_pulse(pInfo->sample_spec.format); + pData->pDeviceInfo->nativeDataFormats[0].channels = pInfo->sample_spec.channels; + pData->pDeviceInfo->nativeDataFormats[0].sampleRate = pInfo->sample_spec.rate; + pData->pDeviceInfo->nativeDataFormats[0].flags = 0; + pData->pDeviceInfo->nativeDataFormatCount = 1; + + if (pData->defaultDeviceIndex == pInfo->index) { + pData->pDeviceInfo->isDefault = MA_TRUE; + } + + (void)pPulseContext; /* Unused. */ +} + +static void ma_context_get_device_info_source_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData) +{ + ma_context_get_device_info_callback_data__pulse* pData = (ma_context_get_device_info_callback_data__pulse*)pUserData; + + if (endOfList > 0) { + return; + } + + 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); + } + + /* + We're just reporting a single data format here. I think technically PulseAudio might support + all formats, but I don't trust that PulseAudio will do *anything* right, so I'm just going to + report the "native" device format. + */ + pData->pDeviceInfo->nativeDataFormats[0].format = ma_format_from_pulse(pInfo->sample_spec.format); + pData->pDeviceInfo->nativeDataFormats[0].channels = pInfo->sample_spec.channels; + pData->pDeviceInfo->nativeDataFormats[0].sampleRate = pInfo->sample_spec.rate; + pData->pDeviceInfo->nativeDataFormats[0].flags = 0; + pData->pDeviceInfo->nativeDataFormatCount = 1; + + if (pData->defaultDeviceIndex == pInfo->index) { + pData->pDeviceInfo->isDefault = MA_TRUE; + } + + (void)pPulseContext; /* Unused. */ +} + +static ma_result ma_context_get_device_info__pulse(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo) +{ + ma_result result = MA_SUCCESS; + ma_context_get_device_info_callback_data__pulse callbackData; + ma_pa_operation* pOP = NULL; + const char* pDeviceName = NULL; + + MA_ASSERT(pContext != NULL); + + callbackData.pDeviceInfo = pDeviceInfo; + callbackData.foundDevice = MA_FALSE; + + if (pDeviceID != NULL) { + pDeviceName = pDeviceID->pulse; + } else { + pDeviceName = NULL; + } + + result = ma_context_get_default_device_index__pulse(pContext, deviceType, &callbackData.defaultDeviceIndex); + + 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)((ma_pa_context*)(pContext->pulse.pPulseContext), pDeviceName, 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)((ma_pa_context*)(pContext->pulse.pPulseContext), pDeviceName, ma_context_get_device_info_source_callback__pulse, &callbackData); + } + + if (pOP != NULL) { + ma_wait_for_operation_and_unref__pulse(pContext, pContext->pulse.pMainLoop, pOP); + } else { + result = MA_ERROR; + goto done; + } + + if (!callbackData.foundDevice) { + result = MA_NO_DEVICE; + goto done; + } + +done: + return result; +} + +static ma_result ma_device_uninit__pulse(ma_device* pDevice) +{ + ma_context* pContext; + + MA_ASSERT(pDevice != NULL); + + 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); + } + + if (pDevice->type == ma_device_type_duplex) { + ma_duplex_rb_uninit(&pDevice->duplexRB); + } + + ((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); + + return MA_SUCCESS; +} + +static ma_pa_buffer_attr ma_device__pa_buffer_attr_new(ma_uint32 periodSizeInFrames, ma_uint32 periods, const ma_pa_sample_spec* ss) +{ + ma_pa_buffer_attr attr; + attr.maxlength = periodSizeInFrames * periods * ma_get_bytes_per_frame(ma_format_from_pulse(ss->format), ss->channels); + attr.tlength = attr.maxlength / periods; + attr.prebuf = (ma_uint32)-1; + attr.minreq = (ma_uint32)-1; + attr.fragsize = attr.maxlength / periods; + + return attr; +} + +static 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); +} + + +static void ma_device_on_read__pulse(ma_pa_stream* pStream, size_t byteCount, void* pUserData) +{ + ma_device* pDevice = (ma_device*)pUserData; + ma_uint32 bpf; + ma_uint32 deviceState; + ma_uint64 frameCount; + ma_uint64 framesProcessed; + + MA_ASSERT(pDevice != NULL); + + /* + Don't do anything if the device isn't initialized yet. Yes, this can happen because PulseAudio + can fire this callback before the stream has even started. Ridiculous. + */ + deviceState = ma_device_get_state(pDevice); + if (deviceState != ma_device_state_starting && deviceState != ma_device_state_started) { + return; + } + + bpf = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + MA_ASSERT(bpf > 0); + + frameCount = byteCount / bpf; + framesProcessed = 0; + + while (ma_device_get_state(pDevice) == ma_device_state_started && framesProcessed < frameCount) { + const void* pMappedPCMFrames; + size_t bytesMapped; + ma_uint64 framesMapped; + + int pulseResult = ((ma_pa_stream_peek_proc)pDevice->pContext->pulse.pa_stream_peek)(pStream, &pMappedPCMFrames, &bytesMapped); + if (pulseResult < 0) { + break; /* Failed to map. Abort. */ + } + + framesMapped = bytesMapped / bpf; + if (framesMapped > 0) { + if (pMappedPCMFrames != NULL) { + ma_device_handle_backend_data_callback(pDevice, NULL, pMappedPCMFrames, framesMapped); + } else { + /* It's a hole. */ + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[PulseAudio] ma_device_on_read__pulse: Hole.\n"); + } + + pulseResult = ((ma_pa_stream_drop_proc)pDevice->pContext->pulse.pa_stream_drop)(pStream); + if (pulseResult < 0) { + break; /* Failed to drop the buffer. */ + } + + framesProcessed += framesMapped; + + } else { + /* Nothing was mapped. Just abort. */ + break; + } + } +} + +static ma_result ma_device_write_to_stream__pulse(ma_device* pDevice, ma_pa_stream* pStream, ma_uint64* pFramesProcessed) +{ + ma_result result = MA_SUCCESS; + ma_uint64 framesProcessed = 0; + size_t bytesMapped; + ma_uint32 bpf; + ma_uint32 deviceState; + + MA_ASSERT(pDevice != NULL); + MA_ASSERT(pStream != NULL); + + bpf = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + MA_ASSERT(bpf > 0); + + deviceState = ma_device_get_state(pDevice); + + bytesMapped = ((ma_pa_stream_writable_size_proc)pDevice->pContext->pulse.pa_stream_writable_size)(pStream); + if (bytesMapped != (size_t)-1) { + if (bytesMapped > 0) { + ma_uint64 framesMapped; + void* pMappedPCMFrames; + int pulseResult = ((ma_pa_stream_begin_write_proc)pDevice->pContext->pulse.pa_stream_begin_write)(pStream, &pMappedPCMFrames, &bytesMapped); + if (pulseResult < 0) { + result = ma_result_from_pulse(pulseResult); + goto done; + } + + framesMapped = bytesMapped / bpf; + + if (deviceState == ma_device_state_started || deviceState == ma_device_state_starting) { /* Check for starting state just in case this is being used to do the initial fill. */ + ma_device_handle_backend_data_callback(pDevice, pMappedPCMFrames, NULL, framesMapped); + } else { + /* Device is not started. Write silence. */ + ma_silence_pcm_frames(pMappedPCMFrames, framesMapped, pDevice->playback.format, pDevice->playback.channels); + } + + pulseResult = ((ma_pa_stream_write_proc)pDevice->pContext->pulse.pa_stream_write)(pStream, pMappedPCMFrames, bytesMapped, NULL, 0, MA_PA_SEEK_RELATIVE); + if (pulseResult < 0) { + result = ma_result_from_pulse(pulseResult); + goto done; /* Failed to write data to stream. */ + } + + framesProcessed += framesMapped; + } else { + result = MA_SUCCESS; /* No data available for writing. */ + goto done; + } + } else { + result = MA_ERROR; /* Failed to retrieve the writable size. Abort. */ + goto done; + } + +done: + if (pFramesProcessed != NULL) { + *pFramesProcessed = framesProcessed; + } + + return result; +} + +static void ma_device_on_write__pulse(ma_pa_stream* pStream, size_t byteCount, void* pUserData) +{ + ma_device* pDevice = (ma_device*)pUserData; + ma_uint32 bpf; + ma_uint64 frameCount; + ma_uint64 framesProcessed; + ma_uint32 deviceState; + ma_result result; + + MA_ASSERT(pDevice != NULL); + + /* + Don't do anything if the device isn't initialized yet. Yes, this can happen because PulseAudio + can fire this callback before the stream has even started. Ridiculous. + */ + deviceState = ma_device_get_state(pDevice); + if (deviceState != ma_device_state_starting && deviceState != ma_device_state_started) { + return; + } + + bpf = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + MA_ASSERT(bpf > 0); + + frameCount = byteCount / bpf; + framesProcessed = 0; + + while (framesProcessed < frameCount) { + ma_uint64 framesProcessedThisIteration; + + /* Don't keep trying to process frames if the device isn't started. */ + deviceState = ma_device_get_state(pDevice); + if (deviceState != ma_device_state_starting && deviceState != ma_device_state_started) { + break; + } + + result = ma_device_write_to_stream__pulse(pDevice, pStream, &framesProcessedThisIteration); + if (result != MA_SUCCESS) { + break; + } + + framesProcessed += framesProcessedThisIteration; + } +} + +static void ma_device_on_suspended__pulse(ma_pa_stream* pStream, void* pUserData) +{ + ma_device* pDevice = (ma_device*)pUserData; + int suspended; + + (void)pStream; + + suspended = ((ma_pa_stream_is_suspended_proc)pDevice->pContext->pulse.pa_stream_is_suspended)(pStream); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[Pulse] Device suspended state changed. pa_stream_is_suspended() returned %d.\n", suspended); + + if (suspended < 0) { + return; + } + + if (suspended == 1) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[Pulse] Device suspended state changed. Suspended.\n"); + ma_device__on_notification_stopped(pDevice); + } else { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[Pulse] Device suspended state changed. Resumed.\n"); + ma_device__on_notification_started(pDevice); + } +} + +static void ma_device_on_rerouted__pulse(ma_pa_stream* pStream, void* pUserData) +{ + ma_device* pDevice = (ma_device*)pUserData; + + (void)pStream; + (void)pUserData; + + ma_device__on_notification_rerouted(pDevice); +} + +static ma_uint32 ma_calculate_period_size_in_frames_from_descriptor__pulse(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile) +{ + /* + There have been reports from users where buffers of < ~20ms result glitches when running through + PipeWire. To work around this we're going to have to use a different default buffer size. + */ + const ma_uint32 defaultPeriodSizeInMilliseconds_LowLatency = 25; + const ma_uint32 defaultPeriodSizeInMilliseconds_Conservative = MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE; + + MA_ASSERT(nativeSampleRate != 0); + + if (pDescriptor->periodSizeInFrames == 0) { + if (pDescriptor->periodSizeInMilliseconds == 0) { + if (performanceProfile == ma_performance_profile_low_latency) { + return ma_calculate_buffer_size_in_frames_from_milliseconds(defaultPeriodSizeInMilliseconds_LowLatency, nativeSampleRate); + } else { + return ma_calculate_buffer_size_in_frames_from_milliseconds(defaultPeriodSizeInMilliseconds_Conservative, nativeSampleRate); + } + } else { + return ma_calculate_buffer_size_in_frames_from_milliseconds(pDescriptor->periodSizeInMilliseconds, nativeSampleRate); + } + } else { + return pDescriptor->periodSizeInFrames; + } +} + +static ma_result ma_device_init__pulse(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture) +{ + /* + Notes for PulseAudio: + + - When both the period size in frames and milliseconds are 0, we default to miniaudio's + default buffer sizes rather than leaving it up to PulseAudio because I don't trust + PulseAudio to give us any kind of reasonable latency by default. + + - Do not ever, *ever* forget to use MA_PA_STREAM_ADJUST_LATENCY. If you don't specify this + flag, capture mode will just not work properly until you open another PulseAudio app. + */ + + ma_result result = MA_SUCCESS; + int error = 0; + const char* devPlayback = NULL; + const char* devCapture = NULL; + ma_format format = ma_format_unknown; + ma_uint32 channels = 0; + ma_uint32 sampleRate = 0; + ma_pa_sink_info sinkInfo; + ma_pa_source_info sourceInfo; + 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_buffer_attr* pActualAttr = NULL; + ma_uint32 iChannel; + ma_pa_stream_flags_t streamFlags; + + MA_ASSERT(pDevice != NULL); + MA_ZERO_OBJECT(&pDevice->pulse); + + if (pConfig->deviceType == ma_device_type_loopback) { + return MA_DEVICE_TYPE_NOT_SUPPORTED; + } + + /* 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) { + if (pDescriptorPlayback->pDeviceID != NULL) { + devPlayback = pDescriptorPlayback->pDeviceID->pulse; + } + + format = pDescriptorPlayback->format; + channels = pDescriptorPlayback->channels; + sampleRate = pDescriptorPlayback->sampleRate; + } + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + if (pDescriptorCapture->pDeviceID != NULL) { + devCapture = pDescriptorCapture->pDeviceID->pulse; + } + + format = pDescriptorCapture->format; + channels = pDescriptorCapture->channels; + sampleRate = pDescriptorCapture->sampleRate; + } + + + + result = ma_init_pa_mainloop_and_pa_context__pulse(pDevice->pContext, pDevice->pContext->pulse.pApplicationName, pDevice->pContext->pulse.pServerName, MA_FALSE, &pDevice->pulse.pMainLoop, &pDevice->pulse.pPulseContext); + if (result != MA_SUCCESS) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to initialize PA mainloop and context for device.\n"); + return result; + } + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + result = ma_context_get_source_info__pulse(pDevice->pContext, devCapture, &sourceInfo); + if (result != MA_SUCCESS) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to retrieve source info for capture device."); + goto on_error0; + } + + ss = sourceInfo.sample_spec; + cmap = sourceInfo.channel_map; + + /* Use the requested channel count if we have one. */ + if (pDescriptorCapture->channels != 0) { + ss.channels = pDescriptorCapture->channels; + } + + /* Use a default channel map. */ + ((ma_pa_channel_map_init_extend_proc)pDevice->pContext->pulse.pa_channel_map_init_extend)(&cmap, ss.channels, MA_PA_CHANNEL_MAP_DEFAULT); + + /* Use the requested sample rate if one was specified. */ + if (pDescriptorCapture->sampleRate != 0) { + ss.rate = pDescriptorCapture->sampleRate; + } + streamFlags = MA_PA_STREAM_START_CORKED | MA_PA_STREAM_ADJUST_LATENCY; + + if (ma_format_from_pulse(ss.format) == ma_format_unknown) { + if (ma_is_little_endian()) { + ss.format = MA_PA_SAMPLE_FLOAT32LE; + } else { + ss.format = MA_PA_SAMPLE_FLOAT32BE; + } + streamFlags |= MA_PA_STREAM_FIX_FORMAT; + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.format not supported by miniaudio. Defaulting to PA_SAMPLE_FLOAT32.\n"); + } + if (ss.rate == 0) { + ss.rate = MA_DEFAULT_SAMPLE_RATE; + streamFlags |= MA_PA_STREAM_FIX_RATE; + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.rate = 0. Defaulting to %d.\n", ss.rate); + } + if (ss.channels == 0) { + ss.channels = MA_DEFAULT_CHANNELS; + streamFlags |= MA_PA_STREAM_FIX_CHANNELS; + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.channels = 0. Defaulting to %d.\n", ss.channels); + } + + /* We now have enough information to calculate our actual period size in frames. */ + pDescriptorCapture->periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__pulse(pDescriptorCapture, ss.rate, pConfig->performanceProfile); + + attr = ma_device__pa_buffer_attr_new(pDescriptorCapture->periodSizeInFrames, pDescriptorCapture->periodCount, &ss); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Capture attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; periodSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, pDescriptorCapture->periodSizeInFrames); + + pDevice->pulse.pStreamCapture = ma_device__pa_stream_new__pulse(pDevice, pConfig->pulse.pStreamNameCapture, &ss, &cmap); + if (pDevice->pulse.pStreamCapture == NULL) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio capture stream.\n"); + result = MA_ERROR; + goto on_error0; + } + + + /* The callback needs to be set before connecting the stream. */ + ((ma_pa_stream_set_read_callback_proc)pDevice->pContext->pulse.pa_stream_set_read_callback)((ma_pa_stream*)pDevice->pulse.pStreamCapture, ma_device_on_read__pulse, pDevice); + + /* State callback for checking when the device has been corked. */ + ((ma_pa_stream_set_suspended_callback_proc)pDevice->pContext->pulse.pa_stream_set_suspended_callback)((ma_pa_stream*)pDevice->pulse.pStreamCapture, ma_device_on_suspended__pulse, pDevice); + + /* Rerouting notification. */ + ((ma_pa_stream_set_moved_callback_proc)pDevice->pContext->pulse.pa_stream_set_moved_callback)((ma_pa_stream*)pDevice->pulse.pStreamCapture, ma_device_on_rerouted__pulse, pDevice); + + + /* Connect after we've got all of our internal state set up. */ + if (devCapture != NULL) { + streamFlags |= MA_PA_STREAM_DONT_MOVE; + } + + error = ((ma_pa_stream_connect_record_proc)pDevice->pContext->pulse.pa_stream_connect_record)((ma_pa_stream*)pDevice->pulse.pStreamCapture, devCapture, &attr, streamFlags); + if (error != MA_PA_OK) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to connect PulseAudio capture stream."); + result = ma_result_from_pulse(error); + goto on_error1; + } + + result = ma_wait_for_pa_stream_to_connect__pulse(pDevice->pContext, pDevice->pulse.pMainLoop, (ma_pa_stream*)pDevice->pulse.pStreamCapture); + if (result != MA_SUCCESS) { + goto on_error2; + } + + + /* Internal format. */ + pActualSS = ((ma_pa_stream_get_sample_spec_proc)pDevice->pContext->pulse.pa_stream_get_sample_spec)((ma_pa_stream*)pDevice->pulse.pStreamCapture); + if (pActualSS != NULL) { + ss = *pActualSS; + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Capture sample spec: format=%s, channels=%d, rate=%d\n", ma_get_format_name(ma_format_from_pulse(ss.format)), ss.channels, ss.rate); + } else { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Failed to retrieve capture sample spec.\n"); + } + + pDescriptorCapture->format = ma_format_from_pulse(ss.format); + pDescriptorCapture->channels = ss.channels; + pDescriptorCapture->sampleRate = ss.rate; + + if (pDescriptorCapture->format == ma_format_unknown || pDescriptorCapture->channels == 0 || pDescriptorCapture->sampleRate == 0) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Capture sample spec is invalid. Device unusable by miniaudio. format=%s, channels=%d, sampleRate=%d.\n", ma_get_format_name(pDescriptorCapture->format), pDescriptorCapture->channels, pDescriptorCapture->sampleRate); + result = MA_ERROR; + goto on_error4; + } + + /* Internal channel map. */ + + /* + Bug in PipeWire. There have been reports that PipeWire is returning AUX channels when reporting + the channel map. To somewhat workaround this, I'm hacking in a hard coded channel map for mono + and stereo. In this case it should be safe to assume mono = MONO and stereo = LEFT/RIGHT. For + all other channel counts we need to just put up with whatever PipeWire reports and hope it gets + fixed sooner than later. I might remove this hack later. + */ + if (pDescriptorCapture->channels > 2) { + for (iChannel = 0; iChannel < pDescriptorCapture->channels; ++iChannel) { + pDescriptorCapture->channelMap[iChannel] = ma_channel_position_from_pulse(cmap.map[iChannel]); + } + } else { + /* Hack for mono and stereo. */ + if (pDescriptorCapture->channels == 1) { + pDescriptorCapture->channelMap[0] = MA_CHANNEL_MONO; + } else if (pDescriptorCapture->channels == 2) { + pDescriptorCapture->channelMap[0] = MA_CHANNEL_FRONT_LEFT; + pDescriptorCapture->channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + } else { + MA_ASSERT(MA_FALSE); /* Should never hit this. */ + } + } + + + /* Buffer. */ + pActualAttr = ((ma_pa_stream_get_buffer_attr_proc)pDevice->pContext->pulse.pa_stream_get_buffer_attr)((ma_pa_stream*)pDevice->pulse.pStreamCapture); + if (pActualAttr != NULL) { + attr = *pActualAttr; + } + + if (attr.fragsize > 0) { + pDescriptorCapture->periodCount = ma_max(attr.maxlength / attr.fragsize, 1); + } else { + pDescriptorCapture->periodCount = 1; + } + + pDescriptorCapture->periodSizeInFrames = attr.maxlength / ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels) / pDescriptorCapture->periodCount; + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Capture actual attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; periodSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, pDescriptorCapture->periodSizeInFrames); + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + result = ma_context_get_sink_info__pulse(pDevice->pContext, devPlayback, &sinkInfo); + if (result != MA_SUCCESS) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to retrieve sink info for playback device.\n"); + goto on_error2; + } + + ss = sinkInfo.sample_spec; + cmap = sinkInfo.channel_map; + + /* Use the requested channel count if we have one. */ + if (pDescriptorPlayback->channels != 0) { + ss.channels = pDescriptorPlayback->channels; + } + + /* Use a default channel map. */ + ((ma_pa_channel_map_init_extend_proc)pDevice->pContext->pulse.pa_channel_map_init_extend)(&cmap, ss.channels, MA_PA_CHANNEL_MAP_DEFAULT); + + + /* Use the requested sample rate if one was specified. */ + if (pDescriptorPlayback->sampleRate != 0) { + ss.rate = pDescriptorPlayback->sampleRate; + } + + streamFlags = MA_PA_STREAM_START_CORKED | MA_PA_STREAM_ADJUST_LATENCY; + if (ma_format_from_pulse(ss.format) == ma_format_unknown) { + if (ma_is_little_endian()) { + ss.format = MA_PA_SAMPLE_FLOAT32LE; + } else { + ss.format = MA_PA_SAMPLE_FLOAT32BE; + } + streamFlags |= MA_PA_STREAM_FIX_FORMAT; + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.format not supported by miniaudio. Defaulting to PA_SAMPLE_FLOAT32.\n"); + } + if (ss.rate == 0) { + ss.rate = MA_DEFAULT_SAMPLE_RATE; + streamFlags |= MA_PA_STREAM_FIX_RATE; + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.rate = 0. Defaulting to %d.\n", ss.rate); + } + if (ss.channels == 0) { + ss.channels = MA_DEFAULT_CHANNELS; + streamFlags |= MA_PA_STREAM_FIX_CHANNELS; + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.channels = 0. Defaulting to %d.\n", ss.channels); + } + + /* We now have enough information to calculate the actual buffer size in frames. */ + pDescriptorPlayback->periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__pulse(pDescriptorPlayback, ss.rate, pConfig->performanceProfile); + + attr = ma_device__pa_buffer_attr_new(pDescriptorPlayback->periodSizeInFrames, pDescriptorPlayback->periodCount, &ss); + + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Playback attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; periodSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, pDescriptorPlayback->periodSizeInFrames); + + pDevice->pulse.pStreamPlayback = ma_device__pa_stream_new__pulse(pDevice, pConfig->pulse.pStreamNamePlayback, &ss, &cmap); + if (pDevice->pulse.pStreamPlayback == NULL) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio playback stream.\n"); + result = MA_ERROR; + goto on_error2; + } + + + /* + Note that this callback will be fired as soon as the stream is connected, even though it's started as corked. The callback needs to handle a + device state of ma_device_state_uninitialized. + */ + ((ma_pa_stream_set_write_callback_proc)pDevice->pContext->pulse.pa_stream_set_write_callback)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, ma_device_on_write__pulse, pDevice); + + /* State callback for checking when the device has been corked. */ + ((ma_pa_stream_set_suspended_callback_proc)pDevice->pContext->pulse.pa_stream_set_suspended_callback)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, ma_device_on_suspended__pulse, pDevice); + + /* Rerouting notification. */ + ((ma_pa_stream_set_moved_callback_proc)pDevice->pContext->pulse.pa_stream_set_moved_callback)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, ma_device_on_rerouted__pulse, pDevice); + + + /* Connect after we've got all of our internal state set up. */ + if (devPlayback != NULL) { + streamFlags |= MA_PA_STREAM_DONT_MOVE; + } + + error = ((ma_pa_stream_connect_playback_proc)pDevice->pContext->pulse.pa_stream_connect_playback)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, devPlayback, &attr, streamFlags, NULL, NULL); + if (error != MA_PA_OK) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to connect PulseAudio playback stream."); + result = ma_result_from_pulse(error); + goto on_error3; + } + + result = ma_wait_for_pa_stream_to_connect__pulse(pDevice->pContext, pDevice->pulse.pMainLoop, (ma_pa_stream*)pDevice->pulse.pStreamPlayback); + if (result != MA_SUCCESS) { + goto on_error3; + } + + + /* Internal format. */ + pActualSS = ((ma_pa_stream_get_sample_spec_proc)pDevice->pContext->pulse.pa_stream_get_sample_spec)((ma_pa_stream*)pDevice->pulse.pStreamPlayback); + if (pActualSS != NULL) { + ss = *pActualSS; + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Playback sample spec: format=%s, channels=%d, rate=%d\n", ma_get_format_name(ma_format_from_pulse(ss.format)), ss.channels, ss.rate); + } else { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Failed to retrieve playback sample spec.\n"); + } + + pDescriptorPlayback->format = ma_format_from_pulse(ss.format); + pDescriptorPlayback->channels = ss.channels; + pDescriptorPlayback->sampleRate = ss.rate; + + if (pDescriptorPlayback->format == ma_format_unknown || pDescriptorPlayback->channels == 0 || pDescriptorPlayback->sampleRate == 0) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Playback sample spec is invalid. Device unusable by miniaudio. format=%s, channels=%d, sampleRate=%d.\n", ma_get_format_name(pDescriptorPlayback->format), pDescriptorPlayback->channels, pDescriptorPlayback->sampleRate); + result = MA_ERROR; + goto on_error4; + } + + /* Internal channel map. */ + + /* + Bug in PipeWire. There have been reports that PipeWire is returning AUX channels when reporting + the channel map. To somewhat workaround this, I'm hacking in a hard coded channel map for mono + and stereo. In this case it should be safe to assume mono = MONO and stereo = LEFT/RIGHT. For + all other channel counts we need to just put up with whatever PipeWire reports and hope it gets + fixed sooner than later. I might remove this hack later. + */ + if (pDescriptorPlayback->channels > 2) { + for (iChannel = 0; iChannel < pDescriptorPlayback->channels; ++iChannel) { + pDescriptorPlayback->channelMap[iChannel] = ma_channel_position_from_pulse(cmap.map[iChannel]); + } + } else { + /* Hack for mono and stereo. */ + if (pDescriptorPlayback->channels == 1) { + pDescriptorPlayback->channelMap[0] = MA_CHANNEL_MONO; + } else if (pDescriptorPlayback->channels == 2) { + pDescriptorPlayback->channelMap[0] = MA_CHANNEL_FRONT_LEFT; + pDescriptorPlayback->channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + } else { + MA_ASSERT(MA_FALSE); /* Should never hit this. */ + } + } + + + /* Buffer. */ + pActualAttr = ((ma_pa_stream_get_buffer_attr_proc)pDevice->pContext->pulse.pa_stream_get_buffer_attr)((ma_pa_stream*)pDevice->pulse.pStreamPlayback); + if (pActualAttr != NULL) { + attr = *pActualAttr; + } + + if (attr.tlength > 0) { + pDescriptorPlayback->periodCount = ma_max(attr.maxlength / attr.tlength, 1); + } else { + pDescriptorPlayback->periodCount = 1; + } + + pDescriptorPlayback->periodSizeInFrames = attr.maxlength / ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels) / pDescriptorPlayback->periodCount; + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Playback actual attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; internalPeriodSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, pDescriptorPlayback->periodSizeInFrames); + } + + + /* + We need a ring buffer for handling duplex mode. We can use the main duplex ring buffer in the main + part of the ma_device struct. We cannot, however, depend on ma_device_init() initializing this for + us later on because that will only do it if it's a fully asynchronous backend - i.e. the + onDeviceDataLoop callback is NULL, which is not the case for PulseAudio. + */ + if (pConfig->deviceType == ma_device_type_duplex) { + ma_format rbFormat = (format != ma_format_unknown) ? format : pDescriptorCapture->format; + ma_uint32 rbChannels = (channels > 0) ? channels : pDescriptorCapture->channels; + ma_uint32 rbSampleRate = (sampleRate > 0) ? sampleRate : pDescriptorCapture->sampleRate; + + result = ma_duplex_rb_init(rbFormat, rbChannels, rbSampleRate, pDescriptorCapture->sampleRate, pDescriptorCapture->periodSizeInFrames, &pDevice->pContext->allocationCallbacks, &pDevice->duplexRB); + if (result != MA_SUCCESS) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to initialize ring buffer. %s.\n", ma_result_description(result)); + goto on_error4; + } + } + + return MA_SUCCESS; + + +on_error4: + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + ((ma_pa_stream_disconnect_proc)pDevice->pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamPlayback); + } +on_error3: + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + ((ma_pa_stream_unref_proc)pDevice->pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamPlayback); + } +on_error2: + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + ((ma_pa_stream_disconnect_proc)pDevice->pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamCapture); + } +on_error1: + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + ((ma_pa_stream_unref_proc)pDevice->pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamCapture); + } +on_error0: + return result; +} + + +static 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; + + (void)pStream; /* Unused. */ +} + +static ma_result ma_device__cork_stream__pulse(ma_device* pDevice, ma_device_type deviceType, int cork) +{ + ma_context* pContext = pDevice->pContext; + 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; + } + + wasSuccessful = MA_FALSE; + + pStream = (ma_pa_stream*)((deviceType == ma_device_type_capture) ? pDevice->pulse.pStreamCapture : pDevice->pulse.pStreamPlayback); + MA_ASSERT(pStream != NULL); + + pOP = ((ma_pa_stream_cork_proc)pContext->pulse.pa_stream_cork)(pStream, cork, ma_pulse_operation_complete_callback, &wasSuccessful); + if (pOP == NULL) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to cork PulseAudio stream."); + return MA_ERROR; + } + + result = ma_wait_for_operation_and_unref__pulse(pDevice->pContext, pDevice->pulse.pMainLoop, pOP); + if (result != MA_SUCCESS) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while waiting for the PulseAudio stream to cork."); + return result; + } + + if (!wasSuccessful) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to %s PulseAudio stream.", (cork) ? "stop" : "start"); + return MA_ERROR; + } + + return MA_SUCCESS; +} + +static ma_result ma_device_start__pulse(ma_device* pDevice) +{ + ma_result result; + + 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, 0); + if (result != MA_SUCCESS) { + return result; + } + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + /* + We need to fill some data before uncorking. Not doing this will result in the write callback + never getting fired. We're not going to abort if writing fails because I still want the device + to get uncorked. + */ + ma_device_write_to_stream__pulse(pDevice, (ma_pa_stream*)(pDevice->pulse.pStreamPlayback), NULL); /* No need to check the result here. Always want to fall through an uncork.*/ + + result = ma_device__cork_stream__pulse(pDevice, ma_device_type_playback, 0); + if (result != MA_SUCCESS) { + return result; + } + } + + return MA_SUCCESS; +} + +static ma_result ma_device_stop__pulse(ma_device* pDevice) +{ + ma_result result; + + 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) { + /* + Ideally we would drain the device here, but there's been cases where PulseAudio seems to be + broken on some systems to the point where no audio processing seems to happen. When this + happens, draining never completes and we get stuck here. For now I'm disabling draining of + the device so we don't just freeze the application. + */ + #if 0 + ma_pa_operation* pOP = ((ma_pa_stream_drain_proc)pDevice->pContext->pulse.pa_stream_drain)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, ma_pulse_operation_complete_callback, &wasSuccessful); + ma_wait_for_operation_and_unref__pulse(pDevice->pContext, pDevice->pulse.pMainLoop, pOP); + #endif + + result = ma_device__cork_stream__pulse(pDevice, ma_device_type_playback, 1); + if (result != MA_SUCCESS) { + return result; + } + } + + return MA_SUCCESS; +} + +static ma_result ma_device_data_loop__pulse(ma_device* pDevice) +{ + int resultPA; + + MA_ASSERT(pDevice != NULL); + + /* NOTE: Don't start the device here. It'll be done at a higher level. */ + + /* + All data is handled through callbacks. All we need to do is iterate over the main loop and let + the callbacks deal with it. + */ + while (ma_device_get_state(pDevice) == ma_device_state_started) { + resultPA = ((ma_pa_mainloop_iterate_proc)pDevice->pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL); + if (resultPA < 0) { + break; + } + } + + /* NOTE: Don't stop the device here. It'll be done at a higher level. */ + return MA_SUCCESS; +} + +static ma_result ma_device_data_loop_wakeup__pulse(ma_device* pDevice) +{ + MA_ASSERT(pDevice != NULL); + + ((ma_pa_mainloop_wakeup_proc)pDevice->pContext->pulse.pa_mainloop_wakeup)((ma_pa_mainloop*)pDevice->pulse.pMainLoop); + + return MA_SUCCESS; +} + +static ma_result ma_context_uninit__pulse(ma_context* pContext) +{ + MA_ASSERT(pContext != NULL); + MA_ASSERT(pContext->backend == ma_backend_pulseaudio); + + ((ma_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)((ma_pa_context*)pContext->pulse.pPulseContext); + ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)((ma_pa_context*)pContext->pulse.pPulseContext); + ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)pContext->pulse.pMainLoop); + + ma_free(pContext->pulse.pServerName, &pContext->allocationCallbacks); + ma_free(pContext->pulse.pApplicationName, &pContext->allocationCallbacks); + +#ifndef MA_NO_RUNTIME_LINKING + ma_dlclose(ma_context_get_log(pContext), pContext->pulse.pulseSO); +#endif + + return MA_SUCCESS; +} + +static ma_result ma_context_init__pulse(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks) +{ + ma_result result; +#ifndef MA_NO_RUNTIME_LINKING + const char* libpulseNames[] = { + "libpulse.so", + "libpulse.so.0" + }; + size_t i; + + for (i = 0; i < ma_countof(libpulseNames); ++i) { + pContext->pulse.pulseSO = ma_dlopen(ma_context_get_log(pContext), 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(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_mainloop_new"); + pContext->pulse.pa_mainloop_free = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_mainloop_free"); + pContext->pulse.pa_mainloop_quit = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_mainloop_quit"); + pContext->pulse.pa_mainloop_get_api = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_mainloop_get_api"); + pContext->pulse.pa_mainloop_iterate = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_mainloop_iterate"); + pContext->pulse.pa_mainloop_wakeup = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_mainloop_wakeup"); + pContext->pulse.pa_threaded_mainloop_new = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_new"); + pContext->pulse.pa_threaded_mainloop_free = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_free"); + pContext->pulse.pa_threaded_mainloop_start = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_start"); + pContext->pulse.pa_threaded_mainloop_stop = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_stop"); + pContext->pulse.pa_threaded_mainloop_lock = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_lock"); + pContext->pulse.pa_threaded_mainloop_unlock = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_unlock"); + pContext->pulse.pa_threaded_mainloop_wait = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_wait"); + pContext->pulse.pa_threaded_mainloop_signal = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_signal"); + pContext->pulse.pa_threaded_mainloop_accept = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_accept"); + pContext->pulse.pa_threaded_mainloop_get_retval = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_get_retval"); + pContext->pulse.pa_threaded_mainloop_get_api = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_get_api"); + pContext->pulse.pa_threaded_mainloop_in_thread = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_in_thread"); + pContext->pulse.pa_threaded_mainloop_set_name = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_set_name"); + pContext->pulse.pa_context_new = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_context_new"); + pContext->pulse.pa_context_unref = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_context_unref"); + pContext->pulse.pa_context_connect = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_context_connect"); + pContext->pulse.pa_context_disconnect = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_context_disconnect"); + pContext->pulse.pa_context_set_state_callback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_context_set_state_callback"); + pContext->pulse.pa_context_get_state = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_context_get_state"); + pContext->pulse.pa_context_get_sink_info_list = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_context_get_sink_info_list"); + pContext->pulse.pa_context_get_source_info_list = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_context_get_source_info_list"); + pContext->pulse.pa_context_get_sink_info_by_name = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_context_get_sink_info_by_name"); + pContext->pulse.pa_context_get_source_info_by_name = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_context_get_source_info_by_name"); + pContext->pulse.pa_operation_unref = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_operation_unref"); + pContext->pulse.pa_operation_get_state = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_operation_get_state"); + pContext->pulse.pa_channel_map_init_extend = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_channel_map_init_extend"); + pContext->pulse.pa_channel_map_valid = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_channel_map_valid"); + pContext->pulse.pa_channel_map_compatible = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_channel_map_compatible"); + pContext->pulse.pa_stream_new = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_new"); + pContext->pulse.pa_stream_unref = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_unref"); + pContext->pulse.pa_stream_connect_playback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_connect_playback"); + pContext->pulse.pa_stream_connect_record = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_connect_record"); + pContext->pulse.pa_stream_disconnect = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_disconnect"); + pContext->pulse.pa_stream_get_state = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_get_state"); + pContext->pulse.pa_stream_get_sample_spec = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_get_sample_spec"); + pContext->pulse.pa_stream_get_channel_map = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_get_channel_map"); + pContext->pulse.pa_stream_get_buffer_attr = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_get_buffer_attr"); + pContext->pulse.pa_stream_set_buffer_attr = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_set_buffer_attr"); + pContext->pulse.pa_stream_get_device_name = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_get_device_name"); + pContext->pulse.pa_stream_set_write_callback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_set_write_callback"); + pContext->pulse.pa_stream_set_read_callback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_set_read_callback"); + pContext->pulse.pa_stream_set_suspended_callback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_set_suspended_callback"); + pContext->pulse.pa_stream_set_moved_callback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_set_moved_callback"); + pContext->pulse.pa_stream_is_suspended = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_is_suspended"); + pContext->pulse.pa_stream_flush = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_flush"); + pContext->pulse.pa_stream_drain = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_drain"); + pContext->pulse.pa_stream_is_corked = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_is_corked"); + pContext->pulse.pa_stream_cork = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_cork"); + pContext->pulse.pa_stream_trigger = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_trigger"); + pContext->pulse.pa_stream_begin_write = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_begin_write"); + pContext->pulse.pa_stream_write = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_write"); + pContext->pulse.pa_stream_peek = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_peek"); + pContext->pulse.pa_stream_drop = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_drop"); + pContext->pulse.pa_stream_writable_size = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_writable_size"); + pContext->pulse.pa_stream_readable_size = (ma_proc)ma_dlsym(ma_context_get_log(pContext), 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_quit_proc _pa_mainloop_quit = pa_mainloop_quit; + 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_threaded_mainloop_new_proc _pa_threaded_mainloop_new = pa_threaded_mainloop_new; + ma_pa_threaded_mainloop_free_proc _pa_threaded_mainloop_free = pa_threaded_mainloop_free; + ma_pa_threaded_mainloop_start_proc _pa_threaded_mainloop_start = pa_threaded_mainloop_start; + ma_pa_threaded_mainloop_stop_proc _pa_threaded_mainloop_stop = pa_threaded_mainloop_stop; + ma_pa_threaded_mainloop_lock_proc _pa_threaded_mainloop_lock = pa_threaded_mainloop_lock; + ma_pa_threaded_mainloop_unlock_proc _pa_threaded_mainloop_unlock = pa_threaded_mainloop_unlock; + ma_pa_threaded_mainloop_wait_proc _pa_threaded_mainloop_wait = pa_threaded_mainloop_wait; + ma_pa_threaded_mainloop_signal_proc _pa_threaded_mainloop_signal = pa_threaded_mainloop_signal; + ma_pa_threaded_mainloop_accept_proc _pa_threaded_mainloop_accept = pa_threaded_mainloop_accept; + ma_pa_threaded_mainloop_get_retval_proc _pa_threaded_mainloop_get_retval = pa_threaded_mainloop_get_retval; + ma_pa_threaded_mainloop_get_api_proc _pa_threaded_mainloop_get_api = pa_threaded_mainloop_get_api; + ma_pa_threaded_mainloop_in_thread_proc _pa_threaded_mainloop_in_thread = pa_threaded_mainloop_in_thread; + ma_pa_threaded_mainloop_set_name_proc _pa_threaded_mainloop_set_name = pa_threaded_mainloop_set_name; + 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_set_suspended_callback_proc _pa_stream_set_suspended_callback = pa_stream_set_suspended_callback; + ma_pa_stream_set_moved_callback_proc _pa_stream_set_moved_callback = pa_stream_set_moved_callback; + ma_pa_stream_is_suspended_proc _pa_stream_is_suspended = pa_stream_is_suspended; + 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_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; + 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_quit = (ma_proc)_pa_mainloop_quit; + 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_threaded_mainloop_new = (ma_proc)_pa_threaded_mainloop_new; + pContext->pulse.pa_threaded_mainloop_free = (ma_proc)_pa_threaded_mainloop_free; + pContext->pulse.pa_threaded_mainloop_start = (ma_proc)_pa_threaded_mainloop_start; + pContext->pulse.pa_threaded_mainloop_stop = (ma_proc)_pa_threaded_mainloop_stop; + pContext->pulse.pa_threaded_mainloop_lock = (ma_proc)_pa_threaded_mainloop_lock; + pContext->pulse.pa_threaded_mainloop_unlock = (ma_proc)_pa_threaded_mainloop_unlock; + pContext->pulse.pa_threaded_mainloop_wait = (ma_proc)_pa_threaded_mainloop_wait; + pContext->pulse.pa_threaded_mainloop_signal = (ma_proc)_pa_threaded_mainloop_signal; + pContext->pulse.pa_threaded_mainloop_accept = (ma_proc)_pa_threaded_mainloop_accept; + pContext->pulse.pa_threaded_mainloop_get_retval = (ma_proc)_pa_threaded_mainloop_get_retval; + pContext->pulse.pa_threaded_mainloop_get_api = (ma_proc)_pa_threaded_mainloop_get_api; + pContext->pulse.pa_threaded_mainloop_in_thread = (ma_proc)_pa_threaded_mainloop_in_thread; + pContext->pulse.pa_threaded_mainloop_set_name = (ma_proc)_pa_threaded_mainloop_set_name; + 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_set_suspended_callback = (ma_proc)_pa_stream_set_suspended_callback; + pContext->pulse.pa_stream_set_moved_callback = (ma_proc)_pa_stream_set_moved_callback; + pContext->pulse.pa_stream_is_suspended = (ma_proc)_pa_stream_is_suspended; + 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 + + /* We need to make a copy of the application and server names so we can pass them to the pa_context of each device. */ + pContext->pulse.pApplicationName = ma_copy_string(pConfig->pulse.pApplicationName, &pContext->allocationCallbacks); + if (pContext->pulse.pApplicationName == NULL && pConfig->pulse.pApplicationName != NULL) { + return MA_OUT_OF_MEMORY; + } + + pContext->pulse.pServerName = ma_copy_string(pConfig->pulse.pServerName, &pContext->allocationCallbacks); + if (pContext->pulse.pServerName == NULL && pConfig->pulse.pServerName != NULL) { + ma_free(pContext->pulse.pApplicationName, &pContext->allocationCallbacks); + return MA_OUT_OF_MEMORY; + } + + result = ma_init_pa_mainloop_and_pa_context__pulse(pContext, pConfig->pulse.pApplicationName, pConfig->pulse.pServerName, pConfig->pulse.tryAutoSpawn, &pContext->pulse.pMainLoop, &pContext->pulse.pPulseContext); + if (result != MA_SUCCESS) { + ma_free(pContext->pulse.pServerName, &pContext->allocationCallbacks); + ma_free(pContext->pulse.pApplicationName, &pContext->allocationCallbacks); + #ifndef MA_NO_RUNTIME_LINKING + ma_dlclose(ma_context_get_log(pContext), pContext->pulse.pulseSO); + #endif + return result; + } + + /* With pa_mainloop we run a synchronous backend, but we implement our own main loop. */ + pCallbacks->onContextInit = ma_context_init__pulse; + pCallbacks->onContextUninit = ma_context_uninit__pulse; + pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__pulse; + pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__pulse; + pCallbacks->onDeviceInit = ma_device_init__pulse; + pCallbacks->onDeviceUninit = ma_device_uninit__pulse; + pCallbacks->onDeviceStart = ma_device_start__pulse; + pCallbacks->onDeviceStop = ma_device_stop__pulse; + pCallbacks->onDeviceRead = NULL; /* Not used because we're implementing onDeviceDataLoop. */ + pCallbacks->onDeviceWrite = NULL; /* Not used because we're implementing onDeviceDataLoop. */ + pCallbacks->onDeviceDataLoop = ma_device_data_loop__pulse; + pCallbacks->onDeviceDataLoopWakeup = ma_device_data_loop_wakeup__pulse; + + 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) (void); +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); + +static 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); + + if (ppClient) { + *ppClient = NULL; + } + + 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); + + 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; + } + + if (ppClient) { + *ppClient = pClient; + } + + return MA_SUCCESS; +} + + +static 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); + + /* 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); + deviceInfo.isDefault = MA_TRUE; /* JACK only uses default devices. */ + 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); + deviceInfo.isDefault = MA_TRUE; /* JACK only uses default devices. */ + cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData); + } + + (void)cbResult; /* For silencing a static analysis warning. */ + + return MA_SUCCESS; +} + +static ma_result ma_context_get_device_info__jack(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo) +{ + ma_jack_client_t* pClient; + ma_result result; + const char** ppPorts; + + MA_ASSERT(pContext != NULL); + + 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 uses default devices. */ + pDeviceInfo->isDefault = MA_TRUE; + + /* Jack only supports f32 and has a specific channel count and sample rate. */ + pDeviceInfo->nativeDataFormats[0].format = ma_format_f32; + + /* 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) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[JACK] Failed to open client."); + return result; + } + + pDeviceInfo->nativeDataFormats[0].sampleRate = ((ma_jack_get_sample_rate_proc)pContext->jack.jack_get_sample_rate)((ma_jack_client_t*)pClient); + pDeviceInfo->nativeDataFormats[0].channels = 0; + + ppPorts = ((ma_jack_get_ports_proc)pContext->jack.jack_get_ports)((ma_jack_client_t*)pClient, NULL, MA_JACK_DEFAULT_AUDIO_TYPE, 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); + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[JACK] Failed to query physical ports."); + return MA_FAILED_TO_OPEN_BACKEND_DEVICE; + } + + while (ppPorts[pDeviceInfo->nativeDataFormats[0].channels] != NULL) { + pDeviceInfo->nativeDataFormats[0].channels += 1; + } + + pDeviceInfo->nativeDataFormats[0].flags = 0; + pDeviceInfo->nativeDataFormatCount = 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); + + (void)pContext; + return MA_SUCCESS; +} + + +static ma_result ma_device_uninit__jack(ma_device* pDevice) +{ + ma_context* pContext; + + MA_ASSERT(pDevice != NULL); + + 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, &pDevice->pContext->allocationCallbacks); + ma_free(pDevice->jack.ppPortsCapture, &pDevice->pContext->allocationCallbacks); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + ma_free(pDevice->jack.pIntermediaryBufferPlayback, &pDevice->pContext->allocationCallbacks); + ma_free(pDevice->jack.ppPortsPlayback, &pDevice->pContext->allocationCallbacks); + } + + return MA_SUCCESS; +} + +static 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); +} + +static 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) { + size_t newBufferSize = frameCount * (pDevice->capture.internalChannels * ma_get_bytes_per_sample(pDevice->capture.internalFormat)); + float* pNewBuffer = (float*)ma_calloc(newBufferSize, &pDevice->pContext->allocationCallbacks); + if (pNewBuffer == NULL) { + return MA_OUT_OF_MEMORY; + } + + ma_free(pDevice->jack.pIntermediaryBufferCapture, &pDevice->pContext->allocationCallbacks); + + pDevice->jack.pIntermediaryBufferCapture = pNewBuffer; + pDevice->playback.internalPeriodSizeInFrames = frameCount; + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + size_t newBufferSize = frameCount * (pDevice->playback.internalChannels * ma_get_bytes_per_sample(pDevice->playback.internalFormat)); + float* pNewBuffer = (float*)ma_calloc(newBufferSize, &pDevice->pContext->allocationCallbacks); + if (pNewBuffer == NULL) { + return MA_OUT_OF_MEMORY; + } + + ma_free(pDevice->jack.pIntermediaryBufferPlayback, &pDevice->pContext->allocationCallbacks); + + pDevice->jack.pIntermediaryBufferPlayback = pNewBuffer; + pDevice->playback.internalPeriodSizeInFrames = frameCount; + } + + return 0; +} + +static int ma_device__jack_process_callback(ma_jack_nframes_t frameCount, void* pUserData) +{ + ma_device* pDevice; + ma_context* pContext; + ma_uint32 iChannel; + + pDevice = (ma_device*)pUserData; + MA_ASSERT(pDevice != NULL); + + 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 (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.ppPortsCapture[iChannel], frameCount); + if (pSrc != NULL) { + float* pDst = pDevice->jack.pIntermediaryBufferCapture + iChannel; + ma_jack_nframes_t iFrame; + for (iFrame = 0; iFrame < frameCount; ++iFrame) { + *pDst = *pSrc; + + pDst += pDevice->capture.internalChannels; + pSrc += 1; + } + } + } + + ma_device_handle_backend_data_callback(pDevice, NULL, pDevice->jack.pIntermediaryBufferCapture, frameCount); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + ma_device_handle_backend_data_callback(pDevice, pDevice->jack.pIntermediaryBufferPlayback, NULL, frameCount); + + /* 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.ppPortsPlayback[iChannel], frameCount); + if (pDst != NULL) { + const float* pSrc = pDevice->jack.pIntermediaryBufferPlayback + iChannel; + ma_jack_nframes_t iFrame; + for (iFrame = 0; iFrame < frameCount; ++iFrame) { + *pDst = *pSrc; + + pDst += 1; + pSrc += pDevice->playback.internalChannels; + } + } + } + } + + return 0; +} + +static ma_result ma_device_init__jack(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture) +{ + ma_result result; + ma_uint32 periodSizeInFrames; + + MA_ASSERT(pConfig != NULL); + MA_ASSERT(pDevice != NULL); + + if (pConfig->deviceType == ma_device_type_loopback) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Loopback mode not supported."); + return MA_DEVICE_TYPE_NOT_SUPPORTED; + } + + /* Only supporting default devices with JACK. */ + if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->pDeviceID != NULL && pDescriptorPlayback->pDeviceID->jack != 0) || + ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->pDeviceID != NULL && pDescriptorCapture->pDeviceID->jack != 0)) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Only default devices are supported."); + return MA_NO_DEVICE; + } + + /* No exclusive mode with the JACK backend. */ + if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive) || + ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive)) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Exclusive mode not supported."); + return MA_SHARE_MODE_NOT_SUPPORTED; + } + + /* Open the client. */ + result = ma_context_open_client__jack(pDevice->pContext, (ma_jack_client_t**)&pDevice->jack.pClient); + if (result != MA_SUCCESS) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to open client."); + return result; + } + + /* Callbacks. */ + if (((ma_jack_set_process_callback_proc)pDevice->pContext->jack.jack_set_process_callback)((ma_jack_client_t*)pDevice->jack.pClient, ma_device__jack_process_callback, pDevice) != 0) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to set process callback."); + return MA_FAILED_TO_OPEN_BACKEND_DEVICE; + } + if (((ma_jack_set_buffer_size_callback_proc)pDevice->pContext->jack.jack_set_buffer_size_callback)((ma_jack_client_t*)pDevice->jack.pClient, ma_device__jack_buffer_size_callback, pDevice) != 0) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to set buffer size callback."); + return MA_FAILED_TO_OPEN_BACKEND_DEVICE; + } + + ((ma_jack_on_shutdown_proc)pDevice->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. */ + periodSizeInFrames = ((ma_jack_get_buffer_size_proc)pDevice->pContext->jack.jack_get_buffer_size)((ma_jack_client_t*)pDevice->jack.pClient); + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + ma_uint32 iPort; + const char** ppPorts; + + pDescriptorCapture->format = ma_format_f32; + pDescriptorCapture->channels = 0; + pDescriptorCapture->sampleRate = ((ma_jack_get_sample_rate_proc)pDevice->pContext->jack.jack_get_sample_rate)((ma_jack_client_t*)pDevice->jack.pClient); + ma_channel_map_init_standard(ma_standard_channel_map_alsa, pDescriptorCapture->channelMap, ma_countof(pDescriptorCapture->channelMap), pDescriptorCapture->channels); + + ppPorts = ((ma_jack_get_ports_proc)pDevice->pContext->jack.jack_get_ports)((ma_jack_client_t*)pDevice->jack.pClient, NULL, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsPhysical | ma_JackPortIsOutput); + if (ppPorts == NULL) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to query physical ports."); + return MA_FAILED_TO_OPEN_BACKEND_DEVICE; + } + + /* Need to count the number of ports first so we can allocate some memory. */ + while (ppPorts[pDescriptorCapture->channels] != NULL) { + pDescriptorCapture->channels += 1; + } + + pDevice->jack.ppPortsCapture = (ma_ptr*)ma_malloc(sizeof(*pDevice->jack.ppPortsCapture) * pDescriptorCapture->channels, &pDevice->pContext->allocationCallbacks); + if (pDevice->jack.ppPortsCapture == NULL) { + return MA_OUT_OF_MEMORY; + } + + for (iPort = 0; iPort < pDescriptorCapture->channels; iPort += 1) { + char name[64]; + ma_strcpy_s(name, sizeof(name), "capture"); + ma_itoa_s((int)iPort, name+7, sizeof(name)-7, 10); /* 7 = length of "capture" */ + + pDevice->jack.ppPortsCapture[iPort] = ((ma_jack_port_register_proc)pDevice->pContext->jack.jack_port_register)((ma_jack_client_t*)pDevice->jack.pClient, name, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsInput, 0); + if (pDevice->jack.ppPortsCapture[iPort] == NULL) { + ((ma_jack_free_proc)pDevice->pContext->jack.jack_free)((void*)ppPorts); + ma_device_uninit__jack(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to register ports."); + return MA_FAILED_TO_OPEN_BACKEND_DEVICE; + } + } + + ((ma_jack_free_proc)pDevice->pContext->jack.jack_free)((void*)ppPorts); + + pDescriptorCapture->periodSizeInFrames = periodSizeInFrames; + pDescriptorCapture->periodCount = 1; /* There's no notion of a period in JACK. Just set to 1. */ + + pDevice->jack.pIntermediaryBufferCapture = (float*)ma_calloc(pDescriptorCapture->periodSizeInFrames * ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels), &pDevice->pContext->allocationCallbacks); + 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) { + ma_uint32 iPort; + const char** ppPorts; + + pDescriptorPlayback->format = ma_format_f32; + pDescriptorPlayback->channels = 0; + pDescriptorPlayback->sampleRate = ((ma_jack_get_sample_rate_proc)pDevice->pContext->jack.jack_get_sample_rate)((ma_jack_client_t*)pDevice->jack.pClient); + ma_channel_map_init_standard(ma_standard_channel_map_alsa, pDescriptorPlayback->channelMap, ma_countof(pDescriptorPlayback->channelMap), pDescriptorPlayback->channels); + + ppPorts = ((ma_jack_get_ports_proc)pDevice->pContext->jack.jack_get_ports)((ma_jack_client_t*)pDevice->jack.pClient, NULL, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsPhysical | ma_JackPortIsInput); + if (ppPorts == NULL) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to query physical ports."); + return MA_FAILED_TO_OPEN_BACKEND_DEVICE; + } + + /* Need to count the number of ports first so we can allocate some memory. */ + while (ppPorts[pDescriptorPlayback->channels] != NULL) { + pDescriptorPlayback->channels += 1; + } + + pDevice->jack.ppPortsPlayback = (ma_ptr*)ma_malloc(sizeof(*pDevice->jack.ppPortsPlayback) * pDescriptorPlayback->channels, &pDevice->pContext->allocationCallbacks); + if (pDevice->jack.ppPortsPlayback == NULL) { + ma_free(pDevice->jack.ppPortsCapture, &pDevice->pContext->allocationCallbacks); + return MA_OUT_OF_MEMORY; + } + + for (iPort = 0; iPort < pDescriptorPlayback->channels; iPort += 1) { + char name[64]; + ma_strcpy_s(name, sizeof(name), "playback"); + ma_itoa_s((int)iPort, name+8, sizeof(name)-8, 10); /* 8 = length of "playback" */ + + pDevice->jack.ppPortsPlayback[iPort] = ((ma_jack_port_register_proc)pDevice->pContext->jack.jack_port_register)((ma_jack_client_t*)pDevice->jack.pClient, name, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsOutput, 0); + if (pDevice->jack.ppPortsPlayback[iPort] == NULL) { + ((ma_jack_free_proc)pDevice->pContext->jack.jack_free)((void*)ppPorts); + ma_device_uninit__jack(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to register ports."); + return MA_FAILED_TO_OPEN_BACKEND_DEVICE; + } + } + + ((ma_jack_free_proc)pDevice->pContext->jack.jack_free)((void*)ppPorts); + + pDescriptorPlayback->periodSizeInFrames = periodSizeInFrames; + pDescriptorPlayback->periodCount = 1; /* There's no notion of a period in JACK. Just set to 1. */ + + pDevice->jack.pIntermediaryBufferPlayback = (float*)ma_calloc(pDescriptorPlayback->periodSizeInFrames * ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels), &pDevice->pContext->allocationCallbacks); + if (pDevice->jack.pIntermediaryBufferPlayback == NULL) { + ma_device_uninit__jack(pDevice); + return MA_OUT_OF_MEMORY; + } + } + + return MA_SUCCESS; +} + + +static ma_result ma_device_start__jack(ma_device* pDevice) +{ + ma_context* pContext = pDevice->pContext; + int resultJACK; + size_t i; + + resultJACK = ((ma_jack_activate_proc)pContext->jack.jack_activate)((ma_jack_client_t*)pDevice->jack.pClient); + if (resultJACK != 0) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to activate the JACK client."); + return 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, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsPhysical | ma_JackPortIsOutput); + if (ppServerPorts == NULL) { + ((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to retrieve physical ports."); + return MA_ERROR; + } + + 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.ppPortsCapture[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); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to connect ports."); + return 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, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsPhysical | ma_JackPortIsInput); + if (ppServerPorts == NULL) { + ((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to retrieve physical ports."); + return MA_ERROR; + } + + 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.ppPortsPlayback[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); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to connect ports."); + return MA_ERROR; + } + } + + ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts); + } + + return MA_SUCCESS; +} + +static ma_result ma_device_stop__jack(ma_device* pDevice) +{ + ma_context* pContext = pDevice->pContext; + + if (((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient) != 0) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] An error occurred when deactivating the JACK client."); + return MA_ERROR; + } + + ma_device__on_notification_stopped(pDevice); + + return MA_SUCCESS; +} + + +static 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->allocationCallbacks); + pContext->jack.pClientName = NULL; + +#ifndef MA_NO_RUNTIME_LINKING + ma_dlclose(ma_context_get_log(pContext), pContext->jack.jackSO); +#endif + + return MA_SUCCESS; +} + +static ma_result ma_context_init__jack(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks) +{ +#ifndef MA_NO_RUNTIME_LINKING + const char* libjackNames[] = { +#if defined(MA_WIN32) + "libjack.dll", + "libjack64.dll" +#endif +#if defined(MA_UNIX) + "libjack.so", + "libjack.so.0" +#endif + }; + size_t i; + + for (i = 0; i < ma_countof(libjackNames); ++i) { + pContext->jack.jackSO = ma_dlopen(ma_context_get_log(pContext), 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(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_client_open"); + pContext->jack.jack_client_close = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_client_close"); + pContext->jack.jack_client_name_size = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_client_name_size"); + pContext->jack.jack_set_process_callback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_set_process_callback"); + pContext->jack.jack_set_buffer_size_callback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_set_buffer_size_callback"); + pContext->jack.jack_on_shutdown = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_on_shutdown"); + pContext->jack.jack_get_sample_rate = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_get_sample_rate"); + pContext->jack.jack_get_buffer_size = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_get_buffer_size"); + pContext->jack.jack_get_ports = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_get_ports"); + pContext->jack.jack_activate = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_activate"); + pContext->jack.jack_deactivate = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_deactivate"); + pContext->jack.jack_connect = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_connect"); + pContext->jack.jack_port_register = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_port_register"); + pContext->jack.jack_port_name = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_port_name"); + pContext->jack.jack_port_get_buffer = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_port_get_buffer"); + pContext->jack.jack_free = (ma_proc)ma_dlsym(ma_context_get_log(pContext), 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 + + if (pConfig->jack.pClientName != NULL) { + pContext->jack.pClientName = ma_copy_string(pConfig->jack.pClientName, &pContext->allocationCallbacks); + } + 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, &pContext->allocationCallbacks); + #ifndef MA_NO_RUNTIME_LINKING + ma_dlclose(ma_context_get_log(pContext), pContext->jack.jackSO); + #endif + return MA_NO_BACKEND; + } + + ((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pDummyClient); + } + + + pCallbacks->onContextInit = ma_context_init__jack; + pCallbacks->onContextUninit = ma_context_uninit__jack; + pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__jack; + pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__jack; + pCallbacks->onDeviceInit = ma_device_init__jack; + pCallbacks->onDeviceUninit = ma_device_uninit__jack; + pCallbacks->onDeviceStart = ma_device_start__jack; + pCallbacks->onDeviceStop = ma_device_stop__jack; + pCallbacks->onDeviceRead = NULL; /* Not used because JACK is asynchronous. */ + pCallbacks->onDeviceWrite = NULL; /* Not used because JACK is asynchronous. */ + pCallbacks->onDeviceDataLoop = NULL; /* Not used because JACK is asynchronous. */ + + return MA_SUCCESS; +} +#endif /* JACK */ + + + +/****************************************************************************** + +Core Audio Backend + +References +========== +- Technical Note TN2091: Device input using the HAL Output Audio Unit + https://developer.apple.com/library/archive/technotes/tn2091/_index.html + +******************************************************************************/ +#ifdef MA_HAS_COREAUDIO +#include + +#if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1 + #define MA_APPLE_MOBILE + #if defined(TARGET_OS_TV) && TARGET_OS_TV == 1 + #define MA_APPLE_TV + #endif + #if defined(TARGET_OS_WATCH) && TARGET_OS_WATCH == 1 + #define MA_APPLE_WATCH + #endif + #if __has_feature(objc_arc) + #define MA_BRIDGE_TRANSFER __bridge_transfer + #define MA_BRIDGE_RETAINED __bridge_retained + #else + #define MA_BRIDGE_TRANSFER + #define MA_BRIDGE_RETAINED + #endif +#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); +typedef void (* ma_CFRelease_proc)(CFTypeRef cf); + +/* 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); +typedef OSStatus (* ma_AudioObjectRemovePropertyListener_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 + +#if defined(MA_APPLE_DESKTOP) +static ma_result ma_device_reinit_internal__coreaudio(ma_device* pDevice, ma_device_type deviceType, ma_bool32 disposePreviousAudioUnit); +#endif + +/* +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 +kAudioObjectPropertyElementMain 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. +*/ + +#if defined(MA_APPLE_MOBILE) +static void ma_device__on_notification_interruption_began(ma_device* pDevice) +{ + ma_device__on_notification(ma_device_notification_init(pDevice, ma_device_notification_type_interruption_began)); +} + +static void ma_device__on_notification_interruption_ended(ma_device* pDevice) +{ + ma_device__on_notification(ma_device_notification_init(pDevice, ma_device_notification_type_interruption_ended)); +} +#endif + +static 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 +static 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 + +static 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; +} + +#if defined(MA_APPLE_DESKTOP) +static 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; + } +} + +static ma_result ma_get_channel_map_from_AudioChannelLayout(AudioChannelLayout* pChannelLayout, ma_channel* pChannelMap, size_t channelMapCap) +{ + MA_ASSERT(pChannelLayout != NULL); + + if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelDescriptions) { + UInt32 iChannel; + for (iChannel = 0; iChannel < pChannelLayout->mNumberChannelDescriptions && iChannel < channelMapCap; ++iChannel) { + pChannelMap[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; + UInt32 iBit; + AudioChannelBitmap bitmap = pChannelLayout->mChannelBitmap; + for (iBit = 0; iBit < 32 && iChannel < channelMapCap; ++iBit) { + AudioChannelBitmap bit = bitmap & (1 << iBit); + if (bit != 0) { + pChannelMap[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; + + /* Our channel map retrieval APIs below take 32-bit integers, so we'll want to clamp the channel map capacity. */ + if (channelMapCap > 0xFFFFFFFF) { + channelMapCap = 0xFFFFFFFF; + } + + channelCount = ma_min(AudioChannelLayoutTag_GetNumberOfChannels(pChannelLayout->mChannelLayoutTag), (UInt32)channelMapCap); + + 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_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, channelCount); + } break; + + case kAudioChannelLayoutTag_Octagonal: + { + pChannelMap[7] = MA_CHANNEL_SIDE_RIGHT; + pChannelMap[6] = MA_CHANNEL_SIDE_LEFT; + } MA_FALLTHROUGH; /* Intentional fallthrough. */ + case kAudioChannelLayoutTag_Hexagonal: + { + pChannelMap[5] = MA_CHANNEL_BACK_CENTER; + } MA_FALLTHROUGH; /* Intentional fallthrough. */ + case kAudioChannelLayoutTag_Pentagonal: + { + pChannelMap[4] = MA_CHANNEL_FRONT_CENTER; + } MA_FALLTHROUGH; /* Intentional fallthrough. */ + case kAudioChannelLayoutTag_Quadraphonic: + { + pChannelMap[3] = MA_CHANNEL_BACK_RIGHT; + pChannelMap[2] = MA_CHANNEL_BACK_LEFT; + pChannelMap[1] = MA_CHANNEL_RIGHT; + pChannelMap[0] = MA_CHANNEL_LEFT; + } break; + + /* TODO: Add support for more tags here. */ + + default: + { + ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, channelCount); + } break; + } + } + + return MA_SUCCESS; +} + +#if (defined(MAC_OS_VERSION_12_0) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_12_0) || \ + (defined(__IPHONE_15_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_15_0) +#define AUDIO_OBJECT_PROPERTY_ELEMENT kAudioObjectPropertyElementMain +#else +/* kAudioObjectPropertyElementMaster is deprecated. */ +#define AUDIO_OBJECT_PROPERTY_ELEMENT kAudioObjectPropertyElementMaster +#endif + +static 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); + + /* Safety. */ + *pDeviceCount = 0; + *ppDeviceObjectIDs = NULL; + + propAddressDevices.mSelector = kAudioHardwarePropertyDevices; + propAddressDevices.mScope = kAudioObjectPropertyScopeGlobal; + propAddressDevices.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT; + + status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(kAudioObjectSystemObject, &propAddressDevices, 0, NULL, &deviceObjectsDataSize); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } + + pDeviceObjectIDs = (AudioObjectID*)ma_malloc(deviceObjectsDataSize, &pContext->allocationCallbacks); + 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, &pContext->allocationCallbacks); + return ma_result_from_OSStatus(status); + } + + *pDeviceCount = deviceObjectsDataSize / sizeof(AudioObjectID); + *ppDeviceObjectIDs = pDeviceObjectIDs; + + return MA_SUCCESS; +} + +static 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); + + propAddress.mSelector = kAudioDevicePropertyDeviceUID; + propAddress.mScope = kAudioObjectPropertyScopeGlobal; + propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT; + + 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); + } + + return MA_SUCCESS; +} + +static 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); + + 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; + } + + ((ma_CFRelease_proc)pContext->coreaudio.CFRelease)(uid); + return MA_SUCCESS; +} + +static 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); + + propAddress.mSelector = kAudioDevicePropertyDeviceNameCFString; + propAddress.mScope = kAudioObjectPropertyScopeGlobal; + propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT; + + 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); + } + + if (!((ma_CFStringGetCString_proc)pContext->coreaudio.CFStringGetCString)(deviceName, bufferOut, bufferSize, kCFStringEncodingUTF8)) { + return MA_ERROR; + } + + ((ma_CFRelease_proc)pContext->coreaudio.CFRelease)(deviceName); + return MA_SUCCESS; +} + +static 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. */ + propAddress.mSelector = kAudioDevicePropertyStreamConfiguration; + propAddress.mScope = scope; + propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT; + + status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize); + if (status != noErr) { + return MA_FALSE; + } + + pBufferList = (AudioBufferList*)ma_malloc(dataSize, &pContext->allocationCallbacks); + 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, &pContext->allocationCallbacks); + return MA_FALSE; + } + + isSupported = MA_FALSE; + if (pBufferList->mNumberBuffers > 0) { + isSupported = MA_TRUE; + } + + ma_free(pBufferList, &pContext->allocationCallbacks); + return isSupported; +} + +static ma_bool32 ma_does_AudioObject_support_playback(ma_context* pContext, AudioObjectID deviceObjectID) +{ + return ma_does_AudioObject_support_scope(pContext, deviceObjectID, kAudioObjectPropertyScopeOutput); +} + +static ma_bool32 ma_does_AudioObject_support_capture(ma_context* pContext, AudioObjectID deviceObjectID) +{ + return ma_does_AudioObject_support_scope(pContext, deviceObjectID, kAudioObjectPropertyScopeInput); +} + + +static 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. + */ + propAddress.mSelector = kAudioStreamPropertyAvailableVirtualFormats; /*kAudioStreamPropertyAvailablePhysicalFormats;*/ + propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput; + propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT; + + status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } + + pDescriptions = (AudioStreamRangedDescription*)ma_malloc(dataSize, &pContext->allocationCallbacks); + 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, &pContext->allocationCallbacks); + return ma_result_from_OSStatus(status); + } + + *pDescriptionCount = dataSize / sizeof(*pDescriptions); + *ppDescriptions = pDescriptions; + return MA_SUCCESS; +} + + +static 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. */ + + propAddress.mSelector = kAudioDevicePropertyPreferredChannelLayout; + propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput; + propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT; + + status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } + + pChannelLayout = (AudioChannelLayout*)ma_malloc(dataSize, &pContext->allocationCallbacks); + 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, &pContext->allocationCallbacks); + return ma_result_from_OSStatus(status); + } + + *ppChannelLayout = pChannelLayout; + return MA_SUCCESS; +} + +static 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. */ + + 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, &pContext->allocationCallbacks); + return MA_SUCCESS; +} + +#if 0 +static ma_result ma_get_AudioObject_channel_map(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_channel* pChannelMap, size_t channelMapCap) +{ + AudioChannelLayout* pChannelLayout; + ma_result result; + + MA_ASSERT(pContext != NULL); + + 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, pChannelMap, channelMapCap); + if (result != MA_SUCCESS) { + ma_free(pChannelLayout, &pContext->allocationCallbacks); + return result; + } + + ma_free(pChannelLayout, &pContext->allocationCallbacks); + return result; +} +#endif + +static 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. */ + *pSampleRateRangesCount = 0; + *ppSampleRateRanges = NULL; + + propAddress.mSelector = kAudioDevicePropertyAvailableNominalSampleRates; + propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput; + propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT; + + status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } + + pSampleRateRanges = (AudioValueRange*)ma_malloc(dataSize, &pContext->allocationCallbacks); + 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, &pContext->allocationCallbacks); + return ma_result_from_OSStatus(status); + } + + *pSampleRateRangesCount = dataSize / sizeof(*pSampleRateRanges); + *ppSampleRateRanges = pSampleRateRanges; + return MA_SUCCESS; +} + +#if 0 +static 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. */ + + result = ma_get_AudioObject_sample_rates(pContext, deviceObjectID, deviceType, &sampleRateRangeCount, &pSampleRateRanges); + if (result != MA_SUCCESS) { + return result; + } + + if (sampleRateRangeCount == 0) { + ma_free(pSampleRateRanges, &pContext->allocationCallbacks); + return MA_ERROR; /* Should never hit this case should we? */ + } + + if (sampleRateIn == 0) { + /* 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]; + UInt32 iCASampleRate; + for (iCASampleRate = 0; iCASampleRate < sampleRateRangeCount; ++iCASampleRate) { + AudioValueRange caSampleRate = pSampleRateRanges[iCASampleRate]; + if (caSampleRate.mMinimum <= malSampleRate && caSampleRate.mMaximum >= malSampleRate) { + *pSampleRateOut = malSampleRate; + ma_free(pSampleRateRanges, &pContext->allocationCallbacks); + 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, &pContext->allocationCallbacks); + return MA_SUCCESS; + } else { + /* Find the closest match to this sample rate. */ + UInt32 currentAbsoluteDifference = INT32_MAX; + UInt32 iCurrentClosestRange = (UInt32)-1; + UInt32 iRange; + for (iRange = 0; iRange < sampleRateRangeCount; ++iRange) { + if (pSampleRateRanges[iRange].mMinimum <= sampleRateIn && pSampleRateRanges[iRange].mMaximum >= sampleRateIn) { + *pSampleRateOut = sampleRateIn; + ma_free(pSampleRateRanges, &pContext->allocationCallbacks); + 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, &pContext->allocationCallbacks); + return MA_SUCCESS; + } + + /* Should never get here, but it would mean we weren't able to find any suitable sample rates. */ + /*ma_free(pSampleRateRanges, &pContext->allocationCallbacks);*/ + /*return MA_ERROR;*/ +} +#endif + +static 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. */ + + propAddress.mSelector = kAudioDevicePropertyBufferFrameSizeRange; + propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput; + propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT; + + 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. */ + 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; +} + +static ma_result ma_set_AudioObject_buffer_size_in_frames(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_uint32* pPeriodSizeInOut) +{ + ma_result result; + ma_uint32 chosenBufferSizeInFrames; + AudioObjectPropertyAddress propAddress; + UInt32 dataSize; + OSStatus status; + + MA_ASSERT(pContext != NULL); + + result = ma_get_AudioObject_closest_buffer_size_in_frames(pContext, deviceObjectID, deviceType, *pPeriodSizeInOut, &chosenBufferSizeInFrames); + if (result != MA_SUCCESS) { + return result; + } + + /* 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 = AUDIO_OBJECT_PROPERTY_ELEMENT; + + ((ma_AudioObjectSetPropertyData_proc)pContext->coreaudio.AudioObjectSetPropertyData)(deviceObjectID, &propAddress, 0, NULL, sizeof(chosenBufferSizeInFrames), &chosenBufferSizeInFrames); + + /* Get the actual size of the buffer. */ + dataSize = sizeof(*pPeriodSizeInOut); + status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, &chosenBufferSizeInFrames); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } + + *pPeriodSizeInOut = chosenBufferSizeInFrames; + return MA_SUCCESS; +} + +static ma_result ma_find_default_AudioObjectID(ma_context* pContext, ma_device_type deviceType, AudioObjectID* pDeviceObjectID) +{ + AudioObjectPropertyAddress propAddressDefaultDevice; + UInt32 defaultDeviceObjectIDSize = sizeof(AudioObjectID); + AudioObjectID defaultDeviceObjectID; + OSStatus status; + + MA_ASSERT(pContext != NULL); + MA_ASSERT(pDeviceObjectID != NULL); + + /* Safety. */ + *pDeviceObjectID = 0; + + propAddressDefaultDevice.mScope = kAudioObjectPropertyScopeGlobal; + propAddressDefaultDevice.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT; + if (deviceType == ma_device_type_playback) { + propAddressDefaultDevice.mSelector = kAudioHardwarePropertyDefaultOutputDevice; + } else { + propAddressDefaultDevice.mSelector = kAudioHardwarePropertyDefaultInputDevice; + } + + defaultDeviceObjectIDSize = sizeof(AudioObjectID); + status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(kAudioObjectSystemObject, &propAddressDefaultDevice, 0, NULL, &defaultDeviceObjectIDSize, &defaultDeviceObjectID); + if (status == noErr) { + *pDeviceObjectID = defaultDeviceObjectID; + return MA_SUCCESS; + } + + /* If we get here it means we couldn't find the device. */ + return MA_NO_DEVICE; +} + +static 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. */ + return ma_find_default_AudioObjectID(pContext, deviceType, pDeviceObjectID); + } else { + /* Explicit device. */ + UInt32 deviceCount; + AudioObjectID* pDeviceObjectIDs; + ma_result result; + UInt32 iDevice; + + result = ma_get_device_object_ids__coreaudio(pContext, &deviceCount, &pDeviceObjectIDs); + if (result != MA_SUCCESS) { + return result; + } + + for (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; + ma_free(pDeviceObjectIDs, &pContext->allocationCallbacks); + return MA_SUCCESS; + } + } + } else { + if (ma_does_AudioObject_support_capture(pContext, deviceObjectID)) { + if (strcmp(uid, pDeviceID->coreaudio) == 0) { + *pDeviceObjectID = deviceObjectID; + ma_free(pDeviceObjectIDs, &pContext->allocationCallbacks); + return MA_SUCCESS; + } + } + } + } + + ma_free(pDeviceObjectIDs, &pContext->allocationCallbacks); + } + + /* If we get here it means we couldn't find the device. */ + return MA_NO_DEVICE; +} + + +static 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, const AudioStreamBasicDescription* pOrigFormat, AudioStreamBasicDescription* pFormat) +{ + UInt32 deviceFormatDescriptionCount; + AudioStreamRangedDescription* 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; + } + + desiredSampleRate = sampleRate; + if (desiredSampleRate == 0) { + desiredSampleRate = pOrigFormat->mSampleRate; + } + + desiredChannelCount = channels; + if (desiredChannelCount == 0) { + desiredChannelCount = pOrigFormat->mChannelsPerFrame; + } + + desiredFormat = format; + if (desiredFormat == ma_format_unknown) { + result = ma_format_from_AudioStreamBasicDescription(pOrigFormat, &desiredFormat); + if (result != MA_SUCCESS || desiredFormat == ma_format_unknown) { + 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. + */ + MA_ZERO_OBJECT(&bestDeviceFormatSoFar); + + hasSupportedFormat = MA_FALSE; + for (iFormat = 0; iFormat < deviceFormatDescriptionCount; ++iFormat) { + ma_format formatFromDescription; + ma_result formatResult = ma_format_from_AudioStreamBasicDescription(&pDeviceFormatDescriptions[iFormat].mFormat, &formatFromDescription); + if (formatResult == MA_SUCCESS && formatFromDescription != ma_format_unknown) { + hasSupportedFormat = MA_TRUE; + bestDeviceFormatSoFar = pDeviceFormatDescriptions[iFormat].mFormat; + break; + } + } + + if (!hasSupportedFormat) { + ma_free(pDeviceFormatDescriptions, &pContext->allocationCallbacks); + return MA_FORMAT_NOT_SUPPORTED; + } + + + for (iFormat = 0; iFormat < deviceFormatDescriptionCount; ++iFormat) { + AudioStreamBasicDescription thisDeviceFormat = pDeviceFormatDescriptions[iFormat].mFormat; + ma_format 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. */ + } + + 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; + + ma_free(pDeviceFormatDescriptions, &pContext->allocationCallbacks); + return MA_SUCCESS; +} + +static ma_result ma_get_AudioUnit_channel_map(ma_context* pContext, AudioUnit audioUnit, ma_device_type deviceType, ma_channel* pChannelMap, size_t channelMapCap) +{ + 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_Input; + deviceBus = MA_COREAUDIO_OUTPUT_BUS; + } else { + deviceScope = kAudioUnitScope_Output; + deviceBus = MA_COREAUDIO_INPUT_BUS; + } + + status = ((ma_AudioUnitGetPropertyInfo_proc)pContext->coreaudio.AudioUnitGetPropertyInfo)(audioUnit, kAudioUnitProperty_AudioChannelLayout, deviceScope, deviceBus, &channelLayoutSize, NULL); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } + + pChannelLayout = (AudioChannelLayout*)ma_malloc(channelLayoutSize, &pContext->allocationCallbacks); + 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, &pContext->allocationCallbacks); + return ma_result_from_OSStatus(status); + } + + result = ma_get_channel_map_from_AudioChannelLayout(pChannelLayout, pChannelMap, channelMapCap); + if (result != MA_SUCCESS) { + ma_free(pChannelLayout, &pContext->allocationCallbacks); + return result; + } + + ma_free(pChannelLayout, &pContext->allocationCallbacks); + return MA_SUCCESS; +} +#endif /* MA_APPLE_DESKTOP */ + + +#if !defined(MA_APPLE_DESKTOP) +static void ma_AVAudioSessionPortDescription_to_device_info(AVAudioSessionPortDescription* pPortDesc, ma_device_info* pInfo) +{ + MA_ZERO_OBJECT(pInfo); + ma_strncpy_s(pInfo->name, sizeof(pInfo->name), [pPortDesc.portName UTF8String], (size_t)-1); + ma_strncpy_s(pInfo->id.coreaudio, sizeof(pInfo->id.coreaudio), [pPortDesc.UID UTF8String], (size_t)-1); +} +#endif + +static ma_result ma_context_enumerate_devices__coreaudio(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) +{ +#if defined(MA_APPLE_DESKTOP) + UInt32 deviceCount; + AudioObjectID* pDeviceObjectIDs; + AudioObjectID defaultDeviceObjectIDPlayback; + AudioObjectID defaultDeviceObjectIDCapture; + ma_result result; + UInt32 iDevice; + + ma_find_default_AudioObjectID(pContext, ma_device_type_playback, &defaultDeviceObjectIDPlayback); /* OK if this fails. */ + ma_find_default_AudioObjectID(pContext, ma_device_type_capture, &defaultDeviceObjectIDCapture); /* OK if this fails. */ + + result = ma_get_device_object_ids__coreaudio(pContext, &deviceCount, &pDeviceObjectIDs); + if (result != MA_SUCCESS) { + return result; + } + + 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; + } + if (ma_get_AudioObject_name(pContext, deviceObjectID, sizeof(info.name), info.name) != MA_SUCCESS) { + continue; + } + + if (ma_does_AudioObject_support_playback(pContext, deviceObjectID)) { + if (deviceObjectID == defaultDeviceObjectIDPlayback) { + info.isDefault = MA_TRUE; + } + + if (!callback(pContext, ma_device_type_playback, &info, pUserData)) { + break; + } + } + if (ma_does_AudioObject_support_capture(pContext, deviceObjectID)) { + if (deviceObjectID == defaultDeviceObjectIDCapture) { + info.isDefault = MA_TRUE; + } + + if (!callback(pContext, ma_device_type_capture, &info, pUserData)) { + break; + } + } + } + + ma_free(pDeviceObjectIDs, &pContext->allocationCallbacks); +#else + ma_device_info info; + NSArray *pInputs = [[[AVAudioSession sharedInstance] currentRoute] inputs]; + NSArray *pOutputs = [[[AVAudioSession sharedInstance] currentRoute] outputs]; + + for (AVAudioSessionPortDescription* pPortDesc in pOutputs) { + ma_AVAudioSessionPortDescription_to_device_info(pPortDesc, &info); + if (!callback(pContext, ma_device_type_playback, &info, pUserData)) { + return MA_SUCCESS; + } + } + + for (AVAudioSessionPortDescription* pPortDesc in pInputs) { + ma_AVAudioSessionPortDescription_to_device_info(pPortDesc, &info); + if (!callback(pContext, ma_device_type_capture, &info, pUserData)) { + return MA_SUCCESS; + } + } +#endif + + return MA_SUCCESS; +} + +static ma_result ma_context_get_device_info__coreaudio(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo) +{ + ma_result result; + + MA_ASSERT(pContext != NULL); + +#if defined(MA_APPLE_DESKTOP) + /* Desktop */ + { + AudioObjectID deviceObjectID; + AudioObjectID defaultDeviceObjectID; + UInt32 streamDescriptionCount; + AudioStreamRangedDescription* pStreamDescriptions; + UInt32 iStreamDescription; + UInt32 sampleRateRangeCount; + AudioValueRange* pSampleRateRanges; + + ma_find_default_AudioObjectID(pContext, deviceType, &defaultDeviceObjectID); /* OK if this fails. */ + + 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; + } + + if (deviceObjectID == defaultDeviceObjectID) { + pDeviceInfo->isDefault = MA_TRUE; + } + + /* + There could be a large number of permutations here. Fortunately there is only a single channel count + being reported which reduces this quite a bit. For sample rates we're only reporting those that are + one of miniaudio's recognized "standard" rates. If there are still more formats than can fit into + our fixed sized array we'll just need to truncate them. This is unlikely and will probably only happen + if some driver performs software data conversion and therefore reports every possible format and + sample rate. + */ + pDeviceInfo->nativeDataFormatCount = 0; + + /* Formats. */ + { + ma_format uniqueFormats[ma_format_count]; + ma_uint32 uniqueFormatCount = 0; + ma_uint32 channels; + + /* Channels. */ + result = ma_get_AudioObject_channel_count(pContext, deviceObjectID, deviceType, &channels); + if (result != MA_SUCCESS) { + return result; + } + + /* Formats. */ + result = ma_get_AudioObject_stream_descriptions(pContext, deviceObjectID, deviceType, &streamDescriptionCount, &pStreamDescriptions); + if (result != MA_SUCCESS) { + return result; + } + + for (iStreamDescription = 0; iStreamDescription < streamDescriptionCount; ++iStreamDescription) { + ma_format format; + ma_bool32 hasFormatBeenHandled = MA_FALSE; + ma_uint32 iOutputFormat; + ma_uint32 iSampleRate; + + 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. */ + for (iOutputFormat = 0; iOutputFormat < uniqueFormatCount; ++iOutputFormat) { + if (uniqueFormats[iOutputFormat] == format) { + hasFormatBeenHandled = MA_TRUE; + break; + } + } + + /* If we've already handled this format just skip it. */ + if (hasFormatBeenHandled) { + continue; + } + + uniqueFormats[uniqueFormatCount] = format; + uniqueFormatCount += 1; + + /* Sample Rates */ + result = ma_get_AudioObject_sample_rates(pContext, deviceObjectID, deviceType, &sampleRateRangeCount, &pSampleRateRanges); + if (result != MA_SUCCESS) { + return result; + } + + /* + Annoyingly Core Audio reports a sample rate range. We just get all the standard rates that are + between this range. + */ + for (iSampleRate = 0; iSampleRate < sampleRateRangeCount; ++iSampleRate) { + ma_uint32 iStandardSampleRate; + for (iStandardSampleRate = 0; iStandardSampleRate < ma_countof(g_maStandardSampleRatePriorities); iStandardSampleRate += 1) { + ma_uint32 standardSampleRate = g_maStandardSampleRatePriorities[iStandardSampleRate]; + if (standardSampleRate >= pSampleRateRanges[iSampleRate].mMinimum && standardSampleRate <= pSampleRateRanges[iSampleRate].mMaximum) { + /* We have a new data format. Add it to the list. */ + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = format; + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels; + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = standardSampleRate; + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = 0; + pDeviceInfo->nativeDataFormatCount += 1; + + if (pDeviceInfo->nativeDataFormatCount >= ma_countof(pDeviceInfo->nativeDataFormats)) { + break; /* No more room for any more formats. */ + } + } + } + } + + ma_free(pSampleRateRanges, &pContext->allocationCallbacks); + + if (pDeviceInfo->nativeDataFormatCount >= ma_countof(pDeviceInfo->nativeDataFormats)) { + break; /* No more room for any more formats. */ + } + } + + ma_free(pStreamDescriptions, &pContext->allocationCallbacks); + } + } +#else + /* Mobile */ + { + AudioComponentDescription desc; + AudioComponent component; + AudioUnit audioUnit; + OSStatus status; + AudioUnitScope formatScope; + AudioUnitElement formatElement; + AudioStreamBasicDescription bestFormat; + UInt32 propSize; + + /* We want to ensure we use a consistent device name to device enumeration. */ + if (pDeviceID != NULL && pDeviceID->coreaudio[0] != '\0') { + ma_bool32 found = MA_FALSE; + if (deviceType == ma_device_type_playback) { + NSArray *pOutputs = [[[AVAudioSession sharedInstance] currentRoute] outputs]; + for (AVAudioSessionPortDescription* pPortDesc in pOutputs) { + if (strcmp(pDeviceID->coreaudio, [pPortDesc.UID UTF8String]) == 0) { + ma_AVAudioSessionPortDescription_to_device_info(pPortDesc, pDeviceInfo); + found = MA_TRUE; + break; + } + } + } else { + NSArray *pInputs = [[[AVAudioSession sharedInstance] currentRoute] inputs]; + for (AVAudioSessionPortDescription* pPortDesc in pInputs) { + if (strcmp(pDeviceID->coreaudio, [pPortDesc.UID UTF8String]) == 0) { + ma_AVAudioSessionPortDescription_to_device_info(pPortDesc, pDeviceInfo); + found = MA_TRUE; + break; + } + } + } + + if (!found) { + return MA_DOES_NOT_EXIST; + } + } else { + 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. + */ + desc.componentType = kAudioUnitType_Output; + desc.componentSubType = kAudioUnitSubType_RemoteIO; + desc.componentManufacturer = kAudioUnitManufacturer_Apple; + desc.componentFlags = 0; + desc.componentFlagsMask = 0; + + component = ((ma_AudioComponentFindNext_proc)pContext->coreaudio.AudioComponentFindNext)(NULL, &desc); + if (component == NULL) { + return MA_FAILED_TO_INIT_BACKEND; + } + + status = ((ma_AudioComponentInstanceNew_proc)pContext->coreaudio.AudioComponentInstanceNew)(component, &audioUnit); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } + + formatScope = (deviceType == ma_device_type_playback) ? kAudioUnitScope_Input : kAudioUnitScope_Output; + formatElement = (deviceType == ma_device_type_playback) ? MA_COREAUDIO_OUTPUT_BUS : MA_COREAUDIO_INPUT_BUS; + + 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; + + /* Only a single format is being reported for iOS. */ + pDeviceInfo->nativeDataFormatCount = 1; + + result = ma_format_from_AudioStreamBasicDescription(&bestFormat, &pDeviceInfo->nativeDataFormats[0].format); + if (result != MA_SUCCESS) { + return result; + } + + pDeviceInfo->nativeDataFormats[0].channels = bestFormat.mChannelsPerFrame; + + /* + 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->nativeDataFormats[0].sampleRate = (ma_uint32)pAudioSession.sampleRate; + } + } +#endif + + (void)pDeviceInfo; /* Unused. */ + return MA_SUCCESS; +} + +static AudioBufferList* ma_allocate_AudioBufferList__coreaudio(ma_uint32 sizeInFrames, ma_format format, ma_uint32 channels, ma_stream_layout layout, const ma_allocation_callbacks* pAllocationCallbacks) +{ + AudioBufferList* pBufferList; + UInt32 audioBufferSizeInBytes; + size_t allocationSize; + + MA_ASSERT(sizeInFrames > 0); + MA_ASSERT(format != ma_format_unknown); + MA_ASSERT(channels > 0); + + allocationSize = sizeof(AudioBufferList) - sizeof(AudioBuffer); /* Subtract sizeof(AudioBuffer) because that part is dynamically sized. */ + if (layout == ma_stream_layout_interleaved) { + /* Interleaved case. This is the simple case because we just have one buffer. */ + allocationSize += sizeof(AudioBuffer) * 1; + } else { + /* Non-interleaved case. This is the more complex case because there's more than one buffer. */ + allocationSize += sizeof(AudioBuffer) * channels; + } + + allocationSize += sizeInFrames * ma_get_bytes_per_frame(format, channels); + + pBufferList = (AudioBufferList*)ma_malloc(allocationSize, pAllocationCallbacks); + if (pBufferList == NULL) { + return NULL; + } + + audioBufferSizeInBytes = (UInt32)(sizeInFrames * ma_get_bytes_per_sample(format)); + + if (layout == ma_stream_layout_interleaved) { + pBufferList->mNumberBuffers = 1; + pBufferList->mBuffers[0].mNumberChannels = channels; + pBufferList->mBuffers[0].mDataByteSize = audioBufferSizeInBytes * channels; + pBufferList->mBuffers[0].mData = (ma_uint8*)pBufferList + sizeof(AudioBufferList); + } else { + ma_uint32 iBuffer; + pBufferList->mNumberBuffers = channels; + for (iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; ++iBuffer) { + pBufferList->mBuffers[iBuffer].mNumberChannels = 1; + pBufferList->mBuffers[iBuffer].mDataByteSize = audioBufferSizeInBytes; + pBufferList->mBuffers[iBuffer].mData = (ma_uint8*)pBufferList + ((sizeof(AudioBufferList) - sizeof(AudioBuffer)) + (sizeof(AudioBuffer) * channels)) + (audioBufferSizeInBytes * iBuffer); + } + } + + return pBufferList; +} + +static ma_result ma_device_realloc_AudioBufferList__coreaudio(ma_device* pDevice, ma_uint32 sizeInFrames, ma_format format, ma_uint32 channels, ma_stream_layout layout) +{ + MA_ASSERT(pDevice != NULL); + MA_ASSERT(format != ma_format_unknown); + MA_ASSERT(channels > 0); + + /* Only resize the buffer if necessary. */ + if (pDevice->coreaudio.audioBufferCapInFrames < sizeInFrames) { + AudioBufferList* pNewAudioBufferList; + + pNewAudioBufferList = ma_allocate_AudioBufferList__coreaudio(sizeInFrames, format, channels, layout, &pDevice->pContext->allocationCallbacks); + if (pNewAudioBufferList == NULL) { + return MA_OUT_OF_MEMORY; + } + + /* At this point we'll have a new AudioBufferList and we can free the old one. */ + ma_free(pDevice->coreaudio.pAudioBufferList, &pDevice->pContext->allocationCallbacks); + pDevice->coreaudio.pAudioBufferList = pNewAudioBufferList; + pDevice->coreaudio.audioBufferCapInFrames = sizeInFrames; + } + + /* Getting here means the capacity of the audio is fine. */ + return MA_SUCCESS; +} + + +static OSStatus ma_on_output__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pActionFlags, const AudioTimeStamp* pTimeStamp, UInt32 busNumber, UInt32 frameCount, AudioBufferList* pBufferList) +{ + ma_device* pDevice = (ma_device*)pUserData; + ma_stream_layout layout; + + MA_ASSERT(pDevice != NULL); + + /*ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "INFO: Output Callback: busNumber=%d, frameCount=%d, mNumberBuffers=%d\n", (int)busNumber, (int)frameCount, (int)pBufferList->mNumberBuffers);*/ + + /* 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. */ + 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) { + ma_device_handle_backend_data_callback(pDevice, pBufferList->mBuffers[iBuffer].mData, NULL, frameCountForThisBuffer); + } + + /*a_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, " frameCount=%d, mNumberChannels=%d, mDataByteSize=%d\n", (int)frameCount, (int)pBufferList->mBuffers[iBuffer].mNumberChannels, (int)pBufferList->mBuffers[iBuffer].mDataByteSize);*/ + } 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); + /*ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, " WARNING: Outputting silence. frameCount=%d, mNumberChannels=%d, mDataByteSize=%d\n", (int)frameCount, (int)pBufferList->mBuffers[iBuffer].mNumberChannels, (int)pBufferList->mBuffers[iBuffer].mDataByteSize);*/ + } + } + } 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_ASSERT(pDevice->playback.internalChannels <= MA_MAX_CHANNELS); /* This should heve been validated at initialization time. */ + + /* + For safety we'll check that the internal channels is a multiple of the buffer count. If it's not it means something + very strange has happened and we're not going to support it. + */ + if ((pBufferList->mNumberBuffers % pDevice->playback.internalChannels) == 0) { + ma_uint8 tempBuffer[4096]; + 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; + } + + ma_device_handle_backend_data_callback(pDevice, tempBuffer, NULL, framesToRead); + + for (iChannel = 0; iChannel < pDevice->playback.internalChannels; ++iChannel) { + ppDeinterleavedBuffers[iChannel] = (void*)ma_offset_ptr(pBufferList->mBuffers[iBuffer+iChannel].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; + } + } + } + } + + (void)pActionFlags; + (void)pTimeStamp; + (void)busNumber; + (void)frameCount; + + return noErr; +} + +static OSStatus ma_on_input__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pActionFlags, const AudioTimeStamp* pTimeStamp, UInt32 busNumber, UInt32 frameCount, AudioBufferList* pUnusedBufferList) +{ + ma_device* pDevice = (ma_device*)pUserData; + AudioBufferList* pRenderedBufferList; + ma_result result; + ma_stream_layout layout; + ma_uint32 iBuffer; + OSStatus status; + + MA_ASSERT(pDevice != NULL); + + 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. */ + layout = ma_stream_layout_interleaved; + if (pRenderedBufferList->mBuffers[0].mNumberChannels != pDevice->capture.internalChannels) { + layout = ma_stream_layout_deinterleaved; + } + + /*ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "INFO: Input Callback: busNumber=%d, frameCount=%d, mNumberBuffers=%d\n", (int)busNumber, (int)frameCount, (int)pRenderedBufferList->mNumberBuffers);*/ + + /* + There has been a situation reported where frame count passed into this function is greater than the capacity of + our capture buffer. There doesn't seem to be a reliable way to determine what the maximum frame count will be, + so we need to instead resort to dynamically reallocating our buffer to ensure it's large enough to capture the + number of frames requested by this callback. + */ + result = ma_device_realloc_AudioBufferList__coreaudio(pDevice, frameCount, pDevice->capture.internalFormat, pDevice->capture.internalChannels, layout); + if (result != MA_SUCCESS) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "Failed to allocate AudioBufferList for capture.\n"); + return noErr; + } + + pRenderedBufferList = (AudioBufferList*)pDevice->coreaudio.pAudioBufferList; + MA_ASSERT(pRenderedBufferList); + + /* + When you call AudioUnitRender(), Core Audio tries to be helpful by setting the mDataByteSize to the number of bytes + that were actually rendered. The problem with this is that the next call can fail with -50 due to the size no longer + being set to the capacity of the buffer, but instead the size in bytes of the previous render. This will cause a + problem when a future call to this callback specifies a larger number of frames. + + To work around this we need to explicitly set the size of each buffer to their respective size in bytes. + */ + for (iBuffer = 0; iBuffer < pRenderedBufferList->mNumberBuffers; ++iBuffer) { + pRenderedBufferList->mBuffers[iBuffer].mDataByteSize = pDevice->coreaudio.audioBufferCapInFrames * ma_get_bytes_per_sample(pDevice->capture.internalFormat) * pRenderedBufferList->mBuffers[iBuffer].mNumberChannels; + } + + status = ((ma_AudioUnitRender_proc)pDevice->pContext->coreaudio.AudioUnitRender)((AudioUnit)pDevice->coreaudio.audioUnitCapture, pActionFlags, pTimeStamp, busNumber, frameCount, pRenderedBufferList); + if (status != noErr) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, " ERROR: AudioUnitRender() failed with %d.\n", (int)status); + return status; + } + + if (layout == ma_stream_layout_interleaved) { + for (iBuffer = 0; iBuffer < pRenderedBufferList->mNumberBuffers; ++iBuffer) { + if (pRenderedBufferList->mBuffers[iBuffer].mNumberChannels == pDevice->capture.internalChannels) { + ma_device_handle_backend_data_callback(pDevice, NULL, pRenderedBufferList->mBuffers[iBuffer].mData, frameCount); + /*ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, " mDataByteSize=%d.\n", (int)pRenderedBufferList->mBuffers[iBuffer].mDataByteSize);*/ + } 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_uint32 framesRemaining; + + MA_ZERO_MEMORY(silentBuffer, sizeof(silentBuffer)); + + 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; + } + + ma_device_handle_backend_data_callback(pDevice, NULL, silentBuffer, framesToSend); + + framesRemaining -= framesToSend; + } + + /*ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, " WARNING: Outputting silence. frameCount=%d, mNumberChannels=%d, mDataByteSize=%d\n", (int)frameCount, (int)pRenderedBufferList->mBuffers[iBuffer].mNumberChannels, (int)pRenderedBufferList->mBuffers[iBuffer].mDataByteSize);*/ + } + } + } 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_ASSERT(pDevice->capture.internalChannels <= MA_MAX_CHANNELS); /* This should have been validated at initialization time. */ + + /* + For safety we'll check that the internal channels is a multiple of the buffer count. If it's not it means something + very strange has happened and we're not going to support it. + */ + if ((pRenderedBufferList->mNumberBuffers % pDevice->capture.internalChannels) == 0) { + ma_uint8 tempBuffer[4096]; + 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_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + if (framesToSend > framesRemaining) { + framesToSend = framesRemaining; + } + + for (iChannel = 0; iChannel < pDevice->capture.internalChannels; ++iChannel) { + ppDeinterleavedBuffers[iChannel] = (void*)ma_offset_ptr(pRenderedBufferList->mBuffers[iBuffer+iChannel].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); + ma_device_handle_backend_data_callback(pDevice, NULL, tempBuffer, framesToSend); + + framesRemaining -= framesToSend; + } + } + } + } + + (void)pActionFlags; + (void)pTimeStamp; + (void)busNumber; + (void)frameCount; + (void)pUnusedBufferList; + + return noErr; +} + +static void on_start_stop__coreaudio(void* pUserData, AudioUnit audioUnit, AudioUnitPropertyID propertyID, AudioUnitScope scope, AudioUnitElement element) +{ + ma_device* pDevice = (ma_device*)pUserData; + MA_ASSERT(pDevice != NULL); + + /* Don't do anything if it looks like we're just reinitializing due to a device switch. */ + if (((audioUnit == pDevice->coreaudio.audioUnitPlayback) && pDevice->coreaudio.isSwitchingPlaybackDevice) || + ((audioUnit == pDevice->coreaudio.audioUnitCapture) && pDevice->coreaudio.isSwitchingCaptureDevice)) { + return; + } + + /* + 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_device_state_uninitialized || ma_device_get_state(pDevice) == ma_device_state_stopping || ma_device_get_state(pDevice) == ma_device_state_stopped) { + ma_device__on_notification_stopped(pDevice); + } 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) { + goto done; /* 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 stopped 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)) { + goto done; + } + + /* + 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 stopped callback needs to be posted. + */ + goto done; + } + + /* Getting here means we need to stop the device. */ + ma_device__on_notification_stopped(pDevice); + } + } + + (void)propertyID; /* Unused. */ + +done: + /* Always signal the stop event. It's possible for the "else" case to get hit which can happen during an interruption. */ + ma_event_signal(&pDevice->coreaudio.stopEvent); +} + +#if defined(MA_APPLE_DESKTOP) +static ma_spinlock g_DeviceTrackingInitLock_CoreAudio = 0; /* A spinlock for mutal exclusion of the init/uninit of the global tracking data. Initialization to 0 is what we need. */ +static ma_uint32 g_DeviceTrackingInitCounter_CoreAudio = 0; +static ma_mutex g_DeviceTrackingMutex_CoreAudio; +static ma_device** g_ppTrackedDevices_CoreAudio = NULL; +static ma_uint32 g_TrackedDeviceCap_CoreAudio = 0; +static ma_uint32 g_TrackedDeviceCount_CoreAudio = 0; + +static OSStatus ma_default_device_changed__coreaudio(AudioObjectID objectID, UInt32 addressCount, const AudioObjectPropertyAddress* pAddresses, void* pUserData) +{ + ma_device_type deviceType; + + /* 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) { + deviceType = ma_device_type_playback; + } else if (pAddresses[0].mSelector == kAudioHardwarePropertyDefaultInputDevice) { + deviceType = ma_device_type_capture; + } else { + return noErr; /* Should never hit this. */ + } + + ma_mutex_lock(&g_DeviceTrackingMutex_CoreAudio); + { + ma_uint32 iDevice; + for (iDevice = 0; iDevice < g_TrackedDeviceCount_CoreAudio; iDevice += 1) { + ma_result reinitResult; + ma_device* pDevice; + + pDevice = g_ppTrackedDevices_CoreAudio[iDevice]; + if (pDevice->type == deviceType || pDevice->type == ma_device_type_duplex) { + if (deviceType == ma_device_type_playback) { + pDevice->coreaudio.isSwitchingPlaybackDevice = MA_TRUE; + reinitResult = ma_device_reinit_internal__coreaudio(pDevice, deviceType, MA_TRUE); + pDevice->coreaudio.isSwitchingPlaybackDevice = MA_FALSE; + } else { + pDevice->coreaudio.isSwitchingCaptureDevice = MA_TRUE; + reinitResult = ma_device_reinit_internal__coreaudio(pDevice, deviceType, MA_TRUE); + pDevice->coreaudio.isSwitchingCaptureDevice = MA_FALSE; + } + + if (reinitResult == MA_SUCCESS) { + ma_device__post_init_setup(pDevice, deviceType); + + /* Restart the device if required. If this fails we need to stop the device entirely. */ + if (ma_device_get_state(pDevice) == ma_device_state_started) { + OSStatus status; + if (deviceType == ma_device_type_playback) { + 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_device_state_stopped); + } + } else if (deviceType == ma_device_type_capture) { + 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_device_state_stopped); + } + } + } + + ma_device__on_notification_rerouted(pDevice); + } + } + } + } + ma_mutex_unlock(&g_DeviceTrackingMutex_CoreAudio); + + /* Unused parameters. */ + (void)objectID; + (void)pUserData; + + return noErr; +} + +static ma_result ma_context__init_device_tracking__coreaudio(ma_context* pContext) +{ + MA_ASSERT(pContext != NULL); + + ma_spinlock_lock(&g_DeviceTrackingInitLock_CoreAudio); + { + /* Don't do anything if we've already initializd device tracking. */ + if (g_DeviceTrackingInitCounter_CoreAudio == 0) { + AudioObjectPropertyAddress propAddress; + propAddress.mScope = kAudioObjectPropertyScopeGlobal; + propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT; + + ma_mutex_init(&g_DeviceTrackingMutex_CoreAudio); + + propAddress.mSelector = kAudioHardwarePropertyDefaultInputDevice; + ((ma_AudioObjectAddPropertyListener_proc)pContext->coreaudio.AudioObjectAddPropertyListener)(kAudioObjectSystemObject, &propAddress, &ma_default_device_changed__coreaudio, NULL); + + propAddress.mSelector = kAudioHardwarePropertyDefaultOutputDevice; + ((ma_AudioObjectAddPropertyListener_proc)pContext->coreaudio.AudioObjectAddPropertyListener)(kAudioObjectSystemObject, &propAddress, &ma_default_device_changed__coreaudio, NULL); + + } + g_DeviceTrackingInitCounter_CoreAudio += 1; + } + ma_spinlock_unlock(&g_DeviceTrackingInitLock_CoreAudio); + + return MA_SUCCESS; +} + +static ma_result ma_context__uninit_device_tracking__coreaudio(ma_context* pContext) +{ + MA_ASSERT(pContext != NULL); + + ma_spinlock_lock(&g_DeviceTrackingInitLock_CoreAudio); + { + if (g_DeviceTrackingInitCounter_CoreAudio > 0) + g_DeviceTrackingInitCounter_CoreAudio -= 1; + + if (g_DeviceTrackingInitCounter_CoreAudio == 0) { + AudioObjectPropertyAddress propAddress; + propAddress.mScope = kAudioObjectPropertyScopeGlobal; + propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT; + + propAddress.mSelector = kAudioHardwarePropertyDefaultInputDevice; + ((ma_AudioObjectRemovePropertyListener_proc)pContext->coreaudio.AudioObjectRemovePropertyListener)(kAudioObjectSystemObject, &propAddress, &ma_default_device_changed__coreaudio, NULL); + + propAddress.mSelector = kAudioHardwarePropertyDefaultOutputDevice; + ((ma_AudioObjectRemovePropertyListener_proc)pContext->coreaudio.AudioObjectRemovePropertyListener)(kAudioObjectSystemObject, &propAddress, &ma_default_device_changed__coreaudio, NULL); + + /* At this point there should be no tracked devices. If not there's an error somewhere. */ + if (g_ppTrackedDevices_CoreAudio != NULL) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "You have uninitialized all contexts while an associated device is still active."); + ma_spinlock_unlock(&g_DeviceTrackingInitLock_CoreAudio); + return MA_INVALID_OPERATION; + } + + ma_mutex_uninit(&g_DeviceTrackingMutex_CoreAudio); + } + } + ma_spinlock_unlock(&g_DeviceTrackingInitLock_CoreAudio); + + return MA_SUCCESS; +} + +static ma_result ma_device__track__coreaudio(ma_device* pDevice) +{ + MA_ASSERT(pDevice != NULL); + + ma_mutex_lock(&g_DeviceTrackingMutex_CoreAudio); + { + /* Allocate memory if required. */ + if (g_TrackedDeviceCap_CoreAudio <= g_TrackedDeviceCount_CoreAudio) { + ma_uint32 newCap; + ma_device** ppNewDevices; + + newCap = g_TrackedDeviceCap_CoreAudio * 2; + if (newCap == 0) { + newCap = 1; + } + + ppNewDevices = (ma_device**)ma_realloc(g_ppTrackedDevices_CoreAudio, sizeof(*g_ppTrackedDevices_CoreAudio)*newCap, &pDevice->pContext->allocationCallbacks); + if (ppNewDevices == NULL) { + ma_mutex_unlock(&g_DeviceTrackingMutex_CoreAudio); + return MA_OUT_OF_MEMORY; + } + + g_ppTrackedDevices_CoreAudio = ppNewDevices; + g_TrackedDeviceCap_CoreAudio = newCap; + } + + g_ppTrackedDevices_CoreAudio[g_TrackedDeviceCount_CoreAudio] = pDevice; + g_TrackedDeviceCount_CoreAudio += 1; + } + ma_mutex_unlock(&g_DeviceTrackingMutex_CoreAudio); + + return MA_SUCCESS; +} + +static ma_result ma_device__untrack__coreaudio(ma_device* pDevice) +{ + MA_ASSERT(pDevice != NULL); + + ma_mutex_lock(&g_DeviceTrackingMutex_CoreAudio); + { + ma_uint32 iDevice; + for (iDevice = 0; iDevice < g_TrackedDeviceCount_CoreAudio; iDevice += 1) { + if (g_ppTrackedDevices_CoreAudio[iDevice] == pDevice) { + /* We've found the device. We now need to remove it from the list. */ + ma_uint32 jDevice; + for (jDevice = iDevice; jDevice < g_TrackedDeviceCount_CoreAudio-1; jDevice += 1) { + g_ppTrackedDevices_CoreAudio[jDevice] = g_ppTrackedDevices_CoreAudio[jDevice+1]; + } + + g_TrackedDeviceCount_CoreAudio -= 1; + + /* If there's nothing else in the list we need to free memory. */ + if (g_TrackedDeviceCount_CoreAudio == 0) { + ma_free(g_ppTrackedDevices_CoreAudio, &pDevice->pContext->allocationCallbacks); + g_ppTrackedDevices_CoreAudio = NULL; + g_TrackedDeviceCap_CoreAudio = 0; + } + + break; + } + } + } + ma_mutex_unlock(&g_DeviceTrackingMutex_CoreAudio); + + return MA_SUCCESS; +} +#endif + +#if defined(MA_APPLE_MOBILE) +@interface ma_ios_notification_handler:NSObject { + ma_device* m_pDevice; +} +@end + +@implementation ma_ios_notification_handler +-(id)init:(ma_device*)pDevice +{ + self = [super init]; + m_pDevice = pDevice; + + /* For route changes. */ + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handle_route_change:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]]; + + /* For interruptions. */ + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handle_interruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]]; + + return self; +} + +-(void)dealloc +{ + [self remove_handler]; + + #if defined(__has_feature) + #if !__has_feature(objc_arc) + [super dealloc]; + #endif + #endif +} + +-(void)remove_handler +{ + [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionRouteChangeNotification object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionInterruptionNotification object:nil]; +} + +-(void)handle_interruption:(NSNotification*)pNotification +{ + NSInteger type = [[[pNotification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey] integerValue]; + switch (type) + { + case AVAudioSessionInterruptionTypeBegan: + { + ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Interruption: AVAudioSessionInterruptionTypeBegan\n"); + + /* + Core Audio will have stopped the internal device automatically, but we need explicitly + stop it at a higher level to ensure miniaudio-specific state is updated for consistency. + */ + ma_device_stop(m_pDevice); + + /* + Fire the notification after the device has been stopped to ensure it's in the correct + state when the notification handler is invoked. + */ + ma_device__on_notification_interruption_began(m_pDevice); + } break; + + case AVAudioSessionInterruptionTypeEnded: + { + ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Interruption: AVAudioSessionInterruptionTypeEnded\n"); + ma_device__on_notification_interruption_ended(m_pDevice); + } break; + } +} + +-(void)handle_route_change:(NSNotification*)pNotification +{ + AVAudioSession* pSession = [AVAudioSession sharedInstance]; + + NSInteger reason = [[[pNotification userInfo] objectForKey:AVAudioSessionRouteChangeReasonKey] integerValue]; + switch (reason) + { + case AVAudioSessionRouteChangeReasonOldDeviceUnavailable: + { + ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonOldDeviceUnavailable\n"); + } break; + + case AVAudioSessionRouteChangeReasonNewDeviceAvailable: + { + ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonNewDeviceAvailable\n"); + } break; + + case AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory: + { + ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory\n"); + } break; + + case AVAudioSessionRouteChangeReasonWakeFromSleep: + { + ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonWakeFromSleep\n"); + } break; + + case AVAudioSessionRouteChangeReasonOverride: + { + ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonOverride\n"); + } break; + + case AVAudioSessionRouteChangeReasonCategoryChange: + { + ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonCategoryChange\n"); + } break; + + case AVAudioSessionRouteChangeReasonUnknown: + default: + { + ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonUnknown\n"); + } break; + } + + ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_DEBUG, "[Core Audio] Changing Route. inputNumberChannels=%d; outputNumberOfChannels=%d\n", (int)pSession.inputNumberOfChannels, (int)pSession.outputNumberOfChannels); + + /* Let the application know about the route change. */ + ma_device__on_notification_rerouted(m_pDevice); +} +@end +#endif + +static ma_result ma_device_uninit__coreaudio(ma_device* pDevice) +{ + MA_ASSERT(pDevice != NULL); + MA_ASSERT(ma_device_get_state(pDevice) == ma_device_state_uninitialized); + +#if defined(MA_APPLE_DESKTOP) + /* + Make sure we're no longer tracking the device. It doesn't matter if we call this for a non-default device because it'll + just gracefully ignore it. + */ + ma_device__untrack__coreaudio(pDevice); +#endif +#if defined(MA_APPLE_MOBILE) + if (pDevice->coreaudio.pNotificationHandler != NULL) { + ma_ios_notification_handler* pNotificationHandler = (MA_BRIDGE_TRANSFER ma_ios_notification_handler*)pDevice->coreaudio.pNotificationHandler; + [pNotificationHandler remove_handler]; + } +#endif + + 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, &pDevice->pContext->allocationCallbacks); + } + + return MA_SUCCESS; +} + +typedef struct +{ + ma_bool32 allowNominalSampleRateChange; + + /* Input. */ + ma_format formatIn; + ma_uint32 channelsIn; + ma_uint32 sampleRateIn; + ma_channel channelMapIn[MA_MAX_CHANNELS]; + ma_uint32 periodSizeInFramesIn; + ma_uint32 periodSizeInMillisecondsIn; + ma_uint32 periodsIn; + ma_share_mode shareMode; + ma_performance_profile performanceProfile; + 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 periodSizeInFramesOut; + ma_uint32 periodsOut; + char deviceName[256]; +} ma_device_init_internal_data__coreaudio; + +static 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; + UInt32 actualPeriodSizeInFrames; + 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; + } + + 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; + +#if defined(MA_APPLE_DESKTOP) + 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 == 0) { + pData->periodsOut = MA_DEFAULT_PERIODS; + } + if (pData->periodsOut > 16) { + pData->periodsOut = 16; + } + + + /* 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. */ + 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, 0, &deviceObjectID, sizeof(deviceObjectID)); + if (status != noErr) { + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); + return ma_result_from_OSStatus(result); + } +#else + /* + For some reason it looks like Apple is only allowing selection of the input device. There does not appear to be any way to change + the default output route. I have no idea why this is like this, but for now we'll only be able to configure capture devices. + */ + if (pDeviceID != NULL) { + if (deviceType == ma_device_type_capture) { + ma_bool32 found = MA_FALSE; + NSArray *pInputs = [[[AVAudioSession sharedInstance] currentRoute] inputs]; + for (AVAudioSessionPortDescription* pPortDesc in pInputs) { + if (strcmp(pDeviceID->coreaudio, [pPortDesc.UID UTF8String]) == 0) { + [[AVAudioSession sharedInstance] setPreferredInput:pPortDesc error:nil]; + found = MA_TRUE; + break; + } + } + + if (found == MA_FALSE) { + return MA_DOES_NOT_EXIST; + } + } + } +#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 origFormat; + UInt32 origFormatSize = sizeof(origFormat); + 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 (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 ma_result_from_OSStatus(status); + } + + #if defined(MA_APPLE_DESKTOP) + result = ma_find_best_format__coreaudio(pContext, deviceObjectID, deviceType, pData->formatIn, pData->channelsIn, pData->sampleRateIn, &origFormat, &bestFormat); + if (result != MA_SUCCESS) { + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); + return result; + } + + /* + Technical Note TN2091: Device input using the HAL Output Audio Unit + https://developer.apple.com/library/archive/technotes/tn2091/_index.html + + This documentation says the following: + + The internal AudioConverter can handle any *simple* conversion. Typically, this means that a client can specify ANY + variant of the PCM formats. Consequently, the device's sample rate should match the desired sample rate. If sample rate + conversion is needed, it can be accomplished by buffering the input and converting the data on a separate thread with + another AudioConverter. + + The important part here is the mention that it can handle *simple* conversions, which does *not* include sample rate. We + therefore want to ensure the sample rate stays consistent. This document is specifically for input, but I'm going to play it + safe and apply the same rule to output as well. + + I have tried going against the documentation by setting the sample rate anyway, but this just results in AudioUnitRender() + returning a result code of -10863. I have also tried changing the format directly on the input scope on the input bus, but + this just results in `ca_require: IsStreamFormatWritable(inScope, inElement) NotWritable` when trying to set the format. + + Something that does seem to work, however, has been setting the nominal sample rate on the deivce object. The problem with + this, however, is that it actually changes the sample rate at the operating system level and not just the application. This + could be intrusive to the user, however, so I don't think it's wise to make this the default. Instead I'm making this a + configuration option. When the `coreaudio.allowNominalSampleRateChange` config option is set to true, changing the sample + rate will be allowed. Otherwise it'll be fixed to the current sample rate. To check the system-defined sample rate, run + the Audio MIDI Setup program that comes installed on macOS and observe how the sample rate changes as the sample rate is + changed by miniaudio. + */ + if (pData->allowNominalSampleRateChange) { + AudioValueRange sampleRateRange; + AudioObjectPropertyAddress propAddress; + + sampleRateRange.mMinimum = bestFormat.mSampleRate; + sampleRateRange.mMaximum = bestFormat.mSampleRate; + + propAddress.mSelector = kAudioDevicePropertyNominalSampleRate; + propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput; + propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT; + + status = ((ma_AudioObjectSetPropertyData_proc)pContext->coreaudio.AudioObjectSetPropertyData)(deviceObjectID, &propAddress, 0, NULL, sizeof(sampleRateRange), &sampleRateRange); + if (status != noErr) { + bestFormat.mSampleRate = origFormat.mSampleRate; + } + } else { + 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 + bestFormat = origFormat; + + /* + 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; + + /* + I've had a report that the channel count returned by AudioUnitGetProperty above is inconsistent with + AVAudioSession outputNumberOfChannels. I'm going to try using the AVAudioSession values instead. + */ + if (deviceType == ma_device_type_playback) { + bestFormat.mChannelsPerFrame = (UInt32)pAudioSession.outputNumberOfChannels; + } + if (deviceType == ma_device_type_capture) { + bestFormat.mChannelsPerFrame = (UInt32)pAudioSession.inputNumberOfChannels; + } + } + + 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; + } + + /* Clamp the channel count for safety. */ + if (pData->channelsOut > MA_MAX_CHANNELS) { + pData->channelsOut = MA_MAX_CHANNELS; + } + + /* + 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, pData->channelsOut); + 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, pData->channelsOut); + if (result != MA_SUCCESS) { + return result; + } + #else + /* Fall back to default assumptions. */ + ma_channel_map_init_standard(ma_standard_channel_map_default, pData->channelMapOut, ma_countof(pData->channelMapOut), pData->channelsOut); + #endif + } +#else + /* TODO: Figure out how to get the channel map using AVAudioSession. */ + ma_channel_map_init_standard(ma_standard_channel_map_default, pData->channelMapOut, ma_countof(pData->channelMapOut), pData->channelsOut); +#endif + + + /* Buffer size. Not allowing this to be configurable on iOS. */ + if (pData->periodSizeInFramesIn == 0) { + if (pData->periodSizeInMillisecondsIn == 0) { + if (pData->performanceProfile == ma_performance_profile_low_latency) { + actualPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY, pData->sampleRateOut); + } else { + actualPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE, pData->sampleRateOut); + } + } else { + actualPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pData->periodSizeInMillisecondsIn, pData->sampleRateOut); + } + } else { + actualPeriodSizeInFrames = pData->periodSizeInFramesIn; + } + +#if defined(MA_APPLE_DESKTOP) + result = ma_set_AudioObject_buffer_size_in_frames(pContext, deviceObjectID, deviceType, &actualPeriodSizeInFrames); + if (result != MA_SUCCESS) { + return result; + } +#else + /* + On iOS, the size of the IO buffer needs to be specified in seconds and is a floating point + number. I don't trust any potential truncation errors due to converting from float to integer + so I'm going to explicitly set the actual period size to the next power of 2. + */ + @autoreleasepool { + AVAudioSession* pAudioSession = [AVAudioSession sharedInstance]; + MA_ASSERT(pAudioSession != NULL); + + [pAudioSession setPreferredIOBufferDuration:((float)actualPeriodSizeInFrames / pAudioSession.sampleRate) error:nil]; + actualPeriodSizeInFrames = ma_next_power_of_2((ma_uint32)(pAudioSession.IOBufferDuration * pAudioSession.sampleRate)); + } +#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. + */ + status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, &actualPeriodSizeInFrames, sizeof(actualPeriodSizeInFrames)); + if (status != noErr) { + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); + return ma_result_from_OSStatus(status); + } + + pData->periodSizeInFramesOut = (ma_uint32)actualPeriodSizeInFrames; + + /* 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; + AudioBufferList* pBufferList; + + pBufferList = ma_allocate_AudioBufferList__coreaudio(pData->periodSizeInFramesOut, pData->formatOut, pData->channelsOut, (isInterleaved) ? ma_stream_layout_interleaved : ma_stream_layout_deinterleaved, &pContext->allocationCallbacks); + if (pBufferList == NULL) { + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); + return MA_OUT_OF_MEMORY; + } + + pData->pAudioBufferList = pBufferList; + } + + /* Callbacks. */ + 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, 0, &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, 0, &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, &pContext->allocationCallbacks); + 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; +} + +#if defined(MA_APPLE_DESKTOP) +static 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; + } + + data.allowNominalSampleRateChange = MA_FALSE; /* Don't change the nominal sample rate when switching devices. */ + + 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.shareMode = pDevice->capture.shareMode; + data.performanceProfile = pDevice->coreaudio.originalPerformanceProfile; + 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, &pDevice->pContext->allocationCallbacks); + } + } else 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.shareMode = pDevice->playback.shareMode; + data.performanceProfile = pDevice->coreaudio.originalPerformanceProfile; + 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); + } + } + data.periodSizeInFramesIn = pDevice->coreaudio.originalPeriodSizeInFrames; + data.periodSizeInMillisecondsIn = pDevice->coreaudio.originalPeriodSizeInMilliseconds; + data.periodsIn = pDevice->coreaudio.originalPeriods; + + /* Need at least 3 periods for duplex. */ + if (data.periodsIn < 3 && pDevice->type == ma_device_type_duplex) { + data.periodsIn = 3; + } + + result = ma_device_init_internal__coreaudio(pDevice->pContext, deviceType, NULL, &data, (void*)pDevice); + if (result != MA_SUCCESS) { + return result; + } + + if (deviceType == ma_device_type_capture) { + #if defined(MA_APPLE_DESKTOP) + pDevice->coreaudio.deviceObjectIDCapture = (ma_uint32)data.deviceObjectID; + ma_get_AudioObject_uid(pDevice->pContext, pDevice->coreaudio.deviceObjectIDCapture, sizeof(pDevice->capture.id.coreaudio), pDevice->capture.id.coreaudio); + #endif + pDevice->coreaudio.audioUnitCapture = (ma_ptr)data.audioUnit; + pDevice->coreaudio.pAudioBufferList = (ma_ptr)data.pAudioBufferList; + pDevice->coreaudio.audioBufferCapInFrames = data.periodSizeInFramesOut; + + 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.internalPeriodSizeInFrames = data.periodSizeInFramesOut; + pDevice->capture.internalPeriods = data.periodsOut; + } else if (deviceType == ma_device_type_playback) { + #if defined(MA_APPLE_DESKTOP) + pDevice->coreaudio.deviceObjectIDPlayback = (ma_uint32)data.deviceObjectID; + ma_get_AudioObject_uid(pDevice->pContext, pDevice->coreaudio.deviceObjectIDPlayback, sizeof(pDevice->playback.id.coreaudio), pDevice->playback.id.coreaudio); + #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.internalPeriodSizeInFrames = data.periodSizeInFramesOut; + pDevice->playback.internalPeriods = data.periodsOut; + } + + return MA_SUCCESS; +} +#endif /* MA_APPLE_DESKTOP */ + +static ma_result ma_device_init__coreaudio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture) +{ + ma_result result; + + MA_ASSERT(pDevice != NULL); + MA_ASSERT(pConfig != NULL); + + if (pConfig->deviceType == ma_device_type_loopback) { + return MA_DEVICE_TYPE_NOT_SUPPORTED; + } + + /* No exclusive mode with the Core Audio backend for now. */ + if (((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive) || + ((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->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.allowNominalSampleRateChange = pConfig->coreaudio.allowNominalSampleRateChange; + data.formatIn = pDescriptorCapture->format; + data.channelsIn = pDescriptorCapture->channels; + data.sampleRateIn = pDescriptorCapture->sampleRate; + MA_COPY_MEMORY(data.channelMapIn, pDescriptorCapture->channelMap, sizeof(pDescriptorCapture->channelMap)); + data.periodSizeInFramesIn = pDescriptorCapture->periodSizeInFrames; + data.periodSizeInMillisecondsIn = pDescriptorCapture->periodSizeInMilliseconds; + data.periodsIn = pDescriptorCapture->periodCount; + data.shareMode = pDescriptorCapture->shareMode; + data.performanceProfile = pConfig->performanceProfile; + data.registerStopEvent = MA_TRUE; + + /* Need at least 3 periods for duplex. */ + if (data.periodsIn < 3 && pConfig->deviceType == ma_device_type_duplex) { + data.periodsIn = 3; + } + + result = ma_device_init_internal__coreaudio(pDevice->pContext, ma_device_type_capture, pDescriptorCapture->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->coreaudio.audioBufferCapInFrames = data.periodSizeInFramesOut; + pDevice->coreaudio.originalPeriodSizeInFrames = pDescriptorCapture->periodSizeInFrames; + pDevice->coreaudio.originalPeriodSizeInMilliseconds = pDescriptorCapture->periodSizeInMilliseconds; + pDevice->coreaudio.originalPeriods = pDescriptorCapture->periodCount; + pDevice->coreaudio.originalPerformanceProfile = pConfig->performanceProfile; + + pDescriptorCapture->format = data.formatOut; + pDescriptorCapture->channels = data.channelsOut; + pDescriptorCapture->sampleRate = data.sampleRateOut; + MA_COPY_MEMORY(pDescriptorCapture->channelMap, data.channelMapOut, sizeof(data.channelMapOut)); + pDescriptorCapture->periodSizeInFrames = data.periodSizeInFramesOut; + pDescriptorCapture->periodCount = data.periodsOut; + + #if defined(MA_APPLE_DESKTOP) + ma_get_AudioObject_uid(pDevice->pContext, pDevice->coreaudio.deviceObjectIDCapture, sizeof(pDevice->capture.id.coreaudio), pDevice->capture.id.coreaudio); + + /* + 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) { + ma_device__track__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.allowNominalSampleRateChange = pConfig->coreaudio.allowNominalSampleRateChange; + data.formatIn = pDescriptorPlayback->format; + data.channelsIn = pDescriptorPlayback->channels; + data.sampleRateIn = pDescriptorPlayback->sampleRate; + MA_COPY_MEMORY(data.channelMapIn, pDescriptorPlayback->channelMap, sizeof(pDescriptorPlayback->channelMap)); + data.shareMode = pDescriptorPlayback->shareMode; + data.performanceProfile = pConfig->performanceProfile; + + /* 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.periodSizeInFramesIn = pDescriptorCapture->periodSizeInFrames; + data.periodsIn = pDescriptorCapture->periodCount; + data.registerStopEvent = MA_FALSE; + } else { + data.periodSizeInFramesIn = pDescriptorPlayback->periodSizeInFrames; + data.periodSizeInMillisecondsIn = pDescriptorPlayback->periodSizeInMilliseconds; + data.periodsIn = pDescriptorPlayback->periodCount; + data.registerStopEvent = MA_TRUE; + } + + result = ma_device_init_internal__coreaudio(pDevice->pContext, ma_device_type_playback, pDescriptorPlayback->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, &pDevice->pContext->allocationCallbacks); + } + } + 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->coreaudio.originalPeriodSizeInFrames = pDescriptorPlayback->periodSizeInFrames; + pDevice->coreaudio.originalPeriodSizeInMilliseconds = pDescriptorPlayback->periodSizeInMilliseconds; + pDevice->coreaudio.originalPeriods = pDescriptorPlayback->periodCount; + pDevice->coreaudio.originalPerformanceProfile = pConfig->performanceProfile; + + pDescriptorPlayback->format = data.formatOut; + pDescriptorPlayback->channels = data.channelsOut; + pDescriptorPlayback->sampleRate = data.sampleRateOut; + MA_COPY_MEMORY(pDescriptorPlayback->channelMap, data.channelMapOut, sizeof(data.channelMapOut)); + pDescriptorPlayback->periodSizeInFrames = data.periodSizeInFramesOut; + pDescriptorPlayback->periodCount = data.periodsOut; + + #if defined(MA_APPLE_DESKTOP) + ma_get_AudioObject_uid(pDevice->pContext, pDevice->coreaudio.deviceObjectIDPlayback, sizeof(pDevice->playback.id.coreaudio), pDevice->playback.id.coreaudio); + + /* + 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 (pDescriptorPlayback->pDeviceID == NULL && (pConfig->deviceType != ma_device_type_duplex || pDescriptorCapture->pDeviceID != NULL)) { + ma_device__track__coreaudio(pDevice); + } + #endif + } + + + + /* + 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(&pDevice->coreaudio.stopEvent); + + /* + We need to detect when a route has changed so we can update the data conversion pipeline accordingly. This is done + differently on non-Desktop Apple platforms. + */ +#if defined(MA_APPLE_MOBILE) + pDevice->coreaudio.pNotificationHandler = (MA_BRIDGE_RETAINED void*)[[ma_ios_notification_handler alloc] init:pDevice]; +#endif + + return MA_SUCCESS; +} + + +static 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; +} + +static ma_result ma_device_stop__coreaudio(ma_device* pDevice) +{ + MA_ASSERT(pDevice != NULL); + + /* It's not clear from the documentation whether or not AudioOutputUnitStop() actually drains the device or not. */ + + 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; +} + + +static ma_result ma_context_uninit__coreaudio(ma_context* pContext) +{ + MA_ASSERT(pContext != NULL); + MA_ASSERT(pContext->backend == ma_backend_coreaudio); + +#if defined(MA_APPLE_MOBILE) + if (!pContext->coreaudio.noAudioSessionDeactivate) { + if (![[AVAudioSession sharedInstance] setActive:false error:nil]) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "Failed to deactivate audio session."); + return MA_FAILED_TO_INIT_BACKEND; + } + } +#endif + +#if !defined(MA_NO_RUNTIME_LINKING) && !defined(MA_APPLE_MOBILE) + ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit); + ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreAudio); + ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreFoundation); +#endif + +#if !defined(MA_APPLE_MOBILE) + ma_context__uninit_device_tracking__coreaudio(pContext); +#endif + + (void)pContext; + return MA_SUCCESS; +} + +#if defined(MA_APPLE_MOBILE) && defined(__IPHONE_12_0) +static AVAudioSessionCategory ma_to_AVAudioSessionCategory(ma_ios_session_category category) +{ + /* The "default" and "none" categories are treated different and should not be used as an input into this function. */ + MA_ASSERT(category != ma_ios_session_category_default); + MA_ASSERT(category != ma_ios_session_category_none); + + switch (category) { + case ma_ios_session_category_ambient: return AVAudioSessionCategoryAmbient; + case ma_ios_session_category_solo_ambient: return AVAudioSessionCategorySoloAmbient; + case ma_ios_session_category_playback: return AVAudioSessionCategoryPlayback; + case ma_ios_session_category_record: return AVAudioSessionCategoryRecord; + case ma_ios_session_category_play_and_record: return AVAudioSessionCategoryPlayAndRecord; + case ma_ios_session_category_multi_route: return AVAudioSessionCategoryMultiRoute; + case ma_ios_session_category_none: return AVAudioSessionCategoryAmbient; + case ma_ios_session_category_default: return AVAudioSessionCategoryAmbient; + default: return AVAudioSessionCategoryAmbient; + } +} +#endif + +static ma_result ma_context_init__coreaudio(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks) +{ +#if !defined(MA_APPLE_MOBILE) + ma_result result; +#endif + + MA_ASSERT(pConfig != NULL); + MA_ASSERT(pContext != NULL); + +#if defined(MA_APPLE_MOBILE) + @autoreleasepool { + AVAudioSession* pAudioSession = [AVAudioSession sharedInstance]; + AVAudioSessionCategoryOptions options = pConfig->coreaudio.sessionCategoryOptions; + + MA_ASSERT(pAudioSession != NULL); + + if (pConfig->coreaudio.sessionCategory == ma_ios_session_category_default) { + /* + I'm going to use trial and error to determine our default session category. First we'll try PlayAndRecord. If that fails + we'll try Playback and if that fails we'll try record. If all of these fail we'll just not set the category. + */ + #if !defined(MA_APPLE_TV) && !defined(MA_APPLE_WATCH) + options |= AVAudioSessionCategoryOptionDefaultToSpeaker; + #endif + + if ([pAudioSession setCategory: AVAudioSessionCategoryPlayAndRecord withOptions:options error:nil]) { + /* Using PlayAndRecord */ + } else if ([pAudioSession setCategory: AVAudioSessionCategoryPlayback withOptions:options error:nil]) { + /* Using Playback */ + } else if ([pAudioSession setCategory: AVAudioSessionCategoryRecord withOptions:options error:nil]) { + /* Using Record */ + } else { + /* Leave as default? */ + } + } else { + if (pConfig->coreaudio.sessionCategory != ma_ios_session_category_none) { + #if defined(__IPHONE_12_0) + if (![pAudioSession setCategory: ma_to_AVAudioSessionCategory(pConfig->coreaudio.sessionCategory) withOptions:options error:nil]) { + return MA_INVALID_OPERATION; /* Failed to set session category. */ + } + #else + /* Ignore the session category on version 11 and older, but post a warning. */ + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "Session category only supported in iOS 12 and newer."); + #endif + } + } + + if (!pConfig->coreaudio.noAudioSessionActivate) { + if (![pAudioSession setActive:true error:nil]) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "Failed to activate audio session."); + return MA_FAILED_TO_INIT_BACKEND; + } + } + } +#endif + +#if !defined(MA_NO_RUNTIME_LINKING) && !defined(MA_APPLE_MOBILE) + pContext->coreaudio.hCoreFoundation = ma_dlopen(ma_context_get_log(pContext), "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation"); + if (pContext->coreaudio.hCoreFoundation == NULL) { + return MA_API_NOT_FOUND; + } + + pContext->coreaudio.CFStringGetCString = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hCoreFoundation, "CFStringGetCString"); + pContext->coreaudio.CFRelease = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hCoreFoundation, "CFRelease"); + + + pContext->coreaudio.hCoreAudio = ma_dlopen(ma_context_get_log(pContext), "/System/Library/Frameworks/CoreAudio.framework/CoreAudio"); + if (pContext->coreaudio.hCoreAudio == NULL) { + ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreFoundation); + return MA_API_NOT_FOUND; + } + + pContext->coreaudio.AudioObjectGetPropertyData = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hCoreAudio, "AudioObjectGetPropertyData"); + pContext->coreaudio.AudioObjectGetPropertyDataSize = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hCoreAudio, "AudioObjectGetPropertyDataSize"); + pContext->coreaudio.AudioObjectSetPropertyData = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hCoreAudio, "AudioObjectSetPropertyData"); + pContext->coreaudio.AudioObjectAddPropertyListener = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hCoreAudio, "AudioObjectAddPropertyListener"); + pContext->coreaudio.AudioObjectRemovePropertyListener = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hCoreAudio, "AudioObjectRemovePropertyListener"); + + /* + 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(ma_context_get_log(pContext), "/System/Library/Frameworks/AudioUnit.framework/AudioUnit"); + if (pContext->coreaudio.hAudioUnit == NULL) { + ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreAudio); + ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreFoundation); + return MA_API_NOT_FOUND; + } + + if (ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioComponentFindNext") == NULL) { + /* Couldn't find the required symbols in AudioUnit, so fall back to AudioToolbox. */ + ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit); + pContext->coreaudio.hAudioUnit = ma_dlopen(ma_context_get_log(pContext), "/System/Library/Frameworks/AudioToolbox.framework/AudioToolbox"); + if (pContext->coreaudio.hAudioUnit == NULL) { + ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreAudio); + ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreFoundation); + return MA_API_NOT_FOUND; + } + } + + pContext->coreaudio.AudioComponentFindNext = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioComponentFindNext"); + pContext->coreaudio.AudioComponentInstanceDispose = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioComponentInstanceDispose"); + pContext->coreaudio.AudioComponentInstanceNew = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioComponentInstanceNew"); + pContext->coreaudio.AudioOutputUnitStart = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioOutputUnitStart"); + pContext->coreaudio.AudioOutputUnitStop = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioOutputUnitStop"); + pContext->coreaudio.AudioUnitAddPropertyListener = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioUnitAddPropertyListener"); + pContext->coreaudio.AudioUnitGetPropertyInfo = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioUnitGetPropertyInfo"); + pContext->coreaudio.AudioUnitGetProperty = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioUnitGetProperty"); + pContext->coreaudio.AudioUnitSetProperty = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioUnitSetProperty"); + pContext->coreaudio.AudioUnitInitialize = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioUnitInitialize"); + pContext->coreaudio.AudioUnitRender = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioUnitRender"); +#else + pContext->coreaudio.CFStringGetCString = (ma_proc)CFStringGetCString; + pContext->coreaudio.CFRelease = (ma_proc)CFRelease; + + #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; + pContext->coreaudio.AudioObjectRemovePropertyListener = (ma_proc)AudioObjectRemovePropertyListener; + #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 + + /* 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(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit); + ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreAudio); + ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreFoundation); + #endif + return MA_FAILED_TO_INIT_BACKEND; + } + } + +#if !defined(MA_APPLE_MOBILE) + result = ma_context__init_device_tracking__coreaudio(pContext); + if (result != MA_SUCCESS) { + #if !defined(MA_NO_RUNTIME_LINKING) && !defined(MA_APPLE_MOBILE) + ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit); + ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreAudio); + ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreFoundation); + #endif + return result; + } +#endif + + pContext->coreaudio.noAudioSessionDeactivate = pConfig->coreaudio.noAudioSessionDeactivate; + + pCallbacks->onContextInit = ma_context_init__coreaudio; + pCallbacks->onContextUninit = ma_context_uninit__coreaudio; + pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__coreaudio; + pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__coreaudio; + pCallbacks->onDeviceInit = ma_device_init__coreaudio; + pCallbacks->onDeviceUninit = ma_device_uninit__coreaudio; + pCallbacks->onDeviceStart = ma_device_start__coreaudio; + pCallbacks->onDeviceStop = ma_device_stop__coreaudio; + pCallbacks->onDeviceRead = NULL; + pCallbacks->onDeviceWrite = NULL; + pCallbacks->onDeviceDataLoop = NULL; + + return MA_SUCCESS; +} +#endif /* Core Audio */ + + + +/****************************************************************************** + +sndio Backend + +******************************************************************************/ +#ifdef MA_HAS_SNDIO +#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 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 +#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*); + +static ma_uint32 ma_get_standard_sample_rate_priority_index__sndio(ma_uint32 sampleRate) /* Lower = higher priority */ +{ + ma_uint32 i; + for (i = 0; i < ma_countof(g_maStandardSampleRatePriorities); ++i) { + if (g_maStandardSampleRatePriorities[i] == sampleRate) { + return i; + } + } + + return (ma_uint32)-1; +} + +static 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; +} + +static 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); + + 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; + } + + 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. */ + } + + 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 bestFormat; +} + +static 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. */ + 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; + } + + 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 (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 { + chan = caps->confs[iConfig].rchan; + } + + if ((chan & (1UL << iChannel)) == 0) { + continue; + } + + if (deviceType == ma_device_type_playback) { + channels = caps->pchan[iChannel]; + } else { + channels = caps->rchan[iChannel]; + } + + if (maxChannels < channels) { + maxChannels = channels; + } + } + } + } + + return maxChannels; +} + +static 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); + + 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; + } + + 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 (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 { + chan = caps->confs[iConfig].rchan; + } + + if ((chan & (1UL << iChannel)) == 0) { + continue; + } + + 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 (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. */ + ratePriority = ma_get_standard_sample_rate_priority_index__sndio(rate); + if (ratePriority == (ma_uint32)-1) { + continue; + } + + if (ma_get_standard_sample_rate_priority_index__sndio(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; +} + + +static 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. */ + + /* 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; +} + +static ma_result ma_context_get_device_info__sndio(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo) +{ + char devid[256]; + struct ma_sio_hdl* handle; + struct ma_sio_cap caps; + unsigned int iConfig; + + MA_ASSERT(pContext != NULL); + + /* 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); + } else { + ma_strcpy_s(devid, sizeof(devid), pDeviceID->sndio); + ma_strcpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), devid); + } + + 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; + } + + if (((ma_sio_getcap_proc)pContext->sndio.sio_getcap)(handle, &caps) == 0) { + return MA_ERROR; + } + + pDeviceInfo->nativeDataFormatCount = 0; + + 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; + + if ((caps.confs[iConfig].enc & (1UL << iEncoding)) == 0) { + continue; + } + + 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. */ + } + + + /* 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 { + chan = caps.confs[iConfig].rchan; + } + + if ((chan & (1UL << iChannel)) == 0) { + continue; + } + + if (deviceType == ma_device_type_playback) { + channels = caps.pchan[iChannel]; + } else { + channels = caps.rchan[iChannel]; + } + + + /* Sample Rates. */ + for (iRate = 0; iRate < MA_SIO_NRATE; iRate += 1) { + if ((caps.confs[iConfig].rate & (1UL << iRate)) != 0) { + ma_device_info_add_native_data_format(pDeviceInfo, format, channels, caps.rate[iRate], 0); + } + } + } + } + } + + ((ma_sio_close_proc)pContext->sndio.sio_close)(handle); + return MA_SUCCESS; +} + +static ma_result 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); + } + + return MA_SUCCESS; +} + +static ma_result ma_device_init_handle__sndio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptor, ma_device_type deviceType) +{ + const char* pDeviceName; + ma_ptr handle; + int openFlags = 0; + struct ma_sio_cap caps; + struct ma_sio_par par; + const ma_device_id* pDeviceID; + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + ma_format internalFormat; + ma_uint32 internalChannels; + ma_uint32 internalSampleRate; + ma_uint32 internalPeriodSizeInFrames; + ma_uint32 internalPeriods; + + 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; + } else { + openFlags = MA_SIO_PLAY; + } + + pDeviceID = pDescriptor->pDeviceID; + format = pDescriptor->format; + channels = pDescriptor->channels; + sampleRate = pDescriptor->sampleRate; + + pDeviceName = MA_SIO_DEVANY; + if (pDeviceID != NULL) { + pDeviceName = pDeviceID->sndio; + } + + handle = (ma_ptr)((ma_sio_open_proc)pDevice->pContext->sndio.sio_open)(pDeviceName, openFlags, 0); + if (handle == NULL) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to open device."); + return 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)pDevice->pContext->sndio.sio_getcap)((struct ma_sio_hdl*)handle, &caps) == 0) { + ((ma_sio_close_proc)pDevice->pContext->sndio.sio_close)((struct ma_sio_hdl*)handle); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to retrieve device caps."); + return 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 (format == ma_format_unknown) { + format = ma_find_best_format_from_sio_cap__sndio(&caps); + } + + if (channels == 0) { + if (strlen(pDeviceName) > strlen("rsnd/") && strncmp(pDeviceName, "rsnd/", strlen("rsnd/")) == 0) { + channels = ma_find_best_channels_from_sio_cap__sndio(&caps, deviceType, format); + } else { + channels = MA_DEFAULT_CHANNELS; + } + } + } else { + if (format == ma_format_unknown) { + format = ma_find_best_format_from_sio_cap__sndio(&caps); + } + + if (channels == 0) { + if (strlen(pDeviceName) > strlen("rsnd/") && strncmp(pDeviceName, "rsnd/", strlen("rsnd/")) == 0) { + channels = ma_find_best_channels_from_sio_cap__sndio(&caps, deviceType, format); + } else { + channels = MA_DEFAULT_CHANNELS; + } + } + } + + if (sampleRate == 0) { + 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: + case ma_format_unknown: + 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; + + internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, par.rate, pConfig->performanceProfile); + + par.round = internalPeriodSizeInFrames; + par.appbufsz = par.round * pDescriptor->periodCount; + + if (((ma_sio_setpar_proc)pDevice->pContext->sndio.sio_setpar)((struct ma_sio_hdl*)handle, &par) == 0) { + ((ma_sio_close_proc)pDevice->pContext->sndio.sio_close)((struct ma_sio_hdl*)handle); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to set buffer size."); + return MA_ERROR; + } + + if (((ma_sio_getpar_proc)pDevice->pContext->sndio.sio_getpar)((struct ma_sio_hdl*)handle, &par) == 0) { + ((ma_sio_close_proc)pDevice->pContext->sndio.sio_close)((struct ma_sio_hdl*)handle); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to retrieve buffer size."); + return MA_ERROR; + } + + 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; + internalPeriodSizeInFrames = par.round; + + if (deviceType == ma_device_type_capture) { + pDevice->sndio.handleCapture = handle; + } else { + pDevice->sndio.handlePlayback = handle; + } + + pDescriptor->format = internalFormat; + pDescriptor->channels = internalChannels; + pDescriptor->sampleRate = internalSampleRate; + ma_channel_map_init_standard(ma_standard_channel_map_sndio, pDescriptor->channelMap, ma_countof(pDescriptor->channelMap), internalChannels); + pDescriptor->periodSizeInFrames = internalPeriodSizeInFrames; + pDescriptor->periodCount = internalPeriods; + + return MA_SUCCESS; +} + +static ma_result ma_device_init__sndio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture) +{ + MA_ASSERT(pDevice != NULL); + + MA_ZERO_OBJECT(&pDevice->sndio); + + if (pConfig->deviceType == ma_device_type_loopback) { + return MA_DEVICE_TYPE_NOT_SUPPORTED; + } + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + ma_result result = ma_device_init_handle__sndio(pDevice, pConfig, pDescriptorCapture, ma_device_type_capture); + 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(pDevice, pConfig, pDescriptorPlayback, ma_device_type_playback); + if (result != MA_SUCCESS) { + return result; + } + } + + return MA_SUCCESS; +} + +static ma_result ma_device_start__sndio(ma_device* pDevice) +{ + MA_ASSERT(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + ((ma_sio_start_proc)pDevice->pContext->sndio.sio_start)((struct ma_sio_hdl*)pDevice->sndio.handleCapture); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + ((ma_sio_start_proc)pDevice->pContext->sndio.sio_start)((struct ma_sio_hdl*)pDevice->sndio.handlePlayback); /* <-- Doesn't actually playback until data is written. */ + } + + return MA_SUCCESS; +} + +static ma_result ma_device_stop__sndio(ma_device* pDevice) +{ + MA_ASSERT(pDevice != NULL); + + /* + From the documentation: + + The sio_stop() function puts the audio subsystem in the same state as before sio_start() is called. It stops recording, drains the play buffer and then + stops playback. If samples to play are queued but playback hasn't started yet then playback is forced immediately; playback will actually stop once the + buffer is drained. In no case are samples in the play buffer discarded. + + Therefore, sio_stop() performs all of the necessary draining for us. + */ + + 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); + } + + 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); + } + + return MA_SUCCESS; +} + +static ma_result ma_device_write__sndio(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten) +{ + int result; + + if (pFramesWritten != NULL) { + *pFramesWritten = 0; + } + + 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) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to send data from the client to the device."); + return MA_IO_ERROR; + } + + if (pFramesWritten != NULL) { + *pFramesWritten = frameCount; + } + + return MA_SUCCESS; +} + +static ma_result ma_device_read__sndio(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead) +{ + int result; + + if (pFramesRead != NULL) { + *pFramesRead = 0; + } + + 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) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to read data from the device to be sent to the device."); + return MA_IO_ERROR; + } + + if (pFramesRead != NULL) { + *pFramesRead = frameCount; + } + + return MA_SUCCESS; +} + +static 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; +} + +static ma_result ma_context_init__sndio(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks) +{ +#ifndef MA_NO_RUNTIME_LINKING + const char* libsndioNames[] = { + "libsndio.so" + }; + size_t i; + + for (i = 0; i < ma_countof(libsndioNames); ++i) { + pContext->sndio.sndioSO = ma_dlopen(ma_context_get_log(pContext), 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(ma_context_get_log(pContext), pContext->sndio.sndioSO, "sio_open"); + pContext->sndio.sio_close = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->sndio.sndioSO, "sio_close"); + pContext->sndio.sio_setpar = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->sndio.sndioSO, "sio_setpar"); + pContext->sndio.sio_getpar = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->sndio.sndioSO, "sio_getpar"); + pContext->sndio.sio_getcap = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->sndio.sndioSO, "sio_getcap"); + pContext->sndio.sio_write = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->sndio.sndioSO, "sio_write"); + pContext->sndio.sio_read = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->sndio.sndioSO, "sio_read"); + pContext->sndio.sio_start = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->sndio.sndioSO, "sio_start"); + pContext->sndio.sio_stop = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->sndio.sndioSO, "sio_stop"); + pContext->sndio.sio_initpar = (ma_proc)ma_dlsym(ma_context_get_log(pContext), 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 + + pCallbacks->onContextInit = ma_context_init__sndio; + pCallbacks->onContextUninit = ma_context_uninit__sndio; + pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__sndio; + pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__sndio; + pCallbacks->onDeviceInit = ma_device_init__sndio; + pCallbacks->onDeviceUninit = ma_device_uninit__sndio; + pCallbacks->onDeviceStart = ma_device_start__sndio; + pCallbacks->onDeviceStop = ma_device_stop__sndio; + pCallbacks->onDeviceRead = ma_device_read__sndio; + pCallbacks->onDeviceWrite = ma_device_write__sndio; + pCallbacks->onDeviceDataLoop = NULL; + + (void)pConfig; + 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 + +static 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); + + baseLen = strlen(base); + MA_ASSERT(idSize > baseLen); + + ma_strcpy_s(id, idSize, base); + ma_itoa_s(deviceIndex, id+baseLen, idSize-baseLen, 10); +} + +static 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); + + idLen = strlen(id); + 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. */ + } + + deviceIndexStr = id + baseLen; + if (deviceIndexStr[0] == '\0') { + return MA_ERROR; /* No index specified in the ID. */ + } + + if (pIndexOut) { + *pIndexOut = atoi(deviceIndexStr); + } + + return MA_SUCCESS; +} + + +#if !defined(MA_AUDIO4_USE_NEW_API) /* Old API */ +static 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. */ +} + +static void ma_encoding_from_format__audio4(ma_format format, unsigned int* pEncoding, unsigned int* pPrecision) +{ + 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: + case ma_format_unknown: + default: + { + *pEncoding = (ma_is_little_endian()) ? AUDIO_ENCODING_SLINEAR_LE : AUDIO_ENCODING_SLINEAR_BE; + *pPrecision = 16; + } break; + } +} + +static ma_format ma_format_from_prinfo__audio4(struct audio_prinfo* prinfo) +{ + return ma_format_from_encoding__audio4(prinfo->encoding, prinfo->precision); +} + +static ma_format ma_best_format_from_fd__audio4(int fd, ma_format preferredFormat) +{ + audio_encoding_t encoding; + ma_uint32 iFormat; + int counter = 0; + + /* First check to see if the preferred format is supported. */ + if (preferredFormat != ma_format_unknown) { + counter = 0; + for (;;) { + MA_ZERO_OBJECT(&encoding); + encoding.index = counter; + if (ioctl(fd, AUDIO_GETENC, &encoding) < 0) { + break; + } + + if (preferredFormat == ma_format_from_encoding__audio4(encoding.encoding, encoding.precision)) { + return preferredFormat; /* Found the preferred format. */ + } + + /* Getting here means this encoding does not match our preferred format so we need to more on to the next encoding. */ + counter += 1; + } + } + + /* Getting here means our preferred format is not supported, so fall back to our standard priorities. */ + for (iFormat = 0; iFormat < ma_countof(g_maFormatPriorities); iFormat += 1) { + ma_format format = g_maFormatPriorities[iFormat]; + + counter = 0; + for (;;) { + MA_ZERO_OBJECT(&encoding); + encoding.index = counter; + if (ioctl(fd, AUDIO_GETENC, &encoding) < 0) { + break; + } + + if (format == ma_format_from_encoding__audio4(encoding.encoding, encoding.precision)) { + return format; /* Found a workable format. */ + } + + /* Getting here means this encoding does not match our preferred format so we need to more on to the next encoding. */ + counter += 1; + } + } + + /* Getting here means not appropriate format was found. */ + return ma_format_unknown; +} +#else +static 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 + +static ma_result ma_context_get_device_info_from_fd__audio4(ma_context* pContext, ma_device_type deviceType, int fd, ma_device_info* pDeviceInfo) +{ + audio_device_t fdDevice; + + MA_ASSERT(pContext != NULL); + MA_ASSERT(fd >= 0); + MA_ASSERT(pDeviceInfo != NULL); + + (void)pContext; + (void)deviceType; + + if (ioctl(fd, AUDIO_GETDEV, &fdDevice) < 0) { + return MA_ERROR; /* Failed to retrieve device info. */ + } + + /* Name. */ + ma_strcpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), fdDevice.name); + + #if !defined(MA_AUDIO4_USE_NEW_API) + { + audio_info_t fdInfo; + int counter = 0; + ma_uint32 channels; + ma_uint32 sampleRate; + + if (ioctl(fd, AUDIO_GETINFO, &fdInfo) < 0) { + return MA_ERROR; + } + + if (deviceType == ma_device_type_playback) { + channels = fdInfo.play.channels; + sampleRate = fdInfo.play.sample_rate; + } else { + channels = fdInfo.record.channels; + sampleRate = fdInfo.record.sample_rate; + } + + /* Supported formats. We get this by looking at the encodings. */ + pDeviceInfo->nativeDataFormatCount = 0; + for (;;) { + audio_encoding_t encoding; + ma_format format; + + MA_ZERO_OBJECT(&encoding); + encoding.index = counter; + if (ioctl(fd, AUDIO_GETENC, &encoding) < 0) { + break; + } + + format = ma_format_from_encoding__audio4(encoding.encoding, encoding.precision); + if (format != ma_format_unknown) { + ma_device_info_add_native_data_format(pDeviceInfo, format, channels, sampleRate, 0); + } + + counter += 1; + } + } + #else + { + struct audio_swpar fdPar; + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + + if (ioctl(fd, AUDIO_GETPAR, &fdPar) < 0) { + return MA_ERROR; + } + + format = ma_format_from_swpar__audio4(&fdPar); + if (format == ma_format_unknown) { + return MA_FORMAT_NOT_SUPPORTED; + } + + if (deviceType == ma_device_type_playback) { + channels = fdPar.pchan; + } else { + channels = fdPar.rchan; + } + + sampleRate = fdPar.rate; + + pDeviceInfo->nativeDataFormatCount = 0; + ma_device_info_add_native_data_format(pDeviceInfo, format, channels, sampleRate, 0); + } + #endif + + return MA_SUCCESS; +} + +static 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); + + /* + 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); + + if (stat(devpath, &st) < 0) { + break; + } + + /* The device exists, but we need to check if it's usable as playback and/or capture. */ + + /* 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; +} + +static ma_result ma_context_get_device_info__audio4(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo) +{ + int fd = -1; + int deviceIndex = -1; + char ctlid[256]; + ma_result result; + + MA_ASSERT(pContext != NULL); + + /* + 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. */ + ma_strcpy_s(ctlid, sizeof(ctlid), "/dev/audioctl"); + } else { + /* 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; + } + + 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); + } + + result = ma_context_get_device_info_from_fd__audio4(pContext, deviceType, fd, pDeviceInfo); + + close(fd); + return result; +} + +static ma_result 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); + } + + return MA_SUCCESS; +} + +static ma_result ma_device_init_fd__audio4(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptor, ma_device_type deviceType) +{ + const char* pDefaultDeviceNames[] = { + "/dev/audio", + "/dev/audio0" + }; + const char* pDefaultDeviceCtlNames[] = { + "/dev/audioctl", + "/dev/audioctl0" + }; + int fd; + int fdFlags = 0; + size_t iDefaultDevice = (size_t)-1; + ma_format internalFormat; + ma_uint32 internalChannels; + ma_uint32 internalSampleRate; + ma_uint32 internalPeriodSizeInFrames; + ma_uint32 internalPeriods; + + MA_ASSERT(pConfig != NULL); + MA_ASSERT(deviceType != ma_device_type_duplex); + MA_ASSERT(pDevice != NULL); + + /* 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;*/ + + /* Find the index of the default device as a start. We'll use this index later. Set it to (size_t)-1 otherwise. */ + if (pDescriptor->pDeviceID == NULL) { + /* Default device. */ + for (iDefaultDevice = 0; iDefaultDevice < ma_countof(pDefaultDeviceNames); ++iDefaultDevice) { + fd = open(pDefaultDeviceNames[iDefaultDevice], fdFlags, 0); + if (fd != -1) { + break; + } + } + } else { + /* Specific device. */ + fd = open(pDescriptor->pDeviceID->audio4, fdFlags, 0); + + for (iDefaultDevice = 0; iDefaultDevice < ma_countof(pDefaultDeviceNames); iDefaultDevice += 1) { + if (ma_strcmp(pDefaultDeviceNames[iDefaultDevice], pDescriptor->pDeviceID->audio4) == 0) { + break; + } + } + + if (iDefaultDevice == ma_countof(pDefaultDeviceNames)) { + iDefaultDevice = (size_t)-1; + } + } + + if (fd == -1) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to open device."); + return ma_result_from_errno(errno); + } + + #if !defined(MA_AUDIO4_USE_NEW_API) /* Old API */ + { + audio_info_t fdInfo; + int fdInfoResult = -1; + + /* + The documentation is a little bit unclear to me as to how it handles formats. It says the + following: + + Regardless of formats supported by underlying driver, the audio driver accepts the + following formats. + + By then the next sentence says this: + + `encoding` and `precision` are one of the values obtained by AUDIO_GETENC. + + It sounds like a direct contradiction to me. I'm going to play this safe any only use the + best sample format returned by AUDIO_GETENC. If the requested format is supported we'll + use that, but otherwise we'll just use our standard format priorities to pick an + appropriate one. + */ + AUDIO_INITINFO(&fdInfo); + + /* + Get the default format from the audioctl file if we're asking for a default device. If we + retrieve it from /dev/audio it'll default to mono 8000Hz. + */ + if (iDefaultDevice != (size_t)-1) { + /* We're using a default device. Get the info from the /dev/audioctl file instead of /dev/audio. */ + int fdctl = open(pDefaultDeviceCtlNames[iDefaultDevice], fdFlags, 0); + if (fdctl != -1) { + fdInfoResult = ioctl(fdctl, AUDIO_GETINFO, &fdInfo); + close(fdctl); + } + } + + if (fdInfoResult == -1) { + /* We still don't have the default device info so just retrieve it from the main audio device. */ + if (ioctl(fd, AUDIO_GETINFO, &fdInfo) < 0) { + close(fd); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] AUDIO_GETINFO failed."); + return ma_result_from_errno(errno); + } + } + + /* 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(ma_best_format_from_fd__audio4(fd, pDescriptor->format), &fdInfo.record.encoding, &fdInfo.record.precision); + + if (pDescriptor->channels != 0) { + fdInfo.record.channels = ma_clamp(pDescriptor->channels, 1, 12); /* From the documentation: `channels` ranges from 1 to 12. */ + } + + if (pDescriptor->sampleRate != 0) { + fdInfo.record.sample_rate = ma_clamp(pDescriptor->sampleRate, 1000, 192000); /* From the documentation: `frequency` ranges from 1000Hz to 192000Hz. (They mean `sample_rate` instead of `frequency`.) */ + } + } else { + fdInfo.mode = AUMODE_PLAY; + ma_encoding_from_format__audio4(ma_best_format_from_fd__audio4(fd, pDescriptor->format), &fdInfo.play.encoding, &fdInfo.play.precision); + + if (pDescriptor->channels != 0) { + fdInfo.play.channels = ma_clamp(pDescriptor->channels, 1, 12); /* From the documentation: `channels` ranges from 1 to 12. */ + } + + if (pDescriptor->sampleRate != 0) { + fdInfo.play.sample_rate = ma_clamp(pDescriptor->sampleRate, 1000, 192000); /* From the documentation: `frequency` ranges from 1000Hz to 192000Hz. (They mean `sample_rate` instead of `frequency`.) */ + } + } + + if (ioctl(fd, AUDIO_SETINFO, &fdInfo) < 0) { + close(fd); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to set device format. AUDIO_SETINFO failed."); + return ma_result_from_errno(errno); + } + + if (ioctl(fd, AUDIO_GETINFO, &fdInfo) < 0) { + close(fd); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] AUDIO_GETINFO failed."); + return ma_result_from_errno(errno); + } + + 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); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] The device's internal device format is not supported by miniaudio. The device is unusable."); + return MA_FORMAT_NOT_SUPPORTED; + } + + /* Buffer. */ + { + ma_uint32 internalPeriodSizeInBytes; + + internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, internalSampleRate, pConfig->performanceProfile); + + internalPeriodSizeInBytes = internalPeriodSizeInFrames * ma_get_bytes_per_frame(internalFormat, internalChannels); + if (internalPeriodSizeInBytes < 16) { + internalPeriodSizeInBytes = 16; + } + + internalPeriods = pDescriptor->periodCount; + if (internalPeriods < 2) { + internalPeriods = 2; + } + + /* What miniaudio calls a period, audio4 calls a block. */ + AUDIO_INITINFO(&fdInfo); + fdInfo.hiwat = internalPeriods; + fdInfo.lowat = internalPeriods-1; + fdInfo.blocksize = internalPeriodSizeInBytes; + if (ioctl(fd, AUDIO_SETINFO, &fdInfo) < 0) { + close(fd); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to set internal buffer size. AUDIO_SETINFO failed."); + return ma_result_from_errno(errno); + } + + internalPeriods = fdInfo.hiwat; + internalPeriodSizeInFrames = fdInfo.blocksize / ma_get_bytes_per_frame(internalFormat, internalChannels); + } + } + #else + { + struct audio_swpar fdPar; + + /* 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); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to retrieve initial device parameters."); + return ma_result_from_errno(errno); + } + + 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); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] The device's internal device format is not supported by miniaudio. The device is unusable."); + return MA_FORMAT_NOT_SUPPORTED; + } + + /* Buffer. */ + { + ma_uint32 internalPeriodSizeInBytes; + + internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, internalSampleRate, pConfig->performanceProfile); + + /* What miniaudio calls a period, audio4 calls a block. */ + internalPeriodSizeInBytes = internalPeriodSizeInFrames * ma_get_bytes_per_frame(internalFormat, internalChannels); + if (internalPeriodSizeInBytes < 16) { + internalPeriodSizeInBytes = 16; + } + + fdPar.nblks = pDescriptor->periodCount; + fdPar.round = internalPeriodSizeInBytes; + + if (ioctl(fd, AUDIO_SETPAR, &fdPar) < 0) { + close(fd); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to set device parameters."); + return ma_result_from_errno(errno); + } + + if (ioctl(fd, AUDIO_GETPAR, &fdPar) < 0) { + close(fd); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to retrieve actual device parameters."); + return ma_result_from_errno(errno); + } + } + + internalFormat = ma_format_from_swpar__audio4(&fdPar); + internalChannels = (deviceType == ma_device_type_capture) ? fdPar.rchan : fdPar.pchan; + internalSampleRate = fdPar.rate; + internalPeriods = fdPar.nblks; + internalPeriodSizeInFrames = fdPar.round / ma_get_bytes_per_frame(internalFormat, internalChannels); + } + #endif + + if (internalFormat == ma_format_unknown) { + close(fd); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] The device's internal device format is not supported by miniaudio. The device is unusable."); + return MA_FORMAT_NOT_SUPPORTED; + } + + if (deviceType == ma_device_type_capture) { + pDevice->audio4.fdCapture = fd; + } else { + pDevice->audio4.fdPlayback = fd; + } + + pDescriptor->format = internalFormat; + pDescriptor->channels = internalChannels; + pDescriptor->sampleRate = internalSampleRate; + ma_channel_map_init_standard(ma_standard_channel_map_sound4, pDescriptor->channelMap, ma_countof(pDescriptor->channelMap), internalChannels); + pDescriptor->periodSizeInFrames = internalPeriodSizeInFrames; + pDescriptor->periodCount = internalPeriods; + + return MA_SUCCESS; +} + +static ma_result ma_device_init__audio4(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture) +{ + MA_ASSERT(pDevice != NULL); + + MA_ZERO_OBJECT(&pDevice->audio4); + + if (pConfig->deviceType == ma_device_type_loopback) { + return MA_DEVICE_TYPE_NOT_SUPPORTED; + } + + 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) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive) || + ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->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(pDevice, pConfig, pDescriptorCapture, ma_device_type_capture); + 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(pDevice, pConfig, pDescriptorPlayback, ma_device_type_playback); + if (result != MA_SUCCESS) { + if (pConfig->deviceType == ma_device_type_duplex) { + close(pDevice->audio4.fdCapture); + } + return result; + } + } + + return MA_SUCCESS; +} + +static 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; +} + +static 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) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to stop device. AUDIO_FLUSH failed."); + return ma_result_from_errno(errno); + } +#else + if (ioctl(fd, AUDIO_STOP, 0) < 0) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to stop device. AUDIO_STOP failed."); + return ma_result_from_errno(errno); + } +#endif + + return MA_SUCCESS; +} + +static 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; + + 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; + + /* Drain the device first. If this fails we'll just need to flush without draining. Unfortunately draining isn't available on newer version of OpenBSD. */ + #if !defined(MA_AUDIO4_USE_NEW_API) + ioctl(pDevice->audio4.fdPlayback, AUDIO_DRAIN, 0); + #endif + + /* Here is where the device is stopped immediately. */ + result = ma_device_stop_fd__audio4(pDevice, pDevice->audio4.fdPlayback); + if (result != MA_SUCCESS) { + return result; + } + } + + return MA_SUCCESS; +} + +static ma_result ma_device_write__audio4(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten) +{ + int result; + + if (pFramesWritten != NULL) { + *pFramesWritten = 0; + } + + result = write(pDevice->audio4.fdPlayback, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels)); + if (result < 0) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to write data to the device."); + return ma_result_from_errno(errno); + } + + if (pFramesWritten != NULL) { + *pFramesWritten = (ma_uint32)result / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + } + + return MA_SUCCESS; +} + +static ma_result ma_device_read__audio4(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead) +{ + int result; + + if (pFramesRead != NULL) { + *pFramesRead = 0; + } + + result = read(pDevice->audio4.fdCapture, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels)); + if (result < 0) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to read data from the device."); + return ma_result_from_errno(errno); + } + + if (pFramesRead != NULL) { + *pFramesRead = (ma_uint32)result / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + } + + return MA_SUCCESS; +} + +static 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; +} + +static ma_result ma_context_init__audio4(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks) +{ + MA_ASSERT(pContext != NULL); + + (void)pConfig; + + pCallbacks->onContextInit = ma_context_init__audio4; + pCallbacks->onContextUninit = ma_context_uninit__audio4; + pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__audio4; + pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__audio4; + pCallbacks->onDeviceInit = ma_device_init__audio4; + pCallbacks->onDeviceUninit = ma_device_uninit__audio4; + pCallbacks->onDeviceStart = ma_device_start__audio4; + pCallbacks->onDeviceStop = ma_device_stop__audio4; + pCallbacks->onDeviceRead = ma_device_read__audio4; + pCallbacks->onDeviceWrite = ma_device_write__audio4; + pCallbacks->onDeviceDataLoop = NULL; + + 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 + +#define MA_OSS_DEFAULT_DEVICE_NAME "/dev/dsp" + +static 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; +} + +static 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; + + *pfd = -1; + + /* This function should only be called for playback or capture, not duplex. */ + if (deviceType == ma_device_type_duplex) { + return MA_INVALID_ARGS; + } + + deviceName = MA_OSS_DEFAULT_DEVICE_NAME; + if (pDeviceID != NULL) { + deviceName = pDeviceID->oss; + } + + 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_result_from_errno(errno); + } + + return MA_SUCCESS; +} + +static 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); + + fd = ma_open_temp_device__oss(); + if (fd == -1) { + ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[OSS] Failed to open a temporary device for retrieving system information used for device enumeration."); + return MA_NO_BACKEND; + } + + result = ioctl(fd, SNDCTL_SYSINFO, &si); + if (result != -1) { + 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. */ + ma_device_info deviceInfo; + ma_bool32 isTerminating = MA_FALSE; + + 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. */ + 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); + ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[OSS] Failed to retrieve system information for device enumeration."); + return MA_NO_BACKEND; + } + + close(fd); + return MA_SUCCESS; +} + +static void ma_context_add_native_data_format__oss(ma_context* pContext, oss_audioinfo* pAudioInfo, ma_format format, ma_device_info* pDeviceInfo) +{ + unsigned int minChannels; + unsigned int maxChannels; + unsigned int iRate; + + MA_ASSERT(pContext != NULL); + MA_ASSERT(pAudioInfo != NULL); + MA_ASSERT(pDeviceInfo != NULL); + + /* If we support all channels we just report 0. */ + minChannels = ma_clamp(pAudioInfo->min_channels, MA_MIN_CHANNELS, MA_MAX_CHANNELS); + maxChannels = ma_clamp(pAudioInfo->max_channels, MA_MIN_CHANNELS, MA_MAX_CHANNELS); + + /* + OSS has this annoying thing where sample rates can be reported in two ways. We prefer explicitness, + which OSS has in the form of nrates/rates, however there are times where nrates can be 0, in which + case we'll need to use min_rate and max_rate and report only standard rates. + */ + if (pAudioInfo->nrates > 0) { + for (iRate = 0; iRate < pAudioInfo->nrates; iRate += 1) { + unsigned int rate = pAudioInfo->rates[iRate]; + + if (minChannels == MA_MIN_CHANNELS && maxChannels == MA_MAX_CHANNELS) { + ma_device_info_add_native_data_format(pDeviceInfo, format, 0, rate, 0); /* Set the channel count to 0 to indicate that all channel counts are supported. */ + } else { + unsigned int iChannel; + for (iChannel = minChannels; iChannel <= maxChannels; iChannel += 1) { + ma_device_info_add_native_data_format(pDeviceInfo, format, iChannel, rate, 0); + } + } + } + } else { + for (iRate = 0; iRate < ma_countof(g_maStandardSampleRatePriorities); iRate += 1) { + ma_uint32 standardRate = g_maStandardSampleRatePriorities[iRate]; + + if (standardRate >= (ma_uint32)pAudioInfo->min_rate && standardRate <= (ma_uint32)pAudioInfo->max_rate) { + if (minChannels == MA_MIN_CHANNELS && maxChannels == MA_MAX_CHANNELS) { + ma_device_info_add_native_data_format(pDeviceInfo, format, 0, standardRate, 0); /* Set the channel count to 0 to indicate that all channel counts are supported. */ + } else { + unsigned int iChannel; + for (iChannel = minChannels; iChannel <= maxChannels; iChannel += 1) { + ma_device_info_add_native_data_format(pDeviceInfo, format, iChannel, standardRate, 0); + } + } + } + } + } +} + +static ma_result ma_context_get_device_info__oss(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo) +{ + ma_bool32 foundDevice; + int fdTemp; + oss_sysinfo si; + int result; + + MA_ASSERT(pContext != NULL); + + /* 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. */ + foundDevice = MA_FALSE; + + fdTemp = ma_open_temp_device__oss(); + if (fdTemp == -1) { + ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[OSS] Failed to open a temporary device for retrieving system information used for device enumeration."); + return MA_NO_BACKEND; + } + + result = ioctl(fdTemp, SNDCTL_SYSINFO, &si); + if (result != -1) { + 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. */ + if ((deviceType == ma_device_type_playback && ((ai.caps & PCM_CAP_OUTPUT) != 0)) || + (deviceType == ma_device_type_capture && ((ai.caps & PCM_CAP_INPUT) != 0))) { + 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. + */ + 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->nativeDataFormatCount = 0; + + if (deviceType == ma_device_type_playback) { + formatMask = ai.oformats; + } else { + formatMask = ai.iformats; + } + + if (((formatMask & AFMT_S16_LE) != 0 && ma_is_little_endian()) || (AFMT_S16_BE && ma_is_big_endian())) { + ma_context_add_native_data_format__oss(pContext, &ai, ma_format_s16, pDeviceInfo); + } + if (((formatMask & AFMT_S32_LE) != 0 && ma_is_little_endian()) || (AFMT_S32_BE && ma_is_big_endian())) { + ma_context_add_native_data_format__oss(pContext, &ai, ma_format_s32, pDeviceInfo); + } + if ((formatMask & AFMT_U8) != 0) { + ma_context_add_native_data_format__oss(pContext, &ai, ma_format_u8, pDeviceInfo); + } + + foundDevice = MA_TRUE; + break; + } + } + } + } + } else { + close(fdTemp); + ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[OSS] Failed to retrieve system information for device enumeration."); + return MA_NO_BACKEND; + } + + + close(fdTemp); + + if (!foundDevice) { + return MA_NO_DEVICE; + } + + return MA_SUCCESS; +} + +static ma_result 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); + } + + return MA_SUCCESS; +} + +static 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; +} + +static 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; +} + +static ma_result ma_device_init_fd__oss(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptor, ma_device_type deviceType) +{ + 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(pDevice != NULL); + MA_ASSERT(pConfig != NULL); + MA_ASSERT(deviceType != ma_device_type_duplex); + + pDeviceID = pDescriptor->pDeviceID; + shareMode = pDescriptor->shareMode; + ossFormat = ma_format_to_oss((pDescriptor->format != ma_format_unknown) ? pDescriptor->format : ma_format_s16); /* Use s16 by default because OSS doesn't like floating point. */ + ossChannels = (int)(pDescriptor->channels > 0) ? pDescriptor->channels : MA_DEFAULT_CHANNELS; + ossSampleRate = (int)(pDescriptor->sampleRate > 0) ? pDescriptor->sampleRate : MA_DEFAULT_SAMPLE_RATE; + + result = ma_context_open_device__oss(pDevice->pContext, deviceType, pDeviceID, shareMode, &fd); + if (result != MA_SUCCESS) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to open device."); + return result; + } + + /* + 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); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to set format."); + return ma_result_from_errno(errno); + } + + /* Channels. */ + ossResult = ioctl(fd, SNDCTL_DSP_CHANNELS, &ossChannels); + if (ossResult == -1) { + close(fd); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to set channel count."); + return ma_result_from_errno(errno); + } + + /* Sample Rate. */ + ossResult = ioctl(fd, SNDCTL_DSP_SPEED, &ossSampleRate); + if (ossResult == -1) { + close(fd); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to set sample rate."); + return ma_result_from_errno(errno); + } + + /* + 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 periodSizeInFrames; + ma_uint32 periodSizeInBytes; + ma_uint32 ossFragmentSizePower; + + periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, (ma_uint32)ossSampleRate, pConfig->performanceProfile); + + periodSizeInBytes = ma_round_to_power_of_2(periodSizeInFrames * ma_get_bytes_per_frame(ma_format_from_oss(ossFormat), ossChannels)); + if (periodSizeInBytes < 16) { + periodSizeInBytes = 16; + } + + ossFragmentSizePower = 4; + periodSizeInBytes >>= 4; + while (periodSizeInBytes >>= 1) { + ossFragmentSizePower += 1; + } + + ossFragment = (int)((pConfig->periods << 16) | ossFragmentSizePower); + ossResult = ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &ossFragment); + if (ossResult == -1) { + close(fd); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to set fragment size and period count."); + return ma_result_from_errno(errno); + } + } + + /* Internal settings. */ + if (deviceType == ma_device_type_capture) { + pDevice->oss.fdCapture = fd; + } else { + pDevice->oss.fdPlayback = fd; + } + + pDescriptor->format = ma_format_from_oss(ossFormat); + pDescriptor->channels = ossChannels; + pDescriptor->sampleRate = ossSampleRate; + ma_channel_map_init_standard(ma_standard_channel_map_sound4, pDescriptor->channelMap, ma_countof(pDescriptor->channelMap), pDescriptor->channels); + pDescriptor->periodCount = (ma_uint32)(ossFragment >> 16); + pDescriptor->periodSizeInFrames = (ma_uint32)(1 << (ossFragment & 0xFFFF)) / ma_get_bytes_per_frame(pDescriptor->format, pDescriptor->channels); + + if (pDescriptor->format == ma_format_unknown) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] The device's internal format is not supported by miniaudio."); + return MA_FORMAT_NOT_SUPPORTED; + } + + return MA_SUCCESS; +} + +static ma_result ma_device_init__oss(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture) +{ + MA_ASSERT(pDevice != NULL); + MA_ASSERT(pConfig != NULL); + + MA_ZERO_OBJECT(&pDevice->oss); + + if (pConfig->deviceType == ma_device_type_loopback) { + return MA_DEVICE_TYPE_NOT_SUPPORTED; + } + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + ma_result result = ma_device_init_fd__oss(pDevice, pConfig, pDescriptorCapture, ma_device_type_capture); + if (result != MA_SUCCESS) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to open device."); + return result; + } + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + ma_result result = ma_device_init_fd__oss(pDevice, pConfig, pDescriptorPlayback, ma_device_type_playback); + if (result != MA_SUCCESS) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to open device."); + return result; + } + } + + return MA_SUCCESS; +} + +/* +Note on Starting and Stopping +============================= +In the past I was using SNDCTL_DSP_HALT to stop the device, however this results in issues when +trying to resume the device again. If we use SNDCTL_DSP_HALT, the next write() or read() will +fail. Instead what we need to do is just not write or read to and from the device when the +device is not running. + +As a result, both the start and stop functions for OSS are just empty stubs. The starting and +stopping logic is handled by ma_device_write__oss() and ma_device_read__oss(). These will check +the device state, and if the device is stopped they will simply not do any kind of processing. + +The downside to this technique is that I've noticed a fairly lengthy delay in stopping the +device, up to a second. This is on a virtual machine, and as such might just be due to the +virtual drivers, but I'm not fully sure. I am not sure how to work around this problem so for +the moment that's just how it's going to have to be. + +When starting the device, OSS will automatically start it when write() or read() is called. +*/ +static ma_result ma_device_start__oss(ma_device* pDevice) +{ + MA_ASSERT(pDevice != NULL); + + /* The device is automatically started with reading and writing. */ + (void)pDevice; + + return MA_SUCCESS; +} + +static ma_result ma_device_stop__oss(ma_device* pDevice) +{ + MA_ASSERT(pDevice != NULL); + + /* See note above on why this is empty. */ + (void)pDevice; + + return MA_SUCCESS; +} + +static ma_result ma_device_write__oss(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten) +{ + int resultOSS; + ma_uint32 deviceState; + + if (pFramesWritten != NULL) { + *pFramesWritten = 0; + } + + /* Don't do any processing if the device is stopped. */ + deviceState = ma_device_get_state(pDevice); + if (deviceState != ma_device_state_started && deviceState != ma_device_state_starting) { + return MA_SUCCESS; + } + + resultOSS = write(pDevice->oss.fdPlayback, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels)); + if (resultOSS < 0) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to send data from the client to the device."); + return ma_result_from_errno(errno); + } + + if (pFramesWritten != NULL) { + *pFramesWritten = (ma_uint32)resultOSS / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + } + + return MA_SUCCESS; +} + +static ma_result ma_device_read__oss(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead) +{ + int resultOSS; + ma_uint32 deviceState; + + if (pFramesRead != NULL) { + *pFramesRead = 0; + } + + /* Don't do any processing if the device is stopped. */ + deviceState = ma_device_get_state(pDevice); + if (deviceState != ma_device_state_started && deviceState != ma_device_state_starting) { + return MA_SUCCESS; + } + + resultOSS = read(pDevice->oss.fdCapture, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels)); + if (resultOSS < 0) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to read data from the device to be sent to the client."); + return ma_result_from_errno(errno); + } + + if (pFramesRead != NULL) { + *pFramesRead = (ma_uint32)resultOSS / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + } + + return MA_SUCCESS; +} + +static 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; +} + +static ma_result ma_context_init__oss(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks) +{ + 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. */ + fd = ma_open_temp_device__oss(); + if (fd == -1) { + ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[OSS] Failed to open temporary device for retrieving system properties."); /* Looks liks OSS isn't installed, or there are no available devices. */ + return MA_NO_BACKEND; + } + + /* Grab the OSS version. */ + ossVersion = 0; + result = ioctl(fd, OSS_GETVERSION, &ossVersion); + if (result == -1) { + close(fd); + ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[OSS] Failed to retrieve OSS version."); + return MA_NO_BACKEND; + } + + /* The file handle to temp device is no longer needed. Close ASAP. */ + close(fd); + + pContext->oss.versionMajor = ((ossVersion & 0xFF0000) >> 16); + pContext->oss.versionMinor = ((ossVersion & 0x00FF00) >> 8); + + pCallbacks->onContextInit = ma_context_init__oss; + pCallbacks->onContextUninit = ma_context_uninit__oss; + pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__oss; + pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__oss; + pCallbacks->onDeviceInit = ma_device_init__oss; + pCallbacks->onDeviceUninit = ma_device_uninit__oss; + pCallbacks->onDeviceStart = ma_device_start__oss; + pCallbacks->onDeviceStop = ma_device_stop__oss; + pCallbacks->onDeviceRead = ma_device_read__oss; + pCallbacks->onDeviceWrite = ma_device_write__oss; + pCallbacks->onDeviceDataLoop = NULL; + + return MA_SUCCESS; +} +#endif /* OSS */ + + + + + +/****************************************************************************** + +AAudio Backend + +******************************************************************************/ +#ifdef MA_HAS_AAUDIO + +/*#include */ + +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_usage_t; +typedef int32_t ma_aaudio_content_type_t; +typedef int32_t ma_aaudio_input_preset_t; +typedef int32_t ma_aaudio_allowed_capture_policy_t; +typedef int32_t ma_aaudio_data_callback_result_t; +typedef struct ma_AAudioStreamBuilder_t* ma_AAudioStreamBuilder; +typedef struct ma_AAudioStream_t* ma_AAudioStream; + +#define MA_AAUDIO_UNSPECIFIED 0 + +/* 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 + +/* Usage types. */ +#define MA_AAUDIO_USAGE_MEDIA 1 +#define MA_AAUDIO_USAGE_VOICE_COMMUNICATION 2 +#define MA_AAUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING 3 +#define MA_AAUDIO_USAGE_ALARM 4 +#define MA_AAUDIO_USAGE_NOTIFICATION 5 +#define MA_AAUDIO_USAGE_NOTIFICATION_RINGTONE 6 +#define MA_AAUDIO_USAGE_NOTIFICATION_EVENT 10 +#define MA_AAUDIO_USAGE_ASSISTANCE_ACCESSIBILITY 11 +#define MA_AAUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE 12 +#define MA_AAUDIO_USAGE_ASSISTANCE_SONIFICATION 13 +#define MA_AAUDIO_USAGE_GAME 14 +#define MA_AAUDIO_USAGE_ASSISTANT 16 +#define MA_AAUDIO_SYSTEM_USAGE_EMERGENCY 1000 +#define MA_AAUDIO_SYSTEM_USAGE_SAFETY 1001 +#define MA_AAUDIO_SYSTEM_USAGE_VEHICLE_STATUS 1002 +#define MA_AAUDIO_SYSTEM_USAGE_ANNOUNCEMENT 1003 + +/* Content types. */ +#define MA_AAUDIO_CONTENT_TYPE_SPEECH 1 +#define MA_AAUDIO_CONTENT_TYPE_MUSIC 2 +#define MA_AAUDIO_CONTENT_TYPE_MOVIE 3 +#define MA_AAUDIO_CONTENT_TYPE_SONIFICATION 4 + +/* Input presets. */ +#define MA_AAUDIO_INPUT_PRESET_GENERIC 1 +#define MA_AAUDIO_INPUT_PRESET_CAMCORDER 5 +#define MA_AAUDIO_INPUT_PRESET_VOICE_RECOGNITION 6 +#define MA_AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION 7 +#define MA_AAUDIO_INPUT_PRESET_UNPROCESSED 9 +#define MA_AAUDIO_INPUT_PRESET_VOICE_PERFORMANCE 10 + +/* Allowed Capture Policies */ +#define MA_AAUDIO_ALLOW_CAPTURE_BY_ALL 1 +#define MA_AAUDIO_ALLOW_CAPTURE_BY_SYSTEM 2 +#define MA_AAUDIO_ALLOW_CAPTURE_BY_NONE 3 + +/* Callback results. */ +#define MA_AAUDIO_CALLBACK_RESULT_CONTINUE 0 +#define MA_AAUDIO_CALLBACK_RESULT_STOP 1 + + +typedef ma_aaudio_data_callback_result_t (* ma_AAudioStream_dataCallback) (ma_AAudioStream* pStream, void* pUserData, void* pAudioData, int32_t numFrames); +typedef void (* ma_AAudioStream_errorCallback)(ma_AAudioStream *pStream, void *pUserData, ma_aaudio_result_t error); + +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_setErrorCallback) (ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream_errorCallback callback, void* pUserData); +typedef void (* MA_PFN_AAudioStreamBuilder_setPerformanceMode) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_performance_mode_t mode); +typedef void (* MA_PFN_AAudioStreamBuilder_setUsage) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_usage_t contentType); +typedef void (* MA_PFN_AAudioStreamBuilder_setContentType) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_content_type_t contentType); +typedef void (* MA_PFN_AAudioStreamBuilder_setInputPreset) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_input_preset_t inputPreset); +typedef void (* MA_PFN_AAudioStreamBuilder_setAllowedCapturePolicy) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_allowed_capture_policy_t policy); +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); + +static 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; +} + +static ma_aaudio_usage_t ma_to_usage__aaudio(ma_aaudio_usage usage) +{ + switch (usage) { + case ma_aaudio_usage_media: return MA_AAUDIO_USAGE_MEDIA; + case ma_aaudio_usage_voice_communication: return MA_AAUDIO_USAGE_VOICE_COMMUNICATION; + case ma_aaudio_usage_voice_communication_signalling: return MA_AAUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING; + case ma_aaudio_usage_alarm: return MA_AAUDIO_USAGE_ALARM; + case ma_aaudio_usage_notification: return MA_AAUDIO_USAGE_NOTIFICATION; + case ma_aaudio_usage_notification_ringtone: return MA_AAUDIO_USAGE_NOTIFICATION_RINGTONE; + case ma_aaudio_usage_notification_event: return MA_AAUDIO_USAGE_NOTIFICATION_EVENT; + case ma_aaudio_usage_assistance_accessibility: return MA_AAUDIO_USAGE_ASSISTANCE_ACCESSIBILITY; + case ma_aaudio_usage_assistance_navigation_guidance: return MA_AAUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE; + case ma_aaudio_usage_assistance_sonification: return MA_AAUDIO_USAGE_ASSISTANCE_SONIFICATION; + case ma_aaudio_usage_game: return MA_AAUDIO_USAGE_GAME; + case ma_aaudio_usage_assitant: return MA_AAUDIO_USAGE_ASSISTANT; + case ma_aaudio_usage_emergency: return MA_AAUDIO_SYSTEM_USAGE_EMERGENCY; + case ma_aaudio_usage_safety: return MA_AAUDIO_SYSTEM_USAGE_SAFETY; + case ma_aaudio_usage_vehicle_status: return MA_AAUDIO_SYSTEM_USAGE_VEHICLE_STATUS; + case ma_aaudio_usage_announcement: return MA_AAUDIO_SYSTEM_USAGE_ANNOUNCEMENT; + default: break; + } + + return MA_AAUDIO_USAGE_MEDIA; +} + +static ma_aaudio_content_type_t ma_to_content_type__aaudio(ma_aaudio_content_type contentType) +{ + switch (contentType) { + case ma_aaudio_content_type_speech: return MA_AAUDIO_CONTENT_TYPE_SPEECH; + case ma_aaudio_content_type_music: return MA_AAUDIO_CONTENT_TYPE_MUSIC; + case ma_aaudio_content_type_movie: return MA_AAUDIO_CONTENT_TYPE_MOVIE; + case ma_aaudio_content_type_sonification: return MA_AAUDIO_CONTENT_TYPE_SONIFICATION; + default: break; + } + + return MA_AAUDIO_CONTENT_TYPE_SPEECH; +} + +static ma_aaudio_input_preset_t ma_to_input_preset__aaudio(ma_aaudio_input_preset inputPreset) +{ + switch (inputPreset) { + case ma_aaudio_input_preset_generic: return MA_AAUDIO_INPUT_PRESET_GENERIC; + case ma_aaudio_input_preset_camcorder: return MA_AAUDIO_INPUT_PRESET_CAMCORDER; + case ma_aaudio_input_preset_voice_recognition: return MA_AAUDIO_INPUT_PRESET_VOICE_RECOGNITION; + case ma_aaudio_input_preset_voice_communication: return MA_AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION; + case ma_aaudio_input_preset_unprocessed: return MA_AAUDIO_INPUT_PRESET_UNPROCESSED; + case ma_aaudio_input_preset_voice_performance: return MA_AAUDIO_INPUT_PRESET_VOICE_PERFORMANCE; + default: break; + } + + return MA_AAUDIO_INPUT_PRESET_GENERIC; +} + +static ma_aaudio_allowed_capture_policy_t ma_to_allowed_capture_policy__aaudio(ma_aaudio_allowed_capture_policy allowedCapturePolicy) +{ + switch (allowedCapturePolicy) { + case ma_aaudio_allow_capture_by_all: return MA_AAUDIO_ALLOW_CAPTURE_BY_ALL; + case ma_aaudio_allow_capture_by_system: return MA_AAUDIO_ALLOW_CAPTURE_BY_SYSTEM; + case ma_aaudio_allow_capture_by_none: return MA_AAUDIO_ALLOW_CAPTURE_BY_NONE; + default: break; + } + + return MA_AAUDIO_ALLOW_CAPTURE_BY_ALL; +} + +static void ma_stream_error_callback__aaudio(ma_AAudioStream* pStream, void* pUserData, ma_aaudio_result_t error) +{ + ma_result result; + ma_job job; + ma_device* pDevice = (ma_device*)pUserData; + MA_ASSERT(pDevice != NULL); + + (void)error; + + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[AAudio] ERROR CALLBACK: error=%d, AAudioStream_getState()=%d\n", error, ((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream)); + + /* + When we get an error, we'll assume that the stream is in an erroneous state and needs to be restarted. From the documentation, + we cannot do this from the error callback. Therefore we are going to use an event thread for the AAudio backend to do this + cleanly and safely. + */ + job = ma_job_init(MA_JOB_TYPE_DEVICE_AAUDIO_REROUTE); + job.data.device.aaudio.reroute.pDevice = pDevice; + + if (pStream == pDevice->aaudio.pStreamCapture) { + job.data.device.aaudio.reroute.deviceType = ma_device_type_capture; + } + else { + job.data.device.aaudio.reroute.deviceType = ma_device_type_playback; + } + + result = ma_device_job_thread_post(&pDevice->pContext->aaudio.jobThread, &job); + if (result != MA_SUCCESS) { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[AAudio] Device Disconnected. Failed to post job for rerouting.\n"); + return; + } +} + +static 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); + + ma_device_handle_backend_data_callback(pDevice, NULL, pAudioData, frameCount); + + (void)pStream; + return MA_AAUDIO_CALLBACK_RESULT_CONTINUE; +} + +static 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); + + ma_device_handle_backend_data_callback(pDevice, pAudioData, NULL, frameCount); + + (void)pStream; + return MA_AAUDIO_CALLBACK_RESULT_CONTINUE; +} + +static ma_result ma_create_and_configure_AAudioStreamBuilder__aaudio(ma_context* pContext, const ma_device_id* pDeviceID, ma_device_type deviceType, ma_share_mode shareMode, const ma_device_descriptor* pDescriptor, const ma_device_config* pConfig, ma_device* pDevice, ma_AAudioStreamBuilder** ppBuilder) +{ + ma_AAudioStreamBuilder* pBuilder; + ma_aaudio_result_t resultAA; + + /* Safety. */ + *ppBuilder = 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 we have a device descriptor make sure we configure the stream builder to take our requested parameters. */ + if (pDescriptor != NULL) { + MA_ASSERT(pConfig != NULL); /* We must have a device config if we also have a descriptor. The config is required for AAudio specific configuration options. */ + + if (pDescriptor->sampleRate != 0) { + ((MA_PFN_AAudioStreamBuilder_setSampleRate)pContext->aaudio.AAudioStreamBuilder_setSampleRate)(pBuilder, pDescriptor->sampleRate); + } + + if (deviceType == ma_device_type_capture) { + if (pDescriptor->channels != 0) { + ((MA_PFN_AAudioStreamBuilder_setChannelCount)pContext->aaudio.AAudioStreamBuilder_setChannelCount)(pBuilder, pDescriptor->channels); + } + if (pDescriptor->format != ma_format_unknown) { + ((MA_PFN_AAudioStreamBuilder_setFormat)pContext->aaudio.AAudioStreamBuilder_setFormat)(pBuilder, (pDescriptor->format == ma_format_s16) ? MA_AAUDIO_FORMAT_PCM_I16 : MA_AAUDIO_FORMAT_PCM_FLOAT); + } + } else { + if (pDescriptor->channels != 0) { + ((MA_PFN_AAudioStreamBuilder_setChannelCount)pContext->aaudio.AAudioStreamBuilder_setChannelCount)(pBuilder, pDescriptor->channels); + } + if (pDescriptor->format != ma_format_unknown) { + ((MA_PFN_AAudioStreamBuilder_setFormat)pContext->aaudio.AAudioStreamBuilder_setFormat)(pBuilder, (pDescriptor->format == ma_format_s16) ? MA_AAUDIO_FORMAT_PCM_I16 : MA_AAUDIO_FORMAT_PCM_FLOAT); + } + } + + + /* + There have been reports where setting the frames per data callback results in an error + later on from Android. To address this, I'm experimenting with simply not setting it on + anything from Android 11 and earlier. Suggestions welcome on how we might be able to make + this more targetted. + */ + if (!pConfig->aaudio.enableCompatibilityWorkarounds || ma_android_sdk_version() > 30) { + /* + AAudio is annoying when it comes to it's buffer calculation stuff because it doesn't let you + retrieve the actual sample rate until after you've opened the stream. But you need to configure + the buffer capacity before you open the stream... :/ + + To solve, we're just going to assume MA_DEFAULT_SAMPLE_RATE (48000) and move on. + */ + ma_uint32 bufferCapacityInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, pDescriptor->sampleRate, pConfig->performanceProfile) * pDescriptor->periodCount; + + ((MA_PFN_AAudioStreamBuilder_setBufferCapacityInFrames)pContext->aaudio.AAudioStreamBuilder_setBufferCapacityInFrames)(pBuilder, bufferCapacityInFrames); + ((MA_PFN_AAudioStreamBuilder_setFramesPerDataCallback)pContext->aaudio.AAudioStreamBuilder_setFramesPerDataCallback)(pBuilder, bufferCapacityInFrames / pDescriptor->periodCount); + } + + if (deviceType == ma_device_type_capture) { + if (pConfig->aaudio.inputPreset != ma_aaudio_input_preset_default && pContext->aaudio.AAudioStreamBuilder_setInputPreset != NULL) { + ((MA_PFN_AAudioStreamBuilder_setInputPreset)pContext->aaudio.AAudioStreamBuilder_setInputPreset)(pBuilder, ma_to_input_preset__aaudio(pConfig->aaudio.inputPreset)); + } + + ((MA_PFN_AAudioStreamBuilder_setDataCallback)pContext->aaudio.AAudioStreamBuilder_setDataCallback)(pBuilder, ma_stream_data_callback_capture__aaudio, (void*)pDevice); + } else { + if (pConfig->aaudio.usage != ma_aaudio_usage_default && pContext->aaudio.AAudioStreamBuilder_setUsage != NULL) { + ((MA_PFN_AAudioStreamBuilder_setUsage)pContext->aaudio.AAudioStreamBuilder_setUsage)(pBuilder, ma_to_usage__aaudio(pConfig->aaudio.usage)); + } + + if (pConfig->aaudio.contentType != ma_aaudio_content_type_default && pContext->aaudio.AAudioStreamBuilder_setContentType != NULL) { + ((MA_PFN_AAudioStreamBuilder_setContentType)pContext->aaudio.AAudioStreamBuilder_setContentType)(pBuilder, ma_to_content_type__aaudio(pConfig->aaudio.contentType)); + } + + if (pConfig->aaudio.allowedCapturePolicy != ma_aaudio_allow_capture_default && pContext->aaudio.AAudioStreamBuilder_setAllowedCapturePolicy != NULL) { + ((MA_PFN_AAudioStreamBuilder_setAllowedCapturePolicy)pContext->aaudio.AAudioStreamBuilder_setAllowedCapturePolicy)(pBuilder, ma_to_allowed_capture_policy__aaudio(pConfig->aaudio.allowedCapturePolicy)); + } + + ((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); + + /* We need to set an error callback to detect device changes. */ + if (pDevice != NULL) { /* <-- pDevice should never be null if pDescriptor is not null, which is always the case if we hit this branch. Check anyway for safety. */ + ((MA_PFN_AAudioStreamBuilder_setErrorCallback)pContext->aaudio.AAudioStreamBuilder_setErrorCallback)(pBuilder, ma_stream_error_callback__aaudio, (void*)pDevice); + } + } + + *ppBuilder = pBuilder; + + return MA_SUCCESS; +} + +static ma_result ma_open_stream_and_close_builder__aaudio(ma_context* pContext, ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream** ppStream) +{ + ma_result result; + + result = ma_result_from_aaudio(((MA_PFN_AAudioStreamBuilder_openStream)pContext->aaudio.AAudioStreamBuilder_openStream)(pBuilder, ppStream)); + ((MA_PFN_AAudioStreamBuilder_delete)pContext->aaudio.AAudioStreamBuilder_delete)(pBuilder); + + return result; +} + +static ma_result ma_open_stream_basic__aaudio(ma_context* pContext, const ma_device_id* pDeviceID, ma_device_type deviceType, ma_share_mode shareMode, ma_AAudioStream** ppStream) +{ + ma_result result; + ma_AAudioStreamBuilder* pBuilder; + + *ppStream = NULL; + + result = ma_create_and_configure_AAudioStreamBuilder__aaudio(pContext, pDeviceID, deviceType, shareMode, NULL, NULL, NULL, &pBuilder); + if (result != MA_SUCCESS) { + return result; + } + + return ma_open_stream_and_close_builder__aaudio(pContext, pBuilder, ppStream); +} + +static ma_result ma_open_stream__aaudio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_type deviceType, const ma_device_descriptor* pDescriptor, ma_AAudioStream** ppStream) +{ + ma_result result; + ma_AAudioStreamBuilder* pBuilder; + + MA_ASSERT(pDevice != NULL); + MA_ASSERT(pDescriptor != NULL); + MA_ASSERT(deviceType != ma_device_type_duplex); /* This function should not be called for a full-duplex device type. */ + + *ppStream = NULL; + + result = ma_create_and_configure_AAudioStreamBuilder__aaudio(pDevice->pContext, pDescriptor->pDeviceID, deviceType, pDescriptor->shareMode, pDescriptor, pConfig, pDevice, &pBuilder); + if (result != MA_SUCCESS) { + return result; + } + + return ma_open_stream_and_close_builder__aaudio(pDevice->pContext, pBuilder, ppStream); +} + +static 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)); +} + +static 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_basic__aaudio(pContext, NULL, deviceType, ma_share_mode_shared, &pStream); + if (result != MA_SUCCESS) { + return MA_FALSE; + } + + ma_close_stream__aaudio(pContext, pStream); + return MA_TRUE; +} + +static 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; +} + + +static 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; +} + +static void ma_context_add_native_data_format_from_AAudioStream_ex__aaudio(ma_context* pContext, ma_AAudioStream* pStream, ma_format format, ma_uint32 flags, ma_device_info* pDeviceInfo) +{ + MA_ASSERT(pContext != NULL); + MA_ASSERT(pStream != NULL); + MA_ASSERT(pDeviceInfo != NULL); + + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = format; + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = ((MA_PFN_AAudioStream_getChannelCount)pContext->aaudio.AAudioStream_getChannelCount)(pStream); + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = ((MA_PFN_AAudioStream_getSampleRate)pContext->aaudio.AAudioStream_getSampleRate)(pStream); + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = flags; + pDeviceInfo->nativeDataFormatCount += 1; +} + +static void ma_context_add_native_data_format_from_AAudioStream__aaudio(ma_context* pContext, ma_AAudioStream* pStream, ma_uint32 flags, ma_device_info* pDeviceInfo) +{ + /* AAudio supports s16 and f32. */ + ma_context_add_native_data_format_from_AAudioStream_ex__aaudio(pContext, pStream, ma_format_f32, flags, pDeviceInfo); + ma_context_add_native_data_format_from_AAudioStream_ex__aaudio(pContext, pStream, ma_format_s16, flags, pDeviceInfo); +} + +static ma_result ma_context_get_device_info__aaudio(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo) +{ + ma_AAudioStream* pStream; + ma_result result; + + MA_ASSERT(pContext != NULL); + + /* 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); + } + + + pDeviceInfo->nativeDataFormatCount = 0; + + /* We'll need to open the device to get accurate sample rate and channel count information. */ + result = ma_open_stream_basic__aaudio(pContext, pDeviceID, deviceType, ma_share_mode_shared, &pStream); + if (result != MA_SUCCESS) { + return result; + } + + ma_context_add_native_data_format_from_AAudioStream__aaudio(pContext, pStream, 0, pDeviceInfo); + + ma_close_stream__aaudio(pContext, pStream); + pStream = NULL; + + return MA_SUCCESS; +} + + +static ma_result 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; + } + + return MA_SUCCESS; +} + +static ma_result ma_device_init_by_type__aaudio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_type deviceType, ma_device_descriptor* pDescriptor, ma_AAudioStream** ppStream) +{ + ma_result result; + int32_t bufferCapacityInFrames; + int32_t framesPerDataCallback; + ma_AAudioStream* pStream; + + MA_ASSERT(pDevice != NULL); + MA_ASSERT(pConfig != NULL); + MA_ASSERT(pDescriptor != NULL); + + *ppStream = NULL; /* Safety. */ + + /* First step is to open the stream. From there we'll be able to extract the internal configuration. */ + result = ma_open_stream__aaudio(pDevice, pConfig, deviceType, pDescriptor, &pStream); + if (result != MA_SUCCESS) { + return result; /* Failed to open the AAudio stream. */ + } + + /* Now extract the internal configuration. */ + pDescriptor->format = (((MA_PFN_AAudioStream_getFormat)pDevice->pContext->aaudio.AAudioStream_getFormat)(pStream) == MA_AAUDIO_FORMAT_PCM_I16) ? ma_format_s16 : ma_format_f32; + pDescriptor->channels = ((MA_PFN_AAudioStream_getChannelCount)pDevice->pContext->aaudio.AAudioStream_getChannelCount)(pStream); + pDescriptor->sampleRate = ((MA_PFN_AAudioStream_getSampleRate)pDevice->pContext->aaudio.AAudioStream_getSampleRate)(pStream); + + /* For the channel map we need to be sure we don't overflow any buffers. */ + if (pDescriptor->channels <= MA_MAX_CHANNELS) { + ma_channel_map_init_standard(ma_standard_channel_map_default, pDescriptor->channelMap, ma_countof(pDescriptor->channelMap), pDescriptor->channels); /* <-- Cannot find info on channel order, so assuming a default. */ + } else { + ma_channel_map_init_blank(pDescriptor->channelMap, MA_MAX_CHANNELS); /* Too many channels. Use a blank channel map. */ + } + + bufferCapacityInFrames = ((MA_PFN_AAudioStream_getBufferCapacityInFrames)pDevice->pContext->aaudio.AAudioStream_getBufferCapacityInFrames)(pStream); + framesPerDataCallback = ((MA_PFN_AAudioStream_getFramesPerDataCallback)pDevice->pContext->aaudio.AAudioStream_getFramesPerDataCallback)(pStream); + + if (framesPerDataCallback > 0) { + pDescriptor->periodSizeInFrames = framesPerDataCallback; + pDescriptor->periodCount = bufferCapacityInFrames / framesPerDataCallback; + } else { + pDescriptor->periodSizeInFrames = bufferCapacityInFrames; + pDescriptor->periodCount = 1; + } + + *ppStream = pStream; + + return MA_SUCCESS; +} + +static ma_result ma_device_init__aaudio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture) +{ + ma_result result; + + MA_ASSERT(pDevice != NULL); + + if (pConfig->deviceType == ma_device_type_loopback) { + return MA_DEVICE_TYPE_NOT_SUPPORTED; + } + + pDevice->aaudio.usage = pConfig->aaudio.usage; + pDevice->aaudio.contentType = pConfig->aaudio.contentType; + pDevice->aaudio.inputPreset = pConfig->aaudio.inputPreset; + pDevice->aaudio.allowedCapturePolicy = pConfig->aaudio.allowedCapturePolicy; + pDevice->aaudio.noAutoStartAfterReroute = pConfig->aaudio.noAutoStartAfterReroute; + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + result = ma_device_init_by_type__aaudio(pDevice, pConfig, ma_device_type_capture, pDescriptorCapture, (ma_AAudioStream**)&pDevice->aaudio.pStreamCapture); + 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__aaudio(pDevice, pConfig, ma_device_type_playback, pDescriptorPlayback, (ma_AAudioStream**)&pDevice->aaudio.pStreamPlayback); + if (result != MA_SUCCESS) { + return result; + } + } + + return MA_SUCCESS; +} + +static 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); + + 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. */ + 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; +} + +static 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); + + /* + From the AAudio documentation: + + The stream will stop after all of the data currently buffered has been played. + + This maps with miniaudio's requirement that device's be drained which means we don't need to implement any draining logic. + */ + currentState = ((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream); + if (currentState == MA_AAUDIO_STREAM_STATE_DISCONNECTED) { + return MA_SUCCESS; /* The device is disconnected. Don't try stopping it. */ + } + + 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. */ + 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; +} + +static 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; +} + +static 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_device__on_notification_stopped(pDevice); + + return MA_SUCCESS; +} + +static ma_result ma_device_reinit__aaudio(ma_device* pDevice, ma_device_type deviceType) +{ + ma_result result; + + MA_ASSERT(pDevice != NULL); + + /* The first thing to do is close the streams. */ + if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex) { + ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture); + pDevice->aaudio.pStreamCapture = NULL; + } + + if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) { + ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback); + pDevice->aaudio.pStreamPlayback = NULL; + } + + /* Now we need to reinitialize each streams. The hardest part with this is just filling output the config and descriptors. */ + { + ma_device_config deviceConfig; + ma_device_descriptor descriptorPlayback; + ma_device_descriptor descriptorCapture; + + deviceConfig = ma_device_config_init(deviceType); + deviceConfig.playback.pDeviceID = NULL; /* Only doing rerouting with default devices. */ + deviceConfig.playback.shareMode = pDevice->playback.shareMode; + deviceConfig.playback.format = pDevice->playback.format; + deviceConfig.playback.channels = pDevice->playback.channels; + deviceConfig.capture.pDeviceID = NULL; /* Only doing rerouting with default devices. */ + deviceConfig.capture.shareMode = pDevice->capture.shareMode; + deviceConfig.capture.format = pDevice->capture.format; + deviceConfig.capture.channels = pDevice->capture.channels; + deviceConfig.sampleRate = pDevice->sampleRate; + deviceConfig.aaudio.usage = pDevice->aaudio.usage; + deviceConfig.aaudio.contentType = pDevice->aaudio.contentType; + deviceConfig.aaudio.inputPreset = pDevice->aaudio.inputPreset; + deviceConfig.aaudio.allowedCapturePolicy = pDevice->aaudio.allowedCapturePolicy; + deviceConfig.aaudio.noAutoStartAfterReroute = pDevice->aaudio.noAutoStartAfterReroute; + deviceConfig.periods = 1; + + /* Try to get an accurate period size. */ + if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) { + deviceConfig.periodSizeInFrames = pDevice->playback.internalPeriodSizeInFrames; + } else { + deviceConfig.periodSizeInFrames = pDevice->capture.internalPeriodSizeInFrames; + } + + if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) { + descriptorCapture.pDeviceID = deviceConfig.capture.pDeviceID; + descriptorCapture.shareMode = deviceConfig.capture.shareMode; + descriptorCapture.format = deviceConfig.capture.format; + descriptorCapture.channels = deviceConfig.capture.channels; + descriptorCapture.sampleRate = deviceConfig.sampleRate; + descriptorCapture.periodSizeInFrames = deviceConfig.periodSizeInFrames; + descriptorCapture.periodCount = deviceConfig.periods; + } + + if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) { + descriptorPlayback.pDeviceID = deviceConfig.playback.pDeviceID; + descriptorPlayback.shareMode = deviceConfig.playback.shareMode; + descriptorPlayback.format = deviceConfig.playback.format; + descriptorPlayback.channels = deviceConfig.playback.channels; + descriptorPlayback.sampleRate = deviceConfig.sampleRate; + descriptorPlayback.periodSizeInFrames = deviceConfig.periodSizeInFrames; + descriptorPlayback.periodCount = deviceConfig.periods; + } + + result = ma_device_init__aaudio(pDevice, &deviceConfig, &descriptorPlayback, &descriptorCapture); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_device_post_init(pDevice, deviceType, &descriptorPlayback, &descriptorCapture); + if (result != MA_SUCCESS) { + ma_device_uninit__aaudio(pDevice); + return result; + } + + /* We'll only ever do this in response to a reroute. */ + ma_device__on_notification_rerouted(pDevice); + + /* If the device is started, start the streams. Maybe make this configurable? */ + if (ma_device_get_state(pDevice) == ma_device_state_started) { + if (pDevice->aaudio.noAutoStartAfterReroute == MA_FALSE) { + ma_device_start__aaudio(pDevice); + } else { + ma_device_stop(pDevice); /* Do a full device stop so we set internal state correctly. */ + } + } + + return MA_SUCCESS; + } +} + +static ma_result ma_device_get_info__aaudio(ma_device* pDevice, ma_device_type type, ma_device_info* pDeviceInfo) +{ + ma_AAudioStream* pStream = NULL; + + MA_ASSERT(pDevice != NULL); + MA_ASSERT(type != ma_device_type_duplex); + MA_ASSERT(pDeviceInfo != NULL); + + if (type == ma_device_type_playback) { + pStream = (ma_AAudioStream*)pDevice->aaudio.pStreamCapture; + pDeviceInfo->id.aaudio = pDevice->capture.id.aaudio; + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); /* Only supporting default devices. */ + } + if (type == ma_device_type_capture) { + pStream = (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback; + pDeviceInfo->id.aaudio = pDevice->playback.id.aaudio; + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); /* Only supporting default devices. */ + } + + /* Safety. Should never happen. */ + if (pStream == NULL) { + return MA_INVALID_OPERATION; + } + + pDeviceInfo->nativeDataFormatCount = 0; + ma_context_add_native_data_format_from_AAudioStream__aaudio(pDevice->pContext, pStream, 0, pDeviceInfo); + + return MA_SUCCESS; +} + + +static ma_result ma_context_uninit__aaudio(ma_context* pContext) +{ + MA_ASSERT(pContext != NULL); + MA_ASSERT(pContext->backend == ma_backend_aaudio); + + ma_device_job_thread_uninit(&pContext->aaudio.jobThread, &pContext->allocationCallbacks); + + ma_dlclose(ma_context_get_log(pContext), pContext->aaudio.hAAudio); + pContext->aaudio.hAAudio = NULL; + + return MA_SUCCESS; +} + +static ma_result ma_context_init__aaudio(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks) +{ + size_t i; + const char* libNames[] = { + "libaaudio.so" + }; + + for (i = 0; i < ma_countof(libNames); ++i) { + pContext->aaudio.hAAudio = ma_dlopen(ma_context_get_log(pContext), 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(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudio_createStreamBuilder"); + pContext->aaudio.AAudioStreamBuilder_delete = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_delete"); + pContext->aaudio.AAudioStreamBuilder_setDeviceId = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setDeviceId"); + pContext->aaudio.AAudioStreamBuilder_setDirection = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setDirection"); + pContext->aaudio.AAudioStreamBuilder_setSharingMode = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setSharingMode"); + pContext->aaudio.AAudioStreamBuilder_setFormat = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setFormat"); + pContext->aaudio.AAudioStreamBuilder_setChannelCount = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setChannelCount"); + pContext->aaudio.AAudioStreamBuilder_setSampleRate = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setSampleRate"); + pContext->aaudio.AAudioStreamBuilder_setBufferCapacityInFrames = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setBufferCapacityInFrames"); + pContext->aaudio.AAudioStreamBuilder_setFramesPerDataCallback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setFramesPerDataCallback"); + pContext->aaudio.AAudioStreamBuilder_setDataCallback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setDataCallback"); + pContext->aaudio.AAudioStreamBuilder_setErrorCallback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setErrorCallback"); + pContext->aaudio.AAudioStreamBuilder_setPerformanceMode = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setPerformanceMode"); + pContext->aaudio.AAudioStreamBuilder_setUsage = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setUsage"); + pContext->aaudio.AAudioStreamBuilder_setContentType = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setContentType"); + pContext->aaudio.AAudioStreamBuilder_setInputPreset = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setInputPreset"); + pContext->aaudio.AAudioStreamBuilder_setAllowedCapturePolicy = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setAllowedCapturePolicy"); + pContext->aaudio.AAudioStreamBuilder_openStream = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_openStream"); + pContext->aaudio.AAudioStream_close = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_close"); + pContext->aaudio.AAudioStream_getState = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_getState"); + pContext->aaudio.AAudioStream_waitForStateChange = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_waitForStateChange"); + pContext->aaudio.AAudioStream_getFormat = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_getFormat"); + pContext->aaudio.AAudioStream_getChannelCount = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_getChannelCount"); + pContext->aaudio.AAudioStream_getSampleRate = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_getSampleRate"); + pContext->aaudio.AAudioStream_getBufferCapacityInFrames = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_getBufferCapacityInFrames"); + pContext->aaudio.AAudioStream_getFramesPerDataCallback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_getFramesPerDataCallback"); + pContext->aaudio.AAudioStream_getFramesPerBurst = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_getFramesPerBurst"); + pContext->aaudio.AAudioStream_requestStart = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_requestStart"); + pContext->aaudio.AAudioStream_requestStop = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_requestStop"); + + + pCallbacks->onContextInit = ma_context_init__aaudio; + pCallbacks->onContextUninit = ma_context_uninit__aaudio; + pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__aaudio; + pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__aaudio; + pCallbacks->onDeviceInit = ma_device_init__aaudio; + pCallbacks->onDeviceUninit = ma_device_uninit__aaudio; + pCallbacks->onDeviceStart = ma_device_start__aaudio; + pCallbacks->onDeviceStop = ma_device_stop__aaudio; + pCallbacks->onDeviceRead = NULL; /* Not used because AAudio is asynchronous. */ + pCallbacks->onDeviceWrite = NULL; /* Not used because AAudio is asynchronous. */ + pCallbacks->onDeviceDataLoop = NULL; /* Not used because AAudio is asynchronous. */ + pCallbacks->onDeviceGetInfo = ma_device_get_info__aaudio; + + + /* We need a job thread so we can deal with rerouting. */ + { + ma_result result; + ma_device_job_thread_config jobThreadConfig; + + jobThreadConfig = ma_device_job_thread_config_init(); + + result = ma_device_job_thread_init(&jobThreadConfig, &pContext->allocationCallbacks, &pContext->aaudio.jobThread); + if (result != MA_SUCCESS) { + ma_dlclose(ma_context_get_log(pContext), pContext->aaudio.hAAudio); + pContext->aaudio.hAAudio = NULL; + return result; + } + } + + + (void)pConfig; + return MA_SUCCESS; +} + +static ma_result ma_job_process__device__aaudio_reroute(ma_job* pJob) +{ + ma_device* pDevice; + + MA_ASSERT(pJob != NULL); + + pDevice = (ma_device*)pJob->data.device.aaudio.reroute.pDevice; + MA_ASSERT(pDevice != NULL); + + /* Here is where we need to reroute the device. To do this we need to uninitialize the stream and reinitialize it. */ + return ma_device_reinit__aaudio(pDevice, (ma_device_type)pJob->data.device.aaudio.reroute.deviceType); +} +#else +/* Getting here means there is no AAudio backend so we need a no-op job implementation. */ +static ma_result ma_job_process__device__aaudio_reroute(ma_job* pJob) +{ + return ma_job_process__noop(pJob); +} +#endif /* AAudio */ + + +/****************************************************************************** + +OpenSL|ES Backend + +******************************************************************************/ +#ifdef MA_HAS_OPENSL +#include +#ifdef MA_ANDROID +#include +#endif + +typedef SLresult (SLAPIENTRY * ma_slCreateEngine_proc)(SLObjectItf* pEngine, SLuint32 numOptions, SLEngineOption* pEngineOptions, SLuint32 numInterfaces, SLInterfaceID* pInterfaceIds, SLboolean* pInterfaceRequired); + +/* OpenSL|ES has one-per-application objects :( */ +static SLObjectItf g_maEngineObjectSL = NULL; +static SLEngineItf g_maEngineSL = NULL; +static ma_uint32 g_maOpenSLInitCounter = 0; +static ma_spinlock g_maOpenSLSpinlock = 0; /* For init/uninit. */ + +#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 + +static ma_result ma_result_from_OpenSL(SLuint32 result) +{ + switch (result) + { + case SL_RESULT_SUCCESS: return MA_SUCCESS; + case SL_RESULT_PRECONDITIONS_VIOLATED: return MA_ERROR; + case SL_RESULT_PARAMETER_INVALID: return MA_INVALID_ARGS; + case SL_RESULT_MEMORY_FAILURE: return MA_OUT_OF_MEMORY; + case SL_RESULT_RESOURCE_ERROR: return MA_INVALID_DATA; + case SL_RESULT_RESOURCE_LOST: return MA_ERROR; + case SL_RESULT_IO_ERROR: return MA_IO_ERROR; + case SL_RESULT_BUFFER_INSUFFICIENT: return MA_NO_SPACE; + case SL_RESULT_CONTENT_CORRUPTED: return MA_INVALID_DATA; + case SL_RESULT_CONTENT_UNSUPPORTED: return MA_FORMAT_NOT_SUPPORTED; + case SL_RESULT_CONTENT_NOT_FOUND: return MA_ERROR; + case SL_RESULT_PERMISSION_DENIED: return MA_ACCESS_DENIED; + case SL_RESULT_FEATURE_UNSUPPORTED: return MA_NOT_IMPLEMENTED; + case SL_RESULT_INTERNAL_ERROR: return MA_ERROR; + case SL_RESULT_UNKNOWN_ERROR: return MA_ERROR; + case SL_RESULT_OPERATION_ABORTED: return MA_ERROR; + case SL_RESULT_CONTROL_LOST: return MA_ERROR; + default: return MA_ERROR; + } +} + +/* Converts an individual OpenSL-style channel identifier (SL_SPEAKER_FRONT_LEFT, etc.) to miniaudio. */ +static 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. */ +static 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. */ +static SLuint32 ma_channel_map_to_channel_mask__opensl(const ma_channel* pChannelMap, ma_uint32 channels) +{ + SLuint32 channelMask = 0; + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; ++iChannel) { + channelMask |= ma_channel_id_to_opensl(pChannelMap[iChannel]); + } + + return channelMask; +} + +/* Converts an OpenSL-style channel mask to a miniaudio channel map. */ +static void ma_channel_mask_to_channel_map__opensl(SLuint32 channelMask, ma_uint32 channels, ma_channel* pChannelMap) +{ + if (channels == 1 && channelMask == 0) { + pChannelMap[0] = MA_CHANNEL_MONO; + } else if (channels == 2 && channelMask == 0) { + pChannelMap[0] = MA_CHANNEL_FRONT_LEFT; + pChannelMap[1] = MA_CHANNEL_FRONT_RIGHT; + } else { + if (channels == 1 && (channelMask & SL_SPEAKER_FRONT_CENTER) != 0) { + pChannelMap[0] = MA_CHANNEL_MONO; + } else { + /* Just iterate over each bit. */ + ma_uint32 iChannel = 0; + ma_uint32 iBit; + for (iBit = 0; iBit < 32 && iChannel < channels; ++iBit) { + SLuint32 bitValue = (channelMask & (1UL << iBit)); + if (bitValue != 0) { + /* The bit is set. */ + pChannelMap[iChannel] = ma_channel_id_to_ma__opensl(bitValue); + iChannel += 1; + } + } + } + } +} + +static 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; +} + + +static SLint32 ma_to_stream_type__opensl(ma_opensl_stream_type streamType) +{ + switch (streamType) { + case ma_opensl_stream_type_voice: return SL_ANDROID_STREAM_VOICE; + case ma_opensl_stream_type_system: return SL_ANDROID_STREAM_SYSTEM; + case ma_opensl_stream_type_ring: return SL_ANDROID_STREAM_RING; + case ma_opensl_stream_type_media: return SL_ANDROID_STREAM_MEDIA; + case ma_opensl_stream_type_alarm: return SL_ANDROID_STREAM_ALARM; + case ma_opensl_stream_type_notification: return SL_ANDROID_STREAM_NOTIFICATION; + default: break; + } + + return SL_ANDROID_STREAM_VOICE; +} + +static SLint32 ma_to_recording_preset__opensl(ma_opensl_recording_preset recordingPreset) +{ + switch (recordingPreset) { + case ma_opensl_recording_preset_generic: return SL_ANDROID_RECORDING_PRESET_GENERIC; + case ma_opensl_recording_preset_camcorder: return SL_ANDROID_RECORDING_PRESET_CAMCORDER; + case ma_opensl_recording_preset_voice_recognition: return SL_ANDROID_RECORDING_PRESET_VOICE_RECOGNITION; + case ma_opensl_recording_preset_voice_communication: return SL_ANDROID_RECORDING_PRESET_VOICE_COMMUNICATION; + case ma_opensl_recording_preset_voice_unprocessed: return SL_ANDROID_RECORDING_PRESET_UNPROCESSED; + default: break; + } + + return SL_ANDROID_RECORDING_PRESET_NONE; +} + + +static 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); + + 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, (SLInterfaceID)pContext->opensl.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_result_from_OpenSL(resultSL); + } + + 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_result_from_OpenSL(resultSL); + } + + 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:; + cbResult = MA_TRUE; + + /* Playback. */ + if (cbResult) { + ma_device_info deviceInfo; + MA_ZERO_OBJECT(&deviceInfo); + deviceInfo.id.opensl = SL_DEFAULTDEVICEID_AUDIOOUTPUT; + 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); + deviceInfo.id.opensl = SL_DEFAULTDEVICEID_AUDIOINPUT; + 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; +} + +static void ma_context_add_data_format_ex__opensl(ma_context* pContext, ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_device_info* pDeviceInfo) +{ + MA_ASSERT(pContext != NULL); + MA_ASSERT(pDeviceInfo != NULL); + + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = format; + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels; + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = sampleRate; + pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = 0; + pDeviceInfo->nativeDataFormatCount += 1; +} + +static void ma_context_add_data_format__opensl(ma_context* pContext, ma_format format, ma_device_info* pDeviceInfo) +{ + ma_uint32 minChannels = 1; + ma_uint32 maxChannels = 2; + ma_uint32 minSampleRate = (ma_uint32)ma_standard_sample_rate_8000; + ma_uint32 maxSampleRate = (ma_uint32)ma_standard_sample_rate_48000; + ma_uint32 iChannel; + ma_uint32 iSampleRate; + + MA_ASSERT(pContext != NULL); + MA_ASSERT(pDeviceInfo != NULL); + + /* + Each sample format can support mono and stereo, and we'll support a small subset of standard + rates (up to 48000). A better solution would be to somehow find a native sample rate. + */ + for (iChannel = minChannels; iChannel < maxChannels; iChannel += 1) { + for (iSampleRate = 0; iSampleRate < ma_countof(g_maStandardSampleRatePriorities); iSampleRate += 1) { + ma_uint32 standardSampleRate = g_maStandardSampleRatePriorities[iSampleRate]; + if (standardSampleRate >= minSampleRate && standardSampleRate <= maxSampleRate) { + ma_context_add_data_format_ex__opensl(pContext, format, iChannel, standardSampleRate, pDeviceInfo); + } + } + } +} + +static ma_result ma_context_get_device_info__opensl(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, 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; + } + + /* + 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, (SLInterfaceID)pContext->opensl.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_result_from_OpenSL(resultSL); + } + + 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_result_from_OpenSL(resultSL); + } + + 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. */ + } + } + + /* ID and Name / Description */ + if (deviceType == ma_device_type_playback) { + pDeviceInfo->id.opensl = SL_DEFAULTDEVICEID_AUDIOOUTPUT; + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); + } else { + pDeviceInfo->id.opensl = SL_DEFAULTDEVICEID_AUDIOINPUT; + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); + } + + pDeviceInfo->isDefault = MA_TRUE; + + 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->nativeDataFormatCount = 0; +#if defined(MA_ANDROID) && __ANDROID_API__ >= 21 + ma_context_add_data_format__opensl(pContext, ma_format_f32, pDeviceInfo); +#endif + ma_context_add_data_format__opensl(pContext, ma_format_s16, pDeviceInfo); + ma_context_add_data_format__opensl(pContext, ma_format_u8, pDeviceInfo); + + 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)*/ +static 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 :( + */ + + /* Don't do anything if the device is not started. */ + if (ma_device_get_state(pDevice) != ma_device_state_started) { + return; + } + + /* Don't do anything if the device is being drained. */ + if (pDevice->opensl.isDrainingCapture) { + return; + } + + periodSizeInBytes = pDevice->capture.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + pBuffer = pDevice->opensl.pBufferCapture + (pDevice->opensl.currentBufferIndexCapture * periodSizeInBytes); + + ma_device_handle_backend_data_callback(pDevice, NULL, pBuffer, pDevice->capture.internalPeriodSizeInFrames); + + 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; +} + +static 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; + + /* Don't do anything if the device is not started. */ + if (ma_device_get_state(pDevice) != ma_device_state_started) { + return; + } + + /* Don't do anything if the device is being drained. */ + if (pDevice->opensl.isDrainingPlayback) { + return; + } + + periodSizeInBytes = pDevice->playback.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + pBuffer = pDevice->opensl.pBufferPlayback + (pDevice->opensl.currentBufferIndexPlayback * periodSizeInBytes); + + ma_device_handle_backend_data_callback(pDevice, pBuffer, NULL, pDevice->playback.internalPeriodSizeInFrames); + + 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 + +static ma_result 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 MA_INVALID_OPERATION; + } + + 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, &pDevice->pContext->allocationCallbacks); + } + + 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, &pDevice->pContext->allocationCallbacks); + } + + return MA_SUCCESS; +} + +#if defined(MA_ANDROID) && __ANDROID_API__ >= 21 +typedef SLAndroidDataFormat_PCM_EX ma_SLDataFormat_PCM; +#else +typedef SLDataFormat_PCM ma_SLDataFormat_PCM; +#endif + +static ma_result ma_SLDataFormat_PCM_init__opensl(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, const ma_channel* channelMap, ma_SLDataFormat_PCM* pDataFormat) +{ + /* We need to convert our format/channels/rate so that they aren't set to default. */ + if (format == ma_format_unknown) { + format = MA_DEFAULT_FORMAT; + } + if (channels == 0) { + channels = MA_DEFAULT_CHANNELS; + } + if (sampleRate == 0) { + sampleRate = MA_DEFAULT_SAMPLE_RATE; + } + +#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; +} + +static ma_result ma_deconstruct_SLDataFormat_PCM__opensl(ma_SLDataFormat_PCM* pDataFormat, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + 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, ma_min(pDataFormat->numChannels, channelMapCap), pChannelMap); + + return MA_SUCCESS; +} + +static ma_result ma_device_init__opensl(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture) +{ +#ifdef MA_ANDROID + SLDataLocator_AndroidSimpleBufferQueue queue; + SLresult resultSL; + size_t bufferSizeInBytes; + SLInterfaceID itfIDs[2]; + const SLboolean itfIDsRequired[] = { + SL_BOOLEAN_TRUE, /* SL_IID_ANDROIDSIMPLEBUFFERQUEUE */ + SL_BOOLEAN_FALSE /* SL_IID_ANDROIDCONFIGURATION */ + }; +#endif + + 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; + } + + if (pConfig->deviceType == ma_device_type_loopback) { + return MA_DEVICE_TYPE_NOT_SUPPORTED; + } + + /* + 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). + */ +#ifdef MA_ANDROID + itfIDs[0] = (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE; + itfIDs[1] = (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDCONFIGURATION; + + /* No exclusive mode with OpenSL|ES. */ + if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive) || + ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->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); + + queue.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE; + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + ma_SLDataFormat_PCM pcm; + SLDataLocator_IODevice locatorDevice; + SLDataSource source; + SLDataSink sink; + SLAndroidConfigurationItf pRecorderConfig; + + ma_SLDataFormat_PCM_init__opensl(pDescriptorCapture->format, pDescriptorCapture->channels, pDescriptorCapture->sampleRate, pDescriptorCapture->channelMap, &pcm); + + locatorDevice.locatorType = SL_DATALOCATOR_IODEVICE; + locatorDevice.deviceType = SL_IODEVICE_AUDIOINPUT; + locatorDevice.deviceID = SL_DEFAULTDEVICEID_AUDIOINPUT; /* Must always use the default device with Android. */ + locatorDevice.device = NULL; + + source.pLocator = &locatorDevice; + source.pFormat = NULL; + + queue.numBuffers = pDescriptorCapture->periodCount; + + sink.pLocator = &queue; + sink.pFormat = (SLDataFormat_PCM*)&pcm; + + resultSL = (*g_maEngineSL)->CreateAudioRecorder(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioRecorderObj, &source, &sink, ma_countof(itfIDs), itfIDs, itfIDsRequired); + if (resultSL == SL_RESULT_CONTENT_UNSUPPORTED || resultSL == SL_RESULT_PARAMETER_INVALID) { + /* 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 = 0; + resultSL = (*g_maEngineSL)->CreateAudioRecorder(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioRecorderObj, &source, &sink, ma_countof(itfIDs), itfIDs, itfIDsRequired); + } + + if (resultSL != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to create audio recorder."); + return ma_result_from_OpenSL(resultSL); + } + + + /* Set the recording preset before realizing the player. */ + if (pConfig->opensl.recordingPreset != ma_opensl_recording_preset_default) { + resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioRecorderObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDCONFIGURATION, &pRecorderConfig); + if (resultSL == SL_RESULT_SUCCESS) { + SLint32 recordingPreset = ma_to_recording_preset__opensl(pConfig->opensl.recordingPreset); + resultSL = (*pRecorderConfig)->SetConfiguration(pRecorderConfig, SL_ANDROID_KEY_RECORDING_PRESET, &recordingPreset, sizeof(SLint32)); + if (resultSL != SL_RESULT_SUCCESS) { + /* Failed to set the configuration. Just keep going. */ + } + } + } + + resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->Realize((SLObjectItf)pDevice->opensl.pAudioRecorderObj, SL_BOOLEAN_FALSE); + if (resultSL != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to realize audio recorder."); + return ma_result_from_OpenSL(resultSL); + } + + resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioRecorderObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_RECORD, &pDevice->opensl.pAudioRecorder); + if (resultSL != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_RECORD interface."); + return ma_result_from_OpenSL(resultSL); + } + + resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioRecorderObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &pDevice->opensl.pBufferQueueCapture); + if (resultSL != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_ANDROIDSIMPLEBUFFERQUEUE interface."); + return ma_result_from_OpenSL(resultSL); + } + + resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->RegisterCallback((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture, ma_buffer_queue_callback_capture__opensl_android, pDevice); + if (resultSL != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to register buffer queue callback."); + return ma_result_from_OpenSL(resultSL); + } + + /* The internal format is determined by the "pcm" object. */ + ma_deconstruct_SLDataFormat_PCM__opensl(&pcm, &pDescriptorCapture->format, &pDescriptorCapture->channels, &pDescriptorCapture->sampleRate, pDescriptorCapture->channelMap, ma_countof(pDescriptorCapture->channelMap)); + + /* Buffer. */ + pDescriptorCapture->periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptorCapture, pDescriptorCapture->sampleRate, pConfig->performanceProfile); + pDevice->opensl.currentBufferIndexCapture = 0; + + bufferSizeInBytes = pDescriptorCapture->periodSizeInFrames * ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels) * pDescriptorCapture->periodCount; + pDevice->opensl.pBufferCapture = (ma_uint8*)ma_calloc(bufferSizeInBytes, &pDevice->pContext->allocationCallbacks); + if (pDevice->opensl.pBufferCapture == NULL) { + ma_device_uninit__opensl(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to allocate memory for data buffer."); + return 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; + SLDataSource source; + SLDataLocator_OutputMix outmixLocator; + SLDataSink sink; + SLAndroidConfigurationItf pPlayerConfig; + + ma_SLDataFormat_PCM_init__opensl(pDescriptorPlayback->format, pDescriptorPlayback->channels, pDescriptorPlayback->sampleRate, pDescriptorPlayback->channelMap, &pcm); + + resultSL = (*g_maEngineSL)->CreateOutputMix(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pOutputMixObj, 0, NULL, NULL); + if (resultSL != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to create output mix."); + return ma_result_from_OpenSL(resultSL); + } + + resultSL = MA_OPENSL_OBJ(pDevice->opensl.pOutputMixObj)->Realize((SLObjectItf)pDevice->opensl.pOutputMixObj, SL_BOOLEAN_FALSE); + if (resultSL != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to realize output mix object."); + return ma_result_from_OpenSL(resultSL); + } + + resultSL = MA_OPENSL_OBJ(pDevice->opensl.pOutputMixObj)->GetInterface((SLObjectItf)pDevice->opensl.pOutputMixObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_OUTPUTMIX, &pDevice->opensl.pOutputMix); + if (resultSL != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_OUTPUTMIX interface."); + return ma_result_from_OpenSL(resultSL); + } + + /* Set the output device. */ + if (pDescriptorPlayback->pDeviceID != NULL) { + SLuint32 deviceID_OpenSL = pDescriptorPlayback->pDeviceID->opensl; + MA_OPENSL_OUTPUTMIX(pDevice->opensl.pOutputMix)->ReRoute((SLOutputMixItf)pDevice->opensl.pOutputMix, 1, &deviceID_OpenSL); + } + + queue.numBuffers = pDescriptorPlayback->periodCount; + + source.pLocator = &queue; + source.pFormat = (SLDataFormat_PCM*)&pcm; + + outmixLocator.locatorType = SL_DATALOCATOR_OUTPUTMIX; + outmixLocator.outputMix = (SLObjectItf)pDevice->opensl.pOutputMixObj; + + sink.pLocator = &outmixLocator; + sink.pFormat = NULL; + + resultSL = (*g_maEngineSL)->CreateAudioPlayer(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioPlayerObj, &source, &sink, ma_countof(itfIDs), itfIDs, itfIDsRequired); + if (resultSL == SL_RESULT_CONTENT_UNSUPPORTED || resultSL == SL_RESULT_PARAMETER_INVALID) { + /* 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, ma_countof(itfIDs), itfIDs, itfIDsRequired); + } + + if (resultSL != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to create audio player."); + return ma_result_from_OpenSL(resultSL); + } + + + /* Set the stream type before realizing the player. */ + if (pConfig->opensl.streamType != ma_opensl_stream_type_default) { + resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioPlayerObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDCONFIGURATION, &pPlayerConfig); + if (resultSL == SL_RESULT_SUCCESS) { + SLint32 streamType = ma_to_stream_type__opensl(pConfig->opensl.streamType); + resultSL = (*pPlayerConfig)->SetConfiguration(pPlayerConfig, SL_ANDROID_KEY_STREAM_TYPE, &streamType, sizeof(SLint32)); + if (resultSL != SL_RESULT_SUCCESS) { + /* Failed to set the configuration. Just keep going. */ + } + } + } + + resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->Realize((SLObjectItf)pDevice->opensl.pAudioPlayerObj, SL_BOOLEAN_FALSE); + if (resultSL != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to realize audio player."); + return ma_result_from_OpenSL(resultSL); + } + + resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioPlayerObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_PLAY, &pDevice->opensl.pAudioPlayer); + if (resultSL != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_PLAY interface."); + return ma_result_from_OpenSL(resultSL); + } + + resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioPlayerObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &pDevice->opensl.pBufferQueuePlayback); + if (resultSL != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_ANDROIDSIMPLEBUFFERQUEUE interface."); + return ma_result_from_OpenSL(resultSL); + } + + resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->RegisterCallback((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback, ma_buffer_queue_callback_playback__opensl_android, pDevice); + if (resultSL != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to register buffer queue callback."); + return ma_result_from_OpenSL(resultSL); + } + + /* The internal format is determined by the "pcm" object. */ + ma_deconstruct_SLDataFormat_PCM__opensl(&pcm, &pDescriptorPlayback->format, &pDescriptorPlayback->channels, &pDescriptorPlayback->sampleRate, pDescriptorPlayback->channelMap, ma_countof(pDescriptorPlayback->channelMap)); + + /* Buffer. */ + pDescriptorPlayback->periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptorPlayback, pDescriptorPlayback->sampleRate, pConfig->performanceProfile); + pDevice->opensl.currentBufferIndexPlayback = 0; + + bufferSizeInBytes = pDescriptorPlayback->periodSizeInFrames * ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels) * pDescriptorPlayback->periodCount; + pDevice->opensl.pBufferPlayback = (ma_uint8*)ma_calloc(bufferSizeInBytes, &pDevice->pContext->allocationCallbacks); + if (pDevice->opensl.pBufferPlayback == NULL) { + ma_device_uninit__opensl(pDevice); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to allocate memory for data buffer."); + return MA_OUT_OF_MEMORY; + } + MA_ZERO_MEMORY(pDevice->opensl.pBufferPlayback, bufferSizeInBytes); + } + + return MA_SUCCESS; +#else + return MA_NO_BACKEND; /* Non-Android implementations are not supported. */ +#endif +} + +static 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. */ + if (g_maOpenSLInitCounter == 0) { + return MA_INVALID_OPERATION; + } + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + resultSL = MA_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_RECORDING); + if (resultSL != SL_RESULT_SUCCESS) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to start internal capture device."); + return ma_result_from_OpenSL(resultSL); + } + + periodSizeInBytes = pDevice->capture.internalPeriodSizeInFrames * 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.pBufferQueueCapture)->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); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to enqueue buffer for capture device."); + return ma_result_from_OpenSL(resultSL); + } + } + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + resultSL = MA_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_PLAYING); + if (resultSL != SL_RESULT_SUCCESS) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to start internal playback device."); + return ma_result_from_OpenSL(resultSL); + } + + /* In playback mode (no duplex) we need to load some initial buffers. In duplex mode we need to enqueue silent buffers. */ + if (pDevice->type == ma_device_type_duplex) { + MA_ZERO_MEMORY(pDevice->opensl.pBufferPlayback, pDevice->playback.internalPeriodSizeInFrames * pDevice->playback.internalPeriods * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels)); + } else { + ma_device__read_frames_from_client(pDevice, pDevice->playback.internalPeriodSizeInFrames * pDevice->playback.internalPeriods, pDevice->opensl.pBufferPlayback); + } + + periodSizeInBytes = pDevice->playback.internalPeriodSizeInFrames * 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); + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to enqueue buffer for playback device."); + return ma_result_from_OpenSL(resultSL); + } + } + } + + return MA_SUCCESS; +} + +static ma_result ma_device_drain__opensl(ma_device* pDevice, ma_device_type deviceType) +{ + SLAndroidSimpleBufferQueueItf pBufferQueue; + + MA_ASSERT(deviceType == ma_device_type_capture || deviceType == ma_device_type_playback); + + if (pDevice->type == ma_device_type_capture) { + pBufferQueue = (SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture; + pDevice->opensl.isDrainingCapture = MA_TRUE; + } else { + pBufferQueue = (SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback; + pDevice->opensl.isDrainingPlayback = MA_TRUE; + } + + for (;;) { + SLAndroidSimpleBufferQueueState state; + + MA_OPENSL_BUFFERQUEUE(pBufferQueue)->GetState(pBufferQueue, &state); + if (state.count == 0) { + break; + } + + ma_sleep(10); + } + + if (pDevice->type == ma_device_type_capture) { + pDevice->opensl.isDrainingCapture = MA_FALSE; + } else { + pDevice->opensl.isDrainingPlayback = MA_FALSE; + } + + return MA_SUCCESS; +} + +static ma_result ma_device_stop__opensl(ma_device* pDevice) +{ + SLresult resultSL; + + 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; + } + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + ma_device_drain__opensl(pDevice, ma_device_type_capture); + + resultSL = MA_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_STOPPED); + if (resultSL != SL_RESULT_SUCCESS) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to stop internal capture device."); + return ma_result_from_OpenSL(resultSL); + } + + MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->Clear((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + ma_device_drain__opensl(pDevice, ma_device_type_playback); + + resultSL = MA_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_STOPPED); + if (resultSL != SL_RESULT_SUCCESS) { + ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to stop internal playback device."); + return ma_result_from_OpenSL(resultSL); + } + + 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_device__on_notification_stopped(pDevice); + + return MA_SUCCESS; +} + + +static 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. */ + ma_spinlock_lock(&g_maOpenSLSpinlock); + { + MA_ASSERT(g_maOpenSLInitCounter > 0); /* If you've triggered this, it means you have ma_context_init/uninit mismatch. Each successful call to ma_context_init() must be matched up with a call to ma_context_uninit(). */ + + g_maOpenSLInitCounter -= 1; + if (g_maOpenSLInitCounter == 0) { + (*g_maEngineObjectSL)->Destroy(g_maEngineObjectSL); + } + } + ma_spinlock_unlock(&g_maOpenSLSpinlock); + + return MA_SUCCESS; +} + +static ma_result ma_dlsym_SLInterfaceID__opensl(ma_context* pContext, const char* pName, ma_handle* pHandle) +{ + /* We need to return an error if the symbol cannot be found. This is important because there have been reports that some symbols do not exist. */ + ma_handle* p = (ma_handle*)ma_dlsym(ma_context_get_log(pContext), pContext->opensl.libOpenSLES, pName); + if (p == NULL) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_INFO, "[OpenSL] Cannot find symbol %s", pName); + return MA_NO_BACKEND; + } + + *pHandle = *p; + return MA_SUCCESS; +} + +static ma_result ma_context_init_engine_nolock__opensl(ma_context* pContext) +{ + g_maOpenSLInitCounter += 1; + if (g_maOpenSLInitCounter == 1) { + SLresult resultSL; + + resultSL = ((ma_slCreateEngine_proc)pContext->opensl.slCreateEngine)(&g_maEngineObjectSL, 0, NULL, 0, NULL, NULL); + if (resultSL != SL_RESULT_SUCCESS) { + g_maOpenSLInitCounter -= 1; + return ma_result_from_OpenSL(resultSL); + } + + (*g_maEngineObjectSL)->Realize(g_maEngineObjectSL, SL_BOOLEAN_FALSE); + + resultSL = (*g_maEngineObjectSL)->GetInterface(g_maEngineObjectSL, (SLInterfaceID)pContext->opensl.SL_IID_ENGINE, &g_maEngineSL); + if (resultSL != SL_RESULT_SUCCESS) { + (*g_maEngineObjectSL)->Destroy(g_maEngineObjectSL); + g_maOpenSLInitCounter -= 1; + return ma_result_from_OpenSL(resultSL); + } + } + + return MA_SUCCESS; +} + +static ma_result ma_context_init__opensl(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks) +{ + ma_result result; + +#if !defined(MA_NO_RUNTIME_LINKING) + size_t i; + const char* libOpenSLESNames[] = { + "libOpenSLES.so" + }; +#endif + + MA_ASSERT(pContext != NULL); + + (void)pConfig; + +#if !defined(MA_NO_RUNTIME_LINKING) + /* + Dynamically link against libOpenSLES.so. I have now had multiple reports that SL_IID_ANDROIDSIMPLEBUFFERQUEUE cannot be found. One + report was happening at compile time and another at runtime. To try working around this, I'm going to link to libOpenSLES at runtime + and extract the symbols rather than reference them directly. This should, hopefully, fix these issues as the compiler won't see any + references to the symbols and will hopefully skip the checks. + */ + for (i = 0; i < ma_countof(libOpenSLESNames); i += 1) { + pContext->opensl.libOpenSLES = ma_dlopen(ma_context_get_log(pContext), libOpenSLESNames[i]); + if (pContext->opensl.libOpenSLES != NULL) { + break; + } + } + + if (pContext->opensl.libOpenSLES == NULL) { + ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_INFO, "[OpenSL] Could not find libOpenSLES.so"); + return MA_NO_BACKEND; + } + + result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_ENGINE", &pContext->opensl.SL_IID_ENGINE); + if (result != MA_SUCCESS) { + ma_dlclose(ma_context_get_log(pContext), pContext->opensl.libOpenSLES); + return result; + } + + result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_AUDIOIODEVICECAPABILITIES", &pContext->opensl.SL_IID_AUDIOIODEVICECAPABILITIES); + if (result != MA_SUCCESS) { + ma_dlclose(ma_context_get_log(pContext), pContext->opensl.libOpenSLES); + return result; + } + + result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_ANDROIDSIMPLEBUFFERQUEUE", &pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE); + if (result != MA_SUCCESS) { + ma_dlclose(ma_context_get_log(pContext), pContext->opensl.libOpenSLES); + return result; + } + + result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_RECORD", &pContext->opensl.SL_IID_RECORD); + if (result != MA_SUCCESS) { + ma_dlclose(ma_context_get_log(pContext), pContext->opensl.libOpenSLES); + return result; + } + + result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_PLAY", &pContext->opensl.SL_IID_PLAY); + if (result != MA_SUCCESS) { + ma_dlclose(ma_context_get_log(pContext), pContext->opensl.libOpenSLES); + return result; + } + + result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_OUTPUTMIX", &pContext->opensl.SL_IID_OUTPUTMIX); + if (result != MA_SUCCESS) { + ma_dlclose(ma_context_get_log(pContext), pContext->opensl.libOpenSLES); + return result; + } + + result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_ANDROIDCONFIGURATION", &pContext->opensl.SL_IID_ANDROIDCONFIGURATION); + if (result != MA_SUCCESS) { + ma_dlclose(ma_context_get_log(pContext), pContext->opensl.libOpenSLES); + return result; + } + + pContext->opensl.slCreateEngine = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->opensl.libOpenSLES, "slCreateEngine"); + if (pContext->opensl.slCreateEngine == NULL) { + ma_dlclose(ma_context_get_log(pContext), pContext->opensl.libOpenSLES); + ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_INFO, "[OpenSL] Cannot find symbol slCreateEngine."); + return MA_NO_BACKEND; + } +#else + pContext->opensl.SL_IID_ENGINE = (ma_handle)SL_IID_ENGINE; + pContext->opensl.SL_IID_AUDIOIODEVICECAPABILITIES = (ma_handle)SL_IID_AUDIOIODEVICECAPABILITIES; + pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE = (ma_handle)SL_IID_ANDROIDSIMPLEBUFFERQUEUE; + pContext->opensl.SL_IID_RECORD = (ma_handle)SL_IID_RECORD; + pContext->opensl.SL_IID_PLAY = (ma_handle)SL_IID_PLAY; + pContext->opensl.SL_IID_OUTPUTMIX = (ma_handle)SL_IID_OUTPUTMIX; + pContext->opensl.SL_IID_ANDROIDCONFIGURATION = (ma_handle)SL_IID_ANDROIDCONFIGURATION; + pContext->opensl.slCreateEngine = (ma_proc)slCreateEngine; +#endif + + + /* Initialize global data first if applicable. */ + ma_spinlock_lock(&g_maOpenSLSpinlock); + { + result = ma_context_init_engine_nolock__opensl(pContext); + } + ma_spinlock_unlock(&g_maOpenSLSpinlock); + + if (result != MA_SUCCESS) { + ma_dlclose(ma_context_get_log(pContext), pContext->opensl.libOpenSLES); + ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_INFO, "[OpenSL] Failed to initialize OpenSL engine."); + return result; + } + + pCallbacks->onContextInit = ma_context_init__opensl; + pCallbacks->onContextUninit = ma_context_uninit__opensl; + pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__opensl; + pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__opensl; + pCallbacks->onDeviceInit = ma_device_init__opensl; + pCallbacks->onDeviceUninit = ma_device_uninit__opensl; + pCallbacks->onDeviceStart = ma_device_start__opensl; + pCallbacks->onDeviceStop = ma_device_stop__opensl; + pCallbacks->onDeviceRead = NULL; /* Not needed because OpenSL|ES is asynchronous. */ + pCallbacks->onDeviceWrite = NULL; /* Not needed because OpenSL|ES is asynchronous. */ + pCallbacks->onDeviceDataLoop = NULL; /* Not needed because OpenSL|ES is asynchronous. */ + + return MA_SUCCESS; +} +#endif /* OpenSL|ES */ + + +/****************************************************************************** + +Web Audio Backend + +******************************************************************************/ +#ifdef MA_HAS_WEBAUDIO +#include + +#if (__EMSCRIPTEN_major__ > 3) || (__EMSCRIPTEN_major__ == 3 && (__EMSCRIPTEN_minor__ > 1 || (__EMSCRIPTEN_minor__ == 1 && __EMSCRIPTEN_tiny__ >= 32))) + #include + #define MA_SUPPORT_AUDIO_WORKLETS +#endif + +/* +TODO: Version 0.12: Swap this logic around so that AudioWorklets are used by default. Add MA_NO_AUDIO_WORKLETS. +*/ +#if defined(MA_ENABLE_AUDIO_WORKLETS) && defined(MA_SUPPORT_AUDIO_WORKLETS) + #define MA_USE_AUDIO_WORKLETS +#endif + +/* The thread stack size must be a multiple of 16. */ +#ifndef MA_AUDIO_WORKLETS_THREAD_STACK_SIZE +#define MA_AUDIO_WORKLETS_THREAD_STACK_SIZE 16384 +#endif + +#if defined(MA_USE_AUDIO_WORKLETS) +#define MA_WEBAUDIO_LATENCY_HINT_BALANCED "balanced" +#define MA_WEBAUDIO_LATENCY_HINT_INTERACTIVE "interactive" +#define MA_WEBAUDIO_LATENCY_HINT_PLAYBACK "playback" +#endif + +static 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 +void* EMSCRIPTEN_KEEPALIVE ma_malloc_emscripten(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks) +{ + return ma_malloc(sz, pAllocationCallbacks); +} + +void EMSCRIPTEN_KEEPALIVE ma_free_emscripten(void* p, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_free(p, pAllocationCallbacks); +} + +void EMSCRIPTEN_KEEPALIVE ma_device_process_pcm_frames_capture__webaudio(ma_device* pDevice, int frameCount, float* pFrames) +{ + ma_device_handle_backend_data_callback(pDevice, NULL, pFrames, (ma_uint32)frameCount); +} + +void EMSCRIPTEN_KEEPALIVE ma_device_process_pcm_frames_playback__webaudio(ma_device* pDevice, int frameCount, float* pFrames) +{ + ma_device_handle_backend_data_callback(pDevice, pFrames, NULL, (ma_uint32)frameCount); +} +#ifdef __cplusplus +} +#endif + +static 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. */ + + /* 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); + deviceInfo.isDefault = MA_TRUE; /* Only supporting default devices. */ + 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); + deviceInfo.isDefault = MA_TRUE; /* Only supporting default devices. */ + cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData); + } + } + + return MA_SUCCESS; +} + +static ma_result ma_context_get_device_info__webaudio(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo) +{ + MA_ASSERT(pContext != NULL); + + 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. */ + (void)pDeviceID; + 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); + } + + /* Only supporting default devices. */ + pDeviceInfo->isDefault = MA_TRUE; + + /* Web Audio can support any number of channels and sample rates. It only supports f32 formats, however. */ + pDeviceInfo->nativeDataFormats[0].flags = 0; + pDeviceInfo->nativeDataFormats[0].format = ma_format_unknown; + pDeviceInfo->nativeDataFormats[0].channels = 0; /* All channels are supported. */ + pDeviceInfo->nativeDataFormats[0].sampleRate = 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. */ + + if (pDeviceInfo->nativeDataFormats[0].sampleRate == 0) { + return MA_NO_DEVICE; + } + + pDeviceInfo->nativeDataFormatCount = 1; + + return MA_SUCCESS; +} + +static ma_result ma_device_uninit__webaudio(ma_device* pDevice) +{ + MA_ASSERT(pDevice != NULL); + + #if defined(MA_USE_AUDIO_WORKLETS) + { + EM_ASM({ + var device = miniaudio.get_device_by_index($0); + + if (device.streamNode !== undefined) { + device.streamNode.disconnect(); + device.streamNode = undefined; + } + }, pDevice->webaudio.deviceIndex); + + emscripten_destroy_web_audio_node(pDevice->webaudio.audioWorklet); + emscripten_destroy_audio_context(pDevice->webaudio.audioContext); + ma_free(pDevice->webaudio.pStackBuffer, &pDevice->pContext->allocationCallbacks); + } + #else + { + 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; + device.pDevice = undefined; + }, pDevice->webaudio.deviceIndex); + } + #endif + + /* Clean up the device on the JS side. */ + EM_ASM({ + miniaudio.untrack_device_by_index($0); + }, pDevice->webaudio.deviceIndex); + + ma_free(pDevice->webaudio.pIntermediaryBuffer, &pDevice->pContext->allocationCallbacks); + + return MA_SUCCESS; +} + +#if !defined(MA_USE_AUDIO_WORKLETS) +static ma_uint32 ma_calculate_period_size_in_frames_from_descriptor__webaudio(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile) +{ + /* + There have been reports of the default buffer size being too small on some browsers. If we're using + the default buffer size, we'll make sure the period size is bigger than our standard defaults. + */ + ma_uint32 periodSizeInFrames; + + if (nativeSampleRate == 0) { + nativeSampleRate = MA_DEFAULT_SAMPLE_RATE; + } + + if (pDescriptor->periodSizeInFrames == 0) { + if (pDescriptor->periodSizeInMilliseconds == 0) { + if (performanceProfile == ma_performance_profile_low_latency) { + periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(33, nativeSampleRate); /* 1 frame @ 30 FPS */ + } else { + periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(333, nativeSampleRate); + } + } else { + periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pDescriptor->periodSizeInMilliseconds, nativeSampleRate); + } + } else { + periodSizeInFrames = pDescriptor->periodSizeInFrames; + } + + /* The size of the buffer must be a power of 2 and between 256 and 16384. */ + if (periodSizeInFrames < 256) { + periodSizeInFrames = 256; + } else if (periodSizeInFrames > 16384) { + periodSizeInFrames = 16384; + } else { + periodSizeInFrames = ma_next_power_of_2(periodSizeInFrames); + } + + return periodSizeInFrames; +} +#endif + + +#if defined(MA_USE_AUDIO_WORKLETS) +typedef struct +{ + ma_device* pDevice; + const ma_device_config* pConfig; + ma_device_descriptor* pDescriptorPlayback; + ma_device_descriptor* pDescriptorCapture; +} ma_audio_worklet_thread_initialized_data; + +static EM_BOOL ma_audio_worklet_process_callback__webaudio(int inputCount, const AudioSampleFrame* pInputs, int outputCount, AudioSampleFrame* pOutputs, int paramCount, const AudioParamFrame* pParams, void* pUserData) +{ + ma_device* pDevice = (ma_device*)pUserData; + ma_uint32 frameCount; + + (void)paramCount; + (void)pParams; + + if (ma_device_get_state(pDevice) != ma_device_state_started) { + return EM_TRUE; + } + + /* + The Emscripten documentation says that it'll always be 128 frames being passed in. Hard coding it like that feels + like a very bad idea to me. Even if it's hard coded in the backend, the API and documentation should always refer + to variables instead of a hard coded number. In any case, will follow along for the time being. + + Unfortunately the audio data is not interleaved so we'll need to convert it before we give the data to miniaudio + for further processing. + */ + frameCount = 128; + + if (inputCount > 0) { + /* Input data needs to be interleaved before we hand it to the client. */ + for (ma_uint32 iChannel = 0; iChannel < pDevice->capture.internalChannels; iChannel += 1) { + for (ma_uint32 iFrame = 0; iFrame < frameCount; iFrame += 1) { + pDevice->webaudio.pIntermediaryBuffer[iFrame*pDevice->capture.internalChannels + iChannel] = pInputs[0].data[frameCount*iChannel + iFrame]; + } + } + + ma_device_process_pcm_frames_capture__webaudio(pDevice, frameCount, pDevice->webaudio.pIntermediaryBuffer); + } + + if (outputCount > 0) { + /* If it's a capture-only device, we'll need to output silence. */ + if (pDevice->type == ma_device_type_capture) { + MA_ZERO_MEMORY(pOutputs[0].data, frameCount * pDevice->playback.internalChannels * sizeof(float)); + } else { + ma_device_process_pcm_frames_playback__webaudio(pDevice, frameCount, pDevice->webaudio.pIntermediaryBuffer); + + /* We've read the data from the client. Now we need to deinterleave the buffer and output to the output buffer. */ + for (ma_uint32 iChannel = 0; iChannel < pDevice->playback.internalChannels; iChannel += 1) { + for (ma_uint32 iFrame = 0; iFrame < frameCount; iFrame += 1) { + pOutputs[0].data[frameCount*iChannel + iFrame] = pDevice->webaudio.pIntermediaryBuffer[iFrame*pDevice->playback.internalChannels + iChannel]; + } + } + } + } + + return EM_TRUE; +} + + +static void ma_audio_worklet_processor_created__webaudio(EMSCRIPTEN_WEBAUDIO_T audioContext, EM_BOOL success, void* pUserData) +{ + ma_audio_worklet_thread_initialized_data* pParameters = (ma_audio_worklet_thread_initialized_data*)pUserData; + EmscriptenAudioWorkletNodeCreateOptions audioWorkletOptions; + int channels = 0; + size_t intermediaryBufferSizeInFrames; + int sampleRate; + + if (success == EM_FALSE) { + pParameters->pDevice->webaudio.initResult = MA_ERROR; + ma_free(pParameters, &pParameters->pDevice->pContext->allocationCallbacks); + return; + } + + /* The next step is to initialize the audio worklet node. */ + MA_ZERO_OBJECT(&audioWorkletOptions); + + /* + The way channel counts work with Web Audio is confusing. As far as I can tell, there's no way to know the channel + count from MediaStreamAudioSourceNode (what we use for capture)? The only way to have control is to configure an + output channel count on the capture side. This is slightly confusing for capture mode because intuitively you + wouldn't actually connect an output to an input-only node, but this is what we'll have to do in order to have + proper control over the channel count. In the capture case, we'll have to output silence to it's output node. + */ + if (pParameters->pConfig->deviceType == ma_device_type_capture) { + channels = (int)((pParameters->pDescriptorCapture->channels > 0) ? pParameters->pDescriptorCapture->channels : MA_DEFAULT_CHANNELS); + audioWorkletOptions.numberOfInputs = 1; + } else { + channels = (int)((pParameters->pDescriptorPlayback->channels > 0) ? pParameters->pDescriptorPlayback->channels : MA_DEFAULT_CHANNELS); + + if (pParameters->pConfig->deviceType == ma_device_type_duplex) { + audioWorkletOptions.numberOfInputs = 1; + } else { + audioWorkletOptions.numberOfInputs = 0; + } + } + + audioWorkletOptions.numberOfOutputs = 1; + audioWorkletOptions.outputChannelCounts = &channels; + + + /* + Now that we know the channel count to use we can allocate the intermediary buffer. The + intermediary buffer is used for interleaving and deinterleaving. + */ + intermediaryBufferSizeInFrames = 128; + + pParameters->pDevice->webaudio.pIntermediaryBuffer = (float*)ma_malloc(intermediaryBufferSizeInFrames * (ma_uint32)channels * sizeof(float), &pParameters->pDevice->pContext->allocationCallbacks); + if (pParameters->pDevice->webaudio.pIntermediaryBuffer == NULL) { + pParameters->pDevice->webaudio.initResult = MA_OUT_OF_MEMORY; + ma_free(pParameters, &pParameters->pDevice->pContext->allocationCallbacks); + return; + } + + + pParameters->pDevice->webaudio.audioWorklet = emscripten_create_wasm_audio_worklet_node(audioContext, "miniaudio", &audioWorkletOptions, &ma_audio_worklet_process_callback__webaudio, pParameters->pDevice); + + /* With the audio worklet initialized we can now attach it to the graph. */ + if (pParameters->pConfig->deviceType == ma_device_type_capture || pParameters->pConfig->deviceType == ma_device_type_duplex) { + ma_result attachmentResult = (ma_result)EM_ASM_INT({ + var getUserMediaResult = 0; + var audioWorklet = emscriptenGetAudioObject($0); + var audioContext = emscriptenGetAudioObject($1); + + navigator.mediaDevices.getUserMedia({audio:true, video:false}) + .then(function(stream) { + audioContext.streamNode = audioContext.createMediaStreamSource(stream); + audioContext.streamNode.connect(audioWorklet); + audioWorklet.connect(audioContext.destination); + getUserMediaResult = 0; /* 0 = MA_SUCCESS */ + }) + .catch(function(error) { + console.log("navigator.mediaDevices.getUserMedia Failed: " + error); + getUserMediaResult = -1; /* -1 = MA_ERROR */ + }); + + return getUserMediaResult; + }, pParameters->pDevice->webaudio.audioWorklet, audioContext); + + if (attachmentResult != MA_SUCCESS) { + ma_log_postf(ma_device_get_log(pParameters->pDevice), MA_LOG_LEVEL_ERROR, "Web Audio: Failed to connect capture node."); + emscripten_destroy_web_audio_node(pParameters->pDevice->webaudio.audioWorklet); + pParameters->pDevice->webaudio.initResult = attachmentResult; + ma_free(pParameters, &pParameters->pDevice->pContext->allocationCallbacks); + return; + } + } + + /* If it's playback only we can now attach the worklet node to the graph. This has already been done for the duplex case. */ + if (pParameters->pConfig->deviceType == ma_device_type_playback) { + ma_result attachmentResult = (ma_result)EM_ASM_INT({ + var audioWorklet = emscriptenGetAudioObject($0); + var audioContext = emscriptenGetAudioObject($1); + audioWorklet.connect(audioContext.destination); + return 0; /* 0 = MA_SUCCESS */ + }, pParameters->pDevice->webaudio.audioWorklet, audioContext); + + if (attachmentResult != MA_SUCCESS) { + ma_log_postf(ma_device_get_log(pParameters->pDevice), MA_LOG_LEVEL_ERROR, "Web Audio: Failed to connect playback node."); + pParameters->pDevice->webaudio.initResult = attachmentResult; + ma_free(pParameters, &pParameters->pDevice->pContext->allocationCallbacks); + return; + } + } + + /* We need to update the descriptors so that they reflect the internal data format. Both capture and playback should be the same. */ + sampleRate = EM_ASM_INT({ return emscriptenGetAudioObject($0).sampleRate; }, audioContext); + + if (pParameters->pDescriptorCapture != NULL) { + pParameters->pDescriptorCapture->format = ma_format_f32; + pParameters->pDescriptorCapture->channels = (ma_uint32)channels; + pParameters->pDescriptorCapture->sampleRate = (ma_uint32)sampleRate; + ma_channel_map_init_standard(ma_standard_channel_map_webaudio, pParameters->pDescriptorCapture->channelMap, ma_countof(pParameters->pDescriptorCapture->channelMap), pParameters->pDescriptorCapture->channels); + pParameters->pDescriptorCapture->periodSizeInFrames = intermediaryBufferSizeInFrames; + pParameters->pDescriptorCapture->periodCount = 1; + } + + if (pParameters->pDescriptorPlayback != NULL) { + pParameters->pDescriptorPlayback->format = ma_format_f32; + pParameters->pDescriptorPlayback->channels = (ma_uint32)channels; + pParameters->pDescriptorPlayback->sampleRate = (ma_uint32)sampleRate; + ma_channel_map_init_standard(ma_standard_channel_map_webaudio, pParameters->pDescriptorPlayback->channelMap, ma_countof(pParameters->pDescriptorPlayback->channelMap), pParameters->pDescriptorPlayback->channels); + pParameters->pDescriptorPlayback->periodSizeInFrames = intermediaryBufferSizeInFrames; + pParameters->pDescriptorPlayback->periodCount = 1; + } + + /* At this point we're done and we can return. */ + ma_log_postf(ma_device_get_log(pParameters->pDevice), MA_LOG_LEVEL_DEBUG, "AudioWorklets: Created worklet node: %d\n", pParameters->pDevice->webaudio.audioWorklet); + pParameters->pDevice->webaudio.initResult = MA_SUCCESS; + ma_free(pParameters, &pParameters->pDevice->pContext->allocationCallbacks); +} + +static void ma_audio_worklet_thread_initialized__webaudio(EMSCRIPTEN_WEBAUDIO_T audioContext, EM_BOOL success, void* pUserData) +{ + ma_audio_worklet_thread_initialized_data* pParameters = (ma_audio_worklet_thread_initialized_data*)pUserData; + WebAudioWorkletProcessorCreateOptions workletProcessorOptions; + + MA_ASSERT(pParameters != NULL); + + if (success == EM_FALSE) { + pParameters->pDevice->webaudio.initResult = MA_ERROR; + return; + } + + MA_ZERO_OBJECT(&workletProcessorOptions); + workletProcessorOptions.name = "miniaudio"; /* I'm not entirely sure what to call this. Does this need to be globally unique, or does it need only be unique for a given AudioContext? */ + + emscripten_create_wasm_audio_worklet_processor_async(audioContext, &workletProcessorOptions, ma_audio_worklet_processor_created__webaudio, pParameters); +} +#endif + +static ma_result ma_device_init__webaudio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture) +{ + if (pConfig->deviceType == ma_device_type_loopback) { + return MA_DEVICE_TYPE_NOT_SUPPORTED; + } + + /* No exclusive mode with Web Audio. */ + if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive) || + ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive)) { + return MA_SHARE_MODE_NOT_SUPPORTED; + } + + /* + With AudioWorklets we'll have just a single AudioContext. I'm not sure why I'm not doing this for ScriptProcessorNode so + it might be worthwhile to look into that as well. + */ + #if defined(MA_USE_AUDIO_WORKLETS) + { + EmscriptenWebAudioCreateAttributes audioContextAttributes; + ma_audio_worklet_thread_initialized_data* pInitParameters; + void* pStackBuffer; + + if (pConfig->performanceProfile == ma_performance_profile_conservative) { + audioContextAttributes.latencyHint = MA_WEBAUDIO_LATENCY_HINT_PLAYBACK; + } else { + audioContextAttributes.latencyHint = MA_WEBAUDIO_LATENCY_HINT_INTERACTIVE; + } + + /* + In my testing, Firefox does not seem to capture audio data properly if the sample rate is set + to anything other than 48K. This does not seem to be the case for other browsers. For this reason, + if the device type is anything other than playback, we'll leave the sample rate as-is and let the + browser pick the appropriate rate for us. + */ + if (pConfig->deviceType == ma_device_type_playback) { + audioContextAttributes.sampleRate = pDescriptorPlayback->sampleRate; + } else { + audioContextAttributes.sampleRate = 0; + } + + /* It's not clear if this can return an error. None of the tests in the Emscripten repository check for this, so neither am I for now. */ + pDevice->webaudio.audioContext = emscripten_create_audio_context(&audioContextAttributes); + + + /* + With the context created we can now create the worklet. We can only have a single worklet per audio + context which means we'll need to craft this appropriately to handle duplex devices correctly. + */ + + /* + We now need to create a worker thread. This is a bit weird because we need to allocate our + own buffer for the thread's stack. The stack needs to be aligned to 16 bytes. I'm going to + allocate this on the heap to keep it simple. + */ + pStackBuffer = ma_aligned_malloc(MA_AUDIO_WORKLETS_THREAD_STACK_SIZE, 16, &pDevice->pContext->allocationCallbacks); + if (pStackBuffer == NULL) { + emscripten_destroy_audio_context(pDevice->webaudio.audioContext); + return MA_OUT_OF_MEMORY; + } + + /* Our thread initialization parameters need to be allocated on the heap so they don't go out of scope. */ + pInitParameters = (ma_audio_worklet_thread_initialized_data*)ma_malloc(sizeof(*pInitParameters), &pDevice->pContext->allocationCallbacks); + if (pInitParameters == NULL) { + ma_free(pStackBuffer, &pDevice->pContext->allocationCallbacks); + emscripten_destroy_audio_context(pDevice->webaudio.audioContext); + return MA_OUT_OF_MEMORY; + } + + pInitParameters->pDevice = pDevice; + pInitParameters->pConfig = pConfig; + pInitParameters->pDescriptorPlayback = pDescriptorPlayback; + pInitParameters->pDescriptorCapture = pDescriptorCapture; + + /* + We need to flag the device as not yet initialized so we can wait on it later. Unfortunately all of + the Emscripten WebAudio stuff is asynchronous. + */ + pDevice->webaudio.initResult = MA_BUSY; + { + emscripten_start_wasm_audio_worklet_thread_async(pDevice->webaudio.audioContext, pStackBuffer, MA_AUDIO_WORKLETS_THREAD_STACK_SIZE, ma_audio_worklet_thread_initialized__webaudio, pInitParameters); + } + while (pDevice->webaudio.initResult == MA_BUSY) { emscripten_sleep(1); } /* We must wait for initialization to complete. We're just spinning here. The emscripten_sleep() call is why we need to build with `-sASYNCIFY`. */ + + /* Initialization is now complete. Descriptors were updated when the worklet was initialized. */ + if (pDevice->webaudio.initResult != MA_SUCCESS) { + ma_free(pStackBuffer, &pDevice->pContext->allocationCallbacks); + emscripten_destroy_audio_context(pDevice->webaudio.audioContext); + return pDevice->webaudio.initResult; + } + + /* We need to add an entry to the miniaudio.devices list on the JS side so we can do some JS/C interop. */ + pDevice->webaudio.deviceIndex = EM_ASM_INT({ + return miniaudio.track_device({ + webaudio: emscriptenGetAudioObject($0), + state: 1 /* 1 = ma_device_state_stopped */ + }); + }, pDevice->webaudio.audioContext); + + return MA_SUCCESS; + } + #else + { + /* ScriptProcessorNode. This path requires us to do almost everything in JS, but we'll do as much as we can in C. */ + ma_uint32 deviceIndex; + ma_uint32 channels; + ma_uint32 sampleRate; + ma_uint32 periodSizeInFrames; + + /* The channel count will depend on the device type. If it's a capture, use it's, otherwise use the playback side. */ + if (pConfig->deviceType == ma_device_type_capture) { + channels = (pDescriptorCapture->channels > 0) ? pDescriptorCapture->channels : MA_DEFAULT_CHANNELS; + } else { + channels = (pDescriptorPlayback->channels > 0) ? pDescriptorPlayback->channels : MA_DEFAULT_CHANNELS; + } + + /* + When testing in Firefox, I've seen it where capture mode fails if the sample rate is changed to anything other than it's + native rate. For this reason we're leaving the sample rate untouched for capture devices. + */ + if (pConfig->deviceType == ma_device_type_playback) { + sampleRate = pDescriptorPlayback->sampleRate; + } else { + sampleRate = 0; /* Let the browser decide when capturing. */ + } + + /* The period size needs to be a power of 2. */ + if (pConfig->deviceType == ma_device_type_capture) { + periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__webaudio(pDescriptorCapture, sampleRate, pConfig->performanceProfile); + } else { + periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__webaudio(pDescriptorPlayback, sampleRate, pConfig->performanceProfile); + } + + /* We need an intermediary buffer for doing interleaving and deinterleaving. */ + pDevice->webaudio.pIntermediaryBuffer = (float*)ma_malloc(periodSizeInFrames * channels * sizeof(float), &pDevice->pContext->allocationCallbacks); + if (pDevice->webaudio.pIntermediaryBuffer == NULL) { + return MA_OUT_OF_MEMORY; + } + + deviceIndex = EM_ASM_INT({ + var deviceType = $0; + var channels = $1; + var sampleRate = $2; + var bufferSize = $3; + var pIntermediaryBuffer = $4; + var pDevice = $5; + + if (typeof(window.miniaudio) === 'undefined') { + return -1; /* Context not initialized. */ + } + + var device = {}; + + /* First thing we need is an AudioContext. */ + var audioContextOptions = {}; + if (deviceType == window.miniaudio.device_type.playback && sampleRate != 0) { + audioContextOptions.sampleRate = sampleRate; + } + + device.webaudio = new (window.AudioContext || window.webkitAudioContext)(audioContextOptions); + device.webaudio.suspend(); /* The AudioContext must be created in a suspended state. */ + device.state = window.miniaudio.device_state.stopped; + + /* + We need to create a ScriptProcessorNode. The channel situation is the same as the AudioWorklet path in that we + need to specify an output and configure the channel count there. + */ + var channelCountIn = 0; + var channelCountOut = channels; + if (deviceType != window.miniaudio.device_type.playback) { + channelCountIn = channels; + } + + device.scriptNode = device.webaudio.createScriptProcessor(bufferSize, channelCountIn, channelCountOut); + + /* The node processing callback. */ + device.scriptNode.onaudioprocess = function(e) { + if (device.intermediaryBufferView == null || device.intermediaryBufferView.length == 0) { + device.intermediaryBufferView = new Float32Array(Module.HEAPF32.buffer, pIntermediaryBuffer, bufferSize * channels); + } + + /* Do the capture side first. */ + if (deviceType == miniaudio.device_type.capture || deviceType == miniaudio.device_type.duplex) { + /* The data must be interleaved before being processed miniaudio. */ + for (var iChannel = 0; iChannel < channels; iChannel += 1) { + var inputBuffer = e.inputBuffer.getChannelData(iChannel); + var intermediaryBuffer = device.intermediaryBufferView; + + for (var iFrame = 0; iFrame < bufferSize; iFrame += 1) { + intermediaryBuffer[iFrame*channels + iChannel] = inputBuffer[iFrame]; + } + } + + _ma_device_process_pcm_frames_capture__webaudio(pDevice, bufferSize, pIntermediaryBuffer); + } + + if (deviceType == miniaudio.device_type.playback || deviceType == miniaudio.device_type.duplex) { + _ma_device_process_pcm_frames_playback__webaudio(pDevice, bufferSize, pIntermediaryBuffer); + + for (var iChannel = 0; iChannel < e.outputBuffer.numberOfChannels; ++iChannel) { + var outputBuffer = e.outputBuffer.getChannelData(iChannel); + var intermediaryBuffer = device.intermediaryBufferView; + + for (var iFrame = 0; iFrame < bufferSize; iFrame += 1) { + outputBuffer[iFrame] = intermediaryBuffer[iFrame*channels + iChannel]; + } + } + } else { + /* It's a capture-only device. Make sure the output is silenced. */ + for (var iChannel = 0; iChannel < e.outputBuffer.numberOfChannels; ++iChannel) { + e.outputBuffer.getChannelData(iChannel).fill(0.0); + } + } + }; + + /* Now we need to connect our node to the graph. */ + if (deviceType == miniaudio.device_type.capture || deviceType == miniaudio.device_type.duplex) { + 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) { + console.log("Failed to get user media: " + error); + }); + } + + if (deviceType == miniaudio.device_type.playback) { + device.scriptNode.connect(device.webaudio.destination); + } + + device.pDevice = pDevice; + + return miniaudio.track_device(device); + }, pConfig->deviceType, channels, sampleRate, periodSizeInFrames, pDevice->webaudio.pIntermediaryBuffer, pDevice); + + if (deviceIndex < 0) { + return MA_FAILED_TO_OPEN_BACKEND_DEVICE; + } + + pDevice->webaudio.deviceIndex = deviceIndex; + + /* Grab the sample rate from the audio context directly. */ + sampleRate = (ma_uint32)EM_ASM_INT({ return miniaudio.get_device_by_index($0).webaudio.sampleRate; }, deviceIndex); + + if (pDescriptorCapture != NULL) { + pDescriptorCapture->format = ma_format_f32; + pDescriptorCapture->channels = channels; + pDescriptorCapture->sampleRate = sampleRate; + ma_channel_map_init_standard(ma_standard_channel_map_webaudio, pDescriptorCapture->channelMap, ma_countof(pDescriptorCapture->channelMap), pDescriptorCapture->channels); + pDescriptorCapture->periodSizeInFrames = periodSizeInFrames; + pDescriptorCapture->periodCount = 1; + } + + if (pDescriptorPlayback != NULL) { + pDescriptorPlayback->format = ma_format_f32; + pDescriptorPlayback->channels = channels; + pDescriptorPlayback->sampleRate = sampleRate; + ma_channel_map_init_standard(ma_standard_channel_map_webaudio, pDescriptorPlayback->channelMap, ma_countof(pDescriptorPlayback->channelMap), pDescriptorPlayback->channels); + pDescriptorPlayback->periodSizeInFrames = periodSizeInFrames; + pDescriptorPlayback->periodCount = 1; + } + + return MA_SUCCESS; + } + #endif +} + +static ma_result ma_device_start__webaudio(ma_device* pDevice) +{ + MA_ASSERT(pDevice != NULL); + + EM_ASM({ + var device = miniaudio.get_device_by_index($0); + device.webaudio.resume(); + device.state = miniaudio.device_state.started; + }, pDevice->webaudio.deviceIndex); + + return MA_SUCCESS; +} + +static ma_result ma_device_stop__webaudio(ma_device* pDevice) +{ + MA_ASSERT(pDevice != NULL); + + /* + From the WebAudio API documentation for AudioContext.suspend(): + + Suspends the progression of AudioContext's currentTime, allows any current context processing blocks that are already processed to be played to the + destination, and then allows the system to release its claim on audio hardware. + + I read this to mean that "any current context processing blocks" are processed by suspend() - i.e. They they are drained. We therefore shouldn't need to + do any kind of explicit draining. + */ + EM_ASM({ + var device = miniaudio.get_device_by_index($0); + device.webaudio.suspend(); + device.state = miniaudio.device_state.stopped; + }, pDevice->webaudio.deviceIndex); + + ma_device__on_notification_stopped(pDevice); + + return MA_SUCCESS; +} + +static ma_result ma_context_uninit__webaudio(ma_context* pContext) +{ + MA_ASSERT(pContext != NULL); + MA_ASSERT(pContext->backend == ma_backend_webaudio); + + (void)pContext; /* Unused. */ + + /* Remove the global miniaudio object from window if there are no more references to it. */ + EM_ASM({ + if (typeof(window.miniaudio) !== 'undefined') { + window.miniaudio.referenceCount -= 1; + if (window.miniaudio.referenceCount === 0) { + delete window.miniaudio; + } + } + }); + + return MA_SUCCESS; +} + +static ma_result ma_context_init__webaudio(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks) +{ + int resultFromJS; + + MA_ASSERT(pContext != NULL); + + (void)pConfig; /* Unused. */ + + /* Here is where our global JavaScript object is initialized. */ + resultFromJS = EM_ASM_INT({ + if (typeof window === 'undefined' || (window.AudioContext || window.webkitAudioContext) === undefined) { + return 0; /* Web Audio not supported. */ + } + + if (typeof(window.miniaudio) === 'undefined') { + window.miniaudio = { + referenceCount: 0 + }; + + /* Device types. */ + window.miniaudio.device_type = {}; + window.miniaudio.device_type.playback = $0; + window.miniaudio.device_type.capture = $1; + window.miniaudio.device_type.duplex = $2; + + /* Device states. */ + window.miniaudio.device_state = {}; + window.miniaudio.device_state.stopped = $3; + window.miniaudio.device_state.started = $4; + + /* Device cache for mapping devices to indexes for JavaScript/C interop. */ + miniaudio.devices = []; + + 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]; + }; + + miniaudio.unlock_event_types = (function(){ + return ['touchend', 'click']; + })(); + + miniaudio.unlock = function() { + for(var i = 0; i < miniaudio.devices.length; ++i) { + var device = miniaudio.devices[i]; + if (device != null && + device.webaudio != null && + device.state === window.miniaudio.device_state.started) { + + device.webaudio.resume().then(() => { + Module._ma_device__on_notification_unlocked(device.pDevice); + }, + (error) => {console.error("Failed to resume audiocontext", error); + }); + } + } + miniaudio.unlock_event_types.map(function(event_type) { + document.removeEventListener(event_type, miniaudio.unlock, true); + }); + }; + + miniaudio.unlock_event_types.map(function(event_type) { + document.addEventListener(event_type, miniaudio.unlock, true); + }); + } + + window.miniaudio.referenceCount += 1; + + return 1; + }, ma_device_type_playback, ma_device_type_capture, ma_device_type_duplex, ma_device_state_stopped, ma_device_state_started); + + if (resultFromJS != 1) { + return MA_FAILED_TO_INIT_BACKEND; + } + + pCallbacks->onContextInit = ma_context_init__webaudio; + pCallbacks->onContextUninit = ma_context_uninit__webaudio; + pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__webaudio; + pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__webaudio; + pCallbacks->onDeviceInit = ma_device_init__webaudio; + pCallbacks->onDeviceUninit = ma_device_uninit__webaudio; + pCallbacks->onDeviceStart = ma_device_start__webaudio; + pCallbacks->onDeviceStop = ma_device_stop__webaudio; + pCallbacks->onDeviceRead = NULL; /* Not needed because WebAudio is asynchronous. */ + pCallbacks->onDeviceWrite = NULL; /* Not needed because WebAudio is asynchronous. */ + pCallbacks->onDeviceDataLoop = NULL; /* Not needed because WebAudio is asynchronous. */ + + return MA_SUCCESS; +} +#endif /* Web Audio */ + + + +static ma_bool32 ma__is_channel_map_valid(const ma_channel* pChannelMap, 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 (pChannelMap != NULL && pChannelMap[0] != MA_CHANNEL_NONE) { + ma_uint32 iChannel; + + if (channels == 0 || channels > MA_MAX_CHANNELS) { + return MA_FALSE; /* Channel count out of range. */ + } + + /* 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 (pChannelMap[iChannel] == pChannelMap[jChannel]) { + return MA_FALSE; + } + } + } + } + + return MA_TRUE; +} + + +static ma_bool32 ma_context_is_backend_asynchronous(ma_context* pContext) +{ + MA_ASSERT(pContext != NULL); + + if (pContext->callbacks.onDeviceRead == NULL && pContext->callbacks.onDeviceWrite == NULL) { + if (pContext->callbacks.onDeviceDataLoop == NULL) { + return MA_TRUE; + } else { + return MA_FALSE; + } + } else { + return MA_FALSE; + } +} + + +static ma_result ma_device__post_init_setup(ma_device* pDevice, ma_device_type deviceType) +{ + ma_result result; + + MA_ASSERT(pDevice != NULL); + + if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) { + if (pDevice->capture.format == ma_format_unknown) { + pDevice->capture.format = pDevice->capture.internalFormat; + } + if (pDevice->capture.channels == 0) { + pDevice->capture.channels = pDevice->capture.internalChannels; + } + if (pDevice->capture.channelMap[0] == MA_CHANNEL_NONE) { + MA_ASSERT(pDevice->capture.channels <= MA_MAX_CHANNELS); + if (pDevice->capture.internalChannels == pDevice->capture.channels) { + ma_channel_map_copy(pDevice->capture.channelMap, pDevice->capture.internalChannelMap, pDevice->capture.channels); + } else { + if (pDevice->capture.channelMixMode == ma_channel_mix_mode_simple) { + ma_channel_map_init_blank(pDevice->capture.channelMap, pDevice->capture.channels); + } else { + ma_channel_map_init_standard(ma_standard_channel_map_default, pDevice->capture.channelMap, ma_countof(pDevice->capture.channelMap), pDevice->capture.channels); + } + } + } + } + + if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) { + if (pDevice->playback.format == ma_format_unknown) { + pDevice->playback.format = pDevice->playback.internalFormat; + } + if (pDevice->playback.channels == 0) { + pDevice->playback.channels = pDevice->playback.internalChannels; + } + if (pDevice->playback.channelMap[0] == MA_CHANNEL_NONE) { + MA_ASSERT(pDevice->playback.channels <= MA_MAX_CHANNELS); + if (pDevice->playback.internalChannels == pDevice->playback.channels) { + ma_channel_map_copy(pDevice->playback.channelMap, pDevice->playback.internalChannelMap, pDevice->playback.channels); + } else { + if (pDevice->playback.channelMixMode == ma_channel_mix_mode_simple) { + ma_channel_map_init_blank(pDevice->playback.channelMap, pDevice->playback.channels); + } else { + ma_channel_map_init_standard(ma_standard_channel_map_default, pDevice->playback.channelMap, ma_countof(pDevice->playback.channelMap), pDevice->playback.channels); + } + } + } + } + + if (pDevice->sampleRate == 0) { + if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) { + pDevice->sampleRate = pDevice->capture.internalSampleRate; + } else { + pDevice->sampleRate = pDevice->playback.internalSampleRate; + } + } + + /* Data converters. */ + if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) { + /* Converting from internal device format to client format. */ + ma_data_converter_config converterConfig = ma_data_converter_config_init_default(); + converterConfig.formatIn = pDevice->capture.internalFormat; + converterConfig.channelsIn = pDevice->capture.internalChannels; + converterConfig.sampleRateIn = pDevice->capture.internalSampleRate; + converterConfig.pChannelMapIn = pDevice->capture.internalChannelMap; + converterConfig.formatOut = pDevice->capture.format; + converterConfig.channelsOut = pDevice->capture.channels; + converterConfig.sampleRateOut = pDevice->sampleRate; + converterConfig.pChannelMapOut = pDevice->capture.channelMap; + converterConfig.channelMixMode = pDevice->capture.channelMixMode; + converterConfig.calculateLFEFromSpatialChannels = pDevice->capture.calculateLFEFromSpatialChannels; + converterConfig.allowDynamicSampleRate = MA_FALSE; + converterConfig.resampling.algorithm = pDevice->resampling.algorithm; + converterConfig.resampling.linear.lpfOrder = pDevice->resampling.linear.lpfOrder; + converterConfig.resampling.pBackendVTable = pDevice->resampling.pBackendVTable; + converterConfig.resampling.pBackendUserData = pDevice->resampling.pBackendUserData; + + /* Make sure the old converter is uninitialized first. */ + if (ma_device_get_state(pDevice) != ma_device_state_uninitialized) { + ma_data_converter_uninit(&pDevice->capture.converter, &pDevice->pContext->allocationCallbacks); + } + + result = ma_data_converter_init(&converterConfig, &pDevice->pContext->allocationCallbacks, &pDevice->capture.converter); + if (result != MA_SUCCESS) { + return result; + } + } + + if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) { + /* Converting from client format to device format. */ + ma_data_converter_config converterConfig = ma_data_converter_config_init_default(); + converterConfig.formatIn = pDevice->playback.format; + converterConfig.channelsIn = pDevice->playback.channels; + converterConfig.sampleRateIn = pDevice->sampleRate; + converterConfig.pChannelMapIn = pDevice->playback.channelMap; + converterConfig.formatOut = pDevice->playback.internalFormat; + converterConfig.channelsOut = pDevice->playback.internalChannels; + converterConfig.sampleRateOut = pDevice->playback.internalSampleRate; + converterConfig.pChannelMapOut = pDevice->playback.internalChannelMap; + converterConfig.channelMixMode = pDevice->playback.channelMixMode; + converterConfig.calculateLFEFromSpatialChannels = pDevice->playback.calculateLFEFromSpatialChannels; + converterConfig.allowDynamicSampleRate = MA_FALSE; + converterConfig.resampling.algorithm = pDevice->resampling.algorithm; + converterConfig.resampling.linear.lpfOrder = pDevice->resampling.linear.lpfOrder; + converterConfig.resampling.pBackendVTable = pDevice->resampling.pBackendVTable; + converterConfig.resampling.pBackendUserData = pDevice->resampling.pBackendUserData; + + /* Make sure the old converter is uninitialized first. */ + if (ma_device_get_state(pDevice) != ma_device_state_uninitialized) { + ma_data_converter_uninit(&pDevice->playback.converter, &pDevice->pContext->allocationCallbacks); + } + + result = ma_data_converter_init(&converterConfig, &pDevice->pContext->allocationCallbacks, &pDevice->playback.converter); + if (result != MA_SUCCESS) { + return result; + } + } + + + /* + If the device is doing playback (ma_device_type_playback or ma_device_type_duplex), there's + a couple of situations where we'll need a heap allocated cache. + + The first is a duplex device for backends that use a callback for data delivery. The reason + this is needed is that the input stage needs to have a buffer to place the input data while it + waits for the playback stage, after which the miniaudio data callback will get fired. This is + not needed for backends that use a blocking API because miniaudio manages temporary buffers on + the stack to achieve this. + + The other situation is when the data converter does not have the ability to query the number + of input frames that are required in order to process a given number of output frames. When + performing data conversion, it's useful if miniaudio know exactly how many frames it needs + from the client in order to generate a given number of output frames. This way, only exactly + the number of frames are needed to be read from the client which means no cache is necessary. + On the other hand, if miniaudio doesn't know how many frames to read, it is forced to read + in fixed sized chunks and then cache any residual unused input frames, those of which will be + processed at a later stage. + */ + if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) { + ma_uint64 unused; + + pDevice->playback.inputCacheConsumed = 0; + pDevice->playback.inputCacheRemaining = 0; + + if (pDevice->type == ma_device_type_duplex || /* Duplex. backend may decide to use ma_device_handle_backend_data_callback() which will require this cache. */ + ma_data_converter_get_required_input_frame_count(&pDevice->playback.converter, 1, &unused) != MA_SUCCESS) /* Data conversion required input frame calculation not supported. */ + { + /* We need a heap allocated cache. We want to size this based on the period size. */ + void* pNewInputCache; + ma_uint64 newInputCacheCap; + ma_uint64 newInputCacheSizeInBytes; + + newInputCacheCap = ma_calculate_frame_count_after_resampling(pDevice->playback.internalSampleRate, pDevice->sampleRate, pDevice->playback.internalPeriodSizeInFrames); + + newInputCacheSizeInBytes = newInputCacheCap * ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels); + if (newInputCacheSizeInBytes > MA_SIZE_MAX) { + ma_free(pDevice->playback.pInputCache, &pDevice->pContext->allocationCallbacks); + pDevice->playback.pInputCache = NULL; + pDevice->playback.inputCacheCap = 0; + return MA_OUT_OF_MEMORY; /* Allocation too big. Should never hit this, but makes the cast below safer for 32-bit builds. */ + } + + pNewInputCache = ma_realloc(pDevice->playback.pInputCache, (size_t)newInputCacheSizeInBytes, &pDevice->pContext->allocationCallbacks); + if (pNewInputCache == NULL) { + ma_free(pDevice->playback.pInputCache, &pDevice->pContext->allocationCallbacks); + pDevice->playback.pInputCache = NULL; + pDevice->playback.inputCacheCap = 0; + return MA_OUT_OF_MEMORY; + } + + pDevice->playback.pInputCache = pNewInputCache; + pDevice->playback.inputCacheCap = newInputCacheCap; + } else { + /* Heap allocation not required. Make sure we clear out the old cache just in case this function was called in response to a route change. */ + ma_free(pDevice->playback.pInputCache, &pDevice->pContext->allocationCallbacks); + pDevice->playback.pInputCache = NULL; + pDevice->playback.inputCacheCap = 0; + } + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_device_post_init(ma_device* pDevice, ma_device_type deviceType, const ma_device_descriptor* pDescriptorPlayback, const ma_device_descriptor* pDescriptorCapture) +{ + ma_result result; + + if (pDevice == NULL) { + return MA_INVALID_ARGS; + } + + /* Capture. */ + if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) { + if (ma_device_descriptor_is_valid(pDescriptorCapture) == MA_FALSE) { + return MA_INVALID_ARGS; + } + + pDevice->capture.internalFormat = pDescriptorCapture->format; + pDevice->capture.internalChannels = pDescriptorCapture->channels; + pDevice->capture.internalSampleRate = pDescriptorCapture->sampleRate; + MA_COPY_MEMORY(pDevice->capture.internalChannelMap, pDescriptorCapture->channelMap, sizeof(pDescriptorCapture->channelMap)); + pDevice->capture.internalPeriodSizeInFrames = pDescriptorCapture->periodSizeInFrames; + pDevice->capture.internalPeriods = pDescriptorCapture->periodCount; + + if (pDevice->capture.internalPeriodSizeInFrames == 0) { + pDevice->capture.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pDescriptorCapture->periodSizeInMilliseconds, pDescriptorCapture->sampleRate); + } + } + + /* Playback. */ + if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) { + if (ma_device_descriptor_is_valid(pDescriptorPlayback) == MA_FALSE) { + return MA_INVALID_ARGS; + } + + pDevice->playback.internalFormat = pDescriptorPlayback->format; + pDevice->playback.internalChannels = pDescriptorPlayback->channels; + pDevice->playback.internalSampleRate = pDescriptorPlayback->sampleRate; + MA_COPY_MEMORY(pDevice->playback.internalChannelMap, pDescriptorPlayback->channelMap, sizeof(pDescriptorPlayback->channelMap)); + pDevice->playback.internalPeriodSizeInFrames = pDescriptorPlayback->periodSizeInFrames; + pDevice->playback.internalPeriods = pDescriptorPlayback->periodCount; + + if (pDevice->playback.internalPeriodSizeInFrames == 0) { + pDevice->playback.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pDescriptorPlayback->periodSizeInMilliseconds, pDescriptorPlayback->sampleRate); + } + } + + /* + The name of the device can be retrieved from device info. This may be temporary and replaced with a `ma_device_get_info(pDevice, deviceType)` instead. + For loopback devices, we need to retrieve the name of the playback device. + */ + { + ma_device_info deviceInfo; + + if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) { + result = ma_device_get_info(pDevice, (deviceType == ma_device_type_loopback) ? ma_device_type_playback : ma_device_type_capture, &deviceInfo); + if (result == MA_SUCCESS) { + ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), deviceInfo.name, (size_t)-1); + } else { + /* We failed to retrieve the device info. Fall back to a default name. */ + if (pDescriptorCapture->pDeviceID == NULL) { + ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); + } else { + ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), "Capture Device", (size_t)-1); + } + } + } + + if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) { + result = ma_device_get_info(pDevice, ma_device_type_playback, &deviceInfo); + if (result == MA_SUCCESS) { + ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), deviceInfo.name, (size_t)-1); + } else { + /* We failed to retrieve the device info. Fall back to a default name. */ + if (pDescriptorPlayback->pDeviceID == NULL) { + ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); + } else { + ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), "Playback Device", (size_t)-1); + } + } + } + } + + /* Update data conversion. */ + return ma_device__post_init_setup(pDevice, deviceType); /* TODO: Should probably rename ma_device__post_init_setup() to something better. */ +} + + +static ma_thread_result MA_THREADCALL ma_worker_thread(void* pData) +{ + ma_device* pDevice = (ma_device*)pData; +#ifdef MA_WIN32 + HRESULT CoInitializeResult; +#endif + + MA_ASSERT(pDevice != NULL); + +#ifdef MA_WIN32 + CoInitializeResult = ma_CoInitializeEx(pDevice->pContext, NULL, MA_COINIT_VALUE); +#endif + + /* + When the device is being initialized it's initial state is set to ma_device_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_device_state_stopped); + ma_event_signal(&pDevice->stopEvent); + + for (;;) { /* <-- This loop just keeps the thread alive. The main audio loop is inside. */ + ma_result startResult; + ma_result stopResult; /* <-- This will store the result from onDeviceStop(). If it returns an error, we don't fire the stopped notification callback. */ + + /* 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_device_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_device_state_starting); + + /* If the device has a start callback, start it now. */ + if (pDevice->pContext->callbacks.onDeviceStart != NULL) { + startResult = pDevice->pContext->callbacks.onDeviceStart(pDevice); + } else { + startResult = MA_SUCCESS; + } + + /* + If starting was not successful we'll need to loop back to the start and wait for something + to happen (pDevice->wakeupEvent). + */ + if (startResult != MA_SUCCESS) { + pDevice->workResult = startResult; + ma_event_signal(&pDevice->startEvent); /* <-- Always signal the start event so ma_device_start() can return as it'll be waiting on it. */ + continue; + } + + /* Make sure the state is set appropriately. */ + ma_device__set_state(pDevice, ma_device_state_started); /* <-- Set this before signaling the event so that the state is always guaranteed to be good after ma_device_start() has returned. */ + ma_event_signal(&pDevice->startEvent); + + ma_device__on_notification_started(pDevice); + + if (pDevice->pContext->callbacks.onDeviceDataLoop != NULL) { + pDevice->pContext->callbacks.onDeviceDataLoop(pDevice); + } else { + /* The backend is not using a custom main loop implementation, so now fall back to the blocking read-write implementation. */ + ma_device_audio_thread__default_read_write(pDevice); + } + + /* Getting here means we have broken from the main loop which happens the application has requested that device be stopped. */ + if (pDevice->pContext->callbacks.onDeviceStop != NULL) { + stopResult = pDevice->pContext->callbacks.onDeviceStop(pDevice); + } else { + stopResult = MA_SUCCESS; /* No stop callback with the backend. Just assume successful. */ + } + + /* + After the device has stopped, make sure an event is posted. Don't post a stopped event if + stopping failed. This can happen on some backends when the underlying stream has been + stopped due to the device being physically unplugged or disabled via an OS setting. + */ + if (stopResult == MA_SUCCESS) { + ma_device__on_notification_stopped(pDevice); + } + + /* If we stopped because the device has been uninitialized, abort now. */ + if (ma_device_get_state(pDevice) == ma_device_state_uninitialized) { + break; + } + + /* 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. */ + ma_device__set_state(pDevice, ma_device_state_stopped); + ma_event_signal(&pDevice->stopEvent); + } + +#ifdef MA_WIN32 + if (CoInitializeResult == S_OK) { + ma_CoUninitialize(pDevice->pContext); + } +#endif + + return (ma_thread_result)0; +} + + +/* Helper for determining whether or not the given device is initialized. */ +static ma_bool32 ma_device__is_initialized(ma_device* pDevice) +{ + if (pDevice == NULL) { + return MA_FALSE; + } + + return ma_device_get_state(pDevice) != ma_device_state_uninitialized; +} + + +#ifdef MA_WIN32 +static ma_result ma_context_uninit_backend_apis__win32(ma_context* pContext) +{ + /* For some reason UWP complains when CoUninitialize() is called. I'm just not going to call it on UWP. */ +#if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK) + if (pContext->win32.CoInitializeResult == S_OK) { + ma_CoUninitialize(pContext); + } + + #if defined(MA_WIN32_DESKTOP) + ma_dlclose(ma_context_get_log(pContext), pContext->win32.hUser32DLL); + ma_dlclose(ma_context_get_log(pContext), pContext->win32.hAdvapi32DLL); + #endif + + ma_dlclose(ma_context_get_log(pContext), pContext->win32.hOle32DLL); +#else + (void)pContext; +#endif + + return MA_SUCCESS; +} + +static ma_result ma_context_init_backend_apis__win32(ma_context* pContext) +{ +#if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK) + #if defined(MA_WIN32_DESKTOP) + /* User32.dll */ + pContext->win32.hUser32DLL = ma_dlopen(ma_context_get_log(pContext), "user32.dll"); + if (pContext->win32.hUser32DLL == NULL) { + return MA_FAILED_TO_INIT_BACKEND; + } + + pContext->win32.GetForegroundWindow = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hUser32DLL, "GetForegroundWindow"); + pContext->win32.GetDesktopWindow = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hUser32DLL, "GetDesktopWindow"); + + + /* Advapi32.dll */ + pContext->win32.hAdvapi32DLL = ma_dlopen(ma_context_get_log(pContext), "advapi32.dll"); + if (pContext->win32.hAdvapi32DLL == NULL) { + return MA_FAILED_TO_INIT_BACKEND; + } + + pContext->win32.RegOpenKeyExA = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hAdvapi32DLL, "RegOpenKeyExA"); + pContext->win32.RegCloseKey = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hAdvapi32DLL, "RegCloseKey"); + pContext->win32.RegQueryValueExA = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hAdvapi32DLL, "RegQueryValueExA"); + #endif + + /* Ole32.dll */ + pContext->win32.hOle32DLL = ma_dlopen(ma_context_get_log(pContext), "ole32.dll"); + if (pContext->win32.hOle32DLL == NULL) { + return MA_FAILED_TO_INIT_BACKEND; + } + + pContext->win32.CoInitialize = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hOle32DLL, "CoInitialize"); + pContext->win32.CoInitializeEx = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hOle32DLL, "CoInitializeEx"); + pContext->win32.CoUninitialize = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hOle32DLL, "CoUninitialize"); + pContext->win32.CoCreateInstance = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hOle32DLL, "CoCreateInstance"); + pContext->win32.CoTaskMemFree = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hOle32DLL, "CoTaskMemFree"); + pContext->win32.PropVariantClear = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hOle32DLL, "PropVariantClear"); + pContext->win32.StringFromGUID2 = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hOle32DLL, "StringFromGUID2"); +#else + (void)pContext; /* Unused. */ +#endif + + pContext->win32.CoInitializeResult = ma_CoInitializeEx(pContext, NULL, MA_COINIT_VALUE); + return MA_SUCCESS; +} +#else +static ma_result ma_context_uninit_backend_apis__nix(ma_context* pContext) +{ + (void)pContext; + + return MA_SUCCESS; +} + +static ma_result ma_context_init_backend_apis__nix(ma_context* pContext) +{ + (void)pContext; + + return MA_SUCCESS; +} +#endif + +static 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; +} + +static 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; +} + + +/* The default capacity doesn't need to be too big. */ +#ifndef MA_DEFAULT_DEVICE_JOB_QUEUE_CAPACITY +#define MA_DEFAULT_DEVICE_JOB_QUEUE_CAPACITY 32 +#endif + +MA_API ma_device_job_thread_config ma_device_job_thread_config_init(void) +{ + ma_device_job_thread_config config; + + MA_ZERO_OBJECT(&config); + config.noThread = MA_FALSE; + config.jobQueueCapacity = MA_DEFAULT_DEVICE_JOB_QUEUE_CAPACITY; + config.jobQueueFlags = 0; + + return config; +} + + +static ma_thread_result MA_THREADCALL ma_device_job_thread_entry(void* pUserData) +{ + ma_device_job_thread* pJobThread = (ma_device_job_thread*)pUserData; + MA_ASSERT(pJobThread != NULL); + + for (;;) { + ma_result result; + ma_job job; + + result = ma_device_job_thread_next(pJobThread, &job); + if (result != MA_SUCCESS) { + break; + } + + if (job.toc.breakup.code == MA_JOB_TYPE_QUIT) { + break; + } + + ma_job_process(&job); + } + + return (ma_thread_result)0; +} + +MA_API ma_result ma_device_job_thread_init(const ma_device_job_thread_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_device_job_thread* pJobThread) +{ + ma_result result; + ma_job_queue_config jobQueueConfig; + + if (pJobThread == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pJobThread); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + + /* Initialize the job queue before the thread to ensure it's in a valid state. */ + jobQueueConfig = ma_job_queue_config_init(pConfig->jobQueueFlags, pConfig->jobQueueCapacity); + + result = ma_job_queue_init(&jobQueueConfig, pAllocationCallbacks, &pJobThread->jobQueue); + if (result != MA_SUCCESS) { + return result; /* Failed to initialize job queue. */ + } + + + /* The thread needs to be initialized after the job queue to ensure the thread doesn't try to access it prematurely. */ + if (pConfig->noThread == MA_FALSE) { + result = ma_thread_create(&pJobThread->thread, ma_thread_priority_normal, 0, ma_device_job_thread_entry, pJobThread, pAllocationCallbacks); + if (result != MA_SUCCESS) { + ma_job_queue_uninit(&pJobThread->jobQueue, pAllocationCallbacks); + return result; /* Failed to create the job thread. */ + } + + pJobThread->_hasThread = MA_TRUE; + } else { + pJobThread->_hasThread = MA_FALSE; + } + + + return MA_SUCCESS; +} + +MA_API void ma_device_job_thread_uninit(ma_device_job_thread* pJobThread, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pJobThread == NULL) { + return; + } + + /* The first thing to do is post a quit message to the job queue. If we're using a thread we'll need to wait for it. */ + { + ma_job job = ma_job_init(MA_JOB_TYPE_QUIT); + ma_device_job_thread_post(pJobThread, &job); + } + + /* Wait for the thread to terminate naturally. */ + if (pJobThread->_hasThread) { + ma_thread_wait(&pJobThread->thread); + } + + /* At this point the thread should be terminated so we can safely uninitialize the job queue. */ + ma_job_queue_uninit(&pJobThread->jobQueue, pAllocationCallbacks); +} + +MA_API ma_result ma_device_job_thread_post(ma_device_job_thread* pJobThread, const ma_job* pJob) +{ + if (pJobThread == NULL || pJob == NULL) { + return MA_INVALID_ARGS; + } + + return ma_job_queue_post(&pJobThread->jobQueue, pJob); +} + +MA_API ma_result ma_device_job_thread_next(ma_device_job_thread* pJobThread, ma_job* pJob) +{ + if (pJob == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pJob); + + if (pJobThread == NULL) { + return MA_INVALID_ARGS; + } + + return ma_job_queue_next(&pJobThread->jobQueue, pJob); +} + + + +MA_API ma_context_config ma_context_config_init(void) +{ + ma_context_config config; + MA_ZERO_OBJECT(&config); + + return config; +} + +MA_API 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 defaultConfig; + 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. */ + if (pConfig == NULL) { + defaultConfig = ma_context_config_init(); + pConfig = &defaultConfig; + } + + /* Allocation callbacks need to come first because they'll be passed around to other areas. */ + result = ma_allocation_callbacks_init_copy(&pContext->allocationCallbacks, &pConfig->allocationCallbacks); + if (result != MA_SUCCESS) { + return result; + } + + /* Get a lot set up first so we can start logging ASAP. */ + if (pConfig->pLog != NULL) { + pContext->pLog = pConfig->pLog; + } else { + result = ma_log_init(&pContext->allocationCallbacks, &pContext->log); + if (result == MA_SUCCESS) { + pContext->pLog = &pContext->log; + } else { + pContext->pLog = NULL; /* Logging is not available. */ + } + } + + pContext->threadPriority = pConfig->threadPriority; + pContext->threadStackSize = pConfig->threadStackSize; + pContext->pUserData = pConfig->pUserData; + + /* 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; + } + + for (iBackend = 0; iBackend <= ma_backend_null; ++iBackend) { + defaultBackends[iBackend] = (ma_backend)iBackend; + } + + pBackendsToIterate = (ma_backend*)backends; + backendsToIterateCount = backendCount; + if (pBackendsToIterate == NULL) { + pBackendsToIterate = (ma_backend*)defaultBackends; + backendsToIterateCount = ma_countof(defaultBackends); + } + + MA_ASSERT(pBackendsToIterate != NULL); + + for (iBackend = 0; iBackend < backendsToIterateCount; iBackend += 1) { + ma_backend backend = pBackendsToIterate[iBackend]; + + /* Make sure all callbacks are reset so we don't accidentally drag in any from previously failed initialization attempts. */ + MA_ZERO_OBJECT(&pContext->callbacks); + + /* These backends are using the new callback system. */ + switch (backend) { + #ifdef MA_HAS_WASAPI + case ma_backend_wasapi: + { + pContext->callbacks.onContextInit = ma_context_init__wasapi; + } break; + #endif + #ifdef MA_HAS_DSOUND + case ma_backend_dsound: + { + pContext->callbacks.onContextInit = ma_context_init__dsound; + } break; + #endif + #ifdef MA_HAS_WINMM + case ma_backend_winmm: + { + pContext->callbacks.onContextInit = ma_context_init__winmm; + } break; + #endif + #ifdef MA_HAS_COREAUDIO + case ma_backend_coreaudio: + { + pContext->callbacks.onContextInit = ma_context_init__coreaudio; + } break; + #endif + #ifdef MA_HAS_SNDIO + case ma_backend_sndio: + { + pContext->callbacks.onContextInit = ma_context_init__sndio; + } break; + #endif + #ifdef MA_HAS_AUDIO4 + case ma_backend_audio4: + { + pContext->callbacks.onContextInit = ma_context_init__audio4; + } break; + #endif + #ifdef MA_HAS_OSS + case ma_backend_oss: + { + pContext->callbacks.onContextInit = ma_context_init__oss; + } break; + #endif + #ifdef MA_HAS_PULSEAUDIO + case ma_backend_pulseaudio: + { + pContext->callbacks.onContextInit = ma_context_init__pulse; + } break; + #endif + #ifdef MA_HAS_ALSA + case ma_backend_alsa: + { + pContext->callbacks.onContextInit = ma_context_init__alsa; + } break; + #endif + #ifdef MA_HAS_JACK + case ma_backend_jack: + { + pContext->callbacks.onContextInit = ma_context_init__jack; + } break; + #endif + #ifdef MA_HAS_AAUDIO + case ma_backend_aaudio: + { + if (ma_is_backend_enabled(backend)) { + pContext->callbacks.onContextInit = ma_context_init__aaudio; + } + } break; + #endif + #ifdef MA_HAS_OPENSL + case ma_backend_opensl: + { + if (ma_is_backend_enabled(backend)) { + pContext->callbacks.onContextInit = ma_context_init__opensl; + } + } break; + #endif + #ifdef MA_HAS_WEBAUDIO + case ma_backend_webaudio: + { + pContext->callbacks.onContextInit = ma_context_init__webaudio; + } break; + #endif + #ifdef MA_HAS_CUSTOM + case ma_backend_custom: + { + /* Slightly different logic for custom backends. Custom backends can optionally set all of their callbacks in the config. */ + pContext->callbacks = pConfig->custom; + } break; + #endif + #ifdef MA_HAS_NULL + case ma_backend_null: + { + pContext->callbacks.onContextInit = ma_context_init__null; + } break; + #endif + + default: break; + } + + if (pContext->callbacks.onContextInit != NULL) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "Attempting to initialize %s backend...\n", ma_get_backend_name(backend)); + result = pContext->callbacks.onContextInit(pContext, pConfig, &pContext->callbacks); + } else { + /* Getting here means the onContextInit callback is not set which means the backend is not enabled. Special case for the custom backend. */ + if (backend != ma_backend_custom) { + result = MA_BACKEND_NOT_ENABLED; + } else { + #if !defined(MA_HAS_CUSTOM) + result = MA_BACKEND_NOT_ENABLED; + #else + result = MA_NO_BACKEND; + #endif + } + } + + /* If this iteration was successful, return. */ + if (result == MA_SUCCESS) { + result = ma_mutex_init(&pContext->deviceEnumLock); + if (result != MA_SUCCESS) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "Failed to initialize mutex for device enumeration. ma_context_get_devices() is not thread safe.\n"); + } + + result = ma_mutex_init(&pContext->deviceInfoLock); + if (result != MA_SUCCESS) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "Failed to initialize mutex for device info retrieval. ma_context_get_device_info() is not thread safe.\n"); + } + + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "System Architecture:\n"); + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " Endian: %s\n", ma_is_little_endian() ? "LE" : "BE"); + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " SSE2: %s\n", ma_has_sse2() ? "YES" : "NO"); + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " AVX2: %s\n", ma_has_avx2() ? "YES" : "NO"); + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " NEON: %s\n", ma_has_neon() ? "YES" : "NO"); + + pContext->backend = backend; + return result; + } else { + if (result == MA_BACKEND_NOT_ENABLED) { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "%s backend is disabled.\n", ma_get_backend_name(backend)); + } else { + ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "Failed to initialize %s backend.\n", ma_get_backend_name(backend)); + } + } + } + + /* If we get here it means an error occurred. */ + MA_ZERO_OBJECT(pContext); /* Safety. */ + return MA_NO_BACKEND; +} + +MA_API ma_result ma_context_uninit(ma_context* pContext) +{ + if (pContext == NULL) { + return MA_INVALID_ARGS; + } + + if (pContext->callbacks.onContextUninit != NULL) { + pContext->callbacks.onContextUninit(pContext); + } + + ma_mutex_uninit(&pContext->deviceEnumLock); + ma_mutex_uninit(&pContext->deviceInfoLock); + ma_free(pContext->pDeviceInfos, &pContext->allocationCallbacks); + ma_context_uninit_backend_apis(pContext); + + if (pContext->pLog == &pContext->log) { + ma_log_uninit(&pContext->log); + } + + return MA_SUCCESS; +} + +MA_API size_t ma_context_sizeof(void) +{ + return sizeof(ma_context); +} + + +MA_API ma_log* ma_context_get_log(ma_context* pContext) +{ + if (pContext == NULL) { + return NULL; + } + + return pContext->pLog; +} + + +MA_API ma_result ma_context_enumerate_devices(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) +{ + ma_result result; + + if (pContext == NULL || callback == NULL) { + return MA_INVALID_ARGS; + } + + if (pContext->callbacks.onContextEnumerateDevices == NULL) { + return MA_INVALID_OPERATION; + } + + ma_mutex_lock(&pContext->deviceEnumLock); + { + result = pContext->callbacks.onContextEnumerateDevices(pContext, callback, pUserData); + } + ma_mutex_unlock(&pContext->deviceEnumLock); + + return result; +} + + +static ma_bool32 ma_context_get_devices__enum_callback(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pInfo, 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 (totalDeviceInfoCount >= pContext->deviceInfoCapacity) { + ma_uint32 newCapacity = pContext->deviceInfoCapacity + bufferExpansionCount; + ma_device_info* pNewInfos = (ma_device_info*)ma_realloc(pContext->pDeviceInfos, sizeof(*pContext->pDeviceInfos)*newCapacity, &pContext->allocationCallbacks); + 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; + 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. */ + pContext->pDeviceInfos[iFirstCaptureDevice] = *pInfo; + pContext->playbackDeviceInfoCount += 1; + } else { + /* Capture. Insert at the end. */ + pContext->pDeviceInfos[totalDeviceInfoCount] = *pInfo; + pContext->captureDeviceInfoCount += 1; + } + + (void)pUserData; + return MA_TRUE; +} + +MA_API ma_result ma_context_get_devices(ma_context* pContext, ma_device_info** ppPlaybackDeviceInfos, ma_uint32* pPlaybackDeviceCount, ma_device_info** ppCaptureDeviceInfos, ma_uint32* pCaptureDeviceCount) +{ + ma_result result; + + /* Safety. */ + if (ppPlaybackDeviceInfos != NULL) *ppPlaybackDeviceInfos = NULL; + if (pPlaybackDeviceCount != NULL) *pPlaybackDeviceCount = 0; + if (ppCaptureDeviceInfos != NULL) *ppCaptureDeviceInfos = NULL; + if (pCaptureDeviceCount != NULL) *pCaptureDeviceCount = 0; + + if (pContext == NULL) { + return MA_INVALID_ARGS; + } + + if (pContext->callbacks.onContextEnumerateDevices == NULL) { + return MA_INVALID_OPERATION; + } + + /* 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. */ + pContext->playbackDeviceInfoCount = 0; + pContext->captureDeviceInfoCount = 0; + + /* Now enumerate over available devices. */ + result = pContext->callbacks.onContextEnumerateDevices(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; + /* Capture devices come after playback devices. */ + if (pContext->playbackDeviceInfoCount > 0) { + /* Conditional, because NULL+0 is undefined behavior. */ + *ppCaptureDeviceInfos += pContext->playbackDeviceInfoCount; + } + } + if (pCaptureDeviceCount != NULL) { + *pCaptureDeviceCount = pContext->captureDeviceInfoCount; + } + } + } + ma_mutex_unlock(&pContext->deviceEnumLock); + + return result; +} + +MA_API ma_result ma_context_get_device_info(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo) +{ + ma_result result; + 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_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)); + } + + if (pContext->callbacks.onContextGetDeviceInfo == NULL) { + return MA_INVALID_OPERATION; + } + + ma_mutex_lock(&pContext->deviceInfoLock); + { + result = pContext->callbacks.onContextGetDeviceInfo(pContext, deviceType, pDeviceID, &deviceInfo); + } + ma_mutex_unlock(&pContext->deviceInfoLock); + + *pDeviceInfo = deviceInfo; + return result; +} + +MA_API ma_bool32 ma_context_is_loopback_supported(ma_context* pContext) +{ + if (pContext == NULL) { + return MA_FALSE; + } + + return ma_is_loopback_supported(pContext->backend); +} + + +MA_API ma_device_config ma_device_config_init(ma_device_type deviceType) +{ + ma_device_config config; + MA_ZERO_OBJECT(&config); + config.deviceType = deviceType; + config.resampling = ma_resampler_config_init(ma_format_unknown, 0, 0, 0, ma_resample_algorithm_linear); /* Format/channels/rate don't matter here. */ + + return config; +} + +MA_API ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) +{ + ma_result result; + ma_device_descriptor descriptorPlayback; + ma_device_descriptor descriptorCapture; + + /* The context can be null, in which case we self-manage it. */ + if (pContext == NULL) { + return ma_device_init_ex(NULL, 0, NULL, pConfig, pDevice); + } + + if (pDevice == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pDevice); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + /* Check that we have our callbacks defined. */ + if (pContext->callbacks.onDeviceInit == NULL) { + return MA_INVALID_OPERATION; + } + + /* Basic config validation. */ + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + if (pConfig->capture.channels > MA_MAX_CHANNELS) { + return MA_INVALID_ARGS; + } + + if (!ma__is_channel_map_valid(pConfig->capture.pChannelMap, pConfig->capture.channels)) { + return MA_INVALID_ARGS; + } + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) { + if (pConfig->playback.channels > MA_MAX_CHANNELS) { + return MA_INVALID_ARGS; + } + + if (!ma__is_channel_map_valid(pConfig->playback.pChannelMap, pConfig->playback.channels)) { + return MA_INVALID_ARGS; + } + } + + pDevice->pContext = pContext; + + /* Set the user data and log callback ASAP to ensure it is available for the entire initialization process. */ + pDevice->pUserData = pConfig->pUserData; + pDevice->onData = pConfig->dataCallback; + pDevice->onNotification = pConfig->notificationCallback; + pDevice->onStop = pConfig->stopCallback; + + if (pConfig->playback.pDeviceID != NULL) { + MA_COPY_MEMORY(&pDevice->playback.id, pConfig->playback.pDeviceID, sizeof(pDevice->playback.id)); + pDevice->playback.pID = &pDevice->playback.id; + } else { + pDevice->playback.pID = NULL; + } + + if (pConfig->capture.pDeviceID != NULL) { + MA_COPY_MEMORY(&pDevice->capture.id, pConfig->capture.pDeviceID, sizeof(pDevice->capture.id)); + pDevice->capture.pID = &pDevice->capture.id; + } else { + pDevice->capture.pID = NULL; + } + + pDevice->noPreSilencedOutputBuffer = pConfig->noPreSilencedOutputBuffer; + pDevice->noClip = pConfig->noClip; + pDevice->noDisableDenormals = pConfig->noDisableDenormals; + pDevice->noFixedSizedCallback = pConfig->noFixedSizedCallback; + ma_atomic_float_set(&pDevice->masterVolumeFactor, 1); + + pDevice->type = pConfig->deviceType; + pDevice->sampleRate = pConfig->sampleRate; + pDevice->resampling.algorithm = pConfig->resampling.algorithm; + pDevice->resampling.linear.lpfOrder = pConfig->resampling.linear.lpfOrder; + pDevice->resampling.pBackendVTable = pConfig->resampling.pBackendVTable; + pDevice->resampling.pBackendUserData = pConfig->resampling.pBackendUserData; + + pDevice->capture.shareMode = pConfig->capture.shareMode; + pDevice->capture.format = pConfig->capture.format; + pDevice->capture.channels = pConfig->capture.channels; + ma_channel_map_copy_or_default(pDevice->capture.channelMap, ma_countof(pDevice->capture.channelMap), pConfig->capture.pChannelMap, pConfig->capture.channels); + pDevice->capture.channelMixMode = pConfig->capture.channelMixMode; + pDevice->capture.calculateLFEFromSpatialChannels = pConfig->capture.calculateLFEFromSpatialChannels; + + pDevice->playback.shareMode = pConfig->playback.shareMode; + pDevice->playback.format = pConfig->playback.format; + pDevice->playback.channels = pConfig->playback.channels; + ma_channel_map_copy_or_default(pDevice->playback.channelMap, ma_countof(pDevice->playback.channelMap), pConfig->playback.pChannelMap, pConfig->playback.channels); + pDevice->playback.channelMixMode = pConfig->playback.channelMixMode; + pDevice->playback.calculateLFEFromSpatialChannels = pConfig->playback.calculateLFEFromSpatialChannels; + + result = ma_mutex_init(&pDevice->startStopLock); + if (result != MA_SUCCESS) { + return result; + } + + /* + 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. + */ + result = ma_event_init(&pDevice->wakeupEvent); + if (result != MA_SUCCESS) { + ma_mutex_uninit(&pDevice->startStopLock); + return result; + } + + result = ma_event_init(&pDevice->startEvent); + if (result != MA_SUCCESS) { + ma_event_uninit(&pDevice->wakeupEvent); + ma_mutex_uninit(&pDevice->startStopLock); + return result; + } + + result = ma_event_init(&pDevice->stopEvent); + if (result != MA_SUCCESS) { + ma_event_uninit(&pDevice->startEvent); + ma_event_uninit(&pDevice->wakeupEvent); + ma_mutex_uninit(&pDevice->startStopLock); + return result; + } + + + MA_ZERO_OBJECT(&descriptorPlayback); + descriptorPlayback.pDeviceID = pConfig->playback.pDeviceID; + descriptorPlayback.shareMode = pConfig->playback.shareMode; + descriptorPlayback.format = pConfig->playback.format; + descriptorPlayback.channels = pConfig->playback.channels; + descriptorPlayback.sampleRate = pConfig->sampleRate; + ma_channel_map_copy_or_default(descriptorPlayback.channelMap, ma_countof(descriptorPlayback.channelMap), pConfig->playback.pChannelMap, pConfig->playback.channels); + descriptorPlayback.periodSizeInFrames = pConfig->periodSizeInFrames; + descriptorPlayback.periodSizeInMilliseconds = pConfig->periodSizeInMilliseconds; + descriptorPlayback.periodCount = pConfig->periods; + + if (descriptorPlayback.periodCount == 0) { + descriptorPlayback.periodCount = MA_DEFAULT_PERIODS; + } + + + MA_ZERO_OBJECT(&descriptorCapture); + descriptorCapture.pDeviceID = pConfig->capture.pDeviceID; + descriptorCapture.shareMode = pConfig->capture.shareMode; + descriptorCapture.format = pConfig->capture.format; + descriptorCapture.channels = pConfig->capture.channels; + descriptorCapture.sampleRate = pConfig->sampleRate; + ma_channel_map_copy_or_default(descriptorCapture.channelMap, ma_countof(descriptorCapture.channelMap), pConfig->capture.pChannelMap, pConfig->capture.channels); + descriptorCapture.periodSizeInFrames = pConfig->periodSizeInFrames; + descriptorCapture.periodSizeInMilliseconds = pConfig->periodSizeInMilliseconds; + descriptorCapture.periodCount = pConfig->periods; + + if (descriptorCapture.periodCount == 0) { + descriptorCapture.periodCount = MA_DEFAULT_PERIODS; + } + + + result = pContext->callbacks.onDeviceInit(pDevice, pConfig, &descriptorPlayback, &descriptorCapture); + if (result != MA_SUCCESS) { + ma_event_uninit(&pDevice->startEvent); + ma_event_uninit(&pDevice->wakeupEvent); + ma_mutex_uninit(&pDevice->startStopLock); + return result; + } + +#if 0 + /* + On output the descriptors will contain the *actual* data format of the device. We need this to know how to convert the data between + the requested format and the internal format. + */ + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) { + if (!ma_device_descriptor_is_valid(&descriptorCapture)) { + ma_device_uninit(pDevice); + return MA_INVALID_ARGS; + } + + pDevice->capture.internalFormat = descriptorCapture.format; + pDevice->capture.internalChannels = descriptorCapture.channels; + pDevice->capture.internalSampleRate = descriptorCapture.sampleRate; + ma_channel_map_copy(pDevice->capture.internalChannelMap, descriptorCapture.channelMap, descriptorCapture.channels); + pDevice->capture.internalPeriodSizeInFrames = descriptorCapture.periodSizeInFrames; + pDevice->capture.internalPeriods = descriptorCapture.periodCount; + + if (pDevice->capture.internalPeriodSizeInFrames == 0) { + pDevice->capture.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(descriptorCapture.periodSizeInMilliseconds, descriptorCapture.sampleRate); + } + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + if (!ma_device_descriptor_is_valid(&descriptorPlayback)) { + ma_device_uninit(pDevice); + return MA_INVALID_ARGS; + } + + pDevice->playback.internalFormat = descriptorPlayback.format; + pDevice->playback.internalChannels = descriptorPlayback.channels; + pDevice->playback.internalSampleRate = descriptorPlayback.sampleRate; + ma_channel_map_copy(pDevice->playback.internalChannelMap, descriptorPlayback.channelMap, descriptorPlayback.channels); + pDevice->playback.internalPeriodSizeInFrames = descriptorPlayback.periodSizeInFrames; + pDevice->playback.internalPeriods = descriptorPlayback.periodCount; + + if (pDevice->playback.internalPeriodSizeInFrames == 0) { + pDevice->playback.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(descriptorPlayback.periodSizeInMilliseconds, descriptorPlayback.sampleRate); + } + } + + + /* + The name of the device can be retrieved from device info. This may be temporary and replaced with a `ma_device_get_info(pDevice, deviceType)` instead. + For loopback devices, we need to retrieve the name of the playback device. + */ + { + ma_device_info deviceInfo; + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) { + result = ma_device_get_info(pDevice, (pConfig->deviceType == ma_device_type_loopback) ? ma_device_type_playback : ma_device_type_capture, &deviceInfo); + if (result == MA_SUCCESS) { + ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), deviceInfo.name, (size_t)-1); + } else { + /* We failed to retrieve the device info. Fall back to a default name. */ + if (descriptorCapture.pDeviceID == NULL) { + ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); + } else { + ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), "Capture Device", (size_t)-1); + } + } + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + result = ma_device_get_info(pDevice, ma_device_type_playback, &deviceInfo); + if (result == MA_SUCCESS) { + ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), deviceInfo.name, (size_t)-1); + } else { + /* We failed to retrieve the device info. Fall back to a default name. */ + if (descriptorPlayback.pDeviceID == NULL) { + ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); + } else { + ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), "Playback Device", (size_t)-1); + } + } + } + } + + + ma_device__post_init_setup(pDevice, pConfig->deviceType); +#endif + + result = ma_device_post_init(pDevice, pConfig->deviceType, &descriptorPlayback, &descriptorCapture); + if (result != MA_SUCCESS) { + ma_device_uninit(pDevice); + return result; + } + + + /* + If we're using fixed sized callbacks we'll need to make use of an intermediary buffer. Needs to + be done after post_init_setup() because we'll need access to the sample rate. + */ + if (pConfig->noFixedSizedCallback == MA_FALSE) { + /* We're using a fixed sized data callback so we'll need an intermediary buffer. */ + ma_uint32 intermediaryBufferCap = pConfig->periodSizeInFrames; + if (intermediaryBufferCap == 0) { + intermediaryBufferCap = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->periodSizeInMilliseconds, pDevice->sampleRate); + } + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) { + ma_uint32 intermediaryBufferSizeInBytes; + + pDevice->capture.intermediaryBufferLen = 0; + pDevice->capture.intermediaryBufferCap = intermediaryBufferCap; + if (pDevice->capture.intermediaryBufferCap == 0) { + pDevice->capture.intermediaryBufferCap = pDevice->capture.internalPeriodSizeInFrames; + } + + intermediaryBufferSizeInBytes = pDevice->capture.intermediaryBufferCap * ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels); + + pDevice->capture.pIntermediaryBuffer = ma_malloc((size_t)intermediaryBufferSizeInBytes, &pContext->allocationCallbacks); + if (pDevice->capture.pIntermediaryBuffer == NULL) { + ma_device_uninit(pDevice); + return MA_OUT_OF_MEMORY; + } + + /* Silence the buffer for safety. */ + ma_silence_pcm_frames(pDevice->capture.pIntermediaryBuffer, pDevice->capture.intermediaryBufferCap, pDevice->capture.format, pDevice->capture.channels); + pDevice->capture.intermediaryBufferLen = pDevice->capture.intermediaryBufferCap; + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + ma_uint64 intermediaryBufferSizeInBytes; + + pDevice->playback.intermediaryBufferLen = 0; + if (pConfig->deviceType == ma_device_type_duplex) { + pDevice->playback.intermediaryBufferCap = pDevice->capture.intermediaryBufferCap; /* In duplex mode, make sure the intermediary buffer is always the same size as the capture side. */ + } else { + pDevice->playback.intermediaryBufferCap = intermediaryBufferCap; + if (pDevice->playback.intermediaryBufferCap == 0) { + pDevice->playback.intermediaryBufferCap = pDevice->playback.internalPeriodSizeInFrames; + } + } + + intermediaryBufferSizeInBytes = pDevice->playback.intermediaryBufferCap * ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels); + + pDevice->playback.pIntermediaryBuffer = ma_malloc((size_t)intermediaryBufferSizeInBytes, &pContext->allocationCallbacks); + if (pDevice->playback.pIntermediaryBuffer == NULL) { + ma_device_uninit(pDevice); + return MA_OUT_OF_MEMORY; + } + + /* Silence the buffer for safety. */ + ma_silence_pcm_frames(pDevice->playback.pIntermediaryBuffer, pDevice->playback.intermediaryBufferCap, pDevice->playback.format, pDevice->playback.channels); + pDevice->playback.intermediaryBufferLen = 0; + } + } else { + /* Not using a fixed sized data callback so no need for an intermediary buffer. */ + } + + + /* Some backends don't require the worker thread. */ + if (!ma_context_is_backend_asynchronous(pContext)) { + /* The worker thread. */ + result = ma_thread_create(&pDevice->thread, pContext->threadPriority, pContext->threadStackSize, ma_worker_thread, pDevice, &pContext->allocationCallbacks); + if (result != MA_SUCCESS) { + ma_device_uninit(pDevice); + return result; + } + + /* Wait for the worker thread to put the device into it's stopped state for real. */ + ma_event_wait(&pDevice->stopEvent); + MA_ASSERT(ma_device_get_state(pDevice) == ma_device_state_stopped); + } else { + /* + If the backend is asynchronous and the device is duplex, we'll need an intermediary ring buffer. Note that this needs to be done + after ma_device__post_init_setup(). + */ + if (ma_context_is_backend_asynchronous(pContext)) { + if (pConfig->deviceType == ma_device_type_duplex) { + result = ma_duplex_rb_init(pDevice->capture.format, pDevice->capture.channels, pDevice->sampleRate, pDevice->capture.internalSampleRate, pDevice->capture.internalPeriodSizeInFrames, &pDevice->pContext->allocationCallbacks, &pDevice->duplexRB); + if (result != MA_SUCCESS) { + ma_device_uninit(pDevice); + return result; + } + } + } + + ma_device__set_state(pDevice, ma_device_state_stopped); + } + + /* Log device information. */ + { + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[%s]\n", ma_get_backend_name(pDevice->pContext->backend)); + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) { + char name[MA_MAX_DEVICE_NAME_LENGTH + 1]; + ma_device_get_name(pDevice, (pDevice->type == ma_device_type_loopback) ? ma_device_type_playback : ma_device_type_capture, name, sizeof(name), NULL); + + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " %s (%s)\n", name, "Capture"); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Format: %s -> %s\n", ma_get_format_name(pDevice->capture.internalFormat), ma_get_format_name(pDevice->capture.format)); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channels: %d -> %d\n", pDevice->capture.internalChannels, pDevice->capture.channels); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Sample Rate: %d -> %d\n", pDevice->capture.internalSampleRate, pDevice->sampleRate); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Buffer Size: %d*%d (%d)\n", pDevice->capture.internalPeriodSizeInFrames, pDevice->capture.internalPeriods, (pDevice->capture.internalPeriodSizeInFrames * pDevice->capture.internalPeriods)); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Conversion:\n"); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Pre Format Conversion: %s\n", pDevice->capture.converter.hasPreFormatConversion ? "YES" : "NO"); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Post Format Conversion: %s\n", pDevice->capture.converter.hasPostFormatConversion ? "YES" : "NO"); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Routing: %s\n", pDevice->capture.converter.hasChannelConverter ? "YES" : "NO"); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Resampling: %s\n", pDevice->capture.converter.hasResampler ? "YES" : "NO"); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Passthrough: %s\n", pDevice->capture.converter.isPassthrough ? "YES" : "NO"); + { + char channelMapStr[1024]; + ma_channel_map_to_string(pDevice->capture.internalChannelMap, pDevice->capture.internalChannels, channelMapStr, sizeof(channelMapStr)); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Map In: {%s}\n", channelMapStr); + + ma_channel_map_to_string(pDevice->capture.channelMap, pDevice->capture.channels, channelMapStr, sizeof(channelMapStr)); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Map Out: {%s}\n", channelMapStr); + } + } + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + char name[MA_MAX_DEVICE_NAME_LENGTH + 1]; + ma_device_get_name(pDevice, ma_device_type_playback, name, sizeof(name), NULL); + + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " %s (%s)\n", name, "Playback"); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Format: %s -> %s\n", ma_get_format_name(pDevice->playback.format), ma_get_format_name(pDevice->playback.internalFormat)); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channels: %d -> %d\n", pDevice->playback.channels, pDevice->playback.internalChannels); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Sample Rate: %d -> %d\n", pDevice->sampleRate, pDevice->playback.internalSampleRate); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Buffer Size: %d*%d (%d)\n", pDevice->playback.internalPeriodSizeInFrames, pDevice->playback.internalPeriods, (pDevice->playback.internalPeriodSizeInFrames * pDevice->playback.internalPeriods)); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Conversion:\n"); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Pre Format Conversion: %s\n", pDevice->playback.converter.hasPreFormatConversion ? "YES" : "NO"); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Post Format Conversion: %s\n", pDevice->playback.converter.hasPostFormatConversion ? "YES" : "NO"); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Routing: %s\n", pDevice->playback.converter.hasChannelConverter ? "YES" : "NO"); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Resampling: %s\n", pDevice->playback.converter.hasResampler ? "YES" : "NO"); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Passthrough: %s\n", pDevice->playback.converter.isPassthrough ? "YES" : "NO"); + { + char channelMapStr[1024]; + ma_channel_map_to_string(pDevice->playback.channelMap, pDevice->playback.channels, channelMapStr, sizeof(channelMapStr)); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Map In: {%s}\n", channelMapStr); + + ma_channel_map_to_string(pDevice->playback.internalChannelMap, pDevice->playback.internalChannels, channelMapStr, sizeof(channelMapStr)); + ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Map Out: {%s}\n", channelMapStr); + } + } + } + + MA_ASSERT(ma_device_get_state(pDevice) == ma_device_state_stopped); + return MA_SUCCESS; +} + +MA_API 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; + ma_allocation_callbacks allocationCallbacks; + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pContextConfig != NULL) { + result = ma_allocation_callbacks_init_copy(&allocationCallbacks, &pContextConfig->allocationCallbacks); + if (result != MA_SUCCESS) { + return result; + } + } else { + allocationCallbacks = ma_allocation_callbacks_init_default(); + } + + pContext = (ma_context*)ma_malloc(sizeof(*pContext), &allocationCallbacks); + if (pContext == NULL) { + return MA_OUT_OF_MEMORY; + } + + for (iBackend = 0; iBackend <= ma_backend_null; ++iBackend) { + defaultBackends[iBackend] = (ma_backend)iBackend; + } + + pBackendsToIterate = (ma_backend*)backends; + backendsToIterateCount = backendCount; + if (pBackendsToIterate == NULL) { + pBackendsToIterate = (ma_backend*)defaultBackends; + backendsToIterateCount = ma_countof(defaultBackends); + } + + result = MA_NO_BACKEND; + + for (iBackend = 0; iBackend < backendsToIterateCount; ++iBackend) { + /* + This is a hack for iOS. If the context config is null, there's a good chance the + `ma_device_init(NULL, &deviceConfig, pDevice);` pattern is being used. In this + case, set the session category based on the device type. + */ + #if defined(MA_APPLE_MOBILE) + ma_context_config contextConfig; + + if (pContextConfig == NULL) { + contextConfig = ma_context_config_init(); + switch (pConfig->deviceType) { + case ma_device_type_duplex: { + contextConfig.coreaudio.sessionCategory = ma_ios_session_category_play_and_record; + } break; + case ma_device_type_capture: { + contextConfig.coreaudio.sessionCategory = ma_ios_session_category_record; + } break; + case ma_device_type_playback: + default: { + contextConfig.coreaudio.sessionCategory = ma_ios_session_category_playback; + } break; + } + + pContextConfig = &contextConfig; + } + #endif + + 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, &allocationCallbacks); + return result; + } + + pDevice->isOwnerOfContext = MA_TRUE; + return result; +} + +MA_API void ma_device_uninit(ma_device* pDevice) +{ + if (!ma_device__is_initialized(pDevice)) { + return; + } + + /* + It's possible for the miniaudio side of the device and the backend to not be in sync due to + system-level situations such as the computer being put into sleep mode and the backend not + notifying miniaudio of the fact the device has stopped. It's possible for this to result in a + deadlock due to miniaudio thinking the device is in a running state, when in fact it's not + running at all. For this reason I am no longer explicitly stopping the device. I don't think + this should affect anyone in practice since uninitializing the backend will naturally stop the + device anyway. + */ + #if 0 + { + /* 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); + } + } + #endif + + /* Putting the device into an uninitialized state will make the worker thread return. */ + ma_device__set_state(pDevice, ma_device_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); + } + + if (pDevice->pContext->callbacks.onDeviceUninit != NULL) { + pDevice->pContext->callbacks.onDeviceUninit(pDevice); + } + + + ma_event_uninit(&pDevice->stopEvent); + ma_event_uninit(&pDevice->startEvent); + ma_event_uninit(&pDevice->wakeupEvent); + ma_mutex_uninit(&pDevice->startStopLock); + + if (ma_context_is_backend_asynchronous(pDevice->pContext)) { + if (pDevice->type == ma_device_type_duplex) { + ma_duplex_rb_uninit(&pDevice->duplexRB); + } + } + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) { + ma_data_converter_uninit(&pDevice->capture.converter, &pDevice->pContext->allocationCallbacks); + } + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + ma_data_converter_uninit(&pDevice->playback.converter, &pDevice->pContext->allocationCallbacks); + } + + if (pDevice->playback.pInputCache != NULL) { + ma_free(pDevice->playback.pInputCache, &pDevice->pContext->allocationCallbacks); + } + + if (pDevice->capture.pIntermediaryBuffer != NULL) { + ma_free(pDevice->capture.pIntermediaryBuffer, &pDevice->pContext->allocationCallbacks); + } + if (pDevice->playback.pIntermediaryBuffer != NULL) { + ma_free(pDevice->playback.pIntermediaryBuffer, &pDevice->pContext->allocationCallbacks); + } + + if (pDevice->isOwnerOfContext) { + ma_allocation_callbacks allocationCallbacks = pDevice->pContext->allocationCallbacks; + + ma_context_uninit(pDevice->pContext); + ma_free(pDevice->pContext, &allocationCallbacks); + } + + MA_ZERO_OBJECT(pDevice); +} + +MA_API ma_context* ma_device_get_context(ma_device* pDevice) +{ + if (pDevice == NULL) { + return NULL; + } + + return pDevice->pContext; +} + +MA_API ma_log* ma_device_get_log(ma_device* pDevice) +{ + return ma_context_get_log(ma_device_get_context(pDevice)); +} + +MA_API ma_result ma_device_get_info(ma_device* pDevice, ma_device_type type, ma_device_info* pDeviceInfo) +{ + if (pDeviceInfo == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pDeviceInfo); + + if (pDevice == NULL) { + return MA_INVALID_ARGS; + } + + /* If the onDeviceGetInfo() callback is set, use that. Otherwise we'll fall back to ma_context_get_device_info(). */ + if (pDevice->pContext->callbacks.onDeviceGetInfo != NULL) { + return pDevice->pContext->callbacks.onDeviceGetInfo(pDevice, type, pDeviceInfo); + } + + /* Getting here means onDeviceGetInfo is not implemented so we need to fall back to an alternative. */ + if (type == ma_device_type_playback) { + return ma_context_get_device_info(pDevice->pContext, type, pDevice->playback.pID, pDeviceInfo); + } else { + return ma_context_get_device_info(pDevice->pContext, type, pDevice->capture.pID, pDeviceInfo); + } +} + +MA_API ma_result ma_device_get_name(ma_device* pDevice, ma_device_type type, char* pName, size_t nameCap, size_t* pLengthNotIncludingNullTerminator) +{ + ma_result result; + ma_device_info deviceInfo; + + if (pLengthNotIncludingNullTerminator != NULL) { + *pLengthNotIncludingNullTerminator = 0; + } + + if (pName != NULL && nameCap > 0) { + pName[0] = '\0'; + } + + result = ma_device_get_info(pDevice, type, &deviceInfo); + if (result != MA_SUCCESS) { + return result; + } + + if (pName != NULL) { + ma_strncpy_s(pName, nameCap, deviceInfo.name, (size_t)-1); + + /* + For safety, make sure the length is based on the truncated output string rather than the + source. Otherwise the caller might assume the output buffer contains more content than it + actually does. + */ + if (pLengthNotIncludingNullTerminator != NULL) { + *pLengthNotIncludingNullTerminator = strlen(pName); + } + } else { + /* Name not specified. Just report the length of the source string. */ + if (pLengthNotIncludingNullTerminator != NULL) { + *pLengthNotIncludingNullTerminator = strlen(deviceInfo.name); + } + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_device_start(ma_device* pDevice) +{ + ma_result result; + + if (pDevice == NULL) { + return MA_INVALID_ARGS; + } + + if (ma_device_get_state(pDevice) == ma_device_state_uninitialized) { + return MA_INVALID_OPERATION; /* Not initialized. */ + } + + if (ma_device_get_state(pDevice) == ma_device_state_started) { + return MA_SUCCESS; /* Already started. */ + } + + ma_mutex_lock(&pDevice->startStopLock); + { + /* 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_device_state_stopped); + + ma_device__set_state(pDevice, ma_device_state_starting); + + /* Asynchronous backends need to be handled differently. */ + if (ma_context_is_backend_asynchronous(pDevice->pContext)) { + if (pDevice->pContext->callbacks.onDeviceStart != NULL) { + result = pDevice->pContext->callbacks.onDeviceStart(pDevice); + } else { + result = MA_INVALID_OPERATION; + } + + if (result == MA_SUCCESS) { + ma_device__set_state(pDevice, ma_device_state_started); + ma_device__on_notification_started(pDevice); + } + } 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; + } + + /* We changed the state from stopped to started, so if we failed, make sure we put the state back to stopped. */ + if (result != MA_SUCCESS) { + ma_device__set_state(pDevice, ma_device_state_stopped); + } + } + ma_mutex_unlock(&pDevice->startStopLock); + + return result; +} + +MA_API ma_result ma_device_stop(ma_device* pDevice) +{ + ma_result result; + + if (pDevice == NULL) { + return MA_INVALID_ARGS; + } + + if (ma_device_get_state(pDevice) == ma_device_state_uninitialized) { + return MA_INVALID_OPERATION; /* Not initialized. */ + } + + if (ma_device_get_state(pDevice) == ma_device_state_stopped) { + return MA_SUCCESS; /* Already stopped. */ + } + + ma_mutex_lock(&pDevice->startStopLock); + { + /* 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_device_state_started); + + ma_device__set_state(pDevice, ma_device_state_stopping); + + /* Asynchronous backends need to be handled differently. */ + if (ma_context_is_backend_asynchronous(pDevice->pContext)) { + /* Asynchronous backends must have a stop operation. */ + if (pDevice->pContext->callbacks.onDeviceStop != NULL) { + result = pDevice->pContext->callbacks.onDeviceStop(pDevice); + } else { + result = MA_INVALID_OPERATION; + } + + ma_device__set_state(pDevice, ma_device_state_stopped); + } else { + /* + Synchronous backends. The stop callback is always called from the worker thread. Do not call the stop callback here. If + the backend is implementing it's own audio thread loop we'll need to wake it up if required. Note that we need to make + sure the state of the device is *not* playing right now, which it shouldn't be since we set it above. This is super + important though, so I'm asserting it here as well for extra safety in case we accidentally change something later. + */ + MA_ASSERT(ma_device_get_state(pDevice) != ma_device_state_started); + + if (pDevice->pContext->callbacks.onDeviceDataLoopWakeup != NULL) { + pDevice->pContext->callbacks.onDeviceDataLoopWakeup(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 ma_device__set_state() here. + */ + ma_event_wait(&pDevice->stopEvent); + result = MA_SUCCESS; + } + + /* + This is a safety measure to ensure the internal buffer has been cleared so any leftover + does not get played the next time the device starts. Ideally this should be drained by + the backend first. + */ + pDevice->playback.intermediaryBufferLen = 0; + pDevice->playback.inputCacheConsumed = 0; + pDevice->playback.inputCacheRemaining = 0; + } + ma_mutex_unlock(&pDevice->startStopLock); + + return result; +} + +MA_API ma_bool32 ma_device_is_started(const ma_device* pDevice) +{ + return ma_device_get_state(pDevice) == ma_device_state_started; +} + +MA_API ma_device_state ma_device_get_state(const ma_device* pDevice) +{ + if (pDevice == NULL) { + return ma_device_state_uninitialized; + } + + return ma_atomic_device_state_get((ma_atomic_device_state*)&pDevice->state); /* Naughty cast to get rid of a const warning. */ +} + +MA_API ma_result ma_device_set_master_volume(ma_device* pDevice, float volume) +{ + if (pDevice == NULL) { + return MA_INVALID_ARGS; + } + + if (volume < 0.0f) { + return MA_INVALID_ARGS; + } + + ma_atomic_float_set(&pDevice->masterVolumeFactor, volume); + + return MA_SUCCESS; +} + +MA_API ma_result ma_device_get_master_volume(ma_device* pDevice, float* pVolume) +{ + if (pVolume == NULL) { + return MA_INVALID_ARGS; + } + + if (pDevice == NULL) { + *pVolume = 0; + return MA_INVALID_ARGS; + } + + *pVolume = ma_atomic_float_get(&pDevice->masterVolumeFactor); + + return MA_SUCCESS; +} + +MA_API ma_result ma_device_set_master_volume_db(ma_device* pDevice, float gainDB) +{ + if (gainDB > 0) { + return MA_INVALID_ARGS; + } + + return ma_device_set_master_volume(pDevice, ma_volume_db_to_linear(gainDB)); +} + +MA_API ma_result ma_device_get_master_volume_db(ma_device* pDevice, float* pGainDB) +{ + float factor; + ma_result result; + + if (pGainDB == NULL) { + return MA_INVALID_ARGS; + } + + result = ma_device_get_master_volume(pDevice, &factor); + if (result != MA_SUCCESS) { + *pGainDB = 0; + return result; + } + + *pGainDB = ma_volume_linear_to_db(factor); + + return MA_SUCCESS; +} + + +MA_API ma_result ma_device_handle_backend_data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount) +{ + if (pDevice == NULL) { + return MA_INVALID_ARGS; + } + + if (pOutput == NULL && pInput == NULL) { + return MA_INVALID_ARGS; + } + + if (pDevice->type == ma_device_type_duplex) { + if (pInput != NULL) { + ma_device__handle_duplex_callback_capture(pDevice, frameCount, pInput, &pDevice->duplexRB.rb); + } + + if (pOutput != NULL) { + ma_device__handle_duplex_callback_playback(pDevice, frameCount, pOutput, &pDevice->duplexRB.rb); + } + } else { + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_loopback) { + if (pInput == NULL) { + return MA_INVALID_ARGS; + } + + ma_device__send_frames_to_client(pDevice, frameCount, pInput); + } + + if (pDevice->type == ma_device_type_playback) { + if (pOutput == NULL) { + return MA_INVALID_ARGS; + } + + ma_device__read_frames_from_client(pDevice, frameCount, pOutput); + } + } + + return MA_SUCCESS; +} + +MA_API ma_uint32 ma_calculate_buffer_size_in_frames_from_descriptor(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile) +{ + if (pDescriptor == NULL) { + return 0; + } + + /* + We must have a non-0 native sample rate, but some backends don't allow retrieval of this at the + time when the size of the buffer needs to be determined. In this case we need to just take a best + guess and move on. We'll try using the sample rate in pDescriptor first. If that's not set we'll + just fall back to MA_DEFAULT_SAMPLE_RATE. + */ + if (nativeSampleRate == 0) { + nativeSampleRate = pDescriptor->sampleRate; + } + if (nativeSampleRate == 0) { + nativeSampleRate = MA_DEFAULT_SAMPLE_RATE; + } + + MA_ASSERT(nativeSampleRate != 0); + + if (pDescriptor->periodSizeInFrames == 0) { + if (pDescriptor->periodSizeInMilliseconds == 0) { + if (performanceProfile == ma_performance_profile_low_latency) { + return ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY, nativeSampleRate); + } else { + return ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE, nativeSampleRate); + } + } else { + return ma_calculate_buffer_size_in_frames_from_milliseconds(pDescriptor->periodSizeInMilliseconds, nativeSampleRate); + } + } else { + return pDescriptor->periodSizeInFrames; + } +} +#endif /* MA_NO_DEVICE_IO */ + + +MA_API ma_uint32 ma_calculate_buffer_size_in_milliseconds_from_frames(ma_uint32 bufferSizeInFrames, ma_uint32 sampleRate) +{ + /* Prevent a division by zero. */ + if (sampleRate == 0) { + return 0; + } + + return bufferSizeInFrames*1000 / sampleRate; +} + +MA_API ma_uint32 ma_calculate_buffer_size_in_frames_from_milliseconds(ma_uint32 bufferSizeInMilliseconds, ma_uint32 sampleRate) +{ + /* Prevent a division by zero. */ + if (sampleRate == 0) { + return 0; + } + + return bufferSizeInMilliseconds*sampleRate / 1000; +} + +MA_API void ma_copy_pcm_frames(void* dst, const void* src, ma_uint64 frameCount, ma_format format, ma_uint32 channels) +{ + if (dst == src) { + return; /* No-op. */ + } + + ma_copy_memory_64(dst, src, frameCount * ma_get_bytes_per_frame(format, channels)); +} + +MA_API void ma_silence_pcm_frames(void* p, ma_uint64 frameCount, ma_format format, ma_uint32 channels) +{ + if (format == ma_format_u8) { + ma_uint64 sampleCount = frameCount * channels; + ma_uint64 iSample; + for (iSample = 0; iSample < sampleCount; iSample += 1) { + ((ma_uint8*)p)[iSample] = 128; + } + } else { + ma_zero_memory_64(p, frameCount * ma_get_bytes_per_frame(format, channels)); + } +} + +MA_API void* ma_offset_pcm_frames_ptr(void* p, ma_uint64 offsetInFrames, ma_format format, ma_uint32 channels) +{ + return ma_offset_ptr(p, offsetInFrames * ma_get_bytes_per_frame(format, channels)); +} + +MA_API const void* ma_offset_pcm_frames_const_ptr(const void* p, ma_uint64 offsetInFrames, ma_format format, ma_uint32 channels) +{ + return ma_offset_ptr(p, offsetInFrames * ma_get_bytes_per_frame(format, channels)); +} + + +MA_API void ma_clip_samples_u8(ma_uint8* pDst, const ma_int16* pSrc, ma_uint64 count) +{ + ma_uint64 iSample; + + MA_ASSERT(pDst != NULL); + MA_ASSERT(pSrc != NULL); + + for (iSample = 0; iSample < count; iSample += 1) { + pDst[iSample] = ma_clip_u8(pSrc[iSample]); + } +} + +MA_API void ma_clip_samples_s16(ma_int16* pDst, const ma_int32* pSrc, ma_uint64 count) +{ + ma_uint64 iSample; + + MA_ASSERT(pDst != NULL); + MA_ASSERT(pSrc != NULL); + + for (iSample = 0; iSample < count; iSample += 1) { + pDst[iSample] = ma_clip_s16(pSrc[iSample]); + } +} + +MA_API void ma_clip_samples_s24(ma_uint8* pDst, const ma_int64* pSrc, ma_uint64 count) +{ + ma_uint64 iSample; + + MA_ASSERT(pDst != NULL); + MA_ASSERT(pSrc != NULL); + + for (iSample = 0; iSample < count; iSample += 1) { + ma_int64 s = ma_clip_s24(pSrc[iSample]); + pDst[iSample*3 + 0] = (ma_uint8)((s & 0x000000FF) >> 0); + pDst[iSample*3 + 1] = (ma_uint8)((s & 0x0000FF00) >> 8); + pDst[iSample*3 + 2] = (ma_uint8)((s & 0x00FF0000) >> 16); + } +} + +MA_API void ma_clip_samples_s32(ma_int32* pDst, const ma_int64* pSrc, ma_uint64 count) +{ + ma_uint64 iSample; + + MA_ASSERT(pDst != NULL); + MA_ASSERT(pSrc != NULL); + + for (iSample = 0; iSample < count; iSample += 1) { + pDst[iSample] = ma_clip_s32(pSrc[iSample]); + } +} + +MA_API void ma_clip_samples_f32(float* pDst, const float* pSrc, ma_uint64 count) +{ + ma_uint64 iSample; + + MA_ASSERT(pDst != NULL); + MA_ASSERT(pSrc != NULL); + + for (iSample = 0; iSample < count; iSample += 1) { + pDst[iSample] = ma_clip_f32(pSrc[iSample]); + } +} + +MA_API void ma_clip_pcm_frames(void* pDst, const void* pSrc, ma_uint64 frameCount, ma_format format, ma_uint32 channels) +{ + ma_uint64 sampleCount; + + MA_ASSERT(pDst != NULL); + MA_ASSERT(pSrc != NULL); + + sampleCount = frameCount * channels; + + switch (format) { + case ma_format_u8: ma_clip_samples_u8( (ma_uint8*)pDst, (const ma_int16*)pSrc, sampleCount); break; + case ma_format_s16: ma_clip_samples_s16((ma_int16*)pDst, (const ma_int32*)pSrc, sampleCount); break; + case ma_format_s24: ma_clip_samples_s24((ma_uint8*)pDst, (const ma_int64*)pSrc, sampleCount); break; + case ma_format_s32: ma_clip_samples_s32((ma_int32*)pDst, (const ma_int64*)pSrc, sampleCount); break; + case ma_format_f32: ma_clip_samples_f32(( float*)pDst, (const float*)pSrc, sampleCount); break; + + /* Do nothing if we don't know the format. We're including these here to silence a compiler warning about enums not being handled by the switch. */ + case ma_format_unknown: + case ma_format_count: + break; + } +} + + +MA_API void ma_copy_and_apply_volume_factor_u8(ma_uint8* pSamplesOut, const ma_uint8* pSamplesIn, ma_uint64 sampleCount, float factor) +{ + ma_uint64 iSample; + + if (pSamplesOut == NULL || pSamplesIn == NULL) { + return; + } + + for (iSample = 0; iSample < sampleCount; iSample += 1) { + pSamplesOut[iSample] = (ma_uint8)(pSamplesIn[iSample] * factor); + } +} + +MA_API void ma_copy_and_apply_volume_factor_s16(ma_int16* pSamplesOut, const ma_int16* pSamplesIn, ma_uint64 sampleCount, float factor) +{ + ma_uint64 iSample; + + if (pSamplesOut == NULL || pSamplesIn == NULL) { + return; + } + + for (iSample = 0; iSample < sampleCount; iSample += 1) { + pSamplesOut[iSample] = (ma_int16)(pSamplesIn[iSample] * factor); + } +} + +MA_API void ma_copy_and_apply_volume_factor_s24(void* pSamplesOut, const void* pSamplesIn, ma_uint64 sampleCount, float factor) +{ + ma_uint64 iSample; + ma_uint8* pSamplesOut8; + ma_uint8* pSamplesIn8; + + if (pSamplesOut == NULL || pSamplesIn == NULL) { + return; + } + + pSamplesOut8 = (ma_uint8*)pSamplesOut; + pSamplesIn8 = (ma_uint8*)pSamplesIn; + + for (iSample = 0; iSample < sampleCount; iSample += 1) { + ma_int32 sampleS32; + + sampleS32 = (ma_int32)(((ma_uint32)(pSamplesIn8[iSample*3+0]) << 8) | ((ma_uint32)(pSamplesIn8[iSample*3+1]) << 16) | ((ma_uint32)(pSamplesIn8[iSample*3+2])) << 24); + sampleS32 = (ma_int32)(sampleS32 * factor); + + pSamplesOut8[iSample*3+0] = (ma_uint8)(((ma_uint32)sampleS32 & 0x0000FF00) >> 8); + pSamplesOut8[iSample*3+1] = (ma_uint8)(((ma_uint32)sampleS32 & 0x00FF0000) >> 16); + pSamplesOut8[iSample*3+2] = (ma_uint8)(((ma_uint32)sampleS32 & 0xFF000000) >> 24); + } +} + +MA_API void ma_copy_and_apply_volume_factor_s32(ma_int32* pSamplesOut, const ma_int32* pSamplesIn, ma_uint64 sampleCount, float factor) +{ + ma_uint64 iSample; + + if (pSamplesOut == NULL || pSamplesIn == NULL) { + return; + } + + for (iSample = 0; iSample < sampleCount; iSample += 1) { + pSamplesOut[iSample] = (ma_int32)(pSamplesIn[iSample] * factor); + } +} + +MA_API void ma_copy_and_apply_volume_factor_f32(float* pSamplesOut, const float* pSamplesIn, ma_uint64 sampleCount, float factor) +{ + ma_uint64 iSample; + + if (pSamplesOut == NULL || pSamplesIn == NULL) { + return; + } + + if (factor == 1) { + if (pSamplesOut == pSamplesIn) { + /* In place. No-op. */ + } else { + /* Just a copy. */ + for (iSample = 0; iSample < sampleCount; iSample += 1) { + pSamplesOut[iSample] = pSamplesIn[iSample]; + } + } + } else { + for (iSample = 0; iSample < sampleCount; iSample += 1) { + pSamplesOut[iSample] = pSamplesIn[iSample] * factor; + } + } +} + +MA_API void ma_apply_volume_factor_u8(ma_uint8* pSamples, ma_uint64 sampleCount, float factor) +{ + ma_copy_and_apply_volume_factor_u8(pSamples, pSamples, sampleCount, factor); +} + +MA_API void ma_apply_volume_factor_s16(ma_int16* pSamples, ma_uint64 sampleCount, float factor) +{ + ma_copy_and_apply_volume_factor_s16(pSamples, pSamples, sampleCount, factor); +} + +MA_API void ma_apply_volume_factor_s24(void* pSamples, ma_uint64 sampleCount, float factor) +{ + ma_copy_and_apply_volume_factor_s24(pSamples, pSamples, sampleCount, factor); +} + +MA_API void ma_apply_volume_factor_s32(ma_int32* pSamples, ma_uint64 sampleCount, float factor) +{ + ma_copy_and_apply_volume_factor_s32(pSamples, pSamples, sampleCount, factor); +} + +MA_API void ma_apply_volume_factor_f32(float* pSamples, ma_uint64 sampleCount, float factor) +{ + ma_copy_and_apply_volume_factor_f32(pSamples, pSamples, sampleCount, factor); +} + +MA_API void ma_copy_and_apply_volume_factor_pcm_frames_u8(ma_uint8* pFramesOut, const ma_uint8* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor) +{ + ma_copy_and_apply_volume_factor_u8(pFramesOut, pFramesIn, frameCount*channels, factor); +} + +MA_API void ma_copy_and_apply_volume_factor_pcm_frames_s16(ma_int16* pFramesOut, const ma_int16* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor) +{ + ma_copy_and_apply_volume_factor_s16(pFramesOut, pFramesIn, frameCount*channels, factor); +} + +MA_API void ma_copy_and_apply_volume_factor_pcm_frames_s24(void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor) +{ + ma_copy_and_apply_volume_factor_s24(pFramesOut, pFramesIn, frameCount*channels, factor); +} + +MA_API void ma_copy_and_apply_volume_factor_pcm_frames_s32(ma_int32* pFramesOut, const ma_int32* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor) +{ + ma_copy_and_apply_volume_factor_s32(pFramesOut, pFramesIn, frameCount*channels, factor); +} + +MA_API void ma_copy_and_apply_volume_factor_pcm_frames_f32(float* pFramesOut, const float* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor) +{ + ma_copy_and_apply_volume_factor_f32(pFramesOut, pFramesIn, frameCount*channels, factor); +} + +MA_API void ma_copy_and_apply_volume_factor_pcm_frames(void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount, ma_format format, ma_uint32 channels, float factor) +{ + switch (format) + { + case ma_format_u8: ma_copy_and_apply_volume_factor_pcm_frames_u8 ((ma_uint8*)pFramesOut, (const ma_uint8*)pFramesIn, frameCount, channels, factor); return; + case ma_format_s16: ma_copy_and_apply_volume_factor_pcm_frames_s16((ma_int16*)pFramesOut, (const ma_int16*)pFramesIn, frameCount, channels, factor); return; + case ma_format_s24: ma_copy_and_apply_volume_factor_pcm_frames_s24( pFramesOut, pFramesIn, frameCount, channels, factor); return; + case ma_format_s32: ma_copy_and_apply_volume_factor_pcm_frames_s32((ma_int32*)pFramesOut, (const ma_int32*)pFramesIn, frameCount, channels, factor); return; + case ma_format_f32: ma_copy_and_apply_volume_factor_pcm_frames_f32( (float*)pFramesOut, (const float*)pFramesIn, frameCount, channels, factor); return; + default: return; /* Do nothing. */ + } +} + +MA_API void ma_apply_volume_factor_pcm_frames_u8(ma_uint8* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor) +{ + ma_copy_and_apply_volume_factor_pcm_frames_u8(pFrames, pFrames, frameCount, channels, factor); +} + +MA_API void ma_apply_volume_factor_pcm_frames_s16(ma_int16* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor) +{ + ma_copy_and_apply_volume_factor_pcm_frames_s16(pFrames, pFrames, frameCount, channels, factor); +} + +MA_API void ma_apply_volume_factor_pcm_frames_s24(void* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor) +{ + ma_copy_and_apply_volume_factor_pcm_frames_s24(pFrames, pFrames, frameCount, channels, factor); +} + +MA_API void ma_apply_volume_factor_pcm_frames_s32(ma_int32* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor) +{ + ma_copy_and_apply_volume_factor_pcm_frames_s32(pFrames, pFrames, frameCount, channels, factor); +} + +MA_API void ma_apply_volume_factor_pcm_frames_f32(float* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor) +{ + ma_copy_and_apply_volume_factor_pcm_frames_f32(pFrames, pFrames, frameCount, channels, factor); +} + +MA_API void ma_apply_volume_factor_pcm_frames(void* pFramesOut, ma_uint64 frameCount, ma_format format, ma_uint32 channels, float factor) +{ + ma_copy_and_apply_volume_factor_pcm_frames(pFramesOut, pFramesOut, frameCount, format, channels, factor); +} + + +MA_API void ma_copy_and_apply_volume_factor_per_channel_f32(float* pFramesOut, const float* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float* pChannelGains) +{ + ma_uint64 iFrame; + + if (channels == 2) { + /* TODO: Do an optimized implementation for stereo and mono. Can do a SIMD optimized implementation as well. */ + } + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; iChannel += 1) { + pFramesOut[iFrame * channels + iChannel] = pFramesIn[iFrame * channels + iChannel] * pChannelGains[iChannel]; + } + } +} + + + +static MA_INLINE ma_int16 ma_apply_volume_unclipped_u8(ma_int16 x, ma_int16 volume) +{ + return (ma_int16)(((ma_int32)x * (ma_int32)volume) >> 8); +} + +static MA_INLINE ma_int32 ma_apply_volume_unclipped_s16(ma_int32 x, ma_int16 volume) +{ + return (ma_int32)((x * volume) >> 8); +} + +static MA_INLINE ma_int64 ma_apply_volume_unclipped_s24(ma_int64 x, ma_int16 volume) +{ + return (ma_int64)((x * volume) >> 8); +} + +static MA_INLINE ma_int64 ma_apply_volume_unclipped_s32(ma_int64 x, ma_int16 volume) +{ + return (ma_int64)((x * volume) >> 8); +} + +static MA_INLINE float ma_apply_volume_unclipped_f32(float x, float volume) +{ + return x * volume; +} + + +MA_API void ma_copy_and_apply_volume_and_clip_samples_u8(ma_uint8* pDst, const ma_int16* pSrc, ma_uint64 count, float volume) +{ + ma_uint64 iSample; + ma_int16 volumeFixed; + + MA_ASSERT(pDst != NULL); + MA_ASSERT(pSrc != NULL); + + volumeFixed = ma_float_to_fixed_16(volume); + + for (iSample = 0; iSample < count; iSample += 1) { + pDst[iSample] = ma_clip_u8(ma_apply_volume_unclipped_u8(pSrc[iSample], volumeFixed)); + } +} + +MA_API void ma_copy_and_apply_volume_and_clip_samples_s16(ma_int16* pDst, const ma_int32* pSrc, ma_uint64 count, float volume) +{ + ma_uint64 iSample; + ma_int16 volumeFixed; + + MA_ASSERT(pDst != NULL); + MA_ASSERT(pSrc != NULL); + + volumeFixed = ma_float_to_fixed_16(volume); + + for (iSample = 0; iSample < count; iSample += 1) { + pDst[iSample] = ma_clip_s16(ma_apply_volume_unclipped_s16(pSrc[iSample], volumeFixed)); + } +} + +MA_API void ma_copy_and_apply_volume_and_clip_samples_s24(ma_uint8* pDst, const ma_int64* pSrc, ma_uint64 count, float volume) +{ + ma_uint64 iSample; + ma_int16 volumeFixed; + + MA_ASSERT(pDst != NULL); + MA_ASSERT(pSrc != NULL); + + volumeFixed = ma_float_to_fixed_16(volume); + + for (iSample = 0; iSample < count; iSample += 1) { + ma_int64 s = ma_clip_s24(ma_apply_volume_unclipped_s24(pSrc[iSample], volumeFixed)); + pDst[iSample*3 + 0] = (ma_uint8)((s & 0x000000FF) >> 0); + pDst[iSample*3 + 1] = (ma_uint8)((s & 0x0000FF00) >> 8); + pDst[iSample*3 + 2] = (ma_uint8)((s & 0x00FF0000) >> 16); + } +} + +MA_API void ma_copy_and_apply_volume_and_clip_samples_s32(ma_int32* pDst, const ma_int64* pSrc, ma_uint64 count, float volume) +{ + ma_uint64 iSample; + ma_int16 volumeFixed; + + MA_ASSERT(pDst != NULL); + MA_ASSERT(pSrc != NULL); + + volumeFixed = ma_float_to_fixed_16(volume); + + for (iSample = 0; iSample < count; iSample += 1) { + pDst[iSample] = ma_clip_s32(ma_apply_volume_unclipped_s32(pSrc[iSample], volumeFixed)); + } +} + +MA_API void ma_copy_and_apply_volume_and_clip_samples_f32(float* pDst, const float* pSrc, ma_uint64 count, float volume) +{ + ma_uint64 iSample; + + MA_ASSERT(pDst != NULL); + MA_ASSERT(pSrc != NULL); + + /* For the f32 case we need to make sure this supports in-place processing where the input and output buffers are the same. */ + + for (iSample = 0; iSample < count; iSample += 1) { + pDst[iSample] = ma_clip_f32(ma_apply_volume_unclipped_f32(pSrc[iSample], volume)); + } +} + +MA_API void ma_copy_and_apply_volume_and_clip_pcm_frames(void* pDst, const void* pSrc, ma_uint64 frameCount, ma_format format, ma_uint32 channels, float volume) +{ + MA_ASSERT(pDst != NULL); + MA_ASSERT(pSrc != NULL); + + if (volume == 1) { + ma_clip_pcm_frames(pDst, pSrc, frameCount, format, channels); /* Optimized case for volume = 1. */ + } else if (volume == 0) { + ma_silence_pcm_frames(pDst, frameCount, format, channels); /* Optimized case for volume = 0. */ + } else { + ma_uint64 sampleCount = frameCount * channels; + + switch (format) { + case ma_format_u8: ma_copy_and_apply_volume_and_clip_samples_u8( (ma_uint8*)pDst, (const ma_int16*)pSrc, sampleCount, volume); break; + case ma_format_s16: ma_copy_and_apply_volume_and_clip_samples_s16((ma_int16*)pDst, (const ma_int32*)pSrc, sampleCount, volume); break; + case ma_format_s24: ma_copy_and_apply_volume_and_clip_samples_s24((ma_uint8*)pDst, (const ma_int64*)pSrc, sampleCount, volume); break; + case ma_format_s32: ma_copy_and_apply_volume_and_clip_samples_s32((ma_int32*)pDst, (const ma_int64*)pSrc, sampleCount, volume); break; + case ma_format_f32: ma_copy_and_apply_volume_and_clip_samples_f32(( float*)pDst, (const float*)pSrc, sampleCount, volume); break; + + /* Do nothing if we don't know the format. We're including these here to silence a compiler warning about enums not being handled by the switch. */ + case ma_format_unknown: + case ma_format_count: + break; + } + } +} + + + +MA_API float ma_volume_linear_to_db(float factor) +{ + return 20*ma_log10f(factor); +} + +MA_API float ma_volume_db_to_linear(float gain) +{ + return ma_powf(10, gain/20.0f); +} + + +MA_API ma_result ma_mix_pcm_frames_f32(float* pDst, const float* pSrc, ma_uint64 frameCount, ma_uint32 channels, float volume) +{ + ma_uint64 iSample; + ma_uint64 sampleCount; + + if (pDst == NULL || pSrc == NULL || channels == 0) { + return MA_INVALID_ARGS; + } + + if (volume == 0) { + return MA_SUCCESS; /* No changes if the volume is 0. */ + } + + sampleCount = frameCount * channels; + + if (volume == 1) { + for (iSample = 0; iSample < sampleCount; iSample += 1) { + pDst[iSample] += pSrc[iSample]; + } + } else { + for (iSample = 0; iSample < sampleCount; iSample += 1) { + pDst[iSample] += ma_apply_volume_unclipped_f32(pSrc[iSample], volume); + } + } + + return MA_SUCCESS; +} + + + +/************************************************************************************************************************************************************** + +Format Conversion + +**************************************************************************************************************************************************************/ + +static MA_INLINE ma_int16 ma_pcm_sample_f32_to_s16(float x) +{ + return (ma_int16)(x * 32767.0f); +} + +static MA_INLINE ma_int16 ma_pcm_sample_u8_to_s16_no_scale(ma_uint8 x) +{ + return (ma_int16)((ma_int16)x - 128); +} + +static MA_INLINE ma_int64 ma_pcm_sample_s24_to_s32_no_scale(const ma_uint8* x) +{ + return (ma_int64)(((ma_uint64)x[0] << 40) | ((ma_uint64)x[1] << 48) | ((ma_uint64)x[2] << 56)) >> 40; /* Make sure the sign bits are maintained. */ +} + +static MA_INLINE void ma_pcm_sample_s32_to_s24_no_scale(ma_int64 x, ma_uint8* s24) +{ + s24[0] = (ma_uint8)((x & 0x000000FF) >> 0); + s24[1] = (ma_uint8)((x & 0x0000FF00) >> 8); + s24[2] = (ma_uint8)((x & 0x00FF0000) >> 16); +} + + +/* u8 */ +MA_API 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)); +} + + +static MA_INLINE void ma_pcm_u8_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_u8 = (const ma_uint8*)src; + + ma_uint64 i; + for (i = 0; i < count; i += 1) { + ma_int16 x = src_u8[i]; + x = (ma_int16)(x - 128); + x = (ma_int16)(x << 8); + dst_s16[i] = x; + } + + (void)ditherMode; +} + +static MA_INLINE 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) +static MA_INLINE 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_NEON) +static MA_INLINE 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 + +MA_API 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 + # if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + ma_pcm_u8_to_s16__sse2(dst, src, count, ditherMode); + } else + #elif defined(MA_SUPPORT_NEON) + if (ma_has_neon()) { + ma_pcm_u8_to_s16__neon(dst, src, count, ditherMode); + } else + #endif + { + ma_pcm_u8_to_s16__optimized(dst, src, count, ditherMode); + } +#endif +} + + +static MA_INLINE void ma_pcm_u8_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode 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 = (ma_int16)(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)ditherMode; +} + +static MA_INLINE 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) +static MA_INLINE 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_NEON) +static MA_INLINE 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 + +MA_API 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 + # if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + ma_pcm_u8_to_s24__sse2(dst, src, count, ditherMode); + } else + #elif defined(MA_SUPPORT_NEON) + if (ma_has_neon()) { + ma_pcm_u8_to_s24__neon(dst, src, count, ditherMode); + } else + #endif + { + ma_pcm_u8_to_s24__optimized(dst, src, count, ditherMode); + } +#endif +} + + +static MA_INLINE void ma_pcm_u8_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode 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)ditherMode; +} + +static MA_INLINE 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) +static MA_INLINE 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_NEON) +static MA_INLINE 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 + +MA_API 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 + # if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + ma_pcm_u8_to_s32__sse2(dst, src, count, ditherMode); + } else + #elif defined(MA_SUPPORT_NEON) + if (ma_has_neon()) { + ma_pcm_u8_to_s32__neon(dst, src, count, ditherMode); + } else + #endif + { + ma_pcm_u8_to_s32__optimized(dst, src, count, ditherMode); + } +#endif +} + + +static MA_INLINE void ma_pcm_u8_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode 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)ditherMode; +} + +static MA_INLINE 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) +static MA_INLINE 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_NEON) +static MA_INLINE 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 + +MA_API 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 + # if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + ma_pcm_u8_to_f32__sse2(dst, src, count, ditherMode); + } else + #elif defined(MA_SUPPORT_NEON) + if (ma_has_neon()) { + ma_pcm_u8_to_f32__neon(dst, src, count, ditherMode); + } else + #endif + { + ma_pcm_u8_to_f32__optimized(dst, src, count, ditherMode); + } +#endif +} + + +#ifdef MA_USE_REFERENCE_CONVERSION_APIS +static MA_INLINE 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]; + } + } +} +#else +static MA_INLINE 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]; + } + } + } +} +#endif + +MA_API 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 +} + + +static MA_INLINE 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]; + } + } +} + +static MA_INLINE 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); +} + +MA_API 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 */ +static MA_INLINE 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 = (ma_int16)(x >> 8); + x = (ma_int16)(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 = (ma_int16)(x >> 8); + x = (ma_int16)(x + 128); + dst_u8[i] = (ma_uint8)x; + } + } +} + +static MA_INLINE 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) +static MA_INLINE 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_NEON) +static MA_INLINE 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 + +MA_API 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 + # if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + ma_pcm_s16_to_u8__sse2(dst, src, count, ditherMode); + } else + #elif defined(MA_SUPPORT_NEON) + if (ma_has_neon()) { + ma_pcm_s16_to_u8__neon(dst, src, count, ditherMode); + } else + #endif + { + ma_pcm_s16_to_u8__optimized(dst, src, count, ditherMode); + } +#endif +} + + +MA_API 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)); +} + + +static MA_INLINE void ma_pcm_s16_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode 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)ditherMode; +} + +static MA_INLINE 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) +static MA_INLINE 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_NEON) +static MA_INLINE 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 + +MA_API 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 + # if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + ma_pcm_s16_to_s24__sse2(dst, src, count, ditherMode); + } else + #elif defined(MA_SUPPORT_NEON) + if (ma_has_neon()) { + ma_pcm_s16_to_s24__neon(dst, src, count, ditherMode); + } else + #endif + { + ma_pcm_s16_to_s24__optimized(dst, src, count, ditherMode); + } +#endif +} + + +static MA_INLINE void ma_pcm_s16_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode 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)ditherMode; +} + +static MA_INLINE 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) +static MA_INLINE 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_NEON) +static MA_INLINE 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 + +MA_API 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 + # if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + ma_pcm_s16_to_s32__sse2(dst, src, count, ditherMode); + } else + #elif defined(MA_SUPPORT_NEON) + if (ma_has_neon()) { + ma_pcm_s16_to_s32__neon(dst, src, count, ditherMode); + } else + #endif + { + ma_pcm_s16_to_s32__optimized(dst, src, count, ditherMode); + } +#endif +} + + +static MA_INLINE void ma_pcm_s16_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode 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..65535 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)ditherMode; +} + +static MA_INLINE 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) +static MA_INLINE 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_NEON) +static MA_INLINE 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 + +MA_API 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 + # if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + ma_pcm_s16_to_f32__sse2(dst, src, count, ditherMode); + } else + #elif defined(MA_SUPPORT_NEON) + if (ma_has_neon()) { + ma_pcm_s16_to_f32__neon(dst, src, count, ditherMode); + } else + #endif + { + ma_pcm_s16_to_f32__optimized(dst, src, count, ditherMode); + } +#endif +} + + +static MA_INLINE 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]; + } + } +} + +static MA_INLINE 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); +} + +MA_API 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 +} + + +static MA_INLINE 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]; + } + } +} + +static MA_INLINE 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); +} + +MA_API 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 */ +static MA_INLINE 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) { + dst_u8[i] = (ma_uint8)((ma_int8)src_s24[i*3 + 2] + 128); + } + } 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; + } + } +} + +static MA_INLINE 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) +static MA_INLINE 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_NEON) +static MA_INLINE 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 + +MA_API 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 + # if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + ma_pcm_s24_to_u8__sse2(dst, src, count, ditherMode); + } else + #elif defined(MA_SUPPORT_NEON) + if (ma_has_neon()) { + ma_pcm_s24_to_u8__neon(dst, src, count, ditherMode); + } else + #endif + { + ma_pcm_s24_to_u8__optimized(dst, src, count, ditherMode); + } +#endif +} + + +static MA_INLINE 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)((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; + } + } +} + +static MA_INLINE 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) +static MA_INLINE 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_NEON) +static MA_INLINE 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 + +MA_API 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 + # if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + ma_pcm_s24_to_s16__sse2(dst, src, count, ditherMode); + } else + #elif defined(MA_SUPPORT_NEON) + if (ma_has_neon()) { + ma_pcm_s24_to_s16__neon(dst, src, count, ditherMode); + } else + #endif + { + ma_pcm_s24_to_s16__optimized(dst, src, count, ditherMode); + } +#endif +} + + +MA_API 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); +} + + +static MA_INLINE void ma_pcm_s24_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode 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)ditherMode; +} + +static MA_INLINE 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) +static MA_INLINE 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_NEON) +static MA_INLINE 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 + +MA_API 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 + # if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + ma_pcm_s24_to_s32__sse2(dst, src, count, ditherMode); + } else + #elif defined(MA_SUPPORT_NEON) + if (ma_has_neon()) { + ma_pcm_s24_to_s32__neon(dst, src, count, ditherMode); + } else + #endif + { + ma_pcm_s24_to_s32__optimized(dst, src, count, ditherMode); + } +#endif +} + + +static MA_INLINE void ma_pcm_s24_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode 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)ditherMode; +} + +static MA_INLINE 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) +static MA_INLINE 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_NEON) +static MA_INLINE 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 + +MA_API 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 + # if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + ma_pcm_s24_to_f32__sse2(dst, src, count, ditherMode); + } else + #elif defined(MA_SUPPORT_NEON) + if (ma_has_neon()) { + ma_pcm_s24_to_f32__neon(dst, src, count, ditherMode); + } else + #endif + { + ma_pcm_s24_to_f32__optimized(dst, src, count, ditherMode); + } +#endif +} + + +static MA_INLINE 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]; + } + } +} + +static MA_INLINE 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); +} + +MA_API 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 +} + + +static MA_INLINE 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]; + } + } +} + +static MA_INLINE 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); +} + +MA_API 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 */ +static MA_INLINE 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; + } + } +} + +static MA_INLINE 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) +static MA_INLINE 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_NEON) +static MA_INLINE 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 + +MA_API 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 + # if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + ma_pcm_s32_to_u8__sse2(dst, src, count, ditherMode); + } else + #elif defined(MA_SUPPORT_NEON) + if (ma_has_neon()) { + ma_pcm_s32_to_u8__neon(dst, src, count, ditherMode); + } else + #endif + { + ma_pcm_s32_to_u8__optimized(dst, src, count, ditherMode); + } +#endif +} + + +static MA_INLINE 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; + } + } +} + +static MA_INLINE 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) +static MA_INLINE 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_NEON) +static MA_INLINE 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 + +MA_API 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 + # if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + ma_pcm_s32_to_s16__sse2(dst, src, count, ditherMode); + } else + #elif defined(MA_SUPPORT_NEON) + if (ma_has_neon()) { + ma_pcm_s32_to_s16__neon(dst, src, count, ditherMode); + } else + #endif + { + ma_pcm_s32_to_s16__optimized(dst, src, count, ditherMode); + } +#endif +} + + +static MA_INLINE void ma_pcm_s32_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + 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)ditherMode; /* No dithering for s32 -> s24. */ +} + +static MA_INLINE 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) +static MA_INLINE 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_NEON) +static MA_INLINE 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 + +MA_API 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 + # if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + ma_pcm_s32_to_s24__sse2(dst, src, count, ditherMode); + } else + #elif defined(MA_SUPPORT_NEON) + if (ma_has_neon()) { + ma_pcm_s32_to_s24__neon(dst, src, count, ditherMode); + } else + #endif + { + ma_pcm_s32_to_s24__optimized(dst, src, count, ditherMode); + } +#endif +} + + +MA_API 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)); +} + + +static MA_INLINE void ma_pcm_s32_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + 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)ditherMode; /* No dithering for s32 -> f32. */ +} + +static MA_INLINE 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) +static MA_INLINE 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_NEON) +static MA_INLINE 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 + +MA_API 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 + # if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + ma_pcm_s32_to_f32__sse2(dst, src, count, ditherMode); + } else + #elif defined(MA_SUPPORT_NEON) + if (ma_has_neon()) { + ma_pcm_s32_to_f32__neon(dst, src, count, ditherMode); + } else + #endif + { + ma_pcm_s32_to_f32__optimized(dst, src, count, ditherMode); + } +#endif +} + + +static MA_INLINE 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]; + } + } +} + +static MA_INLINE 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); +} + +MA_API 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 +} + + +static MA_INLINE 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]; + } + } +} + +static MA_INLINE 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); +} + +MA_API 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 */ +static MA_INLINE 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; + + float ditherMin = 0; + float ditherMax = 0; + if (ditherMode != ma_dither_mode_none) { + ditherMin = 1.0f / -128; + ditherMax = 1.0f / 127; + } + + 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; + } +} + +static MA_INLINE 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) +static MA_INLINE 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_NEON) +static MA_INLINE 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 + +MA_API 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 + # if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + ma_pcm_f32_to_u8__sse2(dst, src, count, ditherMode); + } else + #elif defined(MA_SUPPORT_NEON) + if (ma_has_neon()) { + ma_pcm_f32_to_u8__neon(dst, src, count, ditherMode); + } else + #endif + { + ma_pcm_f32_to_u8__optimized(dst, src, count, ditherMode); + } +#endif +} + +#ifdef MA_USE_REFERENCE_CONVERSION_APIS +static MA_INLINE 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; + + float ditherMin = 0; + float ditherMax = 0; + if (ditherMode != ma_dither_mode_none) { + ditherMin = 1.0f / -32768; + ditherMax = 1.0f / 32767; + } + + 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; + } +} +#else +static MA_INLINE 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; + + float ditherMin = 0; + float ditherMax = 0; + if (ditherMode != ma_dither_mode_none) { + ditherMin = 1.0f / -32768; + ditherMax = 1.0f / 32767; + } + + /* 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); + 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) +static MA_INLINE void ma_pcm_f32_to_s16__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + 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; + } + + dst_s16 = (ma_int16*)dst; + src_f32 = (const float*)src; + + ditherMin = 0; + ditherMax = 0; + if (ditherMode != ma_dither_mode_none) { + ditherMin = 1.0f / -32768; + ditherMax = 1.0f / 32767; + } + + i = 0; + + /* 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); + } 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) + ); + } + + x0 = *((__m128*)(src_f32 + i) + 0); + 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 /* SSE2 */ + +#if defined(MA_SUPPORT_NEON) +static MA_INLINE void ma_pcm_f32_to_s16__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_uint64 i; + ma_uint64 i8; + ma_uint64 count8; + ma_int16* dst_s16; + const float* src_f32; + float ditherMin; + float ditherMax; + + if (!ma_has_neon()) { + ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode); + return; + } + + /* 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; + } + + dst_s16 = (ma_int16*)dst; + src_f32 = (const float*)src; + + ditherMin = 0; + ditherMax = 0; + if (ditherMode != ma_dither_mode_none) { + ditherMin = 1.0f / -32768; + ditherMax = 1.0f / 32767; + } + + i = 0; + + /* 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); + } else if (ditherMode == ma_dither_mode_rectangle) { + float d0v[4]; + float d1v[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); + + 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]; + float d1v[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); + + 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); + } + + x0 = *((float32x4_t*)(src_f32 + i) + 0); + 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); + + 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. */ + 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 /* Neon */ +#endif /* MA_USE_REFERENCE_CONVERSION_APIS */ + +MA_API 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 + # if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + ma_pcm_f32_to_s16__sse2(dst, src, count, ditherMode); + } else + #elif defined(MA_SUPPORT_NEON) + if (ma_has_neon()) { + ma_pcm_f32_to_s16__neon(dst, src, count, ditherMode); + } else + #endif + { + ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode); + } +#endif +} + + +static MA_INLINE void ma_pcm_f32_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + 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 */ + +#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 + + 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. */ +} + +static MA_INLINE 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) +static MA_INLINE 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_NEON) +static MA_INLINE 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 + +MA_API 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 + # if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + ma_pcm_f32_to_s24__sse2(dst, src, count, ditherMode); + } else + #elif defined(MA_SUPPORT_NEON) + if (ma_has_neon()) { + ma_pcm_f32_to_s24__neon(dst, src, count, ditherMode); + } else + #endif + { + ma_pcm_f32_to_s24__optimized(dst, src, count, ditherMode); + } +#endif +} + + +static MA_INLINE void ma_pcm_f32_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + 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)ditherMode; /* No dithering for f32 -> s32. */ +} + +static MA_INLINE 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) +static MA_INLINE 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_NEON) +static MA_INLINE 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 + +MA_API 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 + # if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + ma_pcm_f32_to_s32__sse2(dst, src, count, ditherMode); + } else + #elif defined(MA_SUPPORT_NEON) + if (ma_has_neon()) { + ma_pcm_f32_to_s32__neon(dst, src, count, ditherMode); + } else + #endif + { + ma_pcm_f32_to_s32__optimized(dst, src, count, ditherMode); + } +#endif +} + + +MA_API 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)); +} + + +static 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]; + } + } +} + +static 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); +} + +MA_API 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 +} + + +static 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]; + } + } +} + +static 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); +} + +MA_API 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 +} + + +MA_API 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; + } +} + +MA_API void ma_convert_pcm_frames_format(void* pOut, ma_format formatOut, const void* pIn, ma_format formatIn, ma_uint64 frameCount, ma_uint32 channels, ma_dither_mode ditherMode) +{ + ma_pcm_convert(pOut, formatOut, pIn, formatIn, frameCount * channels, ditherMode); +} + +MA_API 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; + 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]; + } + } + } break; + + case ma_format_f32: + { + const float* pSrcF32 = (const float*)pInterleavedPCMFrames; + 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]; + } + } + } break; + + default: + { + ma_uint32 sampleSizeInBytes = ma_get_bytes_per_sample(format); + 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); + } + } + } break; + } +} + +MA_API 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; + 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]; + } + } + } break; + + case ma_format_f32: + { + float* pDstF32 = (float*)pInterleavedPCMFrames; + 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]; + } + } + } break; + + default: + { + ma_uint32 sampleSizeInBytes = ma_get_bytes_per_sample(format); + 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); + } + } + } break; + } +} + + +/************************************************************************************************************************************************************** + +Biquad Filter + +**************************************************************************************************************************************************************/ +#ifndef MA_BIQUAD_FIXED_POINT_SHIFT +#define MA_BIQUAD_FIXED_POINT_SHIFT 14 +#endif + +static ma_int32 ma_biquad_float_to_fp(double x) +{ + return (ma_int32)(x * (1 << MA_BIQUAD_FIXED_POINT_SHIFT)); +} + +MA_API ma_biquad_config ma_biquad_config_init(ma_format format, ma_uint32 channels, double b0, double b1, double b2, double a0, double a1, double a2) +{ + ma_biquad_config config; + + MA_ZERO_OBJECT(&config); + config.format = format; + config.channels = channels; + config.b0 = b0; + config.b1 = b1; + config.b2 = b2; + config.a0 = a0; + config.a1 = a1; + config.a2 = a2; + + return config; +} + + +typedef struct +{ + size_t sizeInBytes; + size_t r1Offset; + size_t r2Offset; +} ma_biquad_heap_layout; + +static ma_result ma_biquad_get_heap_layout(const ma_biquad_config* pConfig, ma_biquad_heap_layout* pHeapLayout) +{ + MA_ASSERT(pHeapLayout != NULL); + + MA_ZERO_OBJECT(pHeapLayout); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->channels == 0) { + return MA_INVALID_ARGS; + } + + pHeapLayout->sizeInBytes = 0; + + /* R0 */ + pHeapLayout->r1Offset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += sizeof(ma_biquad_coefficient) * pConfig->channels; + + /* R1 */ + pHeapLayout->r2Offset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += sizeof(ma_biquad_coefficient) * pConfig->channels; + + /* Make sure allocation size is aligned. */ + pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes); + + return MA_SUCCESS; +} + +MA_API ma_result ma_biquad_get_heap_size(const ma_biquad_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_result result; + ma_biquad_heap_layout heapLayout; + + if (pHeapSizeInBytes == NULL) { + return MA_INVALID_ARGS; + } + + *pHeapSizeInBytes = 0; + + result = ma_biquad_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + *pHeapSizeInBytes = heapLayout.sizeInBytes; + + return MA_SUCCESS; +} + +MA_API ma_result ma_biquad_init_preallocated(const ma_biquad_config* pConfig, void* pHeap, ma_biquad* pBQ) +{ + ma_result result; + ma_biquad_heap_layout heapLayout; + + if (pBQ == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pBQ); + + result = ma_biquad_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + pBQ->_pHeap = pHeap; + MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes); + + pBQ->pR1 = (ma_biquad_coefficient*)ma_offset_ptr(pHeap, heapLayout.r1Offset); + pBQ->pR2 = (ma_biquad_coefficient*)ma_offset_ptr(pHeap, heapLayout.r2Offset); + + return ma_biquad_reinit(pConfig, pBQ); +} + +MA_API ma_result ma_biquad_init(const ma_biquad_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_biquad* pBQ) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_biquad_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_biquad_init_preallocated(pConfig, pHeap, pBQ); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pBQ->_ownsHeap = MA_TRUE; + return MA_SUCCESS; +} + +MA_API void ma_biquad_uninit(ma_biquad* pBQ, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pBQ == NULL) { + return; + } + + if (pBQ->_ownsHeap) { + ma_free(pBQ->_pHeap, pAllocationCallbacks); + } +} + +MA_API ma_result ma_biquad_reinit(const ma_biquad_config* pConfig, ma_biquad* pBQ) +{ + if (pBQ == NULL || pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->a0 == 0) { + return MA_INVALID_ARGS; /* Division by zero. */ + } + + /* Only supporting f32 and s16. */ + if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) { + return MA_INVALID_ARGS; + } + + /* The format cannot be changed after initialization. */ + if (pBQ->format != ma_format_unknown && pBQ->format != pConfig->format) { + return MA_INVALID_OPERATION; + } + + /* The channel count cannot be changed after initialization. */ + if (pBQ->channels != 0 && pBQ->channels != pConfig->channels) { + return MA_INVALID_OPERATION; + } + + + pBQ->format = pConfig->format; + pBQ->channels = pConfig->channels; + + /* Normalize. */ + if (pConfig->format == ma_format_f32) { + pBQ->b0.f32 = (float)(pConfig->b0 / pConfig->a0); + pBQ->b1.f32 = (float)(pConfig->b1 / pConfig->a0); + pBQ->b2.f32 = (float)(pConfig->b2 / pConfig->a0); + pBQ->a1.f32 = (float)(pConfig->a1 / pConfig->a0); + pBQ->a2.f32 = (float)(pConfig->a2 / pConfig->a0); + } else { + pBQ->b0.s32 = ma_biquad_float_to_fp(pConfig->b0 / pConfig->a0); + pBQ->b1.s32 = ma_biquad_float_to_fp(pConfig->b1 / pConfig->a0); + pBQ->b2.s32 = ma_biquad_float_to_fp(pConfig->b2 / pConfig->a0); + pBQ->a1.s32 = ma_biquad_float_to_fp(pConfig->a1 / pConfig->a0); + pBQ->a2.s32 = ma_biquad_float_to_fp(pConfig->a2 / pConfig->a0); + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_biquad_clear_cache(ma_biquad* pBQ) +{ + if (pBQ == NULL) { + return MA_INVALID_ARGS; + } + + if (pBQ->format == ma_format_f32) { + pBQ->pR1->f32 = 0; + pBQ->pR2->f32 = 0; + } else { + pBQ->pR1->s32 = 0; + pBQ->pR2->s32 = 0; + } + + return MA_SUCCESS; +} + +static MA_INLINE void ma_biquad_process_pcm_frame_f32__direct_form_2_transposed(ma_biquad* pBQ, float* pY, const float* pX) +{ + ma_uint32 c; + const ma_uint32 channels = pBQ->channels; + const float b0 = pBQ->b0.f32; + const float b1 = pBQ->b1.f32; + const float b2 = pBQ->b2.f32; + const float a1 = pBQ->a1.f32; + const float a2 = pBQ->a2.f32; + + MA_ASSUME(channels > 0); + for (c = 0; c < channels; c += 1) { + float r1 = pBQ->pR1[c].f32; + float r2 = pBQ->pR2[c].f32; + float x = pX[c]; + float y; + + y = b0*x + r1; + r1 = b1*x - a1*y + r2; + r2 = b2*x - a2*y; + + pY[c] = y; + pBQ->pR1[c].f32 = r1; + pBQ->pR2[c].f32 = r2; + } +} + +static MA_INLINE void ma_biquad_process_pcm_frame_f32(ma_biquad* pBQ, float* pY, const float* pX) +{ + ma_biquad_process_pcm_frame_f32__direct_form_2_transposed(pBQ, pY, pX); +} + +static MA_INLINE void ma_biquad_process_pcm_frame_s16__direct_form_2_transposed(ma_biquad* pBQ, ma_int16* pY, const ma_int16* pX) +{ + ma_uint32 c; + const ma_uint32 channels = pBQ->channels; + const ma_int32 b0 = pBQ->b0.s32; + const ma_int32 b1 = pBQ->b1.s32; + const ma_int32 b2 = pBQ->b2.s32; + const ma_int32 a1 = pBQ->a1.s32; + const ma_int32 a2 = pBQ->a2.s32; + + MA_ASSUME(channels > 0); + for (c = 0; c < channels; c += 1) { + ma_int32 r1 = pBQ->pR1[c].s32; + ma_int32 r2 = pBQ->pR2[c].s32; + ma_int32 x = pX[c]; + ma_int32 y; + + y = (b0*x + r1) >> MA_BIQUAD_FIXED_POINT_SHIFT; + r1 = (b1*x - a1*y + r2); + r2 = (b2*x - a2*y); + + pY[c] = (ma_int16)ma_clamp(y, -32768, 32767); + pBQ->pR1[c].s32 = r1; + pBQ->pR2[c].s32 = r2; + } +} + +static MA_INLINE void ma_biquad_process_pcm_frame_s16(ma_biquad* pBQ, ma_int16* pY, const ma_int16* pX) +{ + ma_biquad_process_pcm_frame_s16__direct_form_2_transposed(pBQ, pY, pX); +} + +MA_API ma_result ma_biquad_process_pcm_frames(ma_biquad* pBQ, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + ma_uint32 n; + + if (pBQ == NULL || pFramesOut == NULL || pFramesIn == NULL) { + return MA_INVALID_ARGS; + } + + /* Note that the logic below needs to support in-place filtering. That is, it must support the case where pFramesOut and pFramesIn are the same. */ + + if (pBQ->format == ma_format_f32) { + /* */ float* pY = ( float*)pFramesOut; + const float* pX = (const float*)pFramesIn; + + for (n = 0; n < frameCount; n += 1) { + ma_biquad_process_pcm_frame_f32__direct_form_2_transposed(pBQ, pY, pX); + pY += pBQ->channels; + pX += pBQ->channels; + } + } else if (pBQ->format == ma_format_s16) { + /* */ ma_int16* pY = ( ma_int16*)pFramesOut; + const ma_int16* pX = (const ma_int16*)pFramesIn; + + for (n = 0; n < frameCount; n += 1) { + ma_biquad_process_pcm_frame_s16__direct_form_2_transposed(pBQ, pY, pX); + pY += pBQ->channels; + pX += pBQ->channels; + } + } else { + MA_ASSERT(MA_FALSE); + return MA_INVALID_ARGS; /* Format not supported. Should never hit this because it's checked in ma_biquad_init() and ma_biquad_reinit(). */ + } + + return MA_SUCCESS; +} + +MA_API ma_uint32 ma_biquad_get_latency(const ma_biquad* pBQ) +{ + if (pBQ == NULL) { + return 0; + } + + return 2; +} + + +/************************************************************************************************************************************************************** + +Low-Pass Filter + +**************************************************************************************************************************************************************/ +MA_API ma_lpf1_config ma_lpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency) +{ + ma_lpf1_config config; + + MA_ZERO_OBJECT(&config); + config.format = format; + config.channels = channels; + config.sampleRate = sampleRate; + config.cutoffFrequency = cutoffFrequency; + config.q = 0.5; + + return config; +} + +MA_API ma_lpf2_config ma_lpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q) +{ + ma_lpf2_config config; + + MA_ZERO_OBJECT(&config); + config.format = format; + config.channels = channels; + config.sampleRate = sampleRate; + config.cutoffFrequency = cutoffFrequency; + config.q = q; + + /* Q cannot be 0 or else it'll result in a division by 0. In this case just default to 0.707107. */ + if (config.q == 0) { + config.q = 0.707107; + } + + return config; +} + + +typedef struct +{ + size_t sizeInBytes; + size_t r1Offset; +} ma_lpf1_heap_layout; + +static ma_result ma_lpf1_get_heap_layout(const ma_lpf1_config* pConfig, ma_lpf1_heap_layout* pHeapLayout) +{ + MA_ASSERT(pHeapLayout != NULL); + + MA_ZERO_OBJECT(pHeapLayout); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->channels == 0) { + return MA_INVALID_ARGS; + } + + pHeapLayout->sizeInBytes = 0; + + /* R1 */ + pHeapLayout->r1Offset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += sizeof(ma_biquad_coefficient) * pConfig->channels; + + /* Make sure allocation size is aligned. */ + pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes); + + return MA_SUCCESS; +} + +MA_API ma_result ma_lpf1_get_heap_size(const ma_lpf1_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_result result; + ma_lpf1_heap_layout heapLayout; + + if (pHeapSizeInBytes == NULL) { + return MA_INVALID_ARGS; + } + + result = ma_lpf1_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + *pHeapSizeInBytes = heapLayout.sizeInBytes; + + return MA_SUCCESS; +} + +MA_API ma_result ma_lpf1_init_preallocated(const ma_lpf1_config* pConfig, void* pHeap, ma_lpf1* pLPF) +{ + ma_result result; + ma_lpf1_heap_layout heapLayout; + + if (pLPF == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pLPF); + + result = ma_lpf1_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + pLPF->_pHeap = pHeap; + MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes); + + pLPF->pR1 = (ma_biquad_coefficient*)ma_offset_ptr(pHeap, heapLayout.r1Offset); + + return ma_lpf1_reinit(pConfig, pLPF); +} + +MA_API ma_result ma_lpf1_init(const ma_lpf1_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf1* pLPF) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_lpf1_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_lpf1_init_preallocated(pConfig, pHeap, pLPF); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pLPF->_ownsHeap = MA_TRUE; + return MA_SUCCESS; +} + +MA_API void ma_lpf1_uninit(ma_lpf1* pLPF, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pLPF == NULL) { + return; + } + + if (pLPF->_ownsHeap) { + ma_free(pLPF->_pHeap, pAllocationCallbacks); + } +} + +MA_API ma_result ma_lpf1_reinit(const ma_lpf1_config* pConfig, ma_lpf1* pLPF) +{ + double a; + + if (pLPF == NULL || pConfig == NULL) { + return MA_INVALID_ARGS; + } + + /* Only supporting f32 and s16. */ + if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) { + return MA_INVALID_ARGS; + } + + /* The format cannot be changed after initialization. */ + if (pLPF->format != ma_format_unknown && pLPF->format != pConfig->format) { + return MA_INVALID_OPERATION; + } + + /* The channel count cannot be changed after initialization. */ + if (pLPF->channels != 0 && pLPF->channels != pConfig->channels) { + return MA_INVALID_OPERATION; + } + + pLPF->format = pConfig->format; + pLPF->channels = pConfig->channels; + + a = ma_expd(-2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate); + if (pConfig->format == ma_format_f32) { + pLPF->a.f32 = (float)a; + } else { + pLPF->a.s32 = ma_biquad_float_to_fp(a); + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_lpf1_clear_cache(ma_lpf1* pLPF) +{ + if (pLPF == NULL) { + return MA_INVALID_ARGS; + } + + if (pLPF->format == ma_format_f32) { + pLPF->a.f32 = 0; + } else { + pLPF->a.s32 = 0; + } + + return MA_SUCCESS; +} + +static MA_INLINE void ma_lpf1_process_pcm_frame_f32(ma_lpf1* pLPF, float* pY, const float* pX) +{ + ma_uint32 c; + const ma_uint32 channels = pLPF->channels; + const float a = pLPF->a.f32; + const float b = 1 - a; + + MA_ASSUME(channels > 0); + for (c = 0; c < channels; c += 1) { + float r1 = pLPF->pR1[c].f32; + float x = pX[c]; + float y; + + y = b*x + a*r1; + + pY[c] = y; + pLPF->pR1[c].f32 = y; + } +} + +static MA_INLINE void ma_lpf1_process_pcm_frame_s16(ma_lpf1* pLPF, ma_int16* pY, const ma_int16* pX) +{ + ma_uint32 c; + const ma_uint32 channels = pLPF->channels; + const ma_int32 a = pLPF->a.s32; + const ma_int32 b = ((1 << MA_BIQUAD_FIXED_POINT_SHIFT) - a); + + MA_ASSUME(channels > 0); + for (c = 0; c < channels; c += 1) { + ma_int32 r1 = pLPF->pR1[c].s32; + ma_int32 x = pX[c]; + ma_int32 y; + + y = (b*x + a*r1) >> MA_BIQUAD_FIXED_POINT_SHIFT; + + pY[c] = (ma_int16)y; + pLPF->pR1[c].s32 = (ma_int32)y; + } +} + +MA_API ma_result ma_lpf1_process_pcm_frames(ma_lpf1* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + ma_uint32 n; + + if (pLPF == NULL || pFramesOut == NULL || pFramesIn == NULL) { + return MA_INVALID_ARGS; + } + + /* Note that the logic below needs to support in-place filtering. That is, it must support the case where pFramesOut and pFramesIn are the same. */ + + if (pLPF->format == ma_format_f32) { + /* */ float* pY = ( float*)pFramesOut; + const float* pX = (const float*)pFramesIn; + + for (n = 0; n < frameCount; n += 1) { + ma_lpf1_process_pcm_frame_f32(pLPF, pY, pX); + pY += pLPF->channels; + pX += pLPF->channels; + } + } else if (pLPF->format == ma_format_s16) { + /* */ ma_int16* pY = ( ma_int16*)pFramesOut; + const ma_int16* pX = (const ma_int16*)pFramesIn; + + for (n = 0; n < frameCount; n += 1) { + ma_lpf1_process_pcm_frame_s16(pLPF, pY, pX); + pY += pLPF->channels; + pX += pLPF->channels; + } + } else { + MA_ASSERT(MA_FALSE); + return MA_INVALID_ARGS; /* Format not supported. Should never hit this because it's checked in ma_biquad_init() and ma_biquad_reinit(). */ + } + + return MA_SUCCESS; +} + +MA_API ma_uint32 ma_lpf1_get_latency(const ma_lpf1* pLPF) +{ + if (pLPF == NULL) { + return 0; + } + + return 1; +} + + +static MA_INLINE ma_biquad_config ma_lpf2__get_biquad_config(const ma_lpf2_config* pConfig) +{ + ma_biquad_config bqConfig; + double q; + double w; + double s; + double c; + double a; + + MA_ASSERT(pConfig != NULL); + + q = pConfig->q; + w = 2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate; + s = ma_sind(w); + c = ma_cosd(w); + a = s / (2*q); + + bqConfig.b0 = (1 - c) / 2; + bqConfig.b1 = 1 - c; + bqConfig.b2 = (1 - c) / 2; + bqConfig.a0 = 1 + a; + bqConfig.a1 = -2 * c; + bqConfig.a2 = 1 - a; + + bqConfig.format = pConfig->format; + bqConfig.channels = pConfig->channels; + + return bqConfig; +} + +MA_API ma_result ma_lpf2_get_heap_size(const ma_lpf2_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_biquad_config bqConfig; + bqConfig = ma_lpf2__get_biquad_config(pConfig); + + return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes); +} + +MA_API ma_result ma_lpf2_init_preallocated(const ma_lpf2_config* pConfig, void* pHeap, ma_lpf2* pLPF) +{ + ma_result result; + ma_biquad_config bqConfig; + + if (pLPF == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pLPF); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + bqConfig = ma_lpf2__get_biquad_config(pConfig); + result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pLPF->bq); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_lpf2_init(const ma_lpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf2* pLPF) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_lpf2_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_lpf2_init_preallocated(pConfig, pHeap, pLPF); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pLPF->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */ + return MA_SUCCESS; +} + +MA_API void ma_lpf2_uninit(ma_lpf2* pLPF, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pLPF == NULL) { + return; + } + + ma_biquad_uninit(&pLPF->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */ +} + +MA_API ma_result ma_lpf2_reinit(const ma_lpf2_config* pConfig, ma_lpf2* pLPF) +{ + ma_result result; + ma_biquad_config bqConfig; + + if (pLPF == NULL || pConfig == NULL) { + return MA_INVALID_ARGS; + } + + bqConfig = ma_lpf2__get_biquad_config(pConfig); + result = ma_biquad_reinit(&bqConfig, &pLPF->bq); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_lpf2_clear_cache(ma_lpf2* pLPF) +{ + if (pLPF == NULL) { + return MA_INVALID_ARGS; + } + + ma_biquad_clear_cache(&pLPF->bq); + + return MA_SUCCESS; +} + +static MA_INLINE void ma_lpf2_process_pcm_frame_s16(ma_lpf2* pLPF, ma_int16* pFrameOut, const ma_int16* pFrameIn) +{ + ma_biquad_process_pcm_frame_s16(&pLPF->bq, pFrameOut, pFrameIn); +} + +static MA_INLINE void ma_lpf2_process_pcm_frame_f32(ma_lpf2* pLPF, float* pFrameOut, const float* pFrameIn) +{ + ma_biquad_process_pcm_frame_f32(&pLPF->bq, pFrameOut, pFrameIn); +} + +MA_API ma_result ma_lpf2_process_pcm_frames(ma_lpf2* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + if (pLPF == NULL) { + return MA_INVALID_ARGS; + } + + return ma_biquad_process_pcm_frames(&pLPF->bq, pFramesOut, pFramesIn, frameCount); +} + +MA_API ma_uint32 ma_lpf2_get_latency(const ma_lpf2* pLPF) +{ + if (pLPF == NULL) { + return 0; + } + + return ma_biquad_get_latency(&pLPF->bq); +} + + +MA_API ma_lpf_config ma_lpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order) +{ + ma_lpf_config config; + + MA_ZERO_OBJECT(&config); + config.format = format; + config.channels = channels; + config.sampleRate = sampleRate; + config.cutoffFrequency = cutoffFrequency; + config.order = ma_min(order, MA_MAX_FILTER_ORDER); + + return config; +} + + +typedef struct +{ + size_t sizeInBytes; + size_t lpf1Offset; + size_t lpf2Offset; /* Offset of the first second order filter. Subsequent filters will come straight after, and will each have the same heap size. */ +} ma_lpf_heap_layout; + +static void ma_lpf_calculate_sub_lpf_counts(ma_uint32 order, ma_uint32* pLPF1Count, ma_uint32* pLPF2Count) +{ + MA_ASSERT(pLPF1Count != NULL); + MA_ASSERT(pLPF2Count != NULL); + + *pLPF1Count = order % 2; + *pLPF2Count = order / 2; +} + +static ma_result ma_lpf_get_heap_layout(const ma_lpf_config* pConfig, ma_lpf_heap_layout* pHeapLayout) +{ + ma_result result; + ma_uint32 lpf1Count; + ma_uint32 lpf2Count; + ma_uint32 ilpf1; + ma_uint32 ilpf2; + + MA_ASSERT(pHeapLayout != NULL); + + MA_ZERO_OBJECT(pHeapLayout); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->channels == 0) { + return MA_INVALID_ARGS; + } + + if (pConfig->order > MA_MAX_FILTER_ORDER) { + return MA_INVALID_ARGS; + } + + ma_lpf_calculate_sub_lpf_counts(pConfig->order, &lpf1Count, &lpf2Count); + + pHeapLayout->sizeInBytes = 0; + + /* LPF 1 */ + pHeapLayout->lpf1Offset = pHeapLayout->sizeInBytes; + for (ilpf1 = 0; ilpf1 < lpf1Count; ilpf1 += 1) { + size_t lpf1HeapSizeInBytes; + ma_lpf1_config lpf1Config = ma_lpf1_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency); + + result = ma_lpf1_get_heap_size(&lpf1Config, &lpf1HeapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + pHeapLayout->sizeInBytes += sizeof(ma_lpf1) + lpf1HeapSizeInBytes; + } + + /* LPF 2*/ + pHeapLayout->lpf2Offset = pHeapLayout->sizeInBytes; + for (ilpf2 = 0; ilpf2 < lpf2Count; ilpf2 += 1) { + size_t lpf2HeapSizeInBytes; + ma_lpf2_config lpf2Config = ma_lpf2_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency, 0.707107); /* <-- The "q" parameter does not matter for the purpose of calculating the heap size. */ + + result = ma_lpf2_get_heap_size(&lpf2Config, &lpf2HeapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + pHeapLayout->sizeInBytes += sizeof(ma_lpf2) + lpf2HeapSizeInBytes; + } + + /* Make sure allocation size is aligned. */ + pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes); + + return MA_SUCCESS; +} + +static ma_result ma_lpf_reinit__internal(const ma_lpf_config* pConfig, void* pHeap, ma_lpf* pLPF, ma_bool32 isNew) +{ + ma_result result; + ma_uint32 lpf1Count; + ma_uint32 lpf2Count; + ma_uint32 ilpf1; + ma_uint32 ilpf2; + ma_lpf_heap_layout heapLayout; /* Only used if isNew is true. */ + + if (pLPF == NULL || pConfig == NULL) { + return MA_INVALID_ARGS; + } + + /* Only supporting f32 and s16. */ + if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) { + return MA_INVALID_ARGS; + } + + /* The format cannot be changed after initialization. */ + if (pLPF->format != ma_format_unknown && pLPF->format != pConfig->format) { + return MA_INVALID_OPERATION; + } + + /* The channel count cannot be changed after initialization. */ + if (pLPF->channels != 0 && pLPF->channels != pConfig->channels) { + return MA_INVALID_OPERATION; + } + + if (pConfig->order > MA_MAX_FILTER_ORDER) { + return MA_INVALID_ARGS; + } + + ma_lpf_calculate_sub_lpf_counts(pConfig->order, &lpf1Count, &lpf2Count); + + /* The filter order can't change between reinits. */ + if (!isNew) { + if (pLPF->lpf1Count != lpf1Count || pLPF->lpf2Count != lpf2Count) { + return MA_INVALID_OPERATION; + } + } + + if (isNew) { + result = ma_lpf_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + pLPF->_pHeap = pHeap; + MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes); + + pLPF->pLPF1 = (ma_lpf1*)ma_offset_ptr(pHeap, heapLayout.lpf1Offset); + pLPF->pLPF2 = (ma_lpf2*)ma_offset_ptr(pHeap, heapLayout.lpf2Offset); + } else { + MA_ZERO_OBJECT(&heapLayout); /* To silence a compiler warning. */ + } + + for (ilpf1 = 0; ilpf1 < lpf1Count; ilpf1 += 1) { + ma_lpf1_config lpf1Config = ma_lpf1_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency); + + if (isNew) { + size_t lpf1HeapSizeInBytes; + + result = ma_lpf1_get_heap_size(&lpf1Config, &lpf1HeapSizeInBytes); + if (result == MA_SUCCESS) { + result = ma_lpf1_init_preallocated(&lpf1Config, ma_offset_ptr(pHeap, heapLayout.lpf1Offset + (sizeof(ma_lpf1) * lpf1Count) + (ilpf1 * lpf1HeapSizeInBytes)), &pLPF->pLPF1[ilpf1]); + } + } else { + result = ma_lpf1_reinit(&lpf1Config, &pLPF->pLPF1[ilpf1]); + } + + if (result != MA_SUCCESS) { + ma_uint32 jlpf1; + + for (jlpf1 = 0; jlpf1 < ilpf1; jlpf1 += 1) { + ma_lpf1_uninit(&pLPF->pLPF1[jlpf1], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */ + } + + return result; + } + } + + for (ilpf2 = 0; ilpf2 < lpf2Count; ilpf2 += 1) { + ma_lpf2_config lpf2Config; + double q; + double a; + + /* Tempting to use 0.707107, but won't result in a Butterworth filter if the order is > 2. */ + if (lpf1Count == 1) { + a = (1 + ilpf2*1) * (MA_PI_D/(pConfig->order*1)); /* Odd order. */ + } else { + a = (1 + ilpf2*2) * (MA_PI_D/(pConfig->order*2)); /* Even order. */ + } + q = 1 / (2*ma_cosd(a)); + + lpf2Config = ma_lpf2_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency, q); + + if (isNew) { + size_t lpf2HeapSizeInBytes; + + result = ma_lpf2_get_heap_size(&lpf2Config, &lpf2HeapSizeInBytes); + if (result == MA_SUCCESS) { + result = ma_lpf2_init_preallocated(&lpf2Config, ma_offset_ptr(pHeap, heapLayout.lpf2Offset + (sizeof(ma_lpf2) * lpf2Count) + (ilpf2 * lpf2HeapSizeInBytes)), &pLPF->pLPF2[ilpf2]); + } + } else { + result = ma_lpf2_reinit(&lpf2Config, &pLPF->pLPF2[ilpf2]); + } + + if (result != MA_SUCCESS) { + ma_uint32 jlpf1; + ma_uint32 jlpf2; + + for (jlpf1 = 0; jlpf1 < lpf1Count; jlpf1 += 1) { + ma_lpf1_uninit(&pLPF->pLPF1[jlpf1], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */ + } + + for (jlpf2 = 0; jlpf2 < ilpf2; jlpf2 += 1) { + ma_lpf2_uninit(&pLPF->pLPF2[jlpf2], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */ + } + + return result; + } + } + + pLPF->lpf1Count = lpf1Count; + pLPF->lpf2Count = lpf2Count; + pLPF->format = pConfig->format; + pLPF->channels = pConfig->channels; + pLPF->sampleRate = pConfig->sampleRate; + + return MA_SUCCESS; +} + +MA_API ma_result ma_lpf_get_heap_size(const ma_lpf_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_result result; + ma_lpf_heap_layout heapLayout; + + if (pHeapSizeInBytes == NULL) { + return MA_INVALID_ARGS; + } + + *pHeapSizeInBytes = 0; + + result = ma_lpf_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + *pHeapSizeInBytes = heapLayout.sizeInBytes; + + return result; +} + +MA_API ma_result ma_lpf_init_preallocated(const ma_lpf_config* pConfig, void* pHeap, ma_lpf* pLPF) +{ + if (pLPF == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pLPF); + + return ma_lpf_reinit__internal(pConfig, pHeap, pLPF, /*isNew*/MA_TRUE); +} + +MA_API ma_result ma_lpf_init(const ma_lpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf* pLPF) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_lpf_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_lpf_init_preallocated(pConfig, pHeap, pLPF); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pLPF->_ownsHeap = MA_TRUE; + return MA_SUCCESS; +} + +MA_API void ma_lpf_uninit(ma_lpf* pLPF, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_uint32 ilpf1; + ma_uint32 ilpf2; + + if (pLPF == NULL) { + return; + } + + for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) { + ma_lpf1_uninit(&pLPF->pLPF1[ilpf1], pAllocationCallbacks); + } + + for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) { + ma_lpf2_uninit(&pLPF->pLPF2[ilpf2], pAllocationCallbacks); + } + + if (pLPF->_ownsHeap) { + ma_free(pLPF->_pHeap, pAllocationCallbacks); + } +} + +MA_API ma_result ma_lpf_reinit(const ma_lpf_config* pConfig, ma_lpf* pLPF) +{ + return ma_lpf_reinit__internal(pConfig, NULL, pLPF, /*isNew*/MA_FALSE); +} + +MA_API ma_result ma_lpf_clear_cache(ma_lpf* pLPF) +{ + ma_uint32 ilpf1; + ma_uint32 ilpf2; + + if (pLPF == NULL) { + return MA_INVALID_ARGS; + } + + for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) { + ma_lpf1_clear_cache(&pLPF->pLPF1[ilpf1]); + } + + for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) { + ma_lpf2_clear_cache(&pLPF->pLPF2[ilpf2]); + } + + return MA_SUCCESS; +} + +static MA_INLINE void ma_lpf_process_pcm_frame_f32(ma_lpf* pLPF, float* pY, const void* pX) +{ + ma_uint32 ilpf1; + ma_uint32 ilpf2; + + MA_ASSERT(pLPF->format == ma_format_f32); + + MA_MOVE_MEMORY(pY, pX, ma_get_bytes_per_frame(pLPF->format, pLPF->channels)); + + for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) { + ma_lpf1_process_pcm_frame_f32(&pLPF->pLPF1[ilpf1], pY, pY); + } + + for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) { + ma_lpf2_process_pcm_frame_f32(&pLPF->pLPF2[ilpf2], pY, pY); + } +} + +static MA_INLINE void ma_lpf_process_pcm_frame_s16(ma_lpf* pLPF, ma_int16* pY, const ma_int16* pX) +{ + ma_uint32 ilpf1; + ma_uint32 ilpf2; + + MA_ASSERT(pLPF->format == ma_format_s16); + + MA_MOVE_MEMORY(pY, pX, ma_get_bytes_per_frame(pLPF->format, pLPF->channels)); + + for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) { + ma_lpf1_process_pcm_frame_s16(&pLPF->pLPF1[ilpf1], pY, pY); + } + + for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) { + ma_lpf2_process_pcm_frame_s16(&pLPF->pLPF2[ilpf2], pY, pY); + } +} + +MA_API ma_result ma_lpf_process_pcm_frames(ma_lpf* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + ma_result result; + ma_uint32 ilpf1; + ma_uint32 ilpf2; + + if (pLPF == NULL) { + return MA_INVALID_ARGS; + } + + /* Faster path for in-place. */ + if (pFramesOut == pFramesIn) { + for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) { + result = ma_lpf1_process_pcm_frames(&pLPF->pLPF1[ilpf1], pFramesOut, pFramesOut, frameCount); + if (result != MA_SUCCESS) { + return result; + } + } + + for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) { + result = ma_lpf2_process_pcm_frames(&pLPF->pLPF2[ilpf2], pFramesOut, pFramesOut, frameCount); + if (result != MA_SUCCESS) { + return result; + } + } + } + + /* Slightly slower path for copying. */ + if (pFramesOut != pFramesIn) { + ma_uint32 iFrame; + + /* */ if (pLPF->format == ma_format_f32) { + /* */ float* pFramesOutF32 = ( float*)pFramesOut; + const float* pFramesInF32 = (const float*)pFramesIn; + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_lpf_process_pcm_frame_f32(pLPF, pFramesOutF32, pFramesInF32); + pFramesOutF32 += pLPF->channels; + pFramesInF32 += pLPF->channels; + } + } else if (pLPF->format == ma_format_s16) { + /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut; + const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn; + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_lpf_process_pcm_frame_s16(pLPF, pFramesOutS16, pFramesInS16); + pFramesOutS16 += pLPF->channels; + pFramesInS16 += pLPF->channels; + } + } else { + MA_ASSERT(MA_FALSE); + return MA_INVALID_OPERATION; /* Should never hit this. */ + } + } + + return MA_SUCCESS; +} + +MA_API ma_uint32 ma_lpf_get_latency(const ma_lpf* pLPF) +{ + if (pLPF == NULL) { + return 0; + } + + return pLPF->lpf2Count*2 + pLPF->lpf1Count; +} + + +/************************************************************************************************************************************************************** + +High-Pass Filtering + +**************************************************************************************************************************************************************/ +MA_API ma_hpf1_config ma_hpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency) +{ + ma_hpf1_config config; + + MA_ZERO_OBJECT(&config); + config.format = format; + config.channels = channels; + config.sampleRate = sampleRate; + config.cutoffFrequency = cutoffFrequency; + + return config; +} + +MA_API ma_hpf2_config ma_hpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q) +{ + ma_hpf2_config config; + + MA_ZERO_OBJECT(&config); + config.format = format; + config.channels = channels; + config.sampleRate = sampleRate; + config.cutoffFrequency = cutoffFrequency; + config.q = q; + + /* Q cannot be 0 or else it'll result in a division by 0. In this case just default to 0.707107. */ + if (config.q == 0) { + config.q = 0.707107; + } + + return config; +} + + +typedef struct +{ + size_t sizeInBytes; + size_t r1Offset; +} ma_hpf1_heap_layout; + +static ma_result ma_hpf1_get_heap_layout(const ma_hpf1_config* pConfig, ma_hpf1_heap_layout* pHeapLayout) +{ + MA_ASSERT(pHeapLayout != NULL); + + MA_ZERO_OBJECT(pHeapLayout); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->channels == 0) { + return MA_INVALID_ARGS; + } + + pHeapLayout->sizeInBytes = 0; + + /* R1 */ + pHeapLayout->r1Offset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += sizeof(ma_biquad_coefficient) * pConfig->channels; + + /* Make sure allocation size is aligned. */ + pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes); + + return MA_SUCCESS; +} + +MA_API ma_result ma_hpf1_get_heap_size(const ma_hpf1_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_result result; + ma_hpf1_heap_layout heapLayout; + + if (pHeapSizeInBytes == NULL) { + return MA_INVALID_ARGS; + } + + result = ma_hpf1_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + *pHeapSizeInBytes = heapLayout.sizeInBytes; + + return MA_SUCCESS; +} + +MA_API ma_result ma_hpf1_init_preallocated(const ma_hpf1_config* pConfig, void* pHeap, ma_hpf1* pLPF) +{ + ma_result result; + ma_hpf1_heap_layout heapLayout; + + if (pLPF == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pLPF); + + result = ma_hpf1_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + pLPF->_pHeap = pHeap; + MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes); + + pLPF->pR1 = (ma_biquad_coefficient*)ma_offset_ptr(pHeap, heapLayout.r1Offset); + + return ma_hpf1_reinit(pConfig, pLPF); +} + +MA_API ma_result ma_hpf1_init(const ma_hpf1_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf1* pLPF) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_hpf1_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_hpf1_init_preallocated(pConfig, pHeap, pLPF); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pLPF->_ownsHeap = MA_TRUE; + return MA_SUCCESS; +} + +MA_API void ma_hpf1_uninit(ma_hpf1* pHPF, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pHPF == NULL) { + return; + } + + if (pHPF->_ownsHeap) { + ma_free(pHPF->_pHeap, pAllocationCallbacks); + } +} + +MA_API ma_result ma_hpf1_reinit(const ma_hpf1_config* pConfig, ma_hpf1* pHPF) +{ + double a; + + if (pHPF == NULL || pConfig == NULL) { + return MA_INVALID_ARGS; + } + + /* Only supporting f32 and s16. */ + if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) { + return MA_INVALID_ARGS; + } + + /* The format cannot be changed after initialization. */ + if (pHPF->format != ma_format_unknown && pHPF->format != pConfig->format) { + return MA_INVALID_OPERATION; + } + + /* The channel count cannot be changed after initialization. */ + if (pHPF->channels != 0 && pHPF->channels != pConfig->channels) { + return MA_INVALID_OPERATION; + } + + pHPF->format = pConfig->format; + pHPF->channels = pConfig->channels; + + a = ma_expd(-2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate); + if (pConfig->format == ma_format_f32) { + pHPF->a.f32 = (float)a; + } else { + pHPF->a.s32 = ma_biquad_float_to_fp(a); + } + + return MA_SUCCESS; +} + +static MA_INLINE void ma_hpf1_process_pcm_frame_f32(ma_hpf1* pHPF, float* pY, const float* pX) +{ + ma_uint32 c; + const ma_uint32 channels = pHPF->channels; + const float a = 1 - pHPF->a.f32; + const float b = 1 - a; + + MA_ASSUME(channels > 0); + for (c = 0; c < channels; c += 1) { + float r1 = pHPF->pR1[c].f32; + float x = pX[c]; + float y; + + y = b*x - a*r1; + + pY[c] = y; + pHPF->pR1[c].f32 = y; + } +} + +static MA_INLINE void ma_hpf1_process_pcm_frame_s16(ma_hpf1* pHPF, ma_int16* pY, const ma_int16* pX) +{ + ma_uint32 c; + const ma_uint32 channels = pHPF->channels; + const ma_int32 a = ((1 << MA_BIQUAD_FIXED_POINT_SHIFT) - pHPF->a.s32); + const ma_int32 b = ((1 << MA_BIQUAD_FIXED_POINT_SHIFT) - a); + + MA_ASSUME(channels > 0); + for (c = 0; c < channels; c += 1) { + ma_int32 r1 = pHPF->pR1[c].s32; + ma_int32 x = pX[c]; + ma_int32 y; + + y = (b*x - a*r1) >> MA_BIQUAD_FIXED_POINT_SHIFT; + + pY[c] = (ma_int16)y; + pHPF->pR1[c].s32 = (ma_int32)y; + } +} + +MA_API ma_result ma_hpf1_process_pcm_frames(ma_hpf1* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + ma_uint32 n; + + if (pHPF == NULL || pFramesOut == NULL || pFramesIn == NULL) { + return MA_INVALID_ARGS; + } + + /* Note that the logic below needs to support in-place filtering. That is, it must support the case where pFramesOut and pFramesIn are the same. */ + + if (pHPF->format == ma_format_f32) { + /* */ float* pY = ( float*)pFramesOut; + const float* pX = (const float*)pFramesIn; + + for (n = 0; n < frameCount; n += 1) { + ma_hpf1_process_pcm_frame_f32(pHPF, pY, pX); + pY += pHPF->channels; + pX += pHPF->channels; + } + } else if (pHPF->format == ma_format_s16) { + /* */ ma_int16* pY = ( ma_int16*)pFramesOut; + const ma_int16* pX = (const ma_int16*)pFramesIn; + + for (n = 0; n < frameCount; n += 1) { + ma_hpf1_process_pcm_frame_s16(pHPF, pY, pX); + pY += pHPF->channels; + pX += pHPF->channels; + } + } else { + MA_ASSERT(MA_FALSE); + return MA_INVALID_ARGS; /* Format not supported. Should never hit this because it's checked in ma_biquad_init() and ma_biquad_reinit(). */ + } + + return MA_SUCCESS; +} + +MA_API ma_uint32 ma_hpf1_get_latency(const ma_hpf1* pHPF) +{ + if (pHPF == NULL) { + return 0; + } + + return 1; +} + + +static MA_INLINE ma_biquad_config ma_hpf2__get_biquad_config(const ma_hpf2_config* pConfig) +{ + ma_biquad_config bqConfig; + double q; + double w; + double s; + double c; + double a; + + MA_ASSERT(pConfig != NULL); + + q = pConfig->q; + w = 2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate; + s = ma_sind(w); + c = ma_cosd(w); + a = s / (2*q); + + bqConfig.b0 = (1 + c) / 2; + bqConfig.b1 = -(1 + c); + bqConfig.b2 = (1 + c) / 2; + bqConfig.a0 = 1 + a; + bqConfig.a1 = -2 * c; + bqConfig.a2 = 1 - a; + + bqConfig.format = pConfig->format; + bqConfig.channels = pConfig->channels; + + return bqConfig; +} + +MA_API ma_result ma_hpf2_get_heap_size(const ma_hpf2_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_biquad_config bqConfig; + bqConfig = ma_hpf2__get_biquad_config(pConfig); + + return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes); +} + +MA_API ma_result ma_hpf2_init_preallocated(const ma_hpf2_config* pConfig, void* pHeap, ma_hpf2* pHPF) +{ + ma_result result; + ma_biquad_config bqConfig; + + if (pHPF == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pHPF); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + bqConfig = ma_hpf2__get_biquad_config(pConfig); + result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pHPF->bq); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_hpf2_init(const ma_hpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf2* pHPF) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_hpf2_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_hpf2_init_preallocated(pConfig, pHeap, pHPF); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pHPF->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */ + return MA_SUCCESS; +} + +MA_API void ma_hpf2_uninit(ma_hpf2* pHPF, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pHPF == NULL) { + return; + } + + ma_biquad_uninit(&pHPF->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */ +} + +MA_API ma_result ma_hpf2_reinit(const ma_hpf2_config* pConfig, ma_hpf2* pHPF) +{ + ma_result result; + ma_biquad_config bqConfig; + + if (pHPF == NULL || pConfig == NULL) { + return MA_INVALID_ARGS; + } + + bqConfig = ma_hpf2__get_biquad_config(pConfig); + result = ma_biquad_reinit(&bqConfig, &pHPF->bq); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +static MA_INLINE void ma_hpf2_process_pcm_frame_s16(ma_hpf2* pHPF, ma_int16* pFrameOut, const ma_int16* pFrameIn) +{ + ma_biquad_process_pcm_frame_s16(&pHPF->bq, pFrameOut, pFrameIn); +} + +static MA_INLINE void ma_hpf2_process_pcm_frame_f32(ma_hpf2* pHPF, float* pFrameOut, const float* pFrameIn) +{ + ma_biquad_process_pcm_frame_f32(&pHPF->bq, pFrameOut, pFrameIn); +} + +MA_API ma_result ma_hpf2_process_pcm_frames(ma_hpf2* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + if (pHPF == NULL) { + return MA_INVALID_ARGS; + } + + return ma_biquad_process_pcm_frames(&pHPF->bq, pFramesOut, pFramesIn, frameCount); +} + +MA_API ma_uint32 ma_hpf2_get_latency(const ma_hpf2* pHPF) +{ + if (pHPF == NULL) { + return 0; + } + + return ma_biquad_get_latency(&pHPF->bq); +} + + +MA_API ma_hpf_config ma_hpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order) +{ + ma_hpf_config config; + + MA_ZERO_OBJECT(&config); + config.format = format; + config.channels = channels; + config.sampleRate = sampleRate; + config.cutoffFrequency = cutoffFrequency; + config.order = ma_min(order, MA_MAX_FILTER_ORDER); + + return config; +} + + +typedef struct +{ + size_t sizeInBytes; + size_t hpf1Offset; + size_t hpf2Offset; /* Offset of the first second order filter. Subsequent filters will come straight after, and will each have the same heap size. */ +} ma_hpf_heap_layout; + +static void ma_hpf_calculate_sub_hpf_counts(ma_uint32 order, ma_uint32* pHPF1Count, ma_uint32* pHPF2Count) +{ + MA_ASSERT(pHPF1Count != NULL); + MA_ASSERT(pHPF2Count != NULL); + + *pHPF1Count = order % 2; + *pHPF2Count = order / 2; +} + +static ma_result ma_hpf_get_heap_layout(const ma_hpf_config* pConfig, ma_hpf_heap_layout* pHeapLayout) +{ + ma_result result; + ma_uint32 hpf1Count; + ma_uint32 hpf2Count; + ma_uint32 ihpf1; + ma_uint32 ihpf2; + + MA_ASSERT(pHeapLayout != NULL); + + MA_ZERO_OBJECT(pHeapLayout); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->channels == 0) { + return MA_INVALID_ARGS; + } + + if (pConfig->order > MA_MAX_FILTER_ORDER) { + return MA_INVALID_ARGS; + } + + ma_hpf_calculate_sub_hpf_counts(pConfig->order, &hpf1Count, &hpf2Count); + + pHeapLayout->sizeInBytes = 0; + + /* HPF 1 */ + pHeapLayout->hpf1Offset = pHeapLayout->sizeInBytes; + for (ihpf1 = 0; ihpf1 < hpf1Count; ihpf1 += 1) { + size_t hpf1HeapSizeInBytes; + ma_hpf1_config hpf1Config = ma_hpf1_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency); + + result = ma_hpf1_get_heap_size(&hpf1Config, &hpf1HeapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + pHeapLayout->sizeInBytes += sizeof(ma_hpf1) + hpf1HeapSizeInBytes; + } + + /* HPF 2*/ + pHeapLayout->hpf2Offset = pHeapLayout->sizeInBytes; + for (ihpf2 = 0; ihpf2 < hpf2Count; ihpf2 += 1) { + size_t hpf2HeapSizeInBytes; + ma_hpf2_config hpf2Config = ma_hpf2_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency, 0.707107); /* <-- The "q" parameter does not matter for the purpose of calculating the heap size. */ + + result = ma_hpf2_get_heap_size(&hpf2Config, &hpf2HeapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + pHeapLayout->sizeInBytes += sizeof(ma_hpf2) + hpf2HeapSizeInBytes; + } + + /* Make sure allocation size is aligned. */ + pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes); + + return MA_SUCCESS; +} + +static ma_result ma_hpf_reinit__internal(const ma_hpf_config* pConfig, void* pHeap, ma_hpf* pHPF, ma_bool32 isNew) +{ + ma_result result; + ma_uint32 hpf1Count; + ma_uint32 hpf2Count; + ma_uint32 ihpf1; + ma_uint32 ihpf2; + ma_hpf_heap_layout heapLayout; /* Only used if isNew is true. */ + + if (pHPF == NULL || pConfig == NULL) { + return MA_INVALID_ARGS; + } + + /* Only supporting f32 and s16. */ + if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) { + return MA_INVALID_ARGS; + } + + /* The format cannot be changed after initialization. */ + if (pHPF->format != ma_format_unknown && pHPF->format != pConfig->format) { + return MA_INVALID_OPERATION; + } + + /* The channel count cannot be changed after initialization. */ + if (pHPF->channels != 0 && pHPF->channels != pConfig->channels) { + return MA_INVALID_OPERATION; + } + + if (pConfig->order > MA_MAX_FILTER_ORDER) { + return MA_INVALID_ARGS; + } + + ma_hpf_calculate_sub_hpf_counts(pConfig->order, &hpf1Count, &hpf2Count); + + /* The filter order can't change between reinits. */ + if (!isNew) { + if (pHPF->hpf1Count != hpf1Count || pHPF->hpf2Count != hpf2Count) { + return MA_INVALID_OPERATION; + } + } + + if (isNew) { + result = ma_hpf_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + pHPF->_pHeap = pHeap; + MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes); + + pHPF->pHPF1 = (ma_hpf1*)ma_offset_ptr(pHeap, heapLayout.hpf1Offset); + pHPF->pHPF2 = (ma_hpf2*)ma_offset_ptr(pHeap, heapLayout.hpf2Offset); + } else { + MA_ZERO_OBJECT(&heapLayout); /* To silence a compiler warning. */ + } + + for (ihpf1 = 0; ihpf1 < hpf1Count; ihpf1 += 1) { + ma_hpf1_config hpf1Config = ma_hpf1_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency); + + if (isNew) { + size_t hpf1HeapSizeInBytes; + + result = ma_hpf1_get_heap_size(&hpf1Config, &hpf1HeapSizeInBytes); + if (result == MA_SUCCESS) { + result = ma_hpf1_init_preallocated(&hpf1Config, ma_offset_ptr(pHeap, heapLayout.hpf1Offset + (sizeof(ma_hpf1) * hpf1Count) + (ihpf1 * hpf1HeapSizeInBytes)), &pHPF->pHPF1[ihpf1]); + } + } else { + result = ma_hpf1_reinit(&hpf1Config, &pHPF->pHPF1[ihpf1]); + } + + if (result != MA_SUCCESS) { + ma_uint32 jhpf1; + + for (jhpf1 = 0; jhpf1 < ihpf1; jhpf1 += 1) { + ma_hpf1_uninit(&pHPF->pHPF1[jhpf1], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */ + } + + return result; + } + } + + for (ihpf2 = 0; ihpf2 < hpf2Count; ihpf2 += 1) { + ma_hpf2_config hpf2Config; + double q; + double a; + + /* Tempting to use 0.707107, but won't result in a Butterworth filter if the order is > 2. */ + if (hpf1Count == 1) { + a = (1 + ihpf2*1) * (MA_PI_D/(pConfig->order*1)); /* Odd order. */ + } else { + a = (1 + ihpf2*2) * (MA_PI_D/(pConfig->order*2)); /* Even order. */ + } + q = 1 / (2*ma_cosd(a)); + + hpf2Config = ma_hpf2_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency, q); + + if (isNew) { + size_t hpf2HeapSizeInBytes; + + result = ma_hpf2_get_heap_size(&hpf2Config, &hpf2HeapSizeInBytes); + if (result == MA_SUCCESS) { + result = ma_hpf2_init_preallocated(&hpf2Config, ma_offset_ptr(pHeap, heapLayout.hpf2Offset + (sizeof(ma_hpf2) * hpf2Count) + (ihpf2 * hpf2HeapSizeInBytes)), &pHPF->pHPF2[ihpf2]); + } + } else { + result = ma_hpf2_reinit(&hpf2Config, &pHPF->pHPF2[ihpf2]); + } + + if (result != MA_SUCCESS) { + ma_uint32 jhpf1; + ma_uint32 jhpf2; + + for (jhpf1 = 0; jhpf1 < hpf1Count; jhpf1 += 1) { + ma_hpf1_uninit(&pHPF->pHPF1[jhpf1], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */ + } + + for (jhpf2 = 0; jhpf2 < ihpf2; jhpf2 += 1) { + ma_hpf2_uninit(&pHPF->pHPF2[jhpf2], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */ + } + + return result; + } + } + + pHPF->hpf1Count = hpf1Count; + pHPF->hpf2Count = hpf2Count; + pHPF->format = pConfig->format; + pHPF->channels = pConfig->channels; + pHPF->sampleRate = pConfig->sampleRate; + + return MA_SUCCESS; +} + +MA_API ma_result ma_hpf_get_heap_size(const ma_hpf_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_result result; + ma_hpf_heap_layout heapLayout; + + if (pHeapSizeInBytes == NULL) { + return MA_INVALID_ARGS; + } + + *pHeapSizeInBytes = 0; + + result = ma_hpf_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + *pHeapSizeInBytes = heapLayout.sizeInBytes; + + return result; +} + +MA_API ma_result ma_hpf_init_preallocated(const ma_hpf_config* pConfig, void* pHeap, ma_hpf* pLPF) +{ + if (pLPF == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pLPF); + + return ma_hpf_reinit__internal(pConfig, pHeap, pLPF, /*isNew*/MA_TRUE); +} + +MA_API ma_result ma_hpf_init(const ma_hpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf* pHPF) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_hpf_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_hpf_init_preallocated(pConfig, pHeap, pHPF); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pHPF->_ownsHeap = MA_TRUE; + return MA_SUCCESS; +} + +MA_API void ma_hpf_uninit(ma_hpf* pHPF, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_uint32 ihpf1; + ma_uint32 ihpf2; + + if (pHPF == NULL) { + return; + } + + for (ihpf1 = 0; ihpf1 < pHPF->hpf1Count; ihpf1 += 1) { + ma_hpf1_uninit(&pHPF->pHPF1[ihpf1], pAllocationCallbacks); + } + + for (ihpf2 = 0; ihpf2 < pHPF->hpf2Count; ihpf2 += 1) { + ma_hpf2_uninit(&pHPF->pHPF2[ihpf2], pAllocationCallbacks); + } + + if (pHPF->_ownsHeap) { + ma_free(pHPF->_pHeap, pAllocationCallbacks); + } +} + +MA_API ma_result ma_hpf_reinit(const ma_hpf_config* pConfig, ma_hpf* pHPF) +{ + return ma_hpf_reinit__internal(pConfig, NULL, pHPF, /*isNew*/MA_FALSE); +} + +MA_API ma_result ma_hpf_process_pcm_frames(ma_hpf* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + ma_result result; + ma_uint32 ihpf1; + ma_uint32 ihpf2; + + if (pHPF == NULL) { + return MA_INVALID_ARGS; + } + + /* Faster path for in-place. */ + if (pFramesOut == pFramesIn) { + for (ihpf1 = 0; ihpf1 < pHPF->hpf1Count; ihpf1 += 1) { + result = ma_hpf1_process_pcm_frames(&pHPF->pHPF1[ihpf1], pFramesOut, pFramesOut, frameCount); + if (result != MA_SUCCESS) { + return result; + } + } + + for (ihpf2 = 0; ihpf2 < pHPF->hpf2Count; ihpf2 += 1) { + result = ma_hpf2_process_pcm_frames(&pHPF->pHPF2[ihpf2], pFramesOut, pFramesOut, frameCount); + if (result != MA_SUCCESS) { + return result; + } + } + } + + /* Slightly slower path for copying. */ + if (pFramesOut != pFramesIn) { + ma_uint32 iFrame; + + /* */ if (pHPF->format == ma_format_f32) { + /* */ float* pFramesOutF32 = ( float*)pFramesOut; + const float* pFramesInF32 = (const float*)pFramesIn; + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + MA_COPY_MEMORY(pFramesOutF32, pFramesInF32, ma_get_bytes_per_frame(pHPF->format, pHPF->channels)); + + for (ihpf1 = 0; ihpf1 < pHPF->hpf1Count; ihpf1 += 1) { + ma_hpf1_process_pcm_frame_f32(&pHPF->pHPF1[ihpf1], pFramesOutF32, pFramesOutF32); + } + + for (ihpf2 = 0; ihpf2 < pHPF->hpf2Count; ihpf2 += 1) { + ma_hpf2_process_pcm_frame_f32(&pHPF->pHPF2[ihpf2], pFramesOutF32, pFramesOutF32); + } + + pFramesOutF32 += pHPF->channels; + pFramesInF32 += pHPF->channels; + } + } else if (pHPF->format == ma_format_s16) { + /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut; + const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn; + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + MA_COPY_MEMORY(pFramesOutS16, pFramesInS16, ma_get_bytes_per_frame(pHPF->format, pHPF->channels)); + + for (ihpf1 = 0; ihpf1 < pHPF->hpf1Count; ihpf1 += 1) { + ma_hpf1_process_pcm_frame_s16(&pHPF->pHPF1[ihpf1], pFramesOutS16, pFramesOutS16); + } + + for (ihpf2 = 0; ihpf2 < pHPF->hpf2Count; ihpf2 += 1) { + ma_hpf2_process_pcm_frame_s16(&pHPF->pHPF2[ihpf2], pFramesOutS16, pFramesOutS16); + } + + pFramesOutS16 += pHPF->channels; + pFramesInS16 += pHPF->channels; + } + } else { + MA_ASSERT(MA_FALSE); + return MA_INVALID_OPERATION; /* Should never hit this. */ + } + } + + return MA_SUCCESS; +} + +MA_API ma_uint32 ma_hpf_get_latency(const ma_hpf* pHPF) +{ + if (pHPF == NULL) { + return 0; + } + + return pHPF->hpf2Count*2 + pHPF->hpf1Count; +} + + +/************************************************************************************************************************************************************** + +Band-Pass Filtering + +**************************************************************************************************************************************************************/ +MA_API ma_bpf2_config ma_bpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q) +{ + ma_bpf2_config config; + + MA_ZERO_OBJECT(&config); + config.format = format; + config.channels = channels; + config.sampleRate = sampleRate; + config.cutoffFrequency = cutoffFrequency; + config.q = q; + + /* Q cannot be 0 or else it'll result in a division by 0. In this case just default to 0.707107. */ + if (config.q == 0) { + config.q = 0.707107; + } + + return config; +} + + +static MA_INLINE ma_biquad_config ma_bpf2__get_biquad_config(const ma_bpf2_config* pConfig) +{ + ma_biquad_config bqConfig; + double q; + double w; + double s; + double c; + double a; + + MA_ASSERT(pConfig != NULL); + + q = pConfig->q; + w = 2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate; + s = ma_sind(w); + c = ma_cosd(w); + a = s / (2*q); + + bqConfig.b0 = q * a; + bqConfig.b1 = 0; + bqConfig.b2 = -q * a; + bqConfig.a0 = 1 + a; + bqConfig.a1 = -2 * c; + bqConfig.a2 = 1 - a; + + bqConfig.format = pConfig->format; + bqConfig.channels = pConfig->channels; + + return bqConfig; +} + +MA_API ma_result ma_bpf2_get_heap_size(const ma_bpf2_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_biquad_config bqConfig; + bqConfig = ma_bpf2__get_biquad_config(pConfig); + + return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes); +} + +MA_API ma_result ma_bpf2_init_preallocated(const ma_bpf2_config* pConfig, void* pHeap, ma_bpf2* pBPF) +{ + ma_result result; + ma_biquad_config bqConfig; + + if (pBPF == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pBPF); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + bqConfig = ma_bpf2__get_biquad_config(pConfig); + result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pBPF->bq); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_bpf2_init(const ma_bpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf2* pBPF) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_bpf2_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_bpf2_init_preallocated(pConfig, pHeap, pBPF); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pBPF->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */ + return MA_SUCCESS; +} + +MA_API void ma_bpf2_uninit(ma_bpf2* pBPF, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pBPF == NULL) { + return; + } + + ma_biquad_uninit(&pBPF->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */ +} + +MA_API ma_result ma_bpf2_reinit(const ma_bpf2_config* pConfig, ma_bpf2* pBPF) +{ + ma_result result; + ma_biquad_config bqConfig; + + if (pBPF == NULL || pConfig == NULL) { + return MA_INVALID_ARGS; + } + + bqConfig = ma_bpf2__get_biquad_config(pConfig); + result = ma_biquad_reinit(&bqConfig, &pBPF->bq); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +static MA_INLINE void ma_bpf2_process_pcm_frame_s16(ma_bpf2* pBPF, ma_int16* pFrameOut, const ma_int16* pFrameIn) +{ + ma_biquad_process_pcm_frame_s16(&pBPF->bq, pFrameOut, pFrameIn); +} + +static MA_INLINE void ma_bpf2_process_pcm_frame_f32(ma_bpf2* pBPF, float* pFrameOut, const float* pFrameIn) +{ + ma_biquad_process_pcm_frame_f32(&pBPF->bq, pFrameOut, pFrameIn); +} + +MA_API ma_result ma_bpf2_process_pcm_frames(ma_bpf2* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + if (pBPF == NULL) { + return MA_INVALID_ARGS; + } + + return ma_biquad_process_pcm_frames(&pBPF->bq, pFramesOut, pFramesIn, frameCount); +} + +MA_API ma_uint32 ma_bpf2_get_latency(const ma_bpf2* pBPF) +{ + if (pBPF == NULL) { + return 0; + } + + return ma_biquad_get_latency(&pBPF->bq); +} + + +MA_API ma_bpf_config ma_bpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order) +{ + ma_bpf_config config; + + MA_ZERO_OBJECT(&config); + config.format = format; + config.channels = channels; + config.sampleRate = sampleRate; + config.cutoffFrequency = cutoffFrequency; + config.order = ma_min(order, MA_MAX_FILTER_ORDER); + + return config; +} + + +typedef struct +{ + size_t sizeInBytes; + size_t bpf2Offset; +} ma_bpf_heap_layout; + +static ma_result ma_bpf_get_heap_layout(const ma_bpf_config* pConfig, ma_bpf_heap_layout* pHeapLayout) +{ + ma_result result; + ma_uint32 bpf2Count; + ma_uint32 ibpf2; + + MA_ASSERT(pHeapLayout != NULL); + + MA_ZERO_OBJECT(pHeapLayout); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->order > MA_MAX_FILTER_ORDER) { + return MA_INVALID_ARGS; + } + + /* We must have an even number of order. */ + if ((pConfig->order & 0x1) != 0) { + return MA_INVALID_ARGS; + } + + bpf2Count = pConfig->channels / 2; + + pHeapLayout->sizeInBytes = 0; + + /* BPF 2 */ + pHeapLayout->bpf2Offset = pHeapLayout->sizeInBytes; + for (ibpf2 = 0; ibpf2 < bpf2Count; ibpf2 += 1) { + size_t bpf2HeapSizeInBytes; + ma_bpf2_config bpf2Config = ma_bpf2_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency, 0.707107); /* <-- The "q" parameter does not matter for the purpose of calculating the heap size. */ + + result = ma_bpf2_get_heap_size(&bpf2Config, &bpf2HeapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + pHeapLayout->sizeInBytes += sizeof(ma_bpf2) + bpf2HeapSizeInBytes; + } + + /* Make sure allocation size is aligned. */ + pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes); + + return MA_SUCCESS; +} + +static ma_result ma_bpf_reinit__internal(const ma_bpf_config* pConfig, void* pHeap, ma_bpf* pBPF, ma_bool32 isNew) +{ + ma_result result; + ma_uint32 bpf2Count; + ma_uint32 ibpf2; + ma_bpf_heap_layout heapLayout; /* Only used if isNew is true. */ + + if (pBPF == NULL || pConfig == NULL) { + return MA_INVALID_ARGS; + } + + /* Only supporting f32 and s16. */ + if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) { + return MA_INVALID_ARGS; + } + + /* The format cannot be changed after initialization. */ + if (pBPF->format != ma_format_unknown && pBPF->format != pConfig->format) { + return MA_INVALID_OPERATION; + } + + /* The channel count cannot be changed after initialization. */ + if (pBPF->channels != 0 && pBPF->channels != pConfig->channels) { + return MA_INVALID_OPERATION; + } + + if (pConfig->order > MA_MAX_FILTER_ORDER) { + return MA_INVALID_ARGS; + } + + /* We must have an even number of order. */ + if ((pConfig->order & 0x1) != 0) { + return MA_INVALID_ARGS; + } + + bpf2Count = pConfig->order / 2; + + /* The filter order can't change between reinits. */ + if (!isNew) { + if (pBPF->bpf2Count != bpf2Count) { + return MA_INVALID_OPERATION; + } + } + + if (isNew) { + result = ma_bpf_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + pBPF->_pHeap = pHeap; + MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes); + + pBPF->pBPF2 = (ma_bpf2*)ma_offset_ptr(pHeap, heapLayout.bpf2Offset); + } else { + MA_ZERO_OBJECT(&heapLayout); + } + + for (ibpf2 = 0; ibpf2 < bpf2Count; ibpf2 += 1) { + ma_bpf2_config bpf2Config; + double q; + + /* TODO: Calculate Q to make this a proper Butterworth filter. */ + q = 0.707107; + + bpf2Config = ma_bpf2_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency, q); + + if (isNew) { + size_t bpf2HeapSizeInBytes; + + result = ma_bpf2_get_heap_size(&bpf2Config, &bpf2HeapSizeInBytes); + if (result == MA_SUCCESS) { + result = ma_bpf2_init_preallocated(&bpf2Config, ma_offset_ptr(pHeap, heapLayout.bpf2Offset + (sizeof(ma_bpf2) * bpf2Count) + (ibpf2 * bpf2HeapSizeInBytes)), &pBPF->pBPF2[ibpf2]); + } + } else { + result = ma_bpf2_reinit(&bpf2Config, &pBPF->pBPF2[ibpf2]); + } + + if (result != MA_SUCCESS) { + return result; + } + } + + pBPF->bpf2Count = bpf2Count; + pBPF->format = pConfig->format; + pBPF->channels = pConfig->channels; + + return MA_SUCCESS; +} + + +MA_API ma_result ma_bpf_get_heap_size(const ma_bpf_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_result result; + ma_bpf_heap_layout heapLayout; + + if (pHeapSizeInBytes == NULL) { + return MA_INVALID_ARGS; + } + + *pHeapSizeInBytes = 0; + + result = ma_bpf_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + *pHeapSizeInBytes = heapLayout.sizeInBytes; + + return MA_SUCCESS; +} + +MA_API ma_result ma_bpf_init_preallocated(const ma_bpf_config* pConfig, void* pHeap, ma_bpf* pBPF) +{ + if (pBPF == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pBPF); + + return ma_bpf_reinit__internal(pConfig, pHeap, pBPF, /*isNew*/MA_TRUE); +} + +MA_API ma_result ma_bpf_init(const ma_bpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf* pBPF) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_bpf_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_bpf_init_preallocated(pConfig, pHeap, pBPF); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pBPF->_ownsHeap = MA_TRUE; + return MA_SUCCESS; +} + +MA_API void ma_bpf_uninit(ma_bpf* pBPF, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_uint32 ibpf2; + + if (pBPF == NULL) { + return; + } + + for (ibpf2 = 0; ibpf2 < pBPF->bpf2Count; ibpf2 += 1) { + ma_bpf2_uninit(&pBPF->pBPF2[ibpf2], pAllocationCallbacks); + } + + if (pBPF->_ownsHeap) { + ma_free(pBPF->_pHeap, pAllocationCallbacks); + } +} + +MA_API ma_result ma_bpf_reinit(const ma_bpf_config* pConfig, ma_bpf* pBPF) +{ + return ma_bpf_reinit__internal(pConfig, NULL, pBPF, /*isNew*/MA_FALSE); +} + +MA_API ma_result ma_bpf_process_pcm_frames(ma_bpf* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + ma_result result; + ma_uint32 ibpf2; + + if (pBPF == NULL) { + return MA_INVALID_ARGS; + } + + /* Faster path for in-place. */ + if (pFramesOut == pFramesIn) { + for (ibpf2 = 0; ibpf2 < pBPF->bpf2Count; ibpf2 += 1) { + result = ma_bpf2_process_pcm_frames(&pBPF->pBPF2[ibpf2], pFramesOut, pFramesOut, frameCount); + if (result != MA_SUCCESS) { + return result; + } + } + } + + /* Slightly slower path for copying. */ + if (pFramesOut != pFramesIn) { + ma_uint32 iFrame; + + /* */ if (pBPF->format == ma_format_f32) { + /* */ float* pFramesOutF32 = ( float*)pFramesOut; + const float* pFramesInF32 = (const float*)pFramesIn; + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + MA_COPY_MEMORY(pFramesOutF32, pFramesInF32, ma_get_bytes_per_frame(pBPF->format, pBPF->channels)); + + for (ibpf2 = 0; ibpf2 < pBPF->bpf2Count; ibpf2 += 1) { + ma_bpf2_process_pcm_frame_f32(&pBPF->pBPF2[ibpf2], pFramesOutF32, pFramesOutF32); + } + + pFramesOutF32 += pBPF->channels; + pFramesInF32 += pBPF->channels; + } + } else if (pBPF->format == ma_format_s16) { + /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut; + const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn; + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + MA_COPY_MEMORY(pFramesOutS16, pFramesInS16, ma_get_bytes_per_frame(pBPF->format, pBPF->channels)); + + for (ibpf2 = 0; ibpf2 < pBPF->bpf2Count; ibpf2 += 1) { + ma_bpf2_process_pcm_frame_s16(&pBPF->pBPF2[ibpf2], pFramesOutS16, pFramesOutS16); + } + + pFramesOutS16 += pBPF->channels; + pFramesInS16 += pBPF->channels; + } + } else { + MA_ASSERT(MA_FALSE); + return MA_INVALID_OPERATION; /* Should never hit this. */ + } + } + + return MA_SUCCESS; +} + +MA_API ma_uint32 ma_bpf_get_latency(const ma_bpf* pBPF) +{ + if (pBPF == NULL) { + return 0; + } + + return pBPF->bpf2Count*2; +} + + +/************************************************************************************************************************************************************** + +Notching Filter + +**************************************************************************************************************************************************************/ +MA_API ma_notch2_config ma_notch2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double q, double frequency) +{ + ma_notch2_config config; + + MA_ZERO_OBJECT(&config); + config.format = format; + config.channels = channels; + config.sampleRate = sampleRate; + config.q = q; + config.frequency = frequency; + + if (config.q == 0) { + config.q = 0.707107; + } + + return config; +} + + +static MA_INLINE ma_biquad_config ma_notch2__get_biquad_config(const ma_notch2_config* pConfig) +{ + ma_biquad_config bqConfig; + double q; + double w; + double s; + double c; + double a; + + MA_ASSERT(pConfig != NULL); + + q = pConfig->q; + w = 2 * MA_PI_D * pConfig->frequency / pConfig->sampleRate; + s = ma_sind(w); + c = ma_cosd(w); + a = s / (2*q); + + bqConfig.b0 = 1; + bqConfig.b1 = -2 * c; + bqConfig.b2 = 1; + bqConfig.a0 = 1 + a; + bqConfig.a1 = -2 * c; + bqConfig.a2 = 1 - a; + + bqConfig.format = pConfig->format; + bqConfig.channels = pConfig->channels; + + return bqConfig; +} + +MA_API ma_result ma_notch2_get_heap_size(const ma_notch2_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_biquad_config bqConfig; + bqConfig = ma_notch2__get_biquad_config(pConfig); + + return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes); +} + +MA_API ma_result ma_notch2_init_preallocated(const ma_notch2_config* pConfig, void* pHeap, ma_notch2* pFilter) +{ + ma_result result; + ma_biquad_config bqConfig; + + if (pFilter == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pFilter); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + bqConfig = ma_notch2__get_biquad_config(pConfig); + result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pFilter->bq); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_notch2_init(const ma_notch2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_notch2* pFilter) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_notch2_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_notch2_init_preallocated(pConfig, pHeap, pFilter); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pFilter->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */ + return MA_SUCCESS; +} + +MA_API void ma_notch2_uninit(ma_notch2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pFilter == NULL) { + return; + } + + ma_biquad_uninit(&pFilter->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */ +} + +MA_API ma_result ma_notch2_reinit(const ma_notch2_config* pConfig, ma_notch2* pFilter) +{ + ma_result result; + ma_biquad_config bqConfig; + + if (pFilter == NULL || pConfig == NULL) { + return MA_INVALID_ARGS; + } + + bqConfig = ma_notch2__get_biquad_config(pConfig); + result = ma_biquad_reinit(&bqConfig, &pFilter->bq); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +static MA_INLINE void ma_notch2_process_pcm_frame_s16(ma_notch2* pFilter, ma_int16* pFrameOut, const ma_int16* pFrameIn) +{ + ma_biquad_process_pcm_frame_s16(&pFilter->bq, pFrameOut, pFrameIn); +} + +static MA_INLINE void ma_notch2_process_pcm_frame_f32(ma_notch2* pFilter, float* pFrameOut, const float* pFrameIn) +{ + ma_biquad_process_pcm_frame_f32(&pFilter->bq, pFrameOut, pFrameIn); +} + +MA_API ma_result ma_notch2_process_pcm_frames(ma_notch2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + if (pFilter == NULL) { + return MA_INVALID_ARGS; + } + + return ma_biquad_process_pcm_frames(&pFilter->bq, pFramesOut, pFramesIn, frameCount); +} + +MA_API ma_uint32 ma_notch2_get_latency(const ma_notch2* pFilter) +{ + if (pFilter == NULL) { + return 0; + } + + return ma_biquad_get_latency(&pFilter->bq); +} + + + +/************************************************************************************************************************************************************** + +Peaking EQ Filter + +**************************************************************************************************************************************************************/ +MA_API ma_peak2_config ma_peak2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency) +{ + ma_peak2_config config; + + MA_ZERO_OBJECT(&config); + config.format = format; + config.channels = channels; + config.sampleRate = sampleRate; + config.gainDB = gainDB; + config.q = q; + config.frequency = frequency; + + if (config.q == 0) { + config.q = 0.707107; + } + + return config; +} + + +static MA_INLINE ma_biquad_config ma_peak2__get_biquad_config(const ma_peak2_config* pConfig) +{ + ma_biquad_config bqConfig; + double q; + double w; + double s; + double c; + double a; + double A; + + MA_ASSERT(pConfig != NULL); + + q = pConfig->q; + w = 2 * MA_PI_D * pConfig->frequency / pConfig->sampleRate; + s = ma_sind(w); + c = ma_cosd(w); + a = s / (2*q); + A = ma_powd(10, (pConfig->gainDB / 40)); + + bqConfig.b0 = 1 + (a * A); + bqConfig.b1 = -2 * c; + bqConfig.b2 = 1 - (a * A); + bqConfig.a0 = 1 + (a / A); + bqConfig.a1 = -2 * c; + bqConfig.a2 = 1 - (a / A); + + bqConfig.format = pConfig->format; + bqConfig.channels = pConfig->channels; + + return bqConfig; +} + +MA_API ma_result ma_peak2_get_heap_size(const ma_peak2_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_biquad_config bqConfig; + bqConfig = ma_peak2__get_biquad_config(pConfig); + + return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes); +} + +MA_API ma_result ma_peak2_init_preallocated(const ma_peak2_config* pConfig, void* pHeap, ma_peak2* pFilter) +{ + ma_result result; + ma_biquad_config bqConfig; + + if (pFilter == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pFilter); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + bqConfig = ma_peak2__get_biquad_config(pConfig); + result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pFilter->bq); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_peak2_init(const ma_peak2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_peak2* pFilter) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_peak2_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_peak2_init_preallocated(pConfig, pHeap, pFilter); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pFilter->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */ + return MA_SUCCESS; +} + +MA_API void ma_peak2_uninit(ma_peak2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pFilter == NULL) { + return; + } + + ma_biquad_uninit(&pFilter->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */ +} + +MA_API ma_result ma_peak2_reinit(const ma_peak2_config* pConfig, ma_peak2* pFilter) +{ + ma_result result; + ma_biquad_config bqConfig; + + if (pFilter == NULL || pConfig == NULL) { + return MA_INVALID_ARGS; + } + + bqConfig = ma_peak2__get_biquad_config(pConfig); + result = ma_biquad_reinit(&bqConfig, &pFilter->bq); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +static MA_INLINE void ma_peak2_process_pcm_frame_s16(ma_peak2* pFilter, ma_int16* pFrameOut, const ma_int16* pFrameIn) +{ + ma_biquad_process_pcm_frame_s16(&pFilter->bq, pFrameOut, pFrameIn); +} + +static MA_INLINE void ma_peak2_process_pcm_frame_f32(ma_peak2* pFilter, float* pFrameOut, const float* pFrameIn) +{ + ma_biquad_process_pcm_frame_f32(&pFilter->bq, pFrameOut, pFrameIn); +} + +MA_API ma_result ma_peak2_process_pcm_frames(ma_peak2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + if (pFilter == NULL) { + return MA_INVALID_ARGS; + } + + return ma_biquad_process_pcm_frames(&pFilter->bq, pFramesOut, pFramesIn, frameCount); +} + +MA_API ma_uint32 ma_peak2_get_latency(const ma_peak2* pFilter) +{ + if (pFilter == NULL) { + return 0; + } + + return ma_biquad_get_latency(&pFilter->bq); +} + + +/************************************************************************************************************************************************************** + +Low Shelf Filter + +**************************************************************************************************************************************************************/ +MA_API ma_loshelf2_config ma_loshelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency) +{ + ma_loshelf2_config config; + + MA_ZERO_OBJECT(&config); + config.format = format; + config.channels = channels; + config.sampleRate = sampleRate; + config.gainDB = gainDB; + config.shelfSlope = shelfSlope; + config.frequency = frequency; + + return config; +} + + +static MA_INLINE ma_biquad_config ma_loshelf2__get_biquad_config(const ma_loshelf2_config* pConfig) +{ + ma_biquad_config bqConfig; + double w; + double s; + double c; + double A; + double S; + double a; + double sqrtA; + + MA_ASSERT(pConfig != NULL); + + w = 2 * MA_PI_D * pConfig->frequency / pConfig->sampleRate; + s = ma_sind(w); + c = ma_cosd(w); + A = ma_powd(10, (pConfig->gainDB / 40)); + S = pConfig->shelfSlope; + a = s/2 * ma_sqrtd((A + 1/A) * (1/S - 1) + 2); + sqrtA = 2*ma_sqrtd(A)*a; + + bqConfig.b0 = A * ((A + 1) - (A - 1)*c + sqrtA); + bqConfig.b1 = 2 * A * ((A - 1) - (A + 1)*c); + bqConfig.b2 = A * ((A + 1) - (A - 1)*c - sqrtA); + bqConfig.a0 = (A + 1) + (A - 1)*c + sqrtA; + bqConfig.a1 = -2 * ((A - 1) + (A + 1)*c); + bqConfig.a2 = (A + 1) + (A - 1)*c - sqrtA; + + bqConfig.format = pConfig->format; + bqConfig.channels = pConfig->channels; + + return bqConfig; +} + +MA_API ma_result ma_loshelf2_get_heap_size(const ma_loshelf2_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_biquad_config bqConfig; + bqConfig = ma_loshelf2__get_biquad_config(pConfig); + + return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes); +} + +MA_API ma_result ma_loshelf2_init_preallocated(const ma_loshelf2_config* pConfig, void* pHeap, ma_loshelf2* pFilter) +{ + ma_result result; + ma_biquad_config bqConfig; + + if (pFilter == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pFilter); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + bqConfig = ma_loshelf2__get_biquad_config(pConfig); + result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pFilter->bq); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_loshelf2_init(const ma_loshelf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_loshelf2* pFilter) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_loshelf2_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_loshelf2_init_preallocated(pConfig, pHeap, pFilter); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pFilter->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */ + return MA_SUCCESS; +} + +MA_API void ma_loshelf2_uninit(ma_loshelf2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pFilter == NULL) { + return; + } + + ma_biquad_uninit(&pFilter->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */ +} + +MA_API ma_result ma_loshelf2_reinit(const ma_loshelf2_config* pConfig, ma_loshelf2* pFilter) +{ + ma_result result; + ma_biquad_config bqConfig; + + if (pFilter == NULL || pConfig == NULL) { + return MA_INVALID_ARGS; + } + + bqConfig = ma_loshelf2__get_biquad_config(pConfig); + result = ma_biquad_reinit(&bqConfig, &pFilter->bq); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +static MA_INLINE void ma_loshelf2_process_pcm_frame_s16(ma_loshelf2* pFilter, ma_int16* pFrameOut, const ma_int16* pFrameIn) +{ + ma_biquad_process_pcm_frame_s16(&pFilter->bq, pFrameOut, pFrameIn); +} + +static MA_INLINE void ma_loshelf2_process_pcm_frame_f32(ma_loshelf2* pFilter, float* pFrameOut, const float* pFrameIn) +{ + ma_biquad_process_pcm_frame_f32(&pFilter->bq, pFrameOut, pFrameIn); +} + +MA_API ma_result ma_loshelf2_process_pcm_frames(ma_loshelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + if (pFilter == NULL) { + return MA_INVALID_ARGS; + } + + return ma_biquad_process_pcm_frames(&pFilter->bq, pFramesOut, pFramesIn, frameCount); +} + +MA_API ma_uint32 ma_loshelf2_get_latency(const ma_loshelf2* pFilter) +{ + if (pFilter == NULL) { + return 0; + } + + return ma_biquad_get_latency(&pFilter->bq); +} + + +/************************************************************************************************************************************************************** + +High Shelf Filter + +**************************************************************************************************************************************************************/ +MA_API ma_hishelf2_config ma_hishelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency) +{ + ma_hishelf2_config config; + + MA_ZERO_OBJECT(&config); + config.format = format; + config.channels = channels; + config.sampleRate = sampleRate; + config.gainDB = gainDB; + config.shelfSlope = shelfSlope; + config.frequency = frequency; + + return config; +} + + +static MA_INLINE ma_biquad_config ma_hishelf2__get_biquad_config(const ma_hishelf2_config* pConfig) +{ + ma_biquad_config bqConfig; + double w; + double s; + double c; + double A; + double S; + double a; + double sqrtA; + + MA_ASSERT(pConfig != NULL); + + w = 2 * MA_PI_D * pConfig->frequency / pConfig->sampleRate; + s = ma_sind(w); + c = ma_cosd(w); + A = ma_powd(10, (pConfig->gainDB / 40)); + S = pConfig->shelfSlope; + a = s/2 * ma_sqrtd((A + 1/A) * (1/S - 1) + 2); + sqrtA = 2*ma_sqrtd(A)*a; + + bqConfig.b0 = A * ((A + 1) + (A - 1)*c + sqrtA); + bqConfig.b1 = -2 * A * ((A - 1) + (A + 1)*c); + bqConfig.b2 = A * ((A + 1) + (A - 1)*c - sqrtA); + bqConfig.a0 = (A + 1) - (A - 1)*c + sqrtA; + bqConfig.a1 = 2 * ((A - 1) - (A + 1)*c); + bqConfig.a2 = (A + 1) - (A - 1)*c - sqrtA; + + bqConfig.format = pConfig->format; + bqConfig.channels = pConfig->channels; + + return bqConfig; +} + +MA_API ma_result ma_hishelf2_get_heap_size(const ma_hishelf2_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_biquad_config bqConfig; + bqConfig = ma_hishelf2__get_biquad_config(pConfig); + + return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes); +} + +MA_API ma_result ma_hishelf2_init_preallocated(const ma_hishelf2_config* pConfig, void* pHeap, ma_hishelf2* pFilter) +{ + ma_result result; + ma_biquad_config bqConfig; + + if (pFilter == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pFilter); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + bqConfig = ma_hishelf2__get_biquad_config(pConfig); + result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pFilter->bq); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_hishelf2_init(const ma_hishelf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hishelf2* pFilter) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_hishelf2_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_hishelf2_init_preallocated(pConfig, pHeap, pFilter); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pFilter->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */ + return MA_SUCCESS; +} + +MA_API void ma_hishelf2_uninit(ma_hishelf2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pFilter == NULL) { + return; + } + + ma_biquad_uninit(&pFilter->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */ +} + +MA_API ma_result ma_hishelf2_reinit(const ma_hishelf2_config* pConfig, ma_hishelf2* pFilter) +{ + ma_result result; + ma_biquad_config bqConfig; + + if (pFilter == NULL || pConfig == NULL) { + return MA_INVALID_ARGS; + } + + bqConfig = ma_hishelf2__get_biquad_config(pConfig); + result = ma_biquad_reinit(&bqConfig, &pFilter->bq); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +static MA_INLINE void ma_hishelf2_process_pcm_frame_s16(ma_hishelf2* pFilter, ma_int16* pFrameOut, const ma_int16* pFrameIn) +{ + ma_biquad_process_pcm_frame_s16(&pFilter->bq, pFrameOut, pFrameIn); +} + +static MA_INLINE void ma_hishelf2_process_pcm_frame_f32(ma_hishelf2* pFilter, float* pFrameOut, const float* pFrameIn) +{ + ma_biquad_process_pcm_frame_f32(&pFilter->bq, pFrameOut, pFrameIn); +} + +MA_API ma_result ma_hishelf2_process_pcm_frames(ma_hishelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + if (pFilter == NULL) { + return MA_INVALID_ARGS; + } + + return ma_biquad_process_pcm_frames(&pFilter->bq, pFramesOut, pFramesIn, frameCount); +} + +MA_API ma_uint32 ma_hishelf2_get_latency(const ma_hishelf2* pFilter) +{ + if (pFilter == NULL) { + return 0; + } + + return ma_biquad_get_latency(&pFilter->bq); +} + + + +/* +Delay +*/ +MA_API ma_delay_config ma_delay_config_init(ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 delayInFrames, float decay) +{ + ma_delay_config config; + + MA_ZERO_OBJECT(&config); + config.channels = channels; + config.sampleRate = sampleRate; + config.delayInFrames = delayInFrames; + config.delayStart = (decay == 0) ? MA_TRUE : MA_FALSE; /* Delay the start if it looks like we're not configuring an echo. */ + config.wet = 1; + config.dry = 1; + config.decay = decay; + + return config; +} + + +MA_API ma_result ma_delay_init(const ma_delay_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_delay* pDelay) +{ + if (pDelay == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pDelay); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->decay < 0 || pConfig->decay > 1) { + return MA_INVALID_ARGS; + } + + pDelay->config = *pConfig; + pDelay->bufferSizeInFrames = pConfig->delayInFrames; + pDelay->cursor = 0; + + pDelay->pBuffer = (float*)ma_malloc((size_t)(pDelay->bufferSizeInFrames * ma_get_bytes_per_frame(ma_format_f32, pConfig->channels)), pAllocationCallbacks); + if (pDelay->pBuffer == NULL) { + return MA_OUT_OF_MEMORY; + } + + ma_silence_pcm_frames(pDelay->pBuffer, pDelay->bufferSizeInFrames, ma_format_f32, pConfig->channels); + + return MA_SUCCESS; +} + +MA_API void ma_delay_uninit(ma_delay* pDelay, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pDelay == NULL) { + return; + } + + ma_free(pDelay->pBuffer, pAllocationCallbacks); +} + +MA_API ma_result ma_delay_process_pcm_frames(ma_delay* pDelay, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount) +{ + ma_uint32 iFrame; + ma_uint32 iChannel; + float* pFramesOutF32 = (float*)pFramesOut; + const float* pFramesInF32 = (const float*)pFramesIn; + + if (pDelay == NULL || pFramesOut == NULL || pFramesIn == NULL) { + return MA_INVALID_ARGS; + } + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannel = 0; iChannel < pDelay->config.channels; iChannel += 1) { + ma_uint32 iBuffer = (pDelay->cursor * pDelay->config.channels) + iChannel; + + if (pDelay->config.delayStart) { + /* Delayed start. */ + + /* Read */ + pFramesOutF32[iChannel] = pDelay->pBuffer[iBuffer] * pDelay->config.wet; + + /* Feedback */ + pDelay->pBuffer[iBuffer] = (pDelay->pBuffer[iBuffer] * pDelay->config.decay) + (pFramesInF32[iChannel] * pDelay->config.dry); + } else { + /* Immediate start */ + + /* Feedback */ + pDelay->pBuffer[iBuffer] = (pDelay->pBuffer[iBuffer] * pDelay->config.decay) + (pFramesInF32[iChannel] * pDelay->config.dry); + + /* Read */ + pFramesOutF32[iChannel] = pDelay->pBuffer[iBuffer] * pDelay->config.wet; + } + } + + pDelay->cursor = (pDelay->cursor + 1) % pDelay->bufferSizeInFrames; + + pFramesOutF32 += pDelay->config.channels; + pFramesInF32 += pDelay->config.channels; + } + + return MA_SUCCESS; +} + +MA_API void ma_delay_set_wet(ma_delay* pDelay, float value) +{ + if (pDelay == NULL) { + return; + } + + pDelay->config.wet = value; +} + +MA_API float ma_delay_get_wet(const ma_delay* pDelay) +{ + if (pDelay == NULL) { + return 0; + } + + return pDelay->config.wet; +} + +MA_API void ma_delay_set_dry(ma_delay* pDelay, float value) +{ + if (pDelay == NULL) { + return; + } + + pDelay->config.dry = value; +} + +MA_API float ma_delay_get_dry(const ma_delay* pDelay) +{ + if (pDelay == NULL) { + return 0; + } + + return pDelay->config.dry; +} + +MA_API void ma_delay_set_decay(ma_delay* pDelay, float value) +{ + if (pDelay == NULL) { + return; + } + + pDelay->config.decay = value; +} + +MA_API float ma_delay_get_decay(const ma_delay* pDelay) +{ + if (pDelay == NULL) { + return 0; + } + + return pDelay->config.decay; +} + + +MA_API ma_gainer_config ma_gainer_config_init(ma_uint32 channels, ma_uint32 smoothTimeInFrames) +{ + ma_gainer_config config; + + MA_ZERO_OBJECT(&config); + config.channels = channels; + config.smoothTimeInFrames = smoothTimeInFrames; + + return config; +} + + +typedef struct +{ + size_t sizeInBytes; + size_t oldGainsOffset; + size_t newGainsOffset; +} ma_gainer_heap_layout; + +static ma_result ma_gainer_get_heap_layout(const ma_gainer_config* pConfig, ma_gainer_heap_layout* pHeapLayout) +{ + MA_ASSERT(pHeapLayout != NULL); + + MA_ZERO_OBJECT(pHeapLayout); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->channels == 0) { + return MA_INVALID_ARGS; + } + + pHeapLayout->sizeInBytes = 0; + + /* Old gains. */ + pHeapLayout->oldGainsOffset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += sizeof(float) * pConfig->channels; + + /* New gains. */ + pHeapLayout->newGainsOffset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += sizeof(float) * pConfig->channels; + + /* Alignment. */ + pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes); + + return MA_SUCCESS; +} + + +MA_API ma_result ma_gainer_get_heap_size(const ma_gainer_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_result result; + ma_gainer_heap_layout heapLayout; + + if (pHeapSizeInBytes == NULL) { + return MA_INVALID_ARGS; + } + + *pHeapSizeInBytes = 0; + + result = ma_gainer_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return MA_INVALID_ARGS; + } + + *pHeapSizeInBytes = heapLayout.sizeInBytes; + + return MA_SUCCESS; +} + + +MA_API ma_result ma_gainer_init_preallocated(const ma_gainer_config* pConfig, void* pHeap, ma_gainer* pGainer) +{ + ma_result result; + ma_gainer_heap_layout heapLayout; + ma_uint32 iChannel; + + if (pGainer == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pGainer); + + if (pConfig == NULL || pHeap == NULL) { + return MA_INVALID_ARGS; + } + + result = ma_gainer_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + pGainer->_pHeap = pHeap; + MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes); + + pGainer->pOldGains = (float*)ma_offset_ptr(pHeap, heapLayout.oldGainsOffset); + pGainer->pNewGains = (float*)ma_offset_ptr(pHeap, heapLayout.newGainsOffset); + pGainer->masterVolume = 1; + + pGainer->config = *pConfig; + pGainer->t = (ma_uint32)-1; /* No interpolation by default. */ + + for (iChannel = 0; iChannel < pConfig->channels; iChannel += 1) { + pGainer->pOldGains[iChannel] = 1; + pGainer->pNewGains[iChannel] = 1; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_gainer_init(const ma_gainer_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_gainer* pGainer) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_gainer_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; /* Failed to retrieve the size of the heap allocation. */ + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_gainer_init_preallocated(pConfig, pHeap, pGainer); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pGainer->_ownsHeap = MA_TRUE; + return MA_SUCCESS; +} + +MA_API void ma_gainer_uninit(ma_gainer* pGainer, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pGainer == NULL) { + return; + } + + if (pGainer->_ownsHeap) { + ma_free(pGainer->_pHeap, pAllocationCallbacks); + } +} + +static float ma_gainer_calculate_current_gain(const ma_gainer* pGainer, ma_uint32 channel) +{ + float a = (float)pGainer->t / pGainer->config.smoothTimeInFrames; + return ma_mix_f32_fast(pGainer->pOldGains[channel], pGainer->pNewGains[channel], a); +} + +static /*__attribute__((noinline))*/ ma_result ma_gainer_process_pcm_frames_internal(ma_gainer * pGainer, void* MA_RESTRICT pFramesOut, const void* MA_RESTRICT pFramesIn, ma_uint64 frameCount) +{ + ma_uint64 iFrame; + ma_uint32 iChannel; + ma_uint64 interpolatedFrameCount; + + MA_ASSERT(pGainer != NULL); + + /* + We don't necessarily need to apply a linear interpolation for the entire frameCount frames. When + linear interpolation is not needed we can do a simple volume adjustment which will be more + efficient than a lerp with an alpha value of 1. + + To do this, all we need to do is determine how many frames need to have a lerp applied. Then we + just process that number of frames with linear interpolation. After that we run on an optimized + path which just applies the new gains without a lerp. + */ + if (pGainer->t >= pGainer->config.smoothTimeInFrames) { + interpolatedFrameCount = 0; + } else { + interpolatedFrameCount = pGainer->t - pGainer->config.smoothTimeInFrames; + if (interpolatedFrameCount > frameCount) { + interpolatedFrameCount = frameCount; + } + } + + /* + Start off with our interpolated frames. When we do this, we'll adjust frameCount and our pointers + so that the fast path can work naturally without consideration of the interpolated path. + */ + if (interpolatedFrameCount > 0) { + /* We can allow the input and output buffers to be null in which case we'll just update the internal timer. */ + if (pFramesOut != NULL && pFramesIn != NULL) { + /* + All we're really doing here is moving the old gains towards the new gains. We don't want to + be modifying the gains inside the ma_gainer object because that will break things. Instead + we can make a copy here on the stack. For extreme channel counts we can fall back to a slower + implementation which just uses a standard lerp. + */ + float* pFramesOutF32 = (float*)pFramesOut; + const float* pFramesInF32 = (const float*)pFramesIn; + float a = (float)pGainer->t / pGainer->config.smoothTimeInFrames; + float d = 1.0f / pGainer->config.smoothTimeInFrames; + + if (pGainer->config.channels <= 32) { + float pRunningGain[32]; + float pRunningGainDelta[32]; /* Could this be heap-allocated as part of the ma_gainer object? */ + + /* Initialize the running gain. */ + for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) { + float t = (pGainer->pNewGains[iChannel] - pGainer->pOldGains[iChannel]) * pGainer->masterVolume; + pRunningGainDelta[iChannel] = t * d; + pRunningGain[iChannel] = (pGainer->pOldGains[iChannel] * pGainer->masterVolume) + (t * a); + } + + iFrame = 0; + + /* Optimized paths for common channel counts. This is mostly just experimenting with some SIMD ideas. It's not necessarily final. */ + if (pGainer->config.channels == 2) { + #if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + ma_uint64 unrolledLoopCount = interpolatedFrameCount >> 1; + + /* Expand some arrays so we can have a clean SIMD loop below. */ + __m128 runningGainDelta0 = _mm_set_ps(pRunningGainDelta[1], pRunningGainDelta[0], pRunningGainDelta[1], pRunningGainDelta[0]); + __m128 runningGain0 = _mm_set_ps(pRunningGain[1] + pRunningGainDelta[1], pRunningGain[0] + pRunningGainDelta[0], pRunningGain[1], pRunningGain[0]); + + for (; iFrame < unrolledLoopCount; iFrame += 1) { + _mm_storeu_ps(&pFramesOutF32[iFrame*4 + 0], _mm_mul_ps(_mm_loadu_ps(&pFramesInF32[iFrame*4 + 0]), runningGain0)); + runningGain0 = _mm_add_ps(runningGain0, runningGainDelta0); + } + + iFrame = unrolledLoopCount << 1; + } else + #endif + { + /* + Two different scalar implementations here. Clang (and I assume GCC) will vectorize + both of these, but the bottom version results in a nicer vectorization with less + instructions emitted. The problem, however, is that the bottom version runs slower + when compiled with MSVC. The top version will be partially vectorized by MSVC. + */ + #if defined(_MSC_VER) && !defined(__clang__) + ma_uint64 unrolledLoopCount = interpolatedFrameCount >> 1; + + /* Expand some arrays so we can have a clean 4x SIMD operation in the loop. */ + pRunningGainDelta[2] = pRunningGainDelta[0]; + pRunningGainDelta[3] = pRunningGainDelta[1]; + pRunningGain[2] = pRunningGain[0] + pRunningGainDelta[0]; + pRunningGain[3] = pRunningGain[1] + pRunningGainDelta[1]; + + for (; iFrame < unrolledLoopCount; iFrame += 1) { + pFramesOutF32[iFrame*4 + 0] = pFramesInF32[iFrame*4 + 0] * pRunningGain[0]; + pFramesOutF32[iFrame*4 + 1] = pFramesInF32[iFrame*4 + 1] * pRunningGain[1]; + pFramesOutF32[iFrame*4 + 2] = pFramesInF32[iFrame*4 + 2] * pRunningGain[2]; + pFramesOutF32[iFrame*4 + 3] = pFramesInF32[iFrame*4 + 3] * pRunningGain[3]; + + /* Move the running gain forward towards the new gain. */ + pRunningGain[0] += pRunningGainDelta[0]; + pRunningGain[1] += pRunningGainDelta[1]; + pRunningGain[2] += pRunningGainDelta[2]; + pRunningGain[3] += pRunningGainDelta[3]; + } + + iFrame = unrolledLoopCount << 1; + #else + for (; iFrame < interpolatedFrameCount; iFrame += 1) { + for (iChannel = 0; iChannel < 2; iChannel += 1) { + pFramesOutF32[iFrame*2 + iChannel] = pFramesInF32[iFrame*2 + iChannel] * pRunningGain[iChannel]; + } + + for (iChannel = 0; iChannel < 2; iChannel += 1) { + pRunningGain[iChannel] += pRunningGainDelta[iChannel]; + } + } + #endif + } + } else if (pGainer->config.channels == 6) { + #if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + /* + For 6 channels things are a bit more complicated because 6 isn't cleanly divisible by 4. We need to do 2 frames + at a time, meaning we'll be doing 12 samples in a group. Like the stereo case we'll need to expand some arrays + so we can do clean 4x SIMD operations. + */ + ma_uint64 unrolledLoopCount = interpolatedFrameCount >> 1; + + /* Expand some arrays so we can have a clean SIMD loop below. */ + __m128 runningGainDelta0 = _mm_set_ps(pRunningGainDelta[3], pRunningGainDelta[2], pRunningGainDelta[1], pRunningGainDelta[0]); + __m128 runningGainDelta1 = _mm_set_ps(pRunningGainDelta[1], pRunningGainDelta[0], pRunningGainDelta[5], pRunningGainDelta[4]); + __m128 runningGainDelta2 = _mm_set_ps(pRunningGainDelta[5], pRunningGainDelta[4], pRunningGainDelta[3], pRunningGainDelta[2]); + + __m128 runningGain0 = _mm_set_ps(pRunningGain[3], pRunningGain[2], pRunningGain[1], pRunningGain[0]); + __m128 runningGain1 = _mm_set_ps(pRunningGain[1] + pRunningGainDelta[1], pRunningGain[0] + pRunningGainDelta[0], pRunningGain[5], pRunningGain[4]); + __m128 runningGain2 = _mm_set_ps(pRunningGain[5] + pRunningGainDelta[5], pRunningGain[4] + pRunningGainDelta[4], pRunningGain[3] + pRunningGainDelta[3], pRunningGain[2] + pRunningGainDelta[2]); + + for (; iFrame < unrolledLoopCount; iFrame += 1) { + _mm_storeu_ps(&pFramesOutF32[iFrame*12 + 0], _mm_mul_ps(_mm_loadu_ps(&pFramesInF32[iFrame*12 + 0]), runningGain0)); + _mm_storeu_ps(&pFramesOutF32[iFrame*12 + 4], _mm_mul_ps(_mm_loadu_ps(&pFramesInF32[iFrame*12 + 4]), runningGain1)); + _mm_storeu_ps(&pFramesOutF32[iFrame*12 + 8], _mm_mul_ps(_mm_loadu_ps(&pFramesInF32[iFrame*12 + 8]), runningGain2)); + + runningGain0 = _mm_add_ps(runningGain0, runningGainDelta0); + runningGain1 = _mm_add_ps(runningGain1, runningGainDelta1); + runningGain2 = _mm_add_ps(runningGain2, runningGainDelta2); + } + + iFrame = unrolledLoopCount << 1; + } else + #endif + { + for (; iFrame < interpolatedFrameCount; iFrame += 1) { + for (iChannel = 0; iChannel < 6; iChannel += 1) { + pFramesOutF32[iFrame*6 + iChannel] = pFramesInF32[iFrame*6 + iChannel] * pRunningGain[iChannel]; + } + + /* Move the running gain forward towards the new gain. */ + for (iChannel = 0; iChannel < 6; iChannel += 1) { + pRunningGain[iChannel] += pRunningGainDelta[iChannel]; + } + } + } + } else if (pGainer->config.channels == 8) { + /* For 8 channels we can just go over frame by frame and do all eight channels as 2 separate 4x SIMD operations. */ + #if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + __m128 runningGainDelta0 = _mm_loadu_ps(&pRunningGainDelta[0]); + __m128 runningGainDelta1 = _mm_loadu_ps(&pRunningGainDelta[4]); + __m128 runningGain0 = _mm_loadu_ps(&pRunningGain[0]); + __m128 runningGain1 = _mm_loadu_ps(&pRunningGain[4]); + + for (; iFrame < interpolatedFrameCount; iFrame += 1) { + _mm_storeu_ps(&pFramesOutF32[iFrame*8 + 0], _mm_mul_ps(_mm_loadu_ps(&pFramesInF32[iFrame*8 + 0]), runningGain0)); + _mm_storeu_ps(&pFramesOutF32[iFrame*8 + 4], _mm_mul_ps(_mm_loadu_ps(&pFramesInF32[iFrame*8 + 4]), runningGain1)); + + runningGain0 = _mm_add_ps(runningGain0, runningGainDelta0); + runningGain1 = _mm_add_ps(runningGain1, runningGainDelta1); + } + } else + #endif + { + /* This is crafted so that it auto-vectorizes when compiled with Clang. */ + for (; iFrame < interpolatedFrameCount; iFrame += 1) { + for (iChannel = 0; iChannel < 8; iChannel += 1) { + pFramesOutF32[iFrame*8 + iChannel] = pFramesInF32[iFrame*8 + iChannel] * pRunningGain[iChannel]; + } + + /* Move the running gain forward towards the new gain. */ + for (iChannel = 0; iChannel < 8; iChannel += 1) { + pRunningGain[iChannel] += pRunningGainDelta[iChannel]; + } + } + } + } + + for (; iFrame < interpolatedFrameCount; iFrame += 1) { + for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) { + pFramesOutF32[iFrame*pGainer->config.channels + iChannel] = pFramesInF32[iFrame*pGainer->config.channels + iChannel] * pRunningGain[iChannel]; + pRunningGain[iChannel] += pRunningGainDelta[iChannel]; + } + } + } else { + /* Slower path for extreme channel counts where we can't fit enough on the stack. We could also move this to the heap as part of the ma_gainer object which might even be better since it'll only be updated when the gains actually change. */ + for (iFrame = 0; iFrame < interpolatedFrameCount; iFrame += 1) { + for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) { + pFramesOutF32[iFrame*pGainer->config.channels + iChannel] = pFramesInF32[iFrame*pGainer->config.channels + iChannel] * ma_mix_f32_fast(pGainer->pOldGains[iChannel], pGainer->pNewGains[iChannel], a) * pGainer->masterVolume; + } + + a += d; + } + } + } + + /* Make sure the timer is updated. */ + pGainer->t = (ma_uint32)ma_min(pGainer->t + interpolatedFrameCount, pGainer->config.smoothTimeInFrames); + + /* Adjust our arguments so the next part can work normally. */ + frameCount -= interpolatedFrameCount; + pFramesOut = ma_offset_ptr(pFramesOut, interpolatedFrameCount * sizeof(float)); + pFramesIn = ma_offset_ptr(pFramesIn, interpolatedFrameCount * sizeof(float)); + } + + /* All we need to do here is apply the new gains using an optimized path. */ + if (pFramesOut != NULL && pFramesIn != NULL) { + if (pGainer->config.channels <= 32) { + float gains[32]; + for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) { + gains[iChannel] = pGainer->pNewGains[iChannel] * pGainer->masterVolume; + } + + ma_copy_and_apply_volume_factor_per_channel_f32((float*)pFramesOut, (const float*)pFramesIn, frameCount, pGainer->config.channels, gains); + } else { + /* Slow path. Too many channels to fit on the stack. Need to apply a master volume as a separate path. */ + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) { + ((float*)pFramesOut)[iFrame*pGainer->config.channels + iChannel] = ((const float*)pFramesIn)[iFrame*pGainer->config.channels + iChannel] * pGainer->pNewGains[iChannel] * pGainer->masterVolume; + } + } + } + } + + /* Now that some frames have been processed we need to make sure future changes to the gain are interpolated. */ + if (pGainer->t == (ma_uint32)-1) { + pGainer->t = (ma_uint32)ma_min(pGainer->config.smoothTimeInFrames, frameCount); + } + +#if 0 + if (pGainer->t >= pGainer->config.smoothTimeInFrames) { + /* Fast path. No gain calculation required. */ + ma_copy_and_apply_volume_factor_per_channel_f32(pFramesOutF32, pFramesInF32, frameCount, pGainer->config.channels, pGainer->pNewGains); + ma_apply_volume_factor_f32(pFramesOutF32, frameCount * pGainer->config.channels, pGainer->masterVolume); + + /* Now that some frames have been processed we need to make sure future changes to the gain are interpolated. */ + if (pGainer->t == (ma_uint32)-1) { + pGainer->t = pGainer->config.smoothTimeInFrames; + } + } else { + /* Slow path. Need to interpolate the gain for each channel individually. */ + + /* We can allow the input and output buffers to be null in which case we'll just update the internal timer. */ + if (pFramesOut != NULL && pFramesIn != NULL) { + float a = (float)pGainer->t / pGainer->config.smoothTimeInFrames; + float d = 1.0f / pGainer->config.smoothTimeInFrames; + ma_uint32 channelCount = pGainer->config.channels; + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannel = 0; iChannel < channelCount; iChannel += 1) { + pFramesOutF32[iChannel] = pFramesInF32[iChannel] * ma_mix_f32_fast(pGainer->pOldGains[iChannel], pGainer->pNewGains[iChannel], a) * pGainer->masterVolume; + } + + pFramesOutF32 += channelCount; + pFramesInF32 += channelCount; + + a += d; + if (a > 1) { + a = 1; + } + } + } + + pGainer->t = (ma_uint32)ma_min(pGainer->t + frameCount, pGainer->config.smoothTimeInFrames); + + #if 0 /* Reference implementation. */ + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + /* We can allow the input and output buffers to be null in which case we'll just update the internal timer. */ + if (pFramesOut != NULL && pFramesIn != NULL) { + for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) { + pFramesOutF32[iFrame * pGainer->config.channels + iChannel] = pFramesInF32[iFrame * pGainer->config.channels + iChannel] * ma_gainer_calculate_current_gain(pGainer, iChannel) * pGainer->masterVolume; + } + } + + /* Move interpolation time forward, but don't go beyond our smoothing time. */ + pGainer->t = ma_min(pGainer->t + 1, pGainer->config.smoothTimeInFrames); + } + #endif + } +#endif + + return MA_SUCCESS; +} + +MA_API ma_result ma_gainer_process_pcm_frames(ma_gainer* pGainer, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + if (pGainer == NULL) { + return MA_INVALID_ARGS; + } + + /* + ma_gainer_process_pcm_frames_internal() marks pFramesOut and pFramesIn with MA_RESTRICT which + helps with auto-vectorization. + */ + return ma_gainer_process_pcm_frames_internal(pGainer, pFramesOut, pFramesIn, frameCount); +} + +static void ma_gainer_set_gain_by_index(ma_gainer* pGainer, float newGain, ma_uint32 iChannel) +{ + pGainer->pOldGains[iChannel] = ma_gainer_calculate_current_gain(pGainer, iChannel); + pGainer->pNewGains[iChannel] = newGain; +} + +static void ma_gainer_reset_smoothing_time(ma_gainer* pGainer) +{ + if (pGainer->t == (ma_uint32)-1) { + pGainer->t = pGainer->config.smoothTimeInFrames; /* No smoothing required for initial gains setting. */ + } else { + pGainer->t = 0; + } +} + +MA_API ma_result ma_gainer_set_gain(ma_gainer* pGainer, float newGain) +{ + ma_uint32 iChannel; + + if (pGainer == NULL) { + return MA_INVALID_ARGS; + } + + for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) { + ma_gainer_set_gain_by_index(pGainer, newGain, iChannel); + } + + /* The smoothing time needs to be reset to ensure we always interpolate by the configured smoothing time, but only if it's not the first setting. */ + ma_gainer_reset_smoothing_time(pGainer); + + return MA_SUCCESS; +} + +MA_API ma_result ma_gainer_set_gains(ma_gainer* pGainer, float* pNewGains) +{ + ma_uint32 iChannel; + + if (pGainer == NULL || pNewGains == NULL) { + return MA_INVALID_ARGS; + } + + for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) { + ma_gainer_set_gain_by_index(pGainer, pNewGains[iChannel], iChannel); + } + + /* The smoothing time needs to be reset to ensure we always interpolate by the configured smoothing time, but only if it's not the first setting. */ + ma_gainer_reset_smoothing_time(pGainer); + + return MA_SUCCESS; +} + +MA_API ma_result ma_gainer_set_master_volume(ma_gainer* pGainer, float volume) +{ + if (pGainer == NULL) { + return MA_INVALID_ARGS; + } + + pGainer->masterVolume = volume; + + return MA_SUCCESS; +} + +MA_API ma_result ma_gainer_get_master_volume(const ma_gainer* pGainer, float* pVolume) +{ + if (pGainer == NULL || pVolume == NULL) { + return MA_INVALID_ARGS; + } + + *pVolume = pGainer->masterVolume; + + return MA_SUCCESS; +} + + +MA_API ma_panner_config ma_panner_config_init(ma_format format, ma_uint32 channels) +{ + ma_panner_config config; + + MA_ZERO_OBJECT(&config); + config.format = format; + config.channels = channels; + config.mode = ma_pan_mode_balance; /* Set to balancing mode by default because it's consistent with other audio engines and most likely what the caller is expecting. */ + config.pan = 0; + + return config; +} + + +MA_API ma_result ma_panner_init(const ma_panner_config* pConfig, ma_panner* pPanner) +{ + if (pPanner == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pPanner); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + pPanner->format = pConfig->format; + pPanner->channels = pConfig->channels; + pPanner->mode = pConfig->mode; + pPanner->pan = pConfig->pan; + + return MA_SUCCESS; +} + +static void ma_stereo_balance_pcm_frames_f32(float* pFramesOut, const float* pFramesIn, ma_uint64 frameCount, float pan) +{ + ma_uint64 iFrame; + + if (pan > 0) { + float factor = 1.0f - pan; + if (pFramesOut == pFramesIn) { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + pFramesOut[iFrame*2 + 0] = pFramesIn[iFrame*2 + 0] * factor; + } + } else { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + pFramesOut[iFrame*2 + 0] = pFramesIn[iFrame*2 + 0] * factor; + pFramesOut[iFrame*2 + 1] = pFramesIn[iFrame*2 + 1]; + } + } + } else { + float factor = 1.0f + pan; + if (pFramesOut == pFramesIn) { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + pFramesOut[iFrame*2 + 1] = pFramesIn[iFrame*2 + 1] * factor; + } + } else { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + pFramesOut[iFrame*2 + 0] = pFramesIn[iFrame*2 + 0]; + pFramesOut[iFrame*2 + 1] = pFramesIn[iFrame*2 + 1] * factor; + } + } + } +} + +static void ma_stereo_balance_pcm_frames(void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount, ma_format format, float pan) +{ + if (pan == 0) { + /* Fast path. No panning required. */ + if (pFramesOut == pFramesIn) { + /* No-op */ + } else { + ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, format, 2); + } + + return; + } + + switch (format) { + case ma_format_f32: ma_stereo_balance_pcm_frames_f32((float*)pFramesOut, (float*)pFramesIn, frameCount, pan); break; + + /* Unknown format. Just copy. */ + default: + { + ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, format, 2); + } break; + } +} + + +static void ma_stereo_pan_pcm_frames_f32(float* pFramesOut, const float* pFramesIn, ma_uint64 frameCount, float pan) +{ + ma_uint64 iFrame; + + if (pan > 0) { + float factorL0 = 1.0f - pan; + float factorL1 = 0.0f + pan; + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + float sample0 = (pFramesIn[iFrame*2 + 0] * factorL0); + float sample1 = (pFramesIn[iFrame*2 + 0] * factorL1) + pFramesIn[iFrame*2 + 1]; + + pFramesOut[iFrame*2 + 0] = sample0; + pFramesOut[iFrame*2 + 1] = sample1; + } + } else { + float factorR0 = 0.0f - pan; + float factorR1 = 1.0f + pan; + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + float sample0 = pFramesIn[iFrame*2 + 0] + (pFramesIn[iFrame*2 + 1] * factorR0); + float sample1 = (pFramesIn[iFrame*2 + 1] * factorR1); + + pFramesOut[iFrame*2 + 0] = sample0; + pFramesOut[iFrame*2 + 1] = sample1; + } + } +} + +static void ma_stereo_pan_pcm_frames(void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount, ma_format format, float pan) +{ + if (pan == 0) { + /* Fast path. No panning required. */ + if (pFramesOut == pFramesIn) { + /* No-op */ + } else { + ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, format, 2); + } + + return; + } + + switch (format) { + case ma_format_f32: ma_stereo_pan_pcm_frames_f32((float*)pFramesOut, (float*)pFramesIn, frameCount, pan); break; + + /* Unknown format. Just copy. */ + default: + { + ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, format, 2); + } break; + } +} + +MA_API ma_result ma_panner_process_pcm_frames(ma_panner* pPanner, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + if (pPanner == NULL || pFramesOut == NULL || pFramesIn == NULL) { + return MA_INVALID_ARGS; + } + + if (pPanner->channels == 2) { + /* Stereo case. For now assume channel 0 is left and channel right is 1, but should probably add support for a channel map. */ + if (pPanner->mode == ma_pan_mode_balance) { + ma_stereo_balance_pcm_frames(pFramesOut, pFramesIn, frameCount, pPanner->format, pPanner->pan); + } else { + ma_stereo_pan_pcm_frames(pFramesOut, pFramesIn, frameCount, pPanner->format, pPanner->pan); + } + } else { + if (pPanner->channels == 1) { + /* Panning has no effect on mono streams. */ + ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, pPanner->format, pPanner->channels); + } else { + /* For now we're not going to support non-stereo set ups. Not sure how I want to handle this case just yet. */ + ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, pPanner->format, pPanner->channels); + } + } + + return MA_SUCCESS; +} + +MA_API void ma_panner_set_mode(ma_panner* pPanner, ma_pan_mode mode) +{ + if (pPanner == NULL) { + return; + } + + pPanner->mode = mode; +} + +MA_API ma_pan_mode ma_panner_get_mode(const ma_panner* pPanner) +{ + if (pPanner == NULL) { + return ma_pan_mode_balance; + } + + return pPanner->mode; +} + +MA_API void ma_panner_set_pan(ma_panner* pPanner, float pan) +{ + if (pPanner == NULL) { + return; + } + + pPanner->pan = ma_clamp(pan, -1.0f, 1.0f); +} + +MA_API float ma_panner_get_pan(const ma_panner* pPanner) +{ + if (pPanner == NULL) { + return 0; + } + + return pPanner->pan; +} + + + + +MA_API ma_fader_config ma_fader_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate) +{ + ma_fader_config config; + + MA_ZERO_OBJECT(&config); + config.format = format; + config.channels = channels; + config.sampleRate = sampleRate; + + return config; +} + + +MA_API ma_result ma_fader_init(const ma_fader_config* pConfig, ma_fader* pFader) +{ + if (pFader == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pFader); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + /* Only f32 is supported for now. */ + if (pConfig->format != ma_format_f32) { + return MA_INVALID_ARGS; + } + + pFader->config = *pConfig; + pFader->volumeBeg = 1; + pFader->volumeEnd = 1; + pFader->lengthInFrames = 0; + pFader->cursorInFrames = 0; + + return MA_SUCCESS; +} + +MA_API ma_result ma_fader_process_pcm_frames(ma_fader* pFader, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + if (pFader == NULL) { + return MA_INVALID_ARGS; + } + + /* If the cursor is still negative we need to just copy the absolute number of those frames, but no more than frameCount. */ + if (pFader->cursorInFrames < 0) { + ma_uint64 absCursorInFrames = (ma_uint64)0 - pFader->cursorInFrames; + if (absCursorInFrames > frameCount) { + absCursorInFrames = frameCount; + } + + ma_copy_pcm_frames(pFramesOut, pFramesIn, absCursorInFrames, pFader->config.format, pFader->config.channels); + + pFader->cursorInFrames += absCursorInFrames; + frameCount -= absCursorInFrames; + pFramesOut = ma_offset_ptr(pFramesOut, ma_get_bytes_per_frame(pFader->config.format, pFader->config.channels)*absCursorInFrames); + pFramesIn = ma_offset_ptr(pFramesIn, ma_get_bytes_per_frame(pFader->config.format, pFader->config.channels)*absCursorInFrames); + } + + if (pFader->cursorInFrames >= 0) { + /* + For now we need to clamp frameCount so that the cursor never overflows 32-bits. This is required for + the conversion to a float which we use for the linear interpolation. This might be changed later. + */ + if (frameCount + pFader->cursorInFrames > UINT_MAX) { + frameCount = UINT_MAX - pFader->cursorInFrames; + } + + /* Optimized path if volumeBeg and volumeEnd are equal. */ + if (pFader->volumeBeg == pFader->volumeEnd) { + if (pFader->volumeBeg == 1) { + /* Straight copy. */ + ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, pFader->config.format, pFader->config.channels); + } else { + /* Copy with volume. */ + ma_copy_and_apply_volume_and_clip_pcm_frames(pFramesOut, pFramesIn, frameCount, pFader->config.format, pFader->config.channels, pFader->volumeBeg); + } + } else { + /* Slower path. Volumes are different, so may need to do an interpolation. */ + if ((ma_uint64)pFader->cursorInFrames >= pFader->lengthInFrames) { + /* Fast path. We've gone past the end of the fade period so just apply the end volume to all samples. */ + ma_copy_and_apply_volume_and_clip_pcm_frames(pFramesOut, pFramesIn, frameCount, pFader->config.format, pFader->config.channels, pFader->volumeEnd); + } else { + /* Slow path. This is where we do the actual fading. */ + ma_uint64 iFrame; + ma_uint32 iChannel; + + /* For now we only support f32. Support for other formats might be added later. */ + if (pFader->config.format == ma_format_f32) { + const float* pFramesInF32 = (const float*)pFramesIn; + /* */ float* pFramesOutF32 = ( float*)pFramesOut; + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + float a = (ma_uint32)ma_min(pFader->cursorInFrames + iFrame, pFader->lengthInFrames) / (float)((ma_uint32)pFader->lengthInFrames); /* Safe cast due to the frameCount clamp at the top of this function. */ + float volume = ma_mix_f32_fast(pFader->volumeBeg, pFader->volumeEnd, a); + + for (iChannel = 0; iChannel < pFader->config.channels; iChannel += 1) { + pFramesOutF32[iFrame*pFader->config.channels + iChannel] = pFramesInF32[iFrame*pFader->config.channels + iChannel] * volume; + } + } + } else { + return MA_NOT_IMPLEMENTED; + } + } + } + } + + pFader->cursorInFrames += frameCount; + + return MA_SUCCESS; +} + +MA_API void ma_fader_get_data_format(const ma_fader* pFader, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate) +{ + if (pFader == NULL) { + return; + } + + if (pFormat != NULL) { + *pFormat = pFader->config.format; + } + + if (pChannels != NULL) { + *pChannels = pFader->config.channels; + } + + if (pSampleRate != NULL) { + *pSampleRate = pFader->config.sampleRate; + } +} + +MA_API void ma_fader_set_fade(ma_fader* pFader, float volumeBeg, float volumeEnd, ma_uint64 lengthInFrames) +{ + ma_fader_set_fade_ex(pFader, volumeBeg, volumeEnd, lengthInFrames, 0); +} + +MA_API void ma_fader_set_fade_ex(ma_fader* pFader, float volumeBeg, float volumeEnd, ma_uint64 lengthInFrames, ma_int64 startOffsetInFrames) +{ + if (pFader == NULL) { + return; + } + + /* If the volume is negative, use current volume. */ + if (volumeBeg < 0) { + volumeBeg = ma_fader_get_current_volume(pFader); + } + + /* + The length needs to be clamped to 32-bits due to how we convert it to a float for linear + interpolation reasons. I might change this requirement later, but for now it's not important. + */ + if (lengthInFrames > UINT_MAX) { + lengthInFrames = UINT_MAX; + } + + /* The start offset needs to be clamped to ensure it doesn't overflow a signed number. */ + if (startOffsetInFrames > INT_MAX) { + startOffsetInFrames = INT_MAX; + } + + pFader->volumeBeg = volumeBeg; + pFader->volumeEnd = volumeEnd; + pFader->lengthInFrames = lengthInFrames; + pFader->cursorInFrames = -startOffsetInFrames; +} + +MA_API float ma_fader_get_current_volume(const ma_fader* pFader) +{ + if (pFader == NULL) { + return 0.0f; + } + + /* Any frames prior to the start of the fade period will be at unfaded volume. */ + if (pFader->cursorInFrames < 0) { + return 1.0f; + } + + /* The current volume depends on the position of the cursor. */ + if (pFader->cursorInFrames == 0) { + return pFader->volumeBeg; + } else if ((ma_uint64)pFader->cursorInFrames >= pFader->lengthInFrames) { /* Safe case because the < 0 case was checked above. */ + return pFader->volumeEnd; + } else { + /* The cursor is somewhere inside the fading period. We can figure this out with a simple linear interpoluation between volumeBeg and volumeEnd based on our cursor position. */ + return ma_mix_f32_fast(pFader->volumeBeg, pFader->volumeEnd, (ma_uint32)pFader->cursorInFrames / (float)((ma_uint32)pFader->lengthInFrames)); /* Safe cast to uint32 because we clamp it in ma_fader_process_pcm_frames(). */ + } +} + + + + + +MA_API ma_vec3f ma_vec3f_init_3f(float x, float y, float z) +{ + ma_vec3f v; + + v.x = x; + v.y = y; + v.z = z; + + return v; +} + +MA_API ma_vec3f ma_vec3f_sub(ma_vec3f a, ma_vec3f b) +{ + return ma_vec3f_init_3f( + a.x - b.x, + a.y - b.y, + a.z - b.z + ); +} + +MA_API ma_vec3f ma_vec3f_neg(ma_vec3f a) +{ + return ma_vec3f_init_3f( + -a.x, + -a.y, + -a.z + ); +} + +MA_API float ma_vec3f_dot(ma_vec3f a, ma_vec3f b) +{ + return a.x*b.x + a.y*b.y + a.z*b.z; +} + +MA_API float ma_vec3f_len2(ma_vec3f v) +{ + return ma_vec3f_dot(v, v); +} + +MA_API float ma_vec3f_len(ma_vec3f v) +{ + return (float)ma_sqrtd(ma_vec3f_len2(v)); +} + + + +MA_API float ma_vec3f_dist(ma_vec3f a, ma_vec3f b) +{ + return ma_vec3f_len(ma_vec3f_sub(a, b)); +} + +MA_API ma_vec3f ma_vec3f_normalize(ma_vec3f v) +{ + float invLen; + float len2 = ma_vec3f_len2(v); + if (len2 == 0) { + return ma_vec3f_init_3f(0, 0, 0); + } + + invLen = ma_rsqrtf(len2); + v.x *= invLen; + v.y *= invLen; + v.z *= invLen; + + return v; +} + +MA_API ma_vec3f ma_vec3f_cross(ma_vec3f a, ma_vec3f b) +{ + return ma_vec3f_init_3f( + a.y*b.z - a.z*b.y, + a.z*b.x - a.x*b.z, + a.x*b.y - a.y*b.x + ); +} + + +MA_API void ma_atomic_vec3f_init(ma_atomic_vec3f* v, ma_vec3f value) +{ + v->v = value; + v->lock = 0; /* Important this is initialized to 0. */ +} + +MA_API void ma_atomic_vec3f_set(ma_atomic_vec3f* v, ma_vec3f value) +{ + ma_spinlock_lock(&v->lock); + { + v->v = value; + } + ma_spinlock_unlock(&v->lock); +} + +MA_API ma_vec3f ma_atomic_vec3f_get(ma_atomic_vec3f* v) +{ + ma_vec3f r; + + ma_spinlock_lock(&v->lock); + { + r = v->v; + } + ma_spinlock_unlock(&v->lock); + + return r; +} + + + +static void ma_channel_map_apply_f32(float* pFramesOut, const ma_channel* pChannelMapOut, ma_uint32 channelsOut, const float* pFramesIn, const ma_channel* pChannelMapIn, ma_uint32 channelsIn, ma_uint64 frameCount, ma_channel_mix_mode mode, ma_mono_expansion_mode monoExpansionMode); +static ma_bool32 ma_is_spatial_channel_position(ma_channel channelPosition); + + +#ifndef MA_DEFAULT_SPEED_OF_SOUND +#define MA_DEFAULT_SPEED_OF_SOUND 343.3f +#endif + +/* +These vectors represent the direction that speakers are facing from the center point. They're used +for panning in the spatializer. Must be normalized. +*/ +static ma_vec3f g_maChannelDirections[MA_CHANNEL_POSITION_COUNT] = { + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_NONE */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_MONO */ + {-0.7071f, 0.0f, -0.7071f }, /* MA_CHANNEL_FRONT_LEFT */ + {+0.7071f, 0.0f, -0.7071f }, /* MA_CHANNEL_FRONT_RIGHT */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_FRONT_CENTER */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_LFE */ + {-0.7071f, 0.0f, +0.7071f }, /* MA_CHANNEL_BACK_LEFT */ + {+0.7071f, 0.0f, +0.7071f }, /* MA_CHANNEL_BACK_RIGHT */ + {-0.3162f, 0.0f, -0.9487f }, /* MA_CHANNEL_FRONT_LEFT_CENTER */ + {+0.3162f, 0.0f, -0.9487f }, /* MA_CHANNEL_FRONT_RIGHT_CENTER */ + { 0.0f, 0.0f, +1.0f }, /* MA_CHANNEL_BACK_CENTER */ + {-1.0f, 0.0f, 0.0f }, /* MA_CHANNEL_SIDE_LEFT */ + {+1.0f, 0.0f, 0.0f }, /* MA_CHANNEL_SIDE_RIGHT */ + { 0.0f, +1.0f, 0.0f }, /* MA_CHANNEL_TOP_CENTER */ + {-0.5774f, +0.5774f, -0.5774f }, /* MA_CHANNEL_TOP_FRONT_LEFT */ + { 0.0f, +0.7071f, -0.7071f }, /* MA_CHANNEL_TOP_FRONT_CENTER */ + {+0.5774f, +0.5774f, -0.5774f }, /* MA_CHANNEL_TOP_FRONT_RIGHT */ + {-0.5774f, +0.5774f, +0.5774f }, /* MA_CHANNEL_TOP_BACK_LEFT */ + { 0.0f, +0.7071f, +0.7071f }, /* MA_CHANNEL_TOP_BACK_CENTER */ + {+0.5774f, +0.5774f, +0.5774f }, /* MA_CHANNEL_TOP_BACK_RIGHT */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_0 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_1 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_2 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_3 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_4 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_5 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_6 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_7 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_8 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_9 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_10 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_11 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_12 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_13 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_14 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_15 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_16 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_17 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_18 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_19 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_20 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_21 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_22 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_23 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_24 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_25 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_26 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_27 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_28 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_29 */ + { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_30 */ + { 0.0f, 0.0f, -1.0f } /* MA_CHANNEL_AUX_31 */ +}; + +static ma_vec3f ma_get_channel_direction(ma_channel channel) +{ + if (channel >= MA_CHANNEL_POSITION_COUNT) { + return ma_vec3f_init_3f(0, 0, -1); + } else { + return g_maChannelDirections[channel]; + } +} + + + +static float ma_attenuation_inverse(float distance, float minDistance, float maxDistance, float rolloff) +{ + if (minDistance >= maxDistance) { + return 1; /* To avoid division by zero. Do not attenuate. */ + } + + return minDistance / (minDistance + rolloff * (ma_clamp(distance, minDistance, maxDistance) - minDistance)); +} + +static float ma_attenuation_linear(float distance, float minDistance, float maxDistance, float rolloff) +{ + if (minDistance >= maxDistance) { + return 1; /* To avoid division by zero. Do not attenuate. */ + } + + return 1 - rolloff * (ma_clamp(distance, minDistance, maxDistance) - minDistance) / (maxDistance - minDistance); +} + +static float ma_attenuation_exponential(float distance, float minDistance, float maxDistance, float rolloff) +{ + if (minDistance >= maxDistance) { + return 1; /* To avoid division by zero. Do not attenuate. */ + } + + return (float)ma_powd(ma_clamp(distance, minDistance, maxDistance) / minDistance, -rolloff); +} + + +/* +Dopper Effect calculation taken from the OpenAL spec, with two main differences: + + 1) The source to listener vector will have already been calcualted at an earlier step so we can + just use that directly. We need only the position of the source relative to the origin. + + 2) We don't scale by a frequency because we actually just want the ratio which we'll plug straight + into the resampler directly. +*/ +static float ma_doppler_pitch(ma_vec3f relativePosition, ma_vec3f sourceVelocity, ma_vec3f listenVelocity, float speedOfSound, float dopplerFactor) +{ + float len; + float vls; + float vss; + + len = ma_vec3f_len(relativePosition); + + /* + There's a case where the position of the source will be right on top of the listener in which + case the length will be 0 and we'll end up with a division by zero. We can just return a ratio + of 1.0 in this case. This is not considered in the OpenAL spec, but is necessary. + */ + if (len == 0) { + return 1.0; + } + + vls = ma_vec3f_dot(relativePosition, listenVelocity) / len; + vss = ma_vec3f_dot(relativePosition, sourceVelocity) / len; + + vls = ma_min(vls, speedOfSound / dopplerFactor); + vss = ma_min(vss, speedOfSound / dopplerFactor); + + return (speedOfSound - dopplerFactor*vls) / (speedOfSound - dopplerFactor*vss); +} + + +static void ma_get_default_channel_map_for_spatializer(ma_channel* pChannelMap, size_t channelMapCap, ma_uint32 channelCount) +{ + /* + Special case for stereo. Want to default the left and right speakers to side left and side + right so that they're facing directly down the X axis rather than slightly forward. Not + doing this will result in sounds being quieter when behind the listener. This might + actually be good for some scenerios, but I don't think it's an appropriate default because + it can be a bit unexpected. + */ + if (channelCount == 2) { + pChannelMap[0] = MA_CHANNEL_SIDE_LEFT; + pChannelMap[1] = MA_CHANNEL_SIDE_RIGHT; + } else { + ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, channelCount); + } +} + + +MA_API ma_spatializer_listener_config ma_spatializer_listener_config_init(ma_uint32 channelsOut) +{ + ma_spatializer_listener_config config; + + MA_ZERO_OBJECT(&config); + config.channelsOut = channelsOut; + config.pChannelMapOut = NULL; + config.handedness = ma_handedness_right; + config.worldUp = ma_vec3f_init_3f(0, 1, 0); + config.coneInnerAngleInRadians = 6.283185f; /* 360 degrees. */ + config.coneOuterAngleInRadians = 6.283185f; /* 360 degrees. */ + config.coneOuterGain = 0; + config.speedOfSound = 343.3f; /* Same as OpenAL. Used for doppler effect. */ + + return config; +} + + +typedef struct +{ + size_t sizeInBytes; + size_t channelMapOutOffset; +} ma_spatializer_listener_heap_layout; + +static ma_result ma_spatializer_listener_get_heap_layout(const ma_spatializer_listener_config* pConfig, ma_spatializer_listener_heap_layout* pHeapLayout) +{ + MA_ASSERT(pHeapLayout != NULL); + + MA_ZERO_OBJECT(pHeapLayout); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->channelsOut == 0) { + return MA_INVALID_ARGS; + } + + pHeapLayout->sizeInBytes = 0; + + /* Channel map. We always need this, even for passthroughs. */ + pHeapLayout->channelMapOutOffset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += ma_align_64(sizeof(*pConfig->pChannelMapOut) * pConfig->channelsOut); + + return MA_SUCCESS; +} + + +MA_API ma_result ma_spatializer_listener_get_heap_size(const ma_spatializer_listener_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_result result; + ma_spatializer_listener_heap_layout heapLayout; + + if (pHeapSizeInBytes == NULL) { + return MA_INVALID_ARGS; + } + + *pHeapSizeInBytes = 0; + + result = ma_spatializer_listener_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + *pHeapSizeInBytes = heapLayout.sizeInBytes; + + return MA_SUCCESS; +} + +MA_API ma_result ma_spatializer_listener_init_preallocated(const ma_spatializer_listener_config* pConfig, void* pHeap, ma_spatializer_listener* pListener) +{ + ma_result result; + ma_spatializer_listener_heap_layout heapLayout; + + if (pListener == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pListener); + + result = ma_spatializer_listener_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + pListener->_pHeap = pHeap; + MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes); + + pListener->config = *pConfig; + ma_atomic_vec3f_init(&pListener->position, ma_vec3f_init_3f(0, 0, 0)); + ma_atomic_vec3f_init(&pListener->direction, ma_vec3f_init_3f(0, 0, -1)); + ma_atomic_vec3f_init(&pListener->velocity, ma_vec3f_init_3f(0, 0, 0)); + pListener->isEnabled = MA_TRUE; + + /* Swap the forward direction if we're left handed (it was initialized based on right handed). */ + if (pListener->config.handedness == ma_handedness_left) { + ma_vec3f negDir = ma_vec3f_neg(ma_spatializer_listener_get_direction(pListener)); + ma_spatializer_listener_set_direction(pListener, negDir.x, negDir.y, negDir.z); + } + + + /* We must always have a valid channel map. */ + pListener->config.pChannelMapOut = (ma_channel*)ma_offset_ptr(pHeap, heapLayout.channelMapOutOffset); + + /* Use a slightly different default channel map for stereo. */ + if (pConfig->pChannelMapOut == NULL) { + ma_get_default_channel_map_for_spatializer(pListener->config.pChannelMapOut, pConfig->channelsOut, pConfig->channelsOut); + } else { + ma_channel_map_copy_or_default(pListener->config.pChannelMapOut, pConfig->channelsOut, pConfig->pChannelMapOut, pConfig->channelsOut); + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_spatializer_listener_init(const ma_spatializer_listener_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_spatializer_listener* pListener) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_spatializer_listener_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_spatializer_listener_init_preallocated(pConfig, pHeap, pListener); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pListener->_ownsHeap = MA_TRUE; + return MA_SUCCESS; +} + +MA_API void ma_spatializer_listener_uninit(ma_spatializer_listener* pListener, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pListener == NULL) { + return; + } + + if (pListener->_ownsHeap) { + ma_free(pListener->_pHeap, pAllocationCallbacks); + } +} + +MA_API ma_channel* ma_spatializer_listener_get_channel_map(ma_spatializer_listener* pListener) +{ + if (pListener == NULL) { + return NULL; + } + + return pListener->config.pChannelMapOut; +} + +MA_API void ma_spatializer_listener_set_cone(ma_spatializer_listener* pListener, float innerAngleInRadians, float outerAngleInRadians, float outerGain) +{ + if (pListener == NULL) { + return; + } + + pListener->config.coneInnerAngleInRadians = innerAngleInRadians; + pListener->config.coneOuterAngleInRadians = outerAngleInRadians; + pListener->config.coneOuterGain = outerGain; +} + +MA_API void ma_spatializer_listener_get_cone(const ma_spatializer_listener* pListener, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain) +{ + if (pListener == NULL) { + return; + } + + if (pInnerAngleInRadians != NULL) { + *pInnerAngleInRadians = pListener->config.coneInnerAngleInRadians; + } + + if (pOuterAngleInRadians != NULL) { + *pOuterAngleInRadians = pListener->config.coneOuterAngleInRadians; + } + + if (pOuterGain != NULL) { + *pOuterGain = pListener->config.coneOuterGain; + } +} + +MA_API void ma_spatializer_listener_set_position(ma_spatializer_listener* pListener, float x, float y, float z) +{ + if (pListener == NULL) { + return; + } + + ma_atomic_vec3f_set(&pListener->position, ma_vec3f_init_3f(x, y, z)); +} + +MA_API ma_vec3f ma_spatializer_listener_get_position(const ma_spatializer_listener* pListener) +{ + if (pListener == NULL) { + return ma_vec3f_init_3f(0, 0, 0); + } + + return ma_atomic_vec3f_get((ma_atomic_vec3f*)&pListener->position); /* Naughty const-cast. It's just for atomically loading the vec3 which should be safe. */ +} + +MA_API void ma_spatializer_listener_set_direction(ma_spatializer_listener* pListener, float x, float y, float z) +{ + if (pListener == NULL) { + return; + } + + ma_atomic_vec3f_set(&pListener->direction, ma_vec3f_init_3f(x, y, z)); +} + +MA_API ma_vec3f ma_spatializer_listener_get_direction(const ma_spatializer_listener* pListener) +{ + if (pListener == NULL) { + return ma_vec3f_init_3f(0, 0, -1); + } + + return ma_atomic_vec3f_get((ma_atomic_vec3f*)&pListener->direction); /* Naughty const-cast. It's just for atomically loading the vec3 which should be safe. */ +} + +MA_API void ma_spatializer_listener_set_velocity(ma_spatializer_listener* pListener, float x, float y, float z) +{ + if (pListener == NULL) { + return; + } + + ma_atomic_vec3f_set(&pListener->velocity, ma_vec3f_init_3f(x, y, z)); +} + +MA_API ma_vec3f ma_spatializer_listener_get_velocity(const ma_spatializer_listener* pListener) +{ + if (pListener == NULL) { + return ma_vec3f_init_3f(0, 0, 0); + } + + return ma_atomic_vec3f_get((ma_atomic_vec3f*)&pListener->velocity); /* Naughty const-cast. It's just for atomically loading the vec3 which should be safe. */ +} + +MA_API void ma_spatializer_listener_set_speed_of_sound(ma_spatializer_listener* pListener, float speedOfSound) +{ + if (pListener == NULL) { + return; + } + + pListener->config.speedOfSound = speedOfSound; +} + +MA_API float ma_spatializer_listener_get_speed_of_sound(const ma_spatializer_listener* pListener) +{ + if (pListener == NULL) { + return 0; + } + + return pListener->config.speedOfSound; +} + +MA_API void ma_spatializer_listener_set_world_up(ma_spatializer_listener* pListener, float x, float y, float z) +{ + if (pListener == NULL) { + return; + } + + pListener->config.worldUp = ma_vec3f_init_3f(x, y, z); +} + +MA_API ma_vec3f ma_spatializer_listener_get_world_up(const ma_spatializer_listener* pListener) +{ + if (pListener == NULL) { + return ma_vec3f_init_3f(0, 1, 0); + } + + return pListener->config.worldUp; +} + +MA_API void ma_spatializer_listener_set_enabled(ma_spatializer_listener* pListener, ma_bool32 isEnabled) +{ + if (pListener == NULL) { + return; + } + + pListener->isEnabled = isEnabled; +} + +MA_API ma_bool32 ma_spatializer_listener_is_enabled(const ma_spatializer_listener* pListener) +{ + if (pListener == NULL) { + return MA_FALSE; + } + + return pListener->isEnabled; +} + + + + +MA_API ma_spatializer_config ma_spatializer_config_init(ma_uint32 channelsIn, ma_uint32 channelsOut) +{ + ma_spatializer_config config; + + MA_ZERO_OBJECT(&config); + config.channelsIn = channelsIn; + config.channelsOut = channelsOut; + config.pChannelMapIn = NULL; + config.attenuationModel = ma_attenuation_model_inverse; + config.positioning = ma_positioning_absolute; + config.handedness = ma_handedness_right; + config.minGain = 0; + config.maxGain = 1; + config.minDistance = 1; + config.maxDistance = MA_FLT_MAX; + config.rolloff = 1; + config.coneInnerAngleInRadians = 6.283185f; /* 360 degrees. */ + config.coneOuterAngleInRadians = 6.283185f; /* 360 degress. */ + config.coneOuterGain = 0.0f; + config.dopplerFactor = 1; + config.directionalAttenuationFactor = 1; + config.minSpatializationChannelGain = 0.2f; + config.gainSmoothTimeInFrames = 360; /* 7.5ms @ 48K. */ + + return config; +} + + +static ma_gainer_config ma_spatializer_gainer_config_init(const ma_spatializer_config* pConfig) +{ + MA_ASSERT(pConfig != NULL); + return ma_gainer_config_init(pConfig->channelsOut, pConfig->gainSmoothTimeInFrames); +} + +static ma_result ma_spatializer_validate_config(const ma_spatializer_config* pConfig) +{ + MA_ASSERT(pConfig != NULL); + + if (pConfig->channelsIn == 0 || pConfig->channelsOut == 0) { + return MA_INVALID_ARGS; + } + + return MA_SUCCESS; +} + +typedef struct +{ + size_t sizeInBytes; + size_t channelMapInOffset; + size_t newChannelGainsOffset; + size_t gainerOffset; +} ma_spatializer_heap_layout; + +static ma_result ma_spatializer_get_heap_layout(const ma_spatializer_config* pConfig, ma_spatializer_heap_layout* pHeapLayout) +{ + ma_result result; + + MA_ASSERT(pHeapLayout != NULL); + + MA_ZERO_OBJECT(pHeapLayout); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + result = ma_spatializer_validate_config(pConfig); + if (result != MA_SUCCESS) { + return result; + } + + pHeapLayout->sizeInBytes = 0; + + /* Channel map. */ + pHeapLayout->channelMapInOffset = MA_SIZE_MAX; /* <-- MA_SIZE_MAX indicates no allocation necessary. */ + if (pConfig->pChannelMapIn != NULL) { + pHeapLayout->channelMapInOffset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += ma_align_64(sizeof(*pConfig->pChannelMapIn) * pConfig->channelsIn); + } + + /* New channel gains for output. */ + pHeapLayout->newChannelGainsOffset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += ma_align_64(sizeof(float) * pConfig->channelsOut); + + /* Gainer. */ + { + size_t gainerHeapSizeInBytes; + ma_gainer_config gainerConfig; + + gainerConfig = ma_spatializer_gainer_config_init(pConfig); + + result = ma_gainer_get_heap_size(&gainerConfig, &gainerHeapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + pHeapLayout->gainerOffset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += ma_align_64(gainerHeapSizeInBytes); + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_spatializer_get_heap_size(const ma_spatializer_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_result result; + ma_spatializer_heap_layout heapLayout; + + if (pHeapSizeInBytes == NULL) { + return MA_INVALID_ARGS; + } + + *pHeapSizeInBytes = 0; /* Safety. */ + + result = ma_spatializer_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + *pHeapSizeInBytes = heapLayout.sizeInBytes; + + return MA_SUCCESS; +} + + +MA_API ma_result ma_spatializer_init_preallocated(const ma_spatializer_config* pConfig, void* pHeap, ma_spatializer* pSpatializer) +{ + ma_result result; + ma_spatializer_heap_layout heapLayout; + ma_gainer_config gainerConfig; + + if (pSpatializer == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pSpatializer); + + if (pConfig == NULL || pHeap == NULL) { + return MA_INVALID_ARGS; + } + + result = ma_spatializer_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + pSpatializer->_pHeap = pHeap; + MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes); + + pSpatializer->channelsIn = pConfig->channelsIn; + pSpatializer->channelsOut = pConfig->channelsOut; + pSpatializer->attenuationModel = pConfig->attenuationModel; + pSpatializer->positioning = pConfig->positioning; + pSpatializer->handedness = pConfig->handedness; + pSpatializer->minGain = pConfig->minGain; + pSpatializer->maxGain = pConfig->maxGain; + pSpatializer->minDistance = pConfig->minDistance; + pSpatializer->maxDistance = pConfig->maxDistance; + pSpatializer->rolloff = pConfig->rolloff; + pSpatializer->coneInnerAngleInRadians = pConfig->coneInnerAngleInRadians; + pSpatializer->coneOuterAngleInRadians = pConfig->coneOuterAngleInRadians; + pSpatializer->coneOuterGain = pConfig->coneOuterGain; + pSpatializer->dopplerFactor = pConfig->dopplerFactor; + pSpatializer->minSpatializationChannelGain = pConfig->minSpatializationChannelGain; + pSpatializer->directionalAttenuationFactor = pConfig->directionalAttenuationFactor; + pSpatializer->gainSmoothTimeInFrames = pConfig->gainSmoothTimeInFrames; + ma_atomic_vec3f_init(&pSpatializer->position, ma_vec3f_init_3f(0, 0, 0)); + ma_atomic_vec3f_init(&pSpatializer->direction, ma_vec3f_init_3f(0, 0, -1)); + ma_atomic_vec3f_init(&pSpatializer->velocity, ma_vec3f_init_3f(0, 0, 0)); + pSpatializer->dopplerPitch = 1; + + /* Swap the forward direction if we're left handed (it was initialized based on right handed). */ + if (pSpatializer->handedness == ma_handedness_left) { + ma_vec3f negDir = ma_vec3f_neg(ma_spatializer_get_direction(pSpatializer)); + ma_spatializer_set_direction(pSpatializer, negDir.x, negDir.y, negDir.z); + } + + /* Channel map. This will be on the heap. */ + if (pConfig->pChannelMapIn != NULL) { + pSpatializer->pChannelMapIn = (ma_channel*)ma_offset_ptr(pHeap, heapLayout.channelMapInOffset); + ma_channel_map_copy_or_default(pSpatializer->pChannelMapIn, pSpatializer->channelsIn, pConfig->pChannelMapIn, pSpatializer->channelsIn); + } + + /* New channel gains for output channels. */ + pSpatializer->pNewChannelGainsOut = (float*)ma_offset_ptr(pHeap, heapLayout.newChannelGainsOffset); + + /* Gainer. */ + gainerConfig = ma_spatializer_gainer_config_init(pConfig); + + result = ma_gainer_init_preallocated(&gainerConfig, ma_offset_ptr(pHeap, heapLayout.gainerOffset), &pSpatializer->gainer); + if (result != MA_SUCCESS) { + return result; /* Failed to initialize the gainer. */ + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_spatializer_init(const ma_spatializer_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_spatializer* pSpatializer) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + /* We'll need a heap allocation to retrieve the size. */ + result = ma_spatializer_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_spatializer_init_preallocated(pConfig, pHeap, pSpatializer); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pSpatializer->_ownsHeap = MA_TRUE; + return MA_SUCCESS; +} + +MA_API void ma_spatializer_uninit(ma_spatializer* pSpatializer, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pSpatializer == NULL) { + return; + } + + ma_gainer_uninit(&pSpatializer->gainer, pAllocationCallbacks); + + if (pSpatializer->_ownsHeap) { + ma_free(pSpatializer->_pHeap, pAllocationCallbacks); + } +} + +static float ma_calculate_angular_gain(ma_vec3f dirA, ma_vec3f dirB, float coneInnerAngleInRadians, float coneOuterAngleInRadians, float coneOuterGain) +{ + /* + Angular attenuation. + + Unlike distance gain, the math for this is not specified by the OpenAL spec so we'll just go ahead and figure + this out for ourselves at the expense of possibly being inconsistent with other implementations. + + To do cone attenuation, I'm just using the same math that we'd use to implement a basic spotlight in OpenGL. We + just need to get the direction from the source to the listener and then do a dot product against that and the + direction of the spotlight. Then we just compare that dot product against the cosine of the inner and outer + angles. If the dot product is greater than the the outer angle, we just use coneOuterGain. If it's less than + the inner angle, we just use a gain of 1. Otherwise we linearly interpolate between 1 and coneOuterGain. + */ + if (coneInnerAngleInRadians < 6.283185f) { + float angularGain = 1; + float cutoffInner = (float)ma_cosd(coneInnerAngleInRadians*0.5f); + float cutoffOuter = (float)ma_cosd(coneOuterAngleInRadians*0.5f); + float d; + + d = ma_vec3f_dot(dirA, dirB); + + if (d > cutoffInner) { + /* It's inside the inner angle. */ + angularGain = 1; + } else { + /* It's outside the inner angle. */ + if (d > cutoffOuter) { + /* It's between the inner and outer angle. We need to linearly interpolate between 1 and coneOuterGain. */ + angularGain = ma_mix_f32(coneOuterGain, 1, (d - cutoffOuter) / (cutoffInner - cutoffOuter)); + } else { + /* It's outside the outer angle. */ + angularGain = coneOuterGain; + } + } + + /*printf("d = %f; cutoffInner = %f; cutoffOuter = %f; angularGain = %f\n", d, cutoffInner, cutoffOuter, angularGain);*/ + return angularGain; + } else { + /* Inner angle is 360 degrees so no need to do any attenuation. */ + return 1; + } +} + +MA_API ma_result ma_spatializer_process_pcm_frames(ma_spatializer* pSpatializer, ma_spatializer_listener* pListener, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + ma_channel* pChannelMapIn = pSpatializer->pChannelMapIn; + ma_channel* pChannelMapOut = pListener->config.pChannelMapOut; + + if (pSpatializer == NULL) { + return MA_INVALID_ARGS; + } + + /* If we're not spatializing we need to run an optimized path. */ + if (ma_atomic_load_i32(&pSpatializer->attenuationModel) == ma_attenuation_model_none) { + if (ma_spatializer_listener_is_enabled(pListener)) { + /* No attenuation is required, but we'll need to do some channel conversion. */ + if (pSpatializer->channelsIn == pSpatializer->channelsOut) { + ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, ma_format_f32, pSpatializer->channelsIn); + } else { + ma_channel_map_apply_f32((float*)pFramesOut, pChannelMapOut, pSpatializer->channelsOut, (const float*)pFramesIn, pChannelMapIn, pSpatializer->channelsIn, frameCount, ma_channel_mix_mode_rectangular, ma_mono_expansion_mode_default); /* Safe casts to float* because f32 is the only supported format. */ + } + } else { + /* The listener is disabled. Output silence. */ + ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, pSpatializer->channelsOut); + } + + /* + We're not doing attenuation so don't bother with doppler for now. I'm not sure if this is + the correct thinking so might need to review this later. + */ + pSpatializer->dopplerPitch = 1; + } else { + /* + Let's first determine which listener the sound is closest to. Need to keep in mind that we + might not have a world or any listeners, in which case we just spatializer based on the + listener being positioned at the origin (0, 0, 0). + */ + ma_vec3f relativePosNormalized; + ma_vec3f relativePos; /* The position relative to the listener. */ + ma_vec3f relativeDir; /* The direction of the sound, relative to the listener. */ + ma_vec3f listenerVel; /* The volocity of the listener. For doppler pitch calculation. */ + float speedOfSound; + float distance = 0; + float gain = 1; + ma_uint32 iChannel; + const ma_uint32 channelsOut = pSpatializer->channelsOut; + const ma_uint32 channelsIn = pSpatializer->channelsIn; + float minDistance = ma_spatializer_get_min_distance(pSpatializer); + float maxDistance = ma_spatializer_get_max_distance(pSpatializer); + float rolloff = ma_spatializer_get_rolloff(pSpatializer); + float dopplerFactor = ma_spatializer_get_doppler_factor(pSpatializer); + + /* + We'll need the listener velocity for doppler pitch calculations. The speed of sound is + defined by the listener, so we'll grab that here too. + */ + if (pListener != NULL) { + listenerVel = ma_spatializer_listener_get_velocity(pListener); + speedOfSound = pListener->config.speedOfSound; + } else { + listenerVel = ma_vec3f_init_3f(0, 0, 0); + speedOfSound = MA_DEFAULT_SPEED_OF_SOUND; + } + + if (pListener == NULL || ma_spatializer_get_positioning(pSpatializer) == ma_positioning_relative) { + /* There's no listener or we're using relative positioning. */ + relativePos = ma_spatializer_get_position(pSpatializer); + relativeDir = ma_spatializer_get_direction(pSpatializer); + } else { + /* + We've found a listener and we're using absolute positioning. We need to transform the + sound's position and direction so that it's relative to listener. Later on we'll use + this for determining the factors to apply to each channel to apply the panning effect. + */ + ma_spatializer_get_relative_position_and_direction(pSpatializer, pListener, &relativePos, &relativeDir); + } + + distance = ma_vec3f_len(relativePos); + + /* We've gathered the data, so now we can apply some spatialization. */ + switch (ma_spatializer_get_attenuation_model(pSpatializer)) { + case ma_attenuation_model_inverse: + { + gain = ma_attenuation_inverse(distance, minDistance, maxDistance, rolloff); + } break; + case ma_attenuation_model_linear: + { + gain = ma_attenuation_linear(distance, minDistance, maxDistance, rolloff); + } break; + case ma_attenuation_model_exponential: + { + gain = ma_attenuation_exponential(distance, minDistance, maxDistance, rolloff); + } break; + case ma_attenuation_model_none: + default: + { + gain = 1; + } break; + } + + /* Normalize the position. */ + if (distance > 0.001f) { + float distanceInv = 1/distance; + relativePosNormalized = relativePos; + relativePosNormalized.x *= distanceInv; + relativePosNormalized.y *= distanceInv; + relativePosNormalized.z *= distanceInv; + } else { + distance = 0; + relativePosNormalized = ma_vec3f_init_3f(0, 0, 0); + } + + /* + Angular attenuation. + + Unlike distance gain, the math for this is not specified by the OpenAL spec so we'll just go ahead and figure + this out for ourselves at the expense of possibly being inconsistent with other implementations. + + To do cone attenuation, I'm just using the same math that we'd use to implement a basic spotlight in OpenGL. We + just need to get the direction from the source to the listener and then do a dot product against that and the + direction of the spotlight. Then we just compare that dot product against the cosine of the inner and outer + angles. If the dot product is greater than the the outer angle, we just use coneOuterGain. If it's less than + the inner angle, we just use a gain of 1. Otherwise we linearly interpolate between 1 and coneOuterGain. + */ + if (distance > 0) { + /* Source anglular gain. */ + float spatializerConeInnerAngle; + float spatializerConeOuterAngle; + float spatializerConeOuterGain; + ma_spatializer_get_cone(pSpatializer, &spatializerConeInnerAngle, &spatializerConeOuterAngle, &spatializerConeOuterGain); + + gain *= ma_calculate_angular_gain(relativeDir, ma_vec3f_neg(relativePosNormalized), spatializerConeInnerAngle, spatializerConeOuterAngle, spatializerConeOuterGain); + + /* + We're supporting angular gain on the listener as well for those who want to reduce the volume of sounds that + are positioned behind the listener. On default settings, this will have no effect. + */ + if (pListener != NULL && pListener->config.coneInnerAngleInRadians < 6.283185f) { + ma_vec3f listenerDirection; + float listenerInnerAngle; + float listenerOuterAngle; + float listenerOuterGain; + + if (pListener->config.handedness == ma_handedness_right) { + listenerDirection = ma_vec3f_init_3f(0, 0, -1); + } else { + listenerDirection = ma_vec3f_init_3f(0, 0, +1); + } + + listenerInnerAngle = pListener->config.coneInnerAngleInRadians; + listenerOuterAngle = pListener->config.coneOuterAngleInRadians; + listenerOuterGain = pListener->config.coneOuterGain; + + gain *= ma_calculate_angular_gain(listenerDirection, relativePosNormalized, listenerInnerAngle, listenerOuterAngle, listenerOuterGain); + } + } else { + /* The sound is right on top of the listener. Don't do any angular attenuation. */ + } + + + /* Clamp the gain. */ + gain = ma_clamp(gain, ma_spatializer_get_min_gain(pSpatializer), ma_spatializer_get_max_gain(pSpatializer)); + + /* + The gain needs to be applied per-channel here. The spatialization code below will be changing the per-channel + gains which will then eventually be passed into the gainer which will deal with smoothing the gain transitions + to avoid harsh changes in gain. + */ + for (iChannel = 0; iChannel < channelsOut; iChannel += 1) { + pSpatializer->pNewChannelGainsOut[iChannel] = gain; + } + + /* + Convert to our output channel count. If the listener is disabled we just output silence here. We cannot ignore + the whole section of code here because we need to update some internal spatialization state. + */ + if (ma_spatializer_listener_is_enabled(pListener)) { + ma_channel_map_apply_f32((float*)pFramesOut, pChannelMapOut, channelsOut, (const float*)pFramesIn, pChannelMapIn, channelsIn, frameCount, ma_channel_mix_mode_rectangular, ma_mono_expansion_mode_default); + } else { + ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, pSpatializer->channelsOut); + } + + + /* + Panning. This is where we'll apply the gain and convert to the output channel count. We have an optimized path for + when we're converting to a mono stream. In that case we don't really need to do any panning - we just apply the + gain to the final output. + */ + /*printf("distance=%f; gain=%f\n", distance, gain);*/ + + /* We must have a valid channel map here to ensure we spatialize properly. */ + MA_ASSERT(pChannelMapOut != NULL); + + /* + We're not converting to mono so we'll want to apply some panning. This is where the feeling of something being + to the left, right, infront or behind the listener is calculated. I'm just using a basic model here. Note that + the code below is not based on any specific algorithm. I'm just implementing this off the top of my head and + seeing how it goes. There might be better ways to do this. + + To determine the direction of the sound relative to a speaker I'm using dot products. Each speaker is given a + direction. For example, the left channel in a stereo system will be -1 on the X axis and the right channel will + be +1 on the X axis. A dot product is performed against the direction vector of the channel and the normalized + position of the sound. + */ + + /* + Calculate our per-channel gains. We do this based on the normalized relative position of the sound and it's + relation to the direction of the channel. + */ + if (distance > 0) { + ma_vec3f unitPos = relativePos; + float distanceInv = 1/distance; + unitPos.x *= distanceInv; + unitPos.y *= distanceInv; + unitPos.z *= distanceInv; + + for (iChannel = 0; iChannel < channelsOut; iChannel += 1) { + ma_channel channelOut; + float d; + float dMin; + + channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannel); + if (ma_is_spatial_channel_position(channelOut)) { + d = ma_mix_f32_fast(1, ma_vec3f_dot(unitPos, ma_get_channel_direction(channelOut)), ma_spatializer_get_directional_attenuation_factor(pSpatializer)); + } else { + d = 1; /* It's not a spatial channel so there's no real notion of direction. */ + } + + /* + In my testing, if the panning effect is too aggressive it makes spatialization feel uncomfortable. + The "dMin" variable below is used to control the aggressiveness of the panning effect. When set to + 0, panning will be most extreme and any sounds that are positioned on the opposite side of the + speaker will be completely silent from that speaker. Not only does this feel uncomfortable, it + doesn't even remotely represent the real world at all because sounds that come from your right side + are still clearly audible from your left side. Setting "dMin" to 1 will result in no panning at + all, which is also not ideal. By setting it to something greater than 0, the spatialization effect + becomes much less dramatic and a lot more bearable. + + Summary: 0 = more extreme panning; 1 = no panning. + */ + dMin = pSpatializer->minSpatializationChannelGain; + + /* + At this point, "d" will be positive if the sound is on the same side as the channel and negative if + it's on the opposite side. It will be in the range of -1..1. There's two ways I can think of to + calculate a panning value. The first is to simply convert it to 0..1, however this has a problem + which I'm not entirely happy with. Considering a stereo system, when a sound is positioned right + in front of the listener it'll result in each speaker getting a gain of 0.5. I don't know if I like + the idea of having a scaling factor of 0.5 being applied to a sound when it's sitting right in front + of the listener. I would intuitively expect that to be played at full volume, or close to it. + + The second idea I think of is to only apply a reduction in gain when the sound is on the opposite + side of the speaker. That is, reduce the gain only when the dot product is negative. The problem + with this is that there will not be any attenuation as the sound sweeps around the 180 degrees + where the dot product is positive. The idea with this option is that you leave the gain at 1 when + the sound is being played on the same side as the speaker and then you just reduce the volume when + the sound is on the other side. + + The summarize, I think the first option should give a better sense of spatialization, but the second + option is better for preserving the sound's power. + + UPDATE: In my testing, I find the first option to sound better. You can feel the sense of space a + bit better, but you can also hear the reduction in volume when it's right in front. + */ + #if 1 + { + /* + Scale the dot product from -1..1 to 0..1. Will result in a sound directly in front losing power + by being played at 0.5 gain. + */ + d = (d + 1) * 0.5f; /* -1..1 to 0..1 */ + d = ma_max(d, dMin); + pSpatializer->pNewChannelGainsOut[iChannel] *= d; + } + #else + { + /* + Only reduce the volume of the sound if it's on the opposite side. This path keeps the volume more + consistent, but comes at the expense of a worse sense of space and positioning. + */ + if (d < 0) { + d += 1; /* Move into the positive range. */ + d = ma_max(d, dMin); + channelGainsOut[iChannel] *= d; + } + } + #endif + } + } else { + /* Assume the sound is right on top of us. Don't do any panning. */ + } + + /* Now we need to apply the volume to each channel. This needs to run through the gainer to ensure we get a smooth volume transition. */ + ma_gainer_set_gains(&pSpatializer->gainer, pSpatializer->pNewChannelGainsOut); + ma_gainer_process_pcm_frames(&pSpatializer->gainer, pFramesOut, pFramesOut, frameCount); + + /* + Before leaving we'll want to update our doppler pitch so that the caller can apply some + pitch shifting if they desire. Note that we need to negate the relative position here + because the doppler calculation needs to be source-to-listener, but ours is listener-to- + source. + */ + if (dopplerFactor > 0) { + pSpatializer->dopplerPitch = ma_doppler_pitch(ma_vec3f_sub(ma_spatializer_listener_get_position(pListener), ma_spatializer_get_position(pSpatializer)), ma_spatializer_get_velocity(pSpatializer), listenerVel, speedOfSound, dopplerFactor); + } else { + pSpatializer->dopplerPitch = 1; + } + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_spatializer_set_master_volume(ma_spatializer* pSpatializer, float volume) +{ + if (pSpatializer == NULL) { + return MA_INVALID_ARGS; + } + + return ma_gainer_set_master_volume(&pSpatializer->gainer, volume); +} + +MA_API ma_result ma_spatializer_get_master_volume(const ma_spatializer* pSpatializer, float* pVolume) +{ + if (pSpatializer == NULL) { + return MA_INVALID_ARGS; + } + + return ma_gainer_get_master_volume(&pSpatializer->gainer, pVolume); +} + +MA_API ma_uint32 ma_spatializer_get_input_channels(const ma_spatializer* pSpatializer) +{ + if (pSpatializer == NULL) { + return 0; + } + + return pSpatializer->channelsIn; +} + +MA_API ma_uint32 ma_spatializer_get_output_channels(const ma_spatializer* pSpatializer) +{ + if (pSpatializer == NULL) { + return 0; + } + + return pSpatializer->channelsOut; +} + +MA_API void ma_spatializer_set_attenuation_model(ma_spatializer* pSpatializer, ma_attenuation_model attenuationModel) +{ + if (pSpatializer == NULL) { + return; + } + + ma_atomic_exchange_i32(&pSpatializer->attenuationModel, attenuationModel); +} + +MA_API ma_attenuation_model ma_spatializer_get_attenuation_model(const ma_spatializer* pSpatializer) +{ + if (pSpatializer == NULL) { + return ma_attenuation_model_none; + } + + return (ma_attenuation_model)ma_atomic_load_i32(&pSpatializer->attenuationModel); +} + +MA_API void ma_spatializer_set_positioning(ma_spatializer* pSpatializer, ma_positioning positioning) +{ + if (pSpatializer == NULL) { + return; + } + + ma_atomic_exchange_i32(&pSpatializer->positioning, positioning); +} + +MA_API ma_positioning ma_spatializer_get_positioning(const ma_spatializer* pSpatializer) +{ + if (pSpatializer == NULL) { + return ma_positioning_absolute; + } + + return (ma_positioning)ma_atomic_load_i32(&pSpatializer->positioning); +} + +MA_API void ma_spatializer_set_rolloff(ma_spatializer* pSpatializer, float rolloff) +{ + if (pSpatializer == NULL) { + return; + } + + ma_atomic_exchange_f32(&pSpatializer->rolloff, rolloff); +} + +MA_API float ma_spatializer_get_rolloff(const ma_spatializer* pSpatializer) +{ + if (pSpatializer == NULL) { + return 0; + } + + return ma_atomic_load_f32(&pSpatializer->rolloff); +} + +MA_API void ma_spatializer_set_min_gain(ma_spatializer* pSpatializer, float minGain) +{ + if (pSpatializer == NULL) { + return; + } + + ma_atomic_exchange_f32(&pSpatializer->minGain, minGain); +} + +MA_API float ma_spatializer_get_min_gain(const ma_spatializer* pSpatializer) +{ + if (pSpatializer == NULL) { + return 0; + } + + return ma_atomic_load_f32(&pSpatializer->minGain); +} + +MA_API void ma_spatializer_set_max_gain(ma_spatializer* pSpatializer, float maxGain) +{ + if (pSpatializer == NULL) { + return; + } + + ma_atomic_exchange_f32(&pSpatializer->maxGain, maxGain); +} + +MA_API float ma_spatializer_get_max_gain(const ma_spatializer* pSpatializer) +{ + if (pSpatializer == NULL) { + return 0; + } + + return ma_atomic_load_f32(&pSpatializer->maxGain); +} + +MA_API void ma_spatializer_set_min_distance(ma_spatializer* pSpatializer, float minDistance) +{ + if (pSpatializer == NULL) { + return; + } + + ma_atomic_exchange_f32(&pSpatializer->minDistance, minDistance); +} + +MA_API float ma_spatializer_get_min_distance(const ma_spatializer* pSpatializer) +{ + if (pSpatializer == NULL) { + return 0; + } + + return ma_atomic_load_f32(&pSpatializer->minDistance); +} + +MA_API void ma_spatializer_set_max_distance(ma_spatializer* pSpatializer, float maxDistance) +{ + if (pSpatializer == NULL) { + return; + } + + ma_atomic_exchange_f32(&pSpatializer->maxDistance, maxDistance); +} + +MA_API float ma_spatializer_get_max_distance(const ma_spatializer* pSpatializer) +{ + if (pSpatializer == NULL) { + return 0; + } + + return ma_atomic_load_f32(&pSpatializer->maxDistance); +} + +MA_API void ma_spatializer_set_cone(ma_spatializer* pSpatializer, float innerAngleInRadians, float outerAngleInRadians, float outerGain) +{ + if (pSpatializer == NULL) { + return; + } + + ma_atomic_exchange_f32(&pSpatializer->coneInnerAngleInRadians, innerAngleInRadians); + ma_atomic_exchange_f32(&pSpatializer->coneOuterAngleInRadians, outerAngleInRadians); + ma_atomic_exchange_f32(&pSpatializer->coneOuterGain, outerGain); +} + +MA_API void ma_spatializer_get_cone(const ma_spatializer* pSpatializer, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain) +{ + if (pSpatializer == NULL) { + return; + } + + if (pInnerAngleInRadians != NULL) { + *pInnerAngleInRadians = ma_atomic_load_f32(&pSpatializer->coneInnerAngleInRadians); + } + + if (pOuterAngleInRadians != NULL) { + *pOuterAngleInRadians = ma_atomic_load_f32(&pSpatializer->coneOuterAngleInRadians); + } + + if (pOuterGain != NULL) { + *pOuterGain = ma_atomic_load_f32(&pSpatializer->coneOuterGain); + } +} + +MA_API void ma_spatializer_set_doppler_factor(ma_spatializer* pSpatializer, float dopplerFactor) +{ + if (pSpatializer == NULL) { + return; + } + + ma_atomic_exchange_f32(&pSpatializer->dopplerFactor, dopplerFactor); +} + +MA_API float ma_spatializer_get_doppler_factor(const ma_spatializer* pSpatializer) +{ + if (pSpatializer == NULL) { + return 1; + } + + return ma_atomic_load_f32(&pSpatializer->dopplerFactor); +} + +MA_API void ma_spatializer_set_directional_attenuation_factor(ma_spatializer* pSpatializer, float directionalAttenuationFactor) +{ + if (pSpatializer == NULL) { + return; + } + + ma_atomic_exchange_f32(&pSpatializer->directionalAttenuationFactor, directionalAttenuationFactor); +} + +MA_API float ma_spatializer_get_directional_attenuation_factor(const ma_spatializer* pSpatializer) +{ + if (pSpatializer == NULL) { + return 1; + } + + return ma_atomic_load_f32(&pSpatializer->directionalAttenuationFactor); +} + +MA_API void ma_spatializer_set_position(ma_spatializer* pSpatializer, float x, float y, float z) +{ + if (pSpatializer == NULL) { + return; + } + + ma_atomic_vec3f_set(&pSpatializer->position, ma_vec3f_init_3f(x, y, z)); +} + +MA_API ma_vec3f ma_spatializer_get_position(const ma_spatializer* pSpatializer) +{ + if (pSpatializer == NULL) { + return ma_vec3f_init_3f(0, 0, 0); + } + + return ma_atomic_vec3f_get((ma_atomic_vec3f*)&pSpatializer->position); /* Naughty const-cast. It's just for atomically loading the vec3 which should be safe. */ +} + +MA_API void ma_spatializer_set_direction(ma_spatializer* pSpatializer, float x, float y, float z) +{ + if (pSpatializer == NULL) { + return; + } + + ma_atomic_vec3f_set(&pSpatializer->direction, ma_vec3f_init_3f(x, y, z)); +} + +MA_API ma_vec3f ma_spatializer_get_direction(const ma_spatializer* pSpatializer) +{ + if (pSpatializer == NULL) { + return ma_vec3f_init_3f(0, 0, -1); + } + + return ma_atomic_vec3f_get((ma_atomic_vec3f*)&pSpatializer->direction); /* Naughty const-cast. It's just for atomically loading the vec3 which should be safe. */ +} + +MA_API void ma_spatializer_set_velocity(ma_spatializer* pSpatializer, float x, float y, float z) +{ + if (pSpatializer == NULL) { + return; + } + + ma_atomic_vec3f_set(&pSpatializer->velocity, ma_vec3f_init_3f(x, y, z)); +} + +MA_API ma_vec3f ma_spatializer_get_velocity(const ma_spatializer* pSpatializer) +{ + if (pSpatializer == NULL) { + return ma_vec3f_init_3f(0, 0, 0); + } + + return ma_atomic_vec3f_get((ma_atomic_vec3f*)&pSpatializer->velocity); /* Naughty const-cast. It's just for atomically loading the vec3 which should be safe. */ +} + +MA_API void ma_spatializer_get_relative_position_and_direction(const ma_spatializer* pSpatializer, const ma_spatializer_listener* pListener, ma_vec3f* pRelativePos, ma_vec3f* pRelativeDir) +{ + if (pRelativePos != NULL) { + pRelativePos->x = 0; + pRelativePos->y = 0; + pRelativePos->z = 0; + } + + if (pRelativeDir != NULL) { + pRelativeDir->x = 0; + pRelativeDir->y = 0; + pRelativeDir->z = -1; + } + + if (pSpatializer == NULL) { + return; + } + + if (pListener == NULL || ma_spatializer_get_positioning(pSpatializer) == ma_positioning_relative) { + /* There's no listener or we're using relative positioning. */ + if (pRelativePos != NULL) { + *pRelativePos = ma_spatializer_get_position(pSpatializer); + } + if (pRelativeDir != NULL) { + *pRelativeDir = ma_spatializer_get_direction(pSpatializer); + } + } else { + ma_vec3f spatializerPosition; + ma_vec3f spatializerDirection; + ma_vec3f listenerPosition; + ma_vec3f listenerDirection; + ma_vec3f v; + ma_vec3f axisX; + ma_vec3f axisY; + ma_vec3f axisZ; + float m[4][4]; + + spatializerPosition = ma_spatializer_get_position(pSpatializer); + spatializerDirection = ma_spatializer_get_direction(pSpatializer); + listenerPosition = ma_spatializer_listener_get_position(pListener); + listenerDirection = ma_spatializer_listener_get_direction(pListener); + + /* + We need to calcualte the right vector from our forward and up vectors. This is done with + a cross product. + */ + axisZ = ma_vec3f_normalize(listenerDirection); /* Normalization required here because we can't trust the caller. */ + axisX = ma_vec3f_normalize(ma_vec3f_cross(axisZ, pListener->config.worldUp)); /* Normalization required here because the world up vector may not be perpendicular with the forward vector. */ + + /* + The calculation of axisX above can result in a zero-length vector if the listener is + looking straight up on the Y axis. We'll need to fall back to a +X in this case so that + the calculations below don't fall apart. This is where a quaternion based listener and + sound orientation would come in handy. + */ + if (ma_vec3f_len2(axisX) == 0) { + axisX = ma_vec3f_init_3f(1, 0, 0); + } + + axisY = ma_vec3f_cross(axisX, axisZ); /* No normalization is required here because axisX and axisZ are unit length and perpendicular. */ + + /* + We need to swap the X axis if we're left handed because otherwise the cross product above + will have resulted in it pointing in the wrong direction (right handed was assumed in the + cross products above). + */ + if (pListener->config.handedness == ma_handedness_left) { + axisX = ma_vec3f_neg(axisX); + } + + /* Lookat. */ + m[0][0] = axisX.x; m[1][0] = axisX.y; m[2][0] = axisX.z; m[3][0] = -ma_vec3f_dot(axisX, listenerPosition); + m[0][1] = axisY.x; m[1][1] = axisY.y; m[2][1] = axisY.z; m[3][1] = -ma_vec3f_dot(axisY, listenerPosition); + m[0][2] = -axisZ.x; m[1][2] = -axisZ.y; m[2][2] = -axisZ.z; m[3][2] = -ma_vec3f_dot(ma_vec3f_neg(axisZ), listenerPosition); + m[0][3] = 0; m[1][3] = 0; m[2][3] = 0; m[3][3] = 1; + + /* + Multiply the lookat matrix by the spatializer position to transform it to listener + space. This allows calculations to work based on the sound being relative to the + origin which makes things simpler. + */ + if (pRelativePos != NULL) { + v = spatializerPosition; + pRelativePos->x = m[0][0] * v.x + m[1][0] * v.y + m[2][0] * v.z + m[3][0] * 1; + pRelativePos->y = m[0][1] * v.x + m[1][1] * v.y + m[2][1] * v.z + m[3][1] * 1; + pRelativePos->z = m[0][2] * v.x + m[1][2] * v.y + m[2][2] * v.z + m[3][2] * 1; + } + + /* + The direction of the sound needs to also be transformed so that it's relative to the + rotation of the listener. + */ + if (pRelativeDir != NULL) { + v = spatializerDirection; + pRelativeDir->x = m[0][0] * v.x + m[1][0] * v.y + m[2][0] * v.z; + pRelativeDir->y = m[0][1] * v.x + m[1][1] * v.y + m[2][1] * v.z; + pRelativeDir->z = m[0][2] * v.x + m[1][2] * v.y + m[2][2] * v.z; + } + } +} + + + + +/************************************************************************************************************************************************************** + +Resampling + +**************************************************************************************************************************************************************/ +MA_API ma_linear_resampler_config ma_linear_resampler_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut) +{ + ma_linear_resampler_config config; + MA_ZERO_OBJECT(&config); + config.format = format; + config.channels = channels; + config.sampleRateIn = sampleRateIn; + config.sampleRateOut = sampleRateOut; + config.lpfOrder = ma_min(MA_DEFAULT_RESAMPLER_LPF_ORDER, MA_MAX_FILTER_ORDER); + config.lpfNyquistFactor = 1; + + return config; +} + + +typedef struct +{ + size_t sizeInBytes; + size_t x0Offset; + size_t x1Offset; + size_t lpfOffset; +} ma_linear_resampler_heap_layout; + + +static void ma_linear_resampler_adjust_timer_for_new_rate(ma_linear_resampler* pResampler, ma_uint32 oldSampleRateOut, ma_uint32 newSampleRateOut) +{ + /* + So what's happening here? Basically we need to adjust the fractional component of the time advance based on the new rate. The old time advance will + be based on the old sample rate, but we are needing to adjust it to that it's based on the new sample rate. + */ + ma_uint32 oldRateTimeWhole = pResampler->inTimeFrac / oldSampleRateOut; /* <-- This should almost never be anything other than 0, but leaving it here to make this more general and robust just in case. */ + ma_uint32 oldRateTimeFract = pResampler->inTimeFrac % oldSampleRateOut; + + pResampler->inTimeFrac = + (oldRateTimeWhole * newSampleRateOut) + + ((oldRateTimeFract * newSampleRateOut) / oldSampleRateOut); + + /* Make sure the fractional part is less than the output sample rate. */ + pResampler->inTimeInt += pResampler->inTimeFrac / pResampler->config.sampleRateOut; + pResampler->inTimeFrac = pResampler->inTimeFrac % pResampler->config.sampleRateOut; +} + +static ma_result ma_linear_resampler_set_rate_internal(ma_linear_resampler* pResampler, void* pHeap, ma_linear_resampler_heap_layout* pHeapLayout, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut, ma_bool32 isResamplerAlreadyInitialized) +{ + ma_result result; + ma_uint32 gcf; + ma_uint32 lpfSampleRate; + double lpfCutoffFrequency; + ma_lpf_config lpfConfig; + ma_uint32 oldSampleRateOut; /* Required for adjusting time advance down the bottom. */ + + if (pResampler == NULL) { + return MA_INVALID_ARGS; + } + + if (sampleRateIn == 0 || sampleRateOut == 0) { + return MA_INVALID_ARGS; + } + + oldSampleRateOut = pResampler->config.sampleRateOut; + + pResampler->config.sampleRateIn = sampleRateIn; + pResampler->config.sampleRateOut = sampleRateOut; + + /* Simplify the sample rate. */ + gcf = ma_gcf_u32(pResampler->config.sampleRateIn, pResampler->config.sampleRateOut); + pResampler->config.sampleRateIn /= gcf; + pResampler->config.sampleRateOut /= gcf; + + /* Always initialize the low-pass filter, even when the order is 0. */ + if (pResampler->config.lpfOrder > MA_MAX_FILTER_ORDER) { + return MA_INVALID_ARGS; + } + + lpfSampleRate = (ma_uint32)(ma_max(pResampler->config.sampleRateIn, pResampler->config.sampleRateOut)); + lpfCutoffFrequency = ( double)(ma_min(pResampler->config.sampleRateIn, pResampler->config.sampleRateOut) * 0.5 * pResampler->config.lpfNyquistFactor); + + lpfConfig = ma_lpf_config_init(pResampler->config.format, pResampler->config.channels, lpfSampleRate, lpfCutoffFrequency, pResampler->config.lpfOrder); + + /* + If the resampler is alreay initialized we don't want to do a fresh initialization of the low-pass filter because it will result in the cached frames + getting cleared. Instead we re-initialize the filter which will maintain any cached frames. + */ + if (isResamplerAlreadyInitialized) { + result = ma_lpf_reinit(&lpfConfig, &pResampler->lpf); + } else { + result = ma_lpf_init_preallocated(&lpfConfig, ma_offset_ptr(pHeap, pHeapLayout->lpfOffset), &pResampler->lpf); + } + + if (result != MA_SUCCESS) { + return result; + } + + + pResampler->inAdvanceInt = pResampler->config.sampleRateIn / pResampler->config.sampleRateOut; + pResampler->inAdvanceFrac = pResampler->config.sampleRateIn % pResampler->config.sampleRateOut; + + /* Our timer was based on the old rate. We need to adjust it so that it's based on the new rate. */ + ma_linear_resampler_adjust_timer_for_new_rate(pResampler, oldSampleRateOut, pResampler->config.sampleRateOut); + + return MA_SUCCESS; +} + +static ma_result ma_linear_resampler_get_heap_layout(const ma_linear_resampler_config* pConfig, ma_linear_resampler_heap_layout* pHeapLayout) +{ + MA_ASSERT(pHeapLayout != NULL); + + MA_ZERO_OBJECT(pHeapLayout); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) { + return MA_INVALID_ARGS; + } + + if (pConfig->channels == 0) { + return MA_INVALID_ARGS; + } + + pHeapLayout->sizeInBytes = 0; + + /* x0 */ + pHeapLayout->x0Offset = pHeapLayout->sizeInBytes; + if (pConfig->format == ma_format_f32) { + pHeapLayout->sizeInBytes += sizeof(float) * pConfig->channels; + } else { + pHeapLayout->sizeInBytes += sizeof(ma_int16) * pConfig->channels; + } + + /* x1 */ + pHeapLayout->x1Offset = pHeapLayout->sizeInBytes; + if (pConfig->format == ma_format_f32) { + pHeapLayout->sizeInBytes += sizeof(float) * pConfig->channels; + } else { + pHeapLayout->sizeInBytes += sizeof(ma_int16) * pConfig->channels; + } + + /* LPF */ + pHeapLayout->lpfOffset = ma_align_64(pHeapLayout->sizeInBytes); + { + ma_result result; + size_t lpfHeapSizeInBytes; + ma_lpf_config lpfConfig = ma_lpf_config_init(pConfig->format, pConfig->channels, 1, 1, pConfig->lpfOrder); /* Sample rate and cutoff frequency do not matter. */ + + result = ma_lpf_get_heap_size(&lpfConfig, &lpfHeapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + pHeapLayout->sizeInBytes += lpfHeapSizeInBytes; + } + + /* Make sure allocation size is aligned. */ + pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes); + + return MA_SUCCESS; +} + +MA_API ma_result ma_linear_resampler_get_heap_size(const ma_linear_resampler_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_result result; + ma_linear_resampler_heap_layout heapLayout; + + if (pHeapSizeInBytes == NULL) { + return MA_INVALID_ARGS; + } + + *pHeapSizeInBytes = 0; + + result = ma_linear_resampler_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + *pHeapSizeInBytes = heapLayout.sizeInBytes; + + return MA_SUCCESS; +} + +MA_API ma_result ma_linear_resampler_init_preallocated(const ma_linear_resampler_config* pConfig, void* pHeap, ma_linear_resampler* pResampler) +{ + ma_result result; + ma_linear_resampler_heap_layout heapLayout; + + if (pResampler == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pResampler); + + result = ma_linear_resampler_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + pResampler->config = *pConfig; + + pResampler->_pHeap = pHeap; + MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes); + + if (pConfig->format == ma_format_f32) { + pResampler->x0.f32 = (float*)ma_offset_ptr(pHeap, heapLayout.x0Offset); + pResampler->x1.f32 = (float*)ma_offset_ptr(pHeap, heapLayout.x1Offset); + } else { + pResampler->x0.s16 = (ma_int16*)ma_offset_ptr(pHeap, heapLayout.x0Offset); + pResampler->x1.s16 = (ma_int16*)ma_offset_ptr(pHeap, heapLayout.x1Offset); + } + + /* Setting the rate will set up the filter and time advances for us. */ + result = ma_linear_resampler_set_rate_internal(pResampler, pHeap, &heapLayout, pConfig->sampleRateIn, pConfig->sampleRateOut, /* isResamplerAlreadyInitialized = */ MA_FALSE); + if (result != MA_SUCCESS) { + return result; + } + + pResampler->inTimeInt = 1; /* Set this to one to force an input sample to always be loaded for the first output frame. */ + pResampler->inTimeFrac = 0; + + return MA_SUCCESS; +} + +MA_API ma_result ma_linear_resampler_init(const ma_linear_resampler_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_linear_resampler* pResampler) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_linear_resampler_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_linear_resampler_init_preallocated(pConfig, pHeap, pResampler); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pResampler->_ownsHeap = MA_TRUE; + return MA_SUCCESS; +} + +MA_API void ma_linear_resampler_uninit(ma_linear_resampler* pResampler, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pResampler == NULL) { + return; + } + + ma_lpf_uninit(&pResampler->lpf, pAllocationCallbacks); + + if (pResampler->_ownsHeap) { + ma_free(pResampler->_pHeap, pAllocationCallbacks); + } +} + +static MA_INLINE ma_int16 ma_linear_resampler_mix_s16(ma_int16 x, ma_int16 y, ma_int32 a, const ma_int32 shift) +{ + ma_int32 b; + ma_int32 c; + ma_int32 r; + + MA_ASSERT(a <= (1<> shift); +} + +static void ma_linear_resampler_interpolate_frame_s16(ma_linear_resampler* pResampler, ma_int16* MA_RESTRICT pFrameOut) +{ + ma_uint32 c; + ma_uint32 a; + const ma_uint32 channels = pResampler->config.channels; + const ma_uint32 shift = 12; + + MA_ASSERT(pResampler != NULL); + MA_ASSERT(pFrameOut != NULL); + + a = (pResampler->inTimeFrac << shift) / pResampler->config.sampleRateOut; + + MA_ASSUME(channels > 0); + for (c = 0; c < channels; c += 1) { + ma_int16 s = ma_linear_resampler_mix_s16(pResampler->x0.s16[c], pResampler->x1.s16[c], a, shift); + pFrameOut[c] = s; + } +} + + +static void ma_linear_resampler_interpolate_frame_f32(ma_linear_resampler* pResampler, float* MA_RESTRICT pFrameOut) +{ + ma_uint32 c; + float a; + const ma_uint32 channels = pResampler->config.channels; + + MA_ASSERT(pResampler != NULL); + MA_ASSERT(pFrameOut != NULL); + + a = (float)pResampler->inTimeFrac / pResampler->config.sampleRateOut; + + MA_ASSUME(channels > 0); + for (c = 0; c < channels; c += 1) { + float s = ma_mix_f32_fast(pResampler->x0.f32[c], pResampler->x1.f32[c], a); + pFrameOut[c] = s; + } +} + +static ma_result ma_linear_resampler_process_pcm_frames_s16_downsample(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut) +{ + const ma_int16* pFramesInS16; + /* */ ma_int16* pFramesOutS16; + ma_uint64 frameCountIn; + ma_uint64 frameCountOut; + ma_uint64 framesProcessedIn; + ma_uint64 framesProcessedOut; + + MA_ASSERT(pResampler != NULL); + MA_ASSERT(pFrameCountIn != NULL); + MA_ASSERT(pFrameCountOut != NULL); + + pFramesInS16 = (const ma_int16*)pFramesIn; + pFramesOutS16 = ( ma_int16*)pFramesOut; + frameCountIn = *pFrameCountIn; + frameCountOut = *pFrameCountOut; + framesProcessedIn = 0; + framesProcessedOut = 0; + + while (framesProcessedOut < frameCountOut) { + /* Before interpolating we need to load the buffers. When doing this we need to ensure we run every input sample through the filter. */ + while (pResampler->inTimeInt > 0 && frameCountIn > framesProcessedIn) { + ma_uint32 iChannel; + + if (pFramesInS16 != NULL) { + for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) { + pResampler->x0.s16[iChannel] = pResampler->x1.s16[iChannel]; + pResampler->x1.s16[iChannel] = pFramesInS16[iChannel]; + } + pFramesInS16 += pResampler->config.channels; + } else { + for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) { + pResampler->x0.s16[iChannel] = pResampler->x1.s16[iChannel]; + pResampler->x1.s16[iChannel] = 0; + } + } + + /* Filter. Do not apply filtering if sample rates are the same or else you'll get dangerous glitching. */ + if (pResampler->config.sampleRateIn != pResampler->config.sampleRateOut) { + ma_lpf_process_pcm_frame_s16(&pResampler->lpf, pResampler->x1.s16, pResampler->x1.s16); + } + + framesProcessedIn += 1; + pResampler->inTimeInt -= 1; + } + + if (pResampler->inTimeInt > 0) { + break; /* Ran out of input data. */ + } + + /* Getting here means the frames have been loaded and filtered and we can generate the next output frame. */ + if (pFramesOutS16 != NULL) { + MA_ASSERT(pResampler->inTimeInt == 0); + ma_linear_resampler_interpolate_frame_s16(pResampler, pFramesOutS16); + + pFramesOutS16 += pResampler->config.channels; + } + + framesProcessedOut += 1; + + /* Advance time forward. */ + pResampler->inTimeInt += pResampler->inAdvanceInt; + pResampler->inTimeFrac += pResampler->inAdvanceFrac; + if (pResampler->inTimeFrac >= pResampler->config.sampleRateOut) { + pResampler->inTimeFrac -= pResampler->config.sampleRateOut; + pResampler->inTimeInt += 1; + } + } + + *pFrameCountIn = framesProcessedIn; + *pFrameCountOut = framesProcessedOut; + + return MA_SUCCESS; +} + +static ma_result ma_linear_resampler_process_pcm_frames_s16_upsample(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut) +{ + const ma_int16* pFramesInS16; + /* */ ma_int16* pFramesOutS16; + ma_uint64 frameCountIn; + ma_uint64 frameCountOut; + ma_uint64 framesProcessedIn; + ma_uint64 framesProcessedOut; + + MA_ASSERT(pResampler != NULL); + MA_ASSERT(pFrameCountIn != NULL); + MA_ASSERT(pFrameCountOut != NULL); + + pFramesInS16 = (const ma_int16*)pFramesIn; + pFramesOutS16 = ( ma_int16*)pFramesOut; + frameCountIn = *pFrameCountIn; + frameCountOut = *pFrameCountOut; + framesProcessedIn = 0; + framesProcessedOut = 0; + + while (framesProcessedOut < frameCountOut) { + /* Before interpolating we need to load the buffers. */ + while (pResampler->inTimeInt > 0 && frameCountIn > framesProcessedIn) { + ma_uint32 iChannel; + + if (pFramesInS16 != NULL) { + for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) { + pResampler->x0.s16[iChannel] = pResampler->x1.s16[iChannel]; + pResampler->x1.s16[iChannel] = pFramesInS16[iChannel]; + } + pFramesInS16 += pResampler->config.channels; + } else { + for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) { + pResampler->x0.s16[iChannel] = pResampler->x1.s16[iChannel]; + pResampler->x1.s16[iChannel] = 0; + } + } + + framesProcessedIn += 1; + pResampler->inTimeInt -= 1; + } + + if (pResampler->inTimeInt > 0) { + break; /* Ran out of input data. */ + } + + /* Getting here means the frames have been loaded and we can generate the next output frame. */ + if (pFramesOutS16 != NULL) { + MA_ASSERT(pResampler->inTimeInt == 0); + ma_linear_resampler_interpolate_frame_s16(pResampler, pFramesOutS16); + + /* Filter. Do not apply filtering if sample rates are the same or else you'll get dangerous glitching. */ + if (pResampler->config.sampleRateIn != pResampler->config.sampleRateOut) { + ma_lpf_process_pcm_frame_s16(&pResampler->lpf, pFramesOutS16, pFramesOutS16); + } + + pFramesOutS16 += pResampler->config.channels; + } + + framesProcessedOut += 1; + + /* Advance time forward. */ + pResampler->inTimeInt += pResampler->inAdvanceInt; + pResampler->inTimeFrac += pResampler->inAdvanceFrac; + if (pResampler->inTimeFrac >= pResampler->config.sampleRateOut) { + pResampler->inTimeFrac -= pResampler->config.sampleRateOut; + pResampler->inTimeInt += 1; + } + } + + *pFrameCountIn = framesProcessedIn; + *pFrameCountOut = framesProcessedOut; + + return MA_SUCCESS; +} + +static ma_result ma_linear_resampler_process_pcm_frames_s16(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut) +{ + MA_ASSERT(pResampler != NULL); + + if (pResampler->config.sampleRateIn > pResampler->config.sampleRateOut) { + return ma_linear_resampler_process_pcm_frames_s16_downsample(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut); + } else { + return ma_linear_resampler_process_pcm_frames_s16_upsample(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut); + } +} + + +static ma_result ma_linear_resampler_process_pcm_frames_f32_downsample(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut) +{ + const float* pFramesInF32; + /* */ float* pFramesOutF32; + ma_uint64 frameCountIn; + ma_uint64 frameCountOut; + ma_uint64 framesProcessedIn; + ma_uint64 framesProcessedOut; + + MA_ASSERT(pResampler != NULL); + MA_ASSERT(pFrameCountIn != NULL); + MA_ASSERT(pFrameCountOut != NULL); + + pFramesInF32 = (const float*)pFramesIn; + pFramesOutF32 = ( float*)pFramesOut; + frameCountIn = *pFrameCountIn; + frameCountOut = *pFrameCountOut; + framesProcessedIn = 0; + framesProcessedOut = 0; + + while (framesProcessedOut < frameCountOut) { + /* Before interpolating we need to load the buffers. When doing this we need to ensure we run every input sample through the filter. */ + while (pResampler->inTimeInt > 0 && frameCountIn > framesProcessedIn) { + ma_uint32 iChannel; + + if (pFramesInF32 != NULL) { + for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) { + pResampler->x0.f32[iChannel] = pResampler->x1.f32[iChannel]; + pResampler->x1.f32[iChannel] = pFramesInF32[iChannel]; + } + pFramesInF32 += pResampler->config.channels; + } else { + for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) { + pResampler->x0.f32[iChannel] = pResampler->x1.f32[iChannel]; + pResampler->x1.f32[iChannel] = 0; + } + } + + /* Filter. Do not apply filtering if sample rates are the same or else you'll get dangerous glitching. */ + if (pResampler->config.sampleRateIn != pResampler->config.sampleRateOut) { + ma_lpf_process_pcm_frame_f32(&pResampler->lpf, pResampler->x1.f32, pResampler->x1.f32); + } + + framesProcessedIn += 1; + pResampler->inTimeInt -= 1; + } + + if (pResampler->inTimeInt > 0) { + break; /* Ran out of input data. */ + } + + /* Getting here means the frames have been loaded and filtered and we can generate the next output frame. */ + if (pFramesOutF32 != NULL) { + MA_ASSERT(pResampler->inTimeInt == 0); + ma_linear_resampler_interpolate_frame_f32(pResampler, pFramesOutF32); + + pFramesOutF32 += pResampler->config.channels; + } + + framesProcessedOut += 1; + + /* Advance time forward. */ + pResampler->inTimeInt += pResampler->inAdvanceInt; + pResampler->inTimeFrac += pResampler->inAdvanceFrac; + if (pResampler->inTimeFrac >= pResampler->config.sampleRateOut) { + pResampler->inTimeFrac -= pResampler->config.sampleRateOut; + pResampler->inTimeInt += 1; + } + } + + *pFrameCountIn = framesProcessedIn; + *pFrameCountOut = framesProcessedOut; + + return MA_SUCCESS; +} + +static ma_result ma_linear_resampler_process_pcm_frames_f32_upsample(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut) +{ + const float* pFramesInF32; + /* */ float* pFramesOutF32; + ma_uint64 frameCountIn; + ma_uint64 frameCountOut; + ma_uint64 framesProcessedIn; + ma_uint64 framesProcessedOut; + + MA_ASSERT(pResampler != NULL); + MA_ASSERT(pFrameCountIn != NULL); + MA_ASSERT(pFrameCountOut != NULL); + + pFramesInF32 = (const float*)pFramesIn; + pFramesOutF32 = ( float*)pFramesOut; + frameCountIn = *pFrameCountIn; + frameCountOut = *pFrameCountOut; + framesProcessedIn = 0; + framesProcessedOut = 0; + + while (framesProcessedOut < frameCountOut) { + /* Before interpolating we need to load the buffers. */ + while (pResampler->inTimeInt > 0 && frameCountIn > framesProcessedIn) { + ma_uint32 iChannel; + + if (pFramesInF32 != NULL) { + for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) { + pResampler->x0.f32[iChannel] = pResampler->x1.f32[iChannel]; + pResampler->x1.f32[iChannel] = pFramesInF32[iChannel]; + } + pFramesInF32 += pResampler->config.channels; + } else { + for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) { + pResampler->x0.f32[iChannel] = pResampler->x1.f32[iChannel]; + pResampler->x1.f32[iChannel] = 0; + } + } + + framesProcessedIn += 1; + pResampler->inTimeInt -= 1; + } + + if (pResampler->inTimeInt > 0) { + break; /* Ran out of input data. */ + } + + /* Getting here means the frames have been loaded and we can generate the next output frame. */ + if (pFramesOutF32 != NULL) { + MA_ASSERT(pResampler->inTimeInt == 0); + ma_linear_resampler_interpolate_frame_f32(pResampler, pFramesOutF32); + + /* Filter. Do not apply filtering if sample rates are the same or else you'll get dangerous glitching. */ + if (pResampler->config.sampleRateIn != pResampler->config.sampleRateOut) { + ma_lpf_process_pcm_frame_f32(&pResampler->lpf, pFramesOutF32, pFramesOutF32); + } + + pFramesOutF32 += pResampler->config.channels; + } + + framesProcessedOut += 1; + + /* Advance time forward. */ + pResampler->inTimeInt += pResampler->inAdvanceInt; + pResampler->inTimeFrac += pResampler->inAdvanceFrac; + if (pResampler->inTimeFrac >= pResampler->config.sampleRateOut) { + pResampler->inTimeFrac -= pResampler->config.sampleRateOut; + pResampler->inTimeInt += 1; + } + } + + *pFrameCountIn = framesProcessedIn; + *pFrameCountOut = framesProcessedOut; + + return MA_SUCCESS; +} + +static ma_result ma_linear_resampler_process_pcm_frames_f32(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut) +{ + MA_ASSERT(pResampler != NULL); + + if (pResampler->config.sampleRateIn > pResampler->config.sampleRateOut) { + return ma_linear_resampler_process_pcm_frames_f32_downsample(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut); + } else { + return ma_linear_resampler_process_pcm_frames_f32_upsample(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut); + } +} + + +MA_API ma_result ma_linear_resampler_process_pcm_frames(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut) +{ + if (pResampler == NULL) { + return MA_INVALID_ARGS; + } + + /* */ if (pResampler->config.format == ma_format_s16) { + return ma_linear_resampler_process_pcm_frames_s16(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut); + } else if (pResampler->config.format == ma_format_f32) { + return ma_linear_resampler_process_pcm_frames_f32(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut); + } else { + /* Should never get here. Getting here means the format is not supported and you didn't check the return value of ma_linear_resampler_init(). */ + MA_ASSERT(MA_FALSE); + return MA_INVALID_ARGS; + } +} + + +MA_API ma_result ma_linear_resampler_set_rate(ma_linear_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut) +{ + return ma_linear_resampler_set_rate_internal(pResampler, NULL, NULL, sampleRateIn, sampleRateOut, /* isResamplerAlreadyInitialized = */ MA_TRUE); +} + +MA_API ma_result ma_linear_resampler_set_rate_ratio(ma_linear_resampler* pResampler, float ratioInOut) +{ + ma_uint32 n; + ma_uint32 d; + + if (pResampler == NULL) { + return MA_INVALID_ARGS; + } + + if (ratioInOut <= 0) { + return MA_INVALID_ARGS; + } + + d = 1000000; + n = (ma_uint32)(ratioInOut * d); + + if (n == 0) { + return MA_INVALID_ARGS; /* Ratio too small. */ + } + + MA_ASSERT(n != 0); + + return ma_linear_resampler_set_rate(pResampler, n, d); +} + +MA_API ma_uint64 ma_linear_resampler_get_input_latency(const ma_linear_resampler* pResampler) +{ + if (pResampler == NULL) { + return 0; + } + + return 1 + ma_lpf_get_latency(&pResampler->lpf); +} + +MA_API ma_uint64 ma_linear_resampler_get_output_latency(const ma_linear_resampler* pResampler) +{ + if (pResampler == NULL) { + return 0; + } + + return ma_linear_resampler_get_input_latency(pResampler) * pResampler->config.sampleRateOut / pResampler->config.sampleRateIn; +} + +MA_API ma_result ma_linear_resampler_get_required_input_frame_count(const ma_linear_resampler* pResampler, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount) +{ + ma_uint64 inputFrameCount; + + if (pInputFrameCount == NULL) { + return MA_INVALID_ARGS; + } + + *pInputFrameCount = 0; + + if (pResampler == NULL) { + return MA_INVALID_ARGS; + } + + if (outputFrameCount == 0) { + return MA_SUCCESS; + } + + /* Any whole input frames are consumed before the first output frame is generated. */ + inputFrameCount = pResampler->inTimeInt; + outputFrameCount -= 1; + + /* The rest of the output frames can be calculated in constant time. */ + inputFrameCount += outputFrameCount * pResampler->inAdvanceInt; + inputFrameCount += (pResampler->inTimeFrac + (outputFrameCount * pResampler->inAdvanceFrac)) / pResampler->config.sampleRateOut; + + *pInputFrameCount = inputFrameCount; + + return MA_SUCCESS; +} + +MA_API ma_result ma_linear_resampler_get_expected_output_frame_count(const ma_linear_resampler* pResampler, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount) +{ + ma_uint64 outputFrameCount; + ma_uint64 preliminaryInputFrameCountFromFrac; + ma_uint64 preliminaryInputFrameCount; + + if (pOutputFrameCount == NULL) { + return MA_INVALID_ARGS; + } + + *pOutputFrameCount = 0; + + if (pResampler == NULL) { + return MA_INVALID_ARGS; + } + + /* + The first step is to get a preliminary output frame count. This will either be exactly equal to what we need, or less by 1. We need to + determine how many input frames will be consumed by this value. If it's greater than our original input frame count it means we won't + be able to generate an extra frame because we will have run out of input data. Otherwise we will have enough input for the generation + of an extra output frame. This add-by-one logic is necessary due to how the data loading logic works when processing frames. + */ + outputFrameCount = (inputFrameCount * pResampler->config.sampleRateOut) / pResampler->config.sampleRateIn; + + /* + We need to determine how many *whole* input frames will have been processed to generate our preliminary output frame count. This is + used in the logic below to determine whether or not we need to add an extra output frame. + */ + preliminaryInputFrameCountFromFrac = (pResampler->inTimeFrac + outputFrameCount*pResampler->inAdvanceFrac) / pResampler->config.sampleRateOut; + preliminaryInputFrameCount = (pResampler->inTimeInt + outputFrameCount*pResampler->inAdvanceInt ) + preliminaryInputFrameCountFromFrac; + + /* + If the total number of *whole* input frames that would be required to generate our preliminary output frame count is greather than + the amount of whole input frames we have available as input we need to *not* add an extra output frame as there won't be enough data + to actually process. Otherwise we need to add the extra output frame. + */ + if (preliminaryInputFrameCount <= inputFrameCount) { + outputFrameCount += 1; + } + + *pOutputFrameCount = outputFrameCount; + + return MA_SUCCESS; +} + +MA_API ma_result ma_linear_resampler_reset(ma_linear_resampler* pResampler) +{ + ma_uint32 iChannel; + + if (pResampler == NULL) { + return MA_INVALID_ARGS; + } + + /* Timers need to be cleared back to zero. */ + pResampler->inTimeInt = 1; /* Set this to one to force an input sample to always be loaded for the first output frame. */ + pResampler->inTimeFrac = 0; + + /* Cached samples need to be cleared. */ + if (pResampler->config.format == ma_format_f32) { + for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) { + pResampler->x0.f32[iChannel] = 0; + pResampler->x1.f32[iChannel] = 0; + } + } else { + for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) { + pResampler->x0.s16[iChannel] = 0; + pResampler->x1.s16[iChannel] = 0; + } + } + + /* The low pass filter needs to have it's cache reset. */ + ma_lpf_clear_cache(&pResampler->lpf); + + return MA_SUCCESS; +} + + + +/* Linear resampler backend vtable. */ +static ma_linear_resampler_config ma_resampling_backend_get_config__linear(const ma_resampler_config* pConfig) +{ + ma_linear_resampler_config linearConfig; + + linearConfig = ma_linear_resampler_config_init(pConfig->format, pConfig->channels, pConfig->sampleRateIn, pConfig->sampleRateOut); + linearConfig.lpfOrder = pConfig->linear.lpfOrder; + + return linearConfig; +} + +static ma_result ma_resampling_backend_get_heap_size__linear(void* pUserData, const ma_resampler_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_linear_resampler_config linearConfig; + + (void)pUserData; + + linearConfig = ma_resampling_backend_get_config__linear(pConfig); + + return ma_linear_resampler_get_heap_size(&linearConfig, pHeapSizeInBytes); +} + +static ma_result ma_resampling_backend_init__linear(void* pUserData, const ma_resampler_config* pConfig, void* pHeap, ma_resampling_backend** ppBackend) +{ + ma_resampler* pResampler = (ma_resampler*)pUserData; + ma_result result; + ma_linear_resampler_config linearConfig; + + (void)pUserData; + + linearConfig = ma_resampling_backend_get_config__linear(pConfig); + + result = ma_linear_resampler_init_preallocated(&linearConfig, pHeap, &pResampler->state.linear); + if (result != MA_SUCCESS) { + return result; + } + + *ppBackend = &pResampler->state.linear; + + return MA_SUCCESS; +} + +static void ma_resampling_backend_uninit__linear(void* pUserData, ma_resampling_backend* pBackend, const ma_allocation_callbacks* pAllocationCallbacks) +{ + (void)pUserData; + + ma_linear_resampler_uninit((ma_linear_resampler*)pBackend, pAllocationCallbacks); +} + +static ma_result ma_resampling_backend_process__linear(void* pUserData, ma_resampling_backend* pBackend, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut) +{ + (void)pUserData; + + return ma_linear_resampler_process_pcm_frames((ma_linear_resampler*)pBackend, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut); +} + +static ma_result ma_resampling_backend_set_rate__linear(void* pUserData, ma_resampling_backend* pBackend, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut) +{ + (void)pUserData; + + return ma_linear_resampler_set_rate((ma_linear_resampler*)pBackend, sampleRateIn, sampleRateOut); +} + +static ma_uint64 ma_resampling_backend_get_input_latency__linear(void* pUserData, const ma_resampling_backend* pBackend) +{ + (void)pUserData; + + return ma_linear_resampler_get_input_latency((const ma_linear_resampler*)pBackend); +} + +static ma_uint64 ma_resampling_backend_get_output_latency__linear(void* pUserData, const ma_resampling_backend* pBackend) +{ + (void)pUserData; + + return ma_linear_resampler_get_output_latency((const ma_linear_resampler*)pBackend); +} + +static ma_result ma_resampling_backend_get_required_input_frame_count__linear(void* pUserData, const ma_resampling_backend* pBackend, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount) +{ + (void)pUserData; + + return ma_linear_resampler_get_required_input_frame_count((const ma_linear_resampler*)pBackend, outputFrameCount, pInputFrameCount); +} + +static ma_result ma_resampling_backend_get_expected_output_frame_count__linear(void* pUserData, const ma_resampling_backend* pBackend, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount) +{ + (void)pUserData; + + return ma_linear_resampler_get_expected_output_frame_count((const ma_linear_resampler*)pBackend, inputFrameCount, pOutputFrameCount); +} + +static ma_result ma_resampling_backend_reset__linear(void* pUserData, ma_resampling_backend* pBackend) +{ + (void)pUserData; + + return ma_linear_resampler_reset((ma_linear_resampler*)pBackend); +} + +static ma_resampling_backend_vtable g_ma_linear_resampler_vtable = +{ + ma_resampling_backend_get_heap_size__linear, + ma_resampling_backend_init__linear, + ma_resampling_backend_uninit__linear, + ma_resampling_backend_process__linear, + ma_resampling_backend_set_rate__linear, + ma_resampling_backend_get_input_latency__linear, + ma_resampling_backend_get_output_latency__linear, + ma_resampling_backend_get_required_input_frame_count__linear, + ma_resampling_backend_get_expected_output_frame_count__linear, + ma_resampling_backend_reset__linear +}; + + + +MA_API ma_resampler_config ma_resampler_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut, ma_resample_algorithm algorithm) +{ + ma_resampler_config config; + + MA_ZERO_OBJECT(&config); + config.format = format; + config.channels = channels; + config.sampleRateIn = sampleRateIn; + config.sampleRateOut = sampleRateOut; + config.algorithm = algorithm; + + /* Linear. */ + config.linear.lpfOrder = ma_min(MA_DEFAULT_RESAMPLER_LPF_ORDER, MA_MAX_FILTER_ORDER); + + return config; +} + +static ma_result ma_resampler_get_vtable(const ma_resampler_config* pConfig, ma_resampler* pResampler, ma_resampling_backend_vtable** ppVTable, void** ppUserData) +{ + MA_ASSERT(pConfig != NULL); + MA_ASSERT(ppVTable != NULL); + MA_ASSERT(ppUserData != NULL); + + /* Safety. */ + *ppVTable = NULL; + *ppUserData = NULL; + + switch (pConfig->algorithm) + { + case ma_resample_algorithm_linear: + { + *ppVTable = &g_ma_linear_resampler_vtable; + *ppUserData = pResampler; + } break; + + case ma_resample_algorithm_custom: + { + *ppVTable = pConfig->pBackendVTable; + *ppUserData = pConfig->pBackendUserData; + } break; + + default: return MA_INVALID_ARGS; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_resampler_get_heap_size(const ma_resampler_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_result result; + ma_resampling_backend_vtable* pVTable; + void* pVTableUserData; + + if (pHeapSizeInBytes == NULL) { + return MA_INVALID_ARGS; + } + + *pHeapSizeInBytes = 0; + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + result = ma_resampler_get_vtable(pConfig, NULL, &pVTable, &pVTableUserData); + if (result != MA_SUCCESS) { + return result; + } + + if (pVTable == NULL || pVTable->onGetHeapSize == NULL) { + return MA_NOT_IMPLEMENTED; + } + + result = pVTable->onGetHeapSize(pVTableUserData, pConfig, pHeapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_resampler_init_preallocated(const ma_resampler_config* pConfig, void* pHeap, ma_resampler* pResampler) +{ + ma_result result; + + if (pResampler == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pResampler); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + pResampler->_pHeap = pHeap; + pResampler->format = pConfig->format; + pResampler->channels = pConfig->channels; + pResampler->sampleRateIn = pConfig->sampleRateIn; + pResampler->sampleRateOut = pConfig->sampleRateOut; + + result = ma_resampler_get_vtable(pConfig, pResampler, &pResampler->pBackendVTable, &pResampler->pBackendUserData); + if (result != MA_SUCCESS) { + return result; + } + + if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onInit == NULL) { + return MA_NOT_IMPLEMENTED; /* onInit not implemented. */ + } + + result = pResampler->pBackendVTable->onInit(pResampler->pBackendUserData, pConfig, pHeap, &pResampler->pBackend); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_resampler_init(const ma_resampler_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_resampler* pResampler) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_resampler_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_resampler_init_preallocated(pConfig, pHeap, pResampler); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pResampler->_ownsHeap = MA_TRUE; + return MA_SUCCESS; +} + +MA_API void ma_resampler_uninit(ma_resampler* pResampler, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pResampler == NULL) { + return; + } + + if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onUninit == NULL) { + return; + } + + pResampler->pBackendVTable->onUninit(pResampler->pBackendUserData, pResampler->pBackend, pAllocationCallbacks); + + if (pResampler->_ownsHeap) { + ma_free(pResampler->_pHeap, pAllocationCallbacks); + } +} + +MA_API ma_result ma_resampler_process_pcm_frames(ma_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut) +{ + if (pResampler == NULL) { + return MA_INVALID_ARGS; + } + + if (pFrameCountOut == NULL && pFrameCountIn == NULL) { + return MA_INVALID_ARGS; + } + + if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onProcess == NULL) { + return MA_NOT_IMPLEMENTED; + } + + return pResampler->pBackendVTable->onProcess(pResampler->pBackendUserData, pResampler->pBackend, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut); +} + +MA_API ma_result ma_resampler_set_rate(ma_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut) +{ + ma_result result; + + if (pResampler == NULL) { + return MA_INVALID_ARGS; + } + + if (sampleRateIn == 0 || sampleRateOut == 0) { + return MA_INVALID_ARGS; + } + + if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onSetRate == NULL) { + return MA_NOT_IMPLEMENTED; + } + + result = pResampler->pBackendVTable->onSetRate(pResampler->pBackendUserData, pResampler->pBackend, sampleRateIn, sampleRateOut); + if (result != MA_SUCCESS) { + return result; + } + + pResampler->sampleRateIn = sampleRateIn; + pResampler->sampleRateOut = sampleRateOut; + + return MA_SUCCESS; +} + +MA_API ma_result ma_resampler_set_rate_ratio(ma_resampler* pResampler, float ratio) +{ + ma_uint32 n; + ma_uint32 d; + + if (pResampler == NULL) { + return MA_INVALID_ARGS; + } + + if (ratio <= 0) { + return MA_INVALID_ARGS; + } + + d = 1000; + n = (ma_uint32)(ratio * d); + + if (n == 0) { + return MA_INVALID_ARGS; /* Ratio too small. */ + } + + MA_ASSERT(n != 0); + + return ma_resampler_set_rate(pResampler, n, d); +} + +MA_API ma_uint64 ma_resampler_get_input_latency(const ma_resampler* pResampler) +{ + if (pResampler == NULL) { + return 0; + } + + if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onGetInputLatency == NULL) { + return 0; + } + + return pResampler->pBackendVTable->onGetInputLatency(pResampler->pBackendUserData, pResampler->pBackend); +} + +MA_API ma_uint64 ma_resampler_get_output_latency(const ma_resampler* pResampler) +{ + if (pResampler == NULL) { + return 0; + } + + if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onGetOutputLatency == NULL) { + return 0; + } + + return pResampler->pBackendVTable->onGetOutputLatency(pResampler->pBackendUserData, pResampler->pBackend); +} + +MA_API ma_result ma_resampler_get_required_input_frame_count(const ma_resampler* pResampler, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount) +{ + if (pInputFrameCount == NULL) { + return MA_INVALID_ARGS; + } + + *pInputFrameCount = 0; + + if (pResampler == NULL) { + return MA_INVALID_ARGS; + } + + if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onGetRequiredInputFrameCount == NULL) { + return MA_NOT_IMPLEMENTED; + } + + return pResampler->pBackendVTable->onGetRequiredInputFrameCount(pResampler->pBackendUserData, pResampler->pBackend, outputFrameCount, pInputFrameCount); +} + +MA_API ma_result ma_resampler_get_expected_output_frame_count(const ma_resampler* pResampler, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount) +{ + if (pOutputFrameCount == NULL) { + return MA_INVALID_ARGS; + } + + *pOutputFrameCount = 0; + + if (pResampler == NULL) { + return MA_INVALID_ARGS; + } + + if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onGetExpectedOutputFrameCount == NULL) { + return MA_NOT_IMPLEMENTED; + } + + return pResampler->pBackendVTable->onGetExpectedOutputFrameCount(pResampler->pBackendUserData, pResampler->pBackend, inputFrameCount, pOutputFrameCount); +} + +MA_API ma_result ma_resampler_reset(ma_resampler* pResampler) +{ + if (pResampler == NULL) { + return MA_INVALID_ARGS; + } + + if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onReset == NULL) { + return MA_NOT_IMPLEMENTED; + } + + return pResampler->pBackendVTable->onReset(pResampler->pBackendUserData, pResampler->pBackend); +} + +/************************************************************************************************************************************************************** + +Channel Conversion + +**************************************************************************************************************************************************************/ +#ifndef MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT +#define MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT 12 +#endif + +#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 + +static 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 */ +}; + +static float ma_calculate_channel_position_rectangular_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; +} + +MA_API ma_channel_converter_config ma_channel_converter_config_init(ma_format format, ma_uint32 channelsIn, const ma_channel* pChannelMapIn, ma_uint32 channelsOut, const ma_channel* pChannelMapOut, ma_channel_mix_mode mixingMode) +{ + ma_channel_converter_config config; + + MA_ZERO_OBJECT(&config); + config.format = format; + config.channelsIn = channelsIn; + config.channelsOut = channelsOut; + config.pChannelMapIn = pChannelMapIn; + config.pChannelMapOut = pChannelMapOut; + config.mixingMode = mixingMode; + + return config; +} + +static ma_int32 ma_channel_converter_float_to_fixed(float x) +{ + return (ma_int32)(x * (1< 0); + + for (iChannel = 0; iChannel < channels; ++iChannel) { + if (ma_is_spatial_channel_position(ma_channel_map_get_channel(pChannelMap, channels, iChannel))) { + spatialChannelCount++; + } + } + + return spatialChannelCount; +} + +static ma_bool32 ma_is_spatial_channel_position(ma_channel channelPosition) +{ + int i; + + if (channelPosition == MA_CHANNEL_NONE || channelPosition == MA_CHANNEL_MONO || channelPosition == MA_CHANNEL_LFE) { + return MA_FALSE; + } + + if (channelPosition >= MA_CHANNEL_AUX_0 && channelPosition <= MA_CHANNEL_AUX_31) { + return MA_FALSE; + } + + for (i = 0; i < 6; ++i) { /* Each side of a cube. */ + if (g_maChannelPlaneRatios[channelPosition][i] != 0) { + return MA_TRUE; + } + } + + return MA_FALSE; +} + + +static ma_bool32 ma_channel_map_is_passthrough(const ma_channel* pChannelMapIn, ma_uint32 channelsIn, const ma_channel* pChannelMapOut, ma_uint32 channelsOut) +{ + if (channelsOut == channelsIn) { + return ma_channel_map_is_equal(pChannelMapOut, pChannelMapIn, channelsOut); + } else { + return MA_FALSE; /* Channel counts differ, so cannot be a passthrough. */ + } +} + +static ma_channel_conversion_path ma_channel_map_get_conversion_path(const ma_channel* pChannelMapIn, ma_uint32 channelsIn, const ma_channel* pChannelMapOut, ma_uint32 channelsOut, ma_channel_mix_mode mode) +{ + if (ma_channel_map_is_passthrough(pChannelMapIn, channelsIn, pChannelMapOut, channelsOut)) { + return ma_channel_conversion_path_passthrough; + } + + if (channelsOut == 1 && (pChannelMapOut == NULL || pChannelMapOut[0] == MA_CHANNEL_MONO)) { + return ma_channel_conversion_path_mono_out; + } + + if (channelsIn == 1 && (pChannelMapIn == NULL || pChannelMapIn[0] == MA_CHANNEL_MONO)) { + return ma_channel_conversion_path_mono_in; + } + + if (mode == ma_channel_mix_mode_custom_weights) { + return ma_channel_conversion_path_weights; + } + + /* + We can use a simple shuffle if both channel maps have the same channel count and all channel + positions are present in both. + */ + if (channelsIn == channelsOut) { + ma_uint32 iChannelIn; + ma_bool32 areAllChannelPositionsPresent = MA_TRUE; + for (iChannelIn = 0; iChannelIn < channelsIn; ++iChannelIn) { + ma_bool32 isInputChannelPositionInOutput = MA_FALSE; + if (ma_channel_map_contains_channel_position(channelsOut, pChannelMapOut, ma_channel_map_get_channel(pChannelMapIn, channelsIn, iChannelIn))) { + isInputChannelPositionInOutput = MA_TRUE; + break; + } + + if (!isInputChannelPositionInOutput) { + areAllChannelPositionsPresent = MA_FALSE; + break; + } + } + + if (areAllChannelPositionsPresent) { + return ma_channel_conversion_path_shuffle; + } + } + + /* Getting here means we'll need to use weights. */ + return ma_channel_conversion_path_weights; +} + + +static ma_result ma_channel_map_build_shuffle_table(const ma_channel* pChannelMapIn, ma_uint32 channelCountIn, const ma_channel* pChannelMapOut, ma_uint32 channelCountOut, ma_uint8* pShuffleTable) +{ + ma_uint32 iChannelIn; + ma_uint32 iChannelOut; + + if (pShuffleTable == NULL || channelCountIn == 0 || channelCountOut == 0) { + return MA_INVALID_ARGS; + } + + /* + When building the shuffle table we just do a 1:1 mapping based on the first occurance of a channel. If the + input channel has more than one occurance of a channel position, the second one will be ignored. + */ + for (iChannelOut = 0; iChannelOut < channelCountOut; iChannelOut += 1) { + ma_channel channelOut; + + /* Default to MA_CHANNEL_INDEX_NULL so that if a mapping is not found it'll be set appropriately. */ + pShuffleTable[iChannelOut] = MA_CHANNEL_INDEX_NULL; + + channelOut = ma_channel_map_get_channel(pChannelMapOut, channelCountOut, iChannelOut); + for (iChannelIn = 0; iChannelIn < channelCountIn; iChannelIn += 1) { + ma_channel channelIn; + + channelIn = ma_channel_map_get_channel(pChannelMapIn, channelCountIn, iChannelIn); + if (channelOut == channelIn) { + pShuffleTable[iChannelOut] = (ma_uint8)iChannelIn; + break; + } + + /* + Getting here means the channels don't exactly match, but we are going to support some + relaxed matching for practicality. If, for example, there are two stereo channel maps, + but one uses front left/right and the other uses side left/right, it makes logical + sense to just map these. The way we'll do it is we'll check if there is a logical + corresponding mapping, and if so, apply it, but we will *not* break from the loop, + thereby giving the loop a chance to find an exact match later which will take priority. + */ + switch (channelOut) + { + /* Left channels. */ + case MA_CHANNEL_FRONT_LEFT: + case MA_CHANNEL_SIDE_LEFT: + { + switch (channelIn) { + case MA_CHANNEL_FRONT_LEFT: + case MA_CHANNEL_SIDE_LEFT: + { + pShuffleTable[iChannelOut] = (ma_uint8)iChannelIn; + } break; + } + } break; + + /* Right channels. */ + case MA_CHANNEL_FRONT_RIGHT: + case MA_CHANNEL_SIDE_RIGHT: + { + switch (channelIn) { + case MA_CHANNEL_FRONT_RIGHT: + case MA_CHANNEL_SIDE_RIGHT: + { + pShuffleTable[iChannelOut] = (ma_uint8)iChannelIn; + } break; + } + } break; + + default: break; + } + } + } + + return MA_SUCCESS; +} + + +static void ma_channel_map_apply_shuffle_table_u8(ma_uint8* pFramesOut, ma_uint32 channelsOut, const ma_uint8* pFramesIn, ma_uint32 channelsIn, ma_uint64 frameCount, const ma_uint8* pShuffleTable) +{ + ma_uint64 iFrame; + ma_uint32 iChannelOut; + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) { + ma_uint8 iChannelIn = pShuffleTable[iChannelOut]; + if (iChannelIn < channelsIn) { /* For safety, and to deal with MA_CHANNEL_INDEX_NULL. */ + pFramesOut[iChannelOut] = pFramesIn[iChannelIn]; + } else { + pFramesOut[iChannelOut] = 0; + } + } + + pFramesOut += channelsOut; + pFramesIn += channelsIn; + } +} + +static void ma_channel_map_apply_shuffle_table_s16(ma_int16* pFramesOut, ma_uint32 channelsOut, const ma_int16* pFramesIn, ma_uint32 channelsIn, ma_uint64 frameCount, const ma_uint8* pShuffleTable) +{ + ma_uint64 iFrame; + ma_uint32 iChannelOut; + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) { + ma_uint8 iChannelIn = pShuffleTable[iChannelOut]; + if (iChannelIn < channelsIn) { /* For safety, and to deal with MA_CHANNEL_INDEX_NULL. */ + pFramesOut[iChannelOut] = pFramesIn[iChannelIn]; + } else { + pFramesOut[iChannelOut] = 0; + } + } + + pFramesOut += channelsOut; + pFramesIn += channelsIn; + } +} + +static void ma_channel_map_apply_shuffle_table_s24(ma_uint8* pFramesOut, ma_uint32 channelsOut, const ma_uint8* pFramesIn, ma_uint32 channelsIn, ma_uint64 frameCount, const ma_uint8* pShuffleTable) +{ + ma_uint64 iFrame; + ma_uint32 iChannelOut; + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) { + ma_uint8 iChannelIn = pShuffleTable[iChannelOut]; + if (iChannelIn < channelsIn) { /* For safety, and to deal with MA_CHANNEL_INDEX_NULL. */ + pFramesOut[iChannelOut*3 + 0] = pFramesIn[iChannelIn*3 + 0]; + pFramesOut[iChannelOut*3 + 1] = pFramesIn[iChannelIn*3 + 1]; + pFramesOut[iChannelOut*3 + 2] = pFramesIn[iChannelIn*3 + 2]; + } else { + pFramesOut[iChannelOut*3 + 0] = 0; + } pFramesOut[iChannelOut*3 + 1] = 0; + } pFramesOut[iChannelOut*3 + 2] = 0; + + pFramesOut += channelsOut*3; + pFramesIn += channelsIn*3; + } +} + +static void ma_channel_map_apply_shuffle_table_s32(ma_int32* pFramesOut, ma_uint32 channelsOut, const ma_int32* pFramesIn, ma_uint32 channelsIn, ma_uint64 frameCount, const ma_uint8* pShuffleTable) +{ + ma_uint64 iFrame; + ma_uint32 iChannelOut; + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) { + ma_uint8 iChannelIn = pShuffleTable[iChannelOut]; + if (iChannelIn < channelsIn) { /* For safety, and to deal with MA_CHANNEL_INDEX_NULL. */ + pFramesOut[iChannelOut] = pFramesIn[iChannelIn]; + } else { + pFramesOut[iChannelOut] = 0; + } + } + + pFramesOut += channelsOut; + pFramesIn += channelsIn; + } +} + +static void ma_channel_map_apply_shuffle_table_f32(float* pFramesOut, ma_uint32 channelsOut, const float* pFramesIn, ma_uint32 channelsIn, ma_uint64 frameCount, const ma_uint8* pShuffleTable) +{ + ma_uint64 iFrame; + ma_uint32 iChannelOut; + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) { + ma_uint8 iChannelIn = pShuffleTable[iChannelOut]; + if (iChannelIn < channelsIn) { /* For safety, and to deal with MA_CHANNEL_INDEX_NULL. */ + pFramesOut[iChannelOut] = pFramesIn[iChannelIn]; + } else { + pFramesOut[iChannelOut] = 0; + } + } + + pFramesOut += channelsOut; + pFramesIn += channelsIn; + } +} + +static ma_result ma_channel_map_apply_shuffle_table(void* pFramesOut, ma_uint32 channelsOut, const void* pFramesIn, ma_uint32 channelsIn, ma_uint64 frameCount, const ma_uint8* pShuffleTable, ma_format format) +{ + if (pFramesOut == NULL || pFramesIn == NULL || channelsOut == 0 || pShuffleTable == NULL) { + return MA_INVALID_ARGS; + } + + switch (format) + { + case ma_format_u8: + { + ma_channel_map_apply_shuffle_table_u8((ma_uint8*)pFramesOut, channelsOut, (const ma_uint8*)pFramesIn, channelsIn, frameCount, pShuffleTable); + } break; + + case ma_format_s16: + { + ma_channel_map_apply_shuffle_table_s16((ma_int16*)pFramesOut, channelsOut, (const ma_int16*)pFramesIn, channelsIn, frameCount, pShuffleTable); + } break; + + case ma_format_s24: + { + ma_channel_map_apply_shuffle_table_s24((ma_uint8*)pFramesOut, channelsOut, (const ma_uint8*)pFramesIn, channelsIn, frameCount, pShuffleTable); + } break; + + case ma_format_s32: + { + ma_channel_map_apply_shuffle_table_s32((ma_int32*)pFramesOut, channelsOut, (const ma_int32*)pFramesIn, channelsIn, frameCount, pShuffleTable); + } break; + + case ma_format_f32: + { + ma_channel_map_apply_shuffle_table_f32((float*)pFramesOut, channelsOut, (const float*)pFramesIn, channelsIn, frameCount, pShuffleTable); + } break; + + default: return MA_INVALID_ARGS; /* Unknown format. */ + } + + return MA_SUCCESS; +} + +static ma_result ma_channel_map_apply_mono_out_f32(float* pFramesOut, const float* pFramesIn, const ma_channel* pChannelMapIn, ma_uint32 channelsIn, ma_uint64 frameCount) +{ + ma_uint64 iFrame; + ma_uint32 iChannelIn; + ma_uint32 accumulationCount; + + if (pFramesOut == NULL || pFramesIn == NULL || channelsIn == 0) { + return MA_INVALID_ARGS; + } + + /* In this case the output stream needs to be the average of all channels, ignoring NONE. */ + + /* A quick pre-processing step to get the accumulation counter since we're ignoring NONE channels. */ + accumulationCount = 0; + for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) { + if (ma_channel_map_get_channel(pChannelMapIn, channelsIn, iChannelIn) != MA_CHANNEL_NONE) { + accumulationCount += 1; + } + } + + if (accumulationCount > 0) { /* <-- Prevent a division by zero. */ + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + float accumulation = 0; + + for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) { + ma_channel channelIn = ma_channel_map_get_channel(pChannelMapIn, channelsIn, iChannelIn); + if (channelIn != MA_CHANNEL_NONE) { + accumulation += pFramesIn[iChannelIn]; + } + } + + pFramesOut[0] = accumulation / accumulationCount; + pFramesOut += 1; + pFramesIn += channelsIn; + } + } else { + ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, 1); + } + + return MA_SUCCESS; +} + +static ma_result ma_channel_map_apply_mono_in_f32(float* MA_RESTRICT pFramesOut, const ma_channel* pChannelMapOut, ma_uint32 channelsOut, const float* MA_RESTRICT pFramesIn, ma_uint64 frameCount, ma_mono_expansion_mode monoExpansionMode) +{ + ma_uint64 iFrame; + ma_uint32 iChannelOut; + + if (pFramesOut == NULL || channelsOut == 0 || pFramesIn == NULL) { + return MA_INVALID_ARGS; + } + + /* Note that the MA_CHANNEL_NONE channel must be ignored in all cases. */ + switch (monoExpansionMode) + { + case ma_mono_expansion_mode_average: + { + float weight; + ma_uint32 validChannelCount = 0; + + for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) { + ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut); + if (channelOut != MA_CHANNEL_NONE) { + validChannelCount += 1; + } + } + + weight = 1.0f / validChannelCount; + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) { + ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut); + if (channelOut != MA_CHANNEL_NONE) { + pFramesOut[iChannelOut] = pFramesIn[0] * weight; + } + } + + pFramesOut += channelsOut; + pFramesIn += 1; + } + } break; + + case ma_mono_expansion_mode_stereo_only: + { + if (channelsOut >= 2) { + ma_uint32 iChannelLeft = (ma_uint32)-1; + ma_uint32 iChannelRight = (ma_uint32)-1; + + /* + We first need to find our stereo channels. We prefer front-left and front-right, but + if they're not available, we'll also try side-left and side-right. If neither are + available we'll fall through to the default case below. + */ + for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) { + ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut); + if (channelOut == MA_CHANNEL_SIDE_LEFT) { + iChannelLeft = iChannelOut; + } + if (channelOut == MA_CHANNEL_SIDE_RIGHT) { + iChannelRight = iChannelOut; + } + } + + for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) { + ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut); + if (channelOut == MA_CHANNEL_FRONT_LEFT) { + iChannelLeft = iChannelOut; + } + if (channelOut == MA_CHANNEL_FRONT_RIGHT) { + iChannelRight = iChannelOut; + } + } + + + if (iChannelLeft != (ma_uint32)-1 && iChannelRight != (ma_uint32)-1) { + /* We found our stereo channels so we can duplicate the signal across those channels. */ + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) { + ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut); + if (channelOut != MA_CHANNEL_NONE) { + if (iChannelOut == iChannelLeft || iChannelOut == iChannelRight) { + pFramesOut[iChannelOut] = pFramesIn[0]; + } else { + pFramesOut[iChannelOut] = 0.0f; + } + } + } + + pFramesOut += channelsOut; + pFramesIn += 1; + } + + break; /* Get out of the switch. */ + } else { + /* Fallthrough. Does not have left and right channels. */ + goto default_handler; + } + } else { + /* Fallthrough. Does not have stereo channels. */ + goto default_handler; + } + }; /* Fallthrough. See comments above. */ + + case ma_mono_expansion_mode_duplicate: + default: + { + default_handler: + { + if (channelsOut <= MA_MAX_CHANNELS) { + ma_bool32 hasEmptyChannel = MA_FALSE; + ma_channel channelPositions[MA_MAX_CHANNELS]; + for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) { + channelPositions[iChannelOut] = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut); + if (channelPositions[iChannelOut] == MA_CHANNEL_NONE) { + hasEmptyChannel = MA_TRUE; + } + } + + if (hasEmptyChannel == MA_FALSE) { + /* + Faster path when there's no MA_CHANNEL_NONE channel positions. This should hopefully + help the compiler with auto-vectorization.m + */ + if (channelsOut == 2) { + #if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + /* We want to do two frames in each iteration. */ + ma_uint64 unrolledFrameCount = frameCount >> 1; + + for (iFrame = 0; iFrame < unrolledFrameCount; iFrame += 1) { + __m128 in0 = _mm_set1_ps(pFramesIn[iFrame*2 + 0]); + __m128 in1 = _mm_set1_ps(pFramesIn[iFrame*2 + 1]); + _mm_storeu_ps(&pFramesOut[iFrame*4 + 0], _mm_shuffle_ps(in0, in1, _MM_SHUFFLE(0, 0, 0, 0))); + } + + /* Tail. */ + iFrame = unrolledFrameCount << 1; + goto generic_on_fastpath; + } else + #endif + { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannelOut = 0; iChannelOut < 2; iChannelOut += 1) { + pFramesOut[iFrame*2 + iChannelOut] = pFramesIn[iFrame]; + } + } + } + } else if (channelsOut == 6) { + #if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + /* We want to do two frames in each iteration so we can have a multiple of 4 samples. */ + ma_uint64 unrolledFrameCount = frameCount >> 1; + + for (iFrame = 0; iFrame < unrolledFrameCount; iFrame += 1) { + __m128 in0 = _mm_set1_ps(pFramesIn[iFrame*2 + 0]); + __m128 in1 = _mm_set1_ps(pFramesIn[iFrame*2 + 1]); + + _mm_storeu_ps(&pFramesOut[iFrame*12 + 0], in0); + _mm_storeu_ps(&pFramesOut[iFrame*12 + 4], _mm_shuffle_ps(in0, in1, _MM_SHUFFLE(0, 0, 0, 0))); + _mm_storeu_ps(&pFramesOut[iFrame*12 + 8], in1); + } + + /* Tail. */ + iFrame = unrolledFrameCount << 1; + goto generic_on_fastpath; + } else + #endif + { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannelOut = 0; iChannelOut < 6; iChannelOut += 1) { + pFramesOut[iFrame*6 + iChannelOut] = pFramesIn[iFrame]; + } + } + } + } else if (channelsOut == 8) { + #if defined(MA_SUPPORT_SSE2) + if (ma_has_sse2()) { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + __m128 in = _mm_set1_ps(pFramesIn[iFrame]); + _mm_storeu_ps(&pFramesOut[iFrame*8 + 0], in); + _mm_storeu_ps(&pFramesOut[iFrame*8 + 4], in); + } + } else + #endif + { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannelOut = 0; iChannelOut < 8; iChannelOut += 1) { + pFramesOut[iFrame*8 + iChannelOut] = pFramesIn[iFrame]; + } + } + } + } else { + iFrame = 0; + + #if defined(MA_SUPPORT_SSE2) /* For silencing a warning with non-x86 builds. */ + generic_on_fastpath: + #endif + { + for (; iFrame < frameCount; iFrame += 1) { + for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) { + pFramesOut[iFrame*channelsOut + iChannelOut] = pFramesIn[iFrame]; + } + } + } + } + } else { + /* Slow path. Need to handle MA_CHANNEL_NONE. */ + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) { + if (channelPositions[iChannelOut] != MA_CHANNEL_NONE) { + pFramesOut[iFrame*channelsOut + iChannelOut] = pFramesIn[iFrame]; + } + } + } + } + } else { + /* Slow path. Too many channels to store on the stack. */ + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) { + ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut); + if (channelOut != MA_CHANNEL_NONE) { + pFramesOut[iFrame*channelsOut + iChannelOut] = pFramesIn[iFrame]; + } + } + } + } + } + } break; + } + + return MA_SUCCESS; +} + +static void ma_channel_map_apply_f32(float* pFramesOut, const ma_channel* pChannelMapOut, ma_uint32 channelsOut, const float* pFramesIn, const ma_channel* pChannelMapIn, ma_uint32 channelsIn, ma_uint64 frameCount, ma_channel_mix_mode mode, ma_mono_expansion_mode monoExpansionMode) +{ + ma_channel_conversion_path conversionPath = ma_channel_map_get_conversion_path(pChannelMapIn, channelsIn, pChannelMapOut, channelsOut, mode); + + /* Optimized Path: Passthrough */ + if (conversionPath == ma_channel_conversion_path_passthrough) { + ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, ma_format_f32, channelsOut); + return; + } + + /* Special Path: Mono Output. */ + if (conversionPath == ma_channel_conversion_path_mono_out) { + ma_channel_map_apply_mono_out_f32(pFramesOut, pFramesIn, pChannelMapIn, channelsIn, frameCount); + return; + } + + /* Special Path: Mono Input. */ + if (conversionPath == ma_channel_conversion_path_mono_in) { + ma_channel_map_apply_mono_in_f32(pFramesOut, pChannelMapOut, channelsOut, pFramesIn, frameCount, monoExpansionMode); + return; + } + + /* Getting here means we aren't running on an optimized conversion path. */ + if (channelsOut <= MA_MAX_CHANNELS) { + ma_result result; + + if (mode == ma_channel_mix_mode_simple) { + ma_channel shuffleTable[MA_MAX_CHANNELS]; + + result = ma_channel_map_build_shuffle_table(pChannelMapIn, channelsIn, pChannelMapOut, channelsOut, shuffleTable); + if (result != MA_SUCCESS) { + return; + } + + result = ma_channel_map_apply_shuffle_table(pFramesOut, channelsOut, pFramesIn, channelsIn, frameCount, shuffleTable, ma_format_f32); + if (result != MA_SUCCESS) { + return; + } + } else { + ma_uint32 iFrame; + ma_uint32 iChannelOut; + ma_uint32 iChannelIn; + float weights[32][32]; /* Do not use MA_MAX_CHANNELS here! */ + + /* + If we have a small enough number of channels, pre-compute the weights. Otherwise we'll just need to + fall back to a slower path because otherwise we'll run out of stack space. + */ + if (channelsIn <= ma_countof(weights) && channelsOut <= ma_countof(weights)) { + /* Pre-compute weights. */ + for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) { + ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut); + for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) { + ma_channel channelIn = ma_channel_map_get_channel(pChannelMapIn, channelsIn, iChannelIn); + weights[iChannelOut][iChannelIn] = ma_calculate_channel_position_rectangular_weight(channelOut, channelIn); + } + } + + iFrame = 0; + + /* Experiment: Try an optimized unroll for some specific cases to see how it improves performance. RESULT: Good gains. */ + if (channelsOut == 8) { + /* Experiment 2: Expand the inner loop to see what kind of different it makes. RESULT: Small, but worthwhile gain. */ + if (channelsIn == 2) { + for (; iFrame < frameCount; iFrame += 1) { + float accumulation[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + + accumulation[0] += pFramesIn[iFrame*2 + 0] * weights[0][0]; + accumulation[1] += pFramesIn[iFrame*2 + 0] * weights[1][0]; + accumulation[2] += pFramesIn[iFrame*2 + 0] * weights[2][0]; + accumulation[3] += pFramesIn[iFrame*2 + 0] * weights[3][0]; + accumulation[4] += pFramesIn[iFrame*2 + 0] * weights[4][0]; + accumulation[5] += pFramesIn[iFrame*2 + 0] * weights[5][0]; + accumulation[6] += pFramesIn[iFrame*2 + 0] * weights[6][0]; + accumulation[7] += pFramesIn[iFrame*2 + 0] * weights[7][0]; + + accumulation[0] += pFramesIn[iFrame*2 + 1] * weights[0][1]; + accumulation[1] += pFramesIn[iFrame*2 + 1] * weights[1][1]; + accumulation[2] += pFramesIn[iFrame*2 + 1] * weights[2][1]; + accumulation[3] += pFramesIn[iFrame*2 + 1] * weights[3][1]; + accumulation[4] += pFramesIn[iFrame*2 + 1] * weights[4][1]; + accumulation[5] += pFramesIn[iFrame*2 + 1] * weights[5][1]; + accumulation[6] += pFramesIn[iFrame*2 + 1] * weights[6][1]; + accumulation[7] += pFramesIn[iFrame*2 + 1] * weights[7][1]; + + pFramesOut[iFrame*8 + 0] = accumulation[0]; + pFramesOut[iFrame*8 + 1] = accumulation[1]; + pFramesOut[iFrame*8 + 2] = accumulation[2]; + pFramesOut[iFrame*8 + 3] = accumulation[3]; + pFramesOut[iFrame*8 + 4] = accumulation[4]; + pFramesOut[iFrame*8 + 5] = accumulation[5]; + pFramesOut[iFrame*8 + 6] = accumulation[6]; + pFramesOut[iFrame*8 + 7] = accumulation[7]; + } + } else { + /* When outputting to 8 channels, we can do everything in groups of two 4x SIMD operations. */ + for (; iFrame < frameCount; iFrame += 1) { + float accumulation[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + + for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) { + accumulation[0] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[0][iChannelIn]; + accumulation[1] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[1][iChannelIn]; + accumulation[2] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[2][iChannelIn]; + accumulation[3] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[3][iChannelIn]; + accumulation[4] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[4][iChannelIn]; + accumulation[5] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[5][iChannelIn]; + accumulation[6] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[6][iChannelIn]; + accumulation[7] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[7][iChannelIn]; + } + + pFramesOut[iFrame*8 + 0] = accumulation[0]; + pFramesOut[iFrame*8 + 1] = accumulation[1]; + pFramesOut[iFrame*8 + 2] = accumulation[2]; + pFramesOut[iFrame*8 + 3] = accumulation[3]; + pFramesOut[iFrame*8 + 4] = accumulation[4]; + pFramesOut[iFrame*8 + 5] = accumulation[5]; + pFramesOut[iFrame*8 + 6] = accumulation[6]; + pFramesOut[iFrame*8 + 7] = accumulation[7]; + } + } + } else if (channelsOut == 6) { + /* + When outputting to 6 channels we unfortunately don't have a nice multiple of 4 to do 4x SIMD operations. Instead we'll + expand our weights and do two frames at a time. + */ + for (; iFrame < frameCount; iFrame += 1) { + float accumulation[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + + for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) { + accumulation[0] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[0][iChannelIn]; + accumulation[1] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[1][iChannelIn]; + accumulation[2] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[2][iChannelIn]; + accumulation[3] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[3][iChannelIn]; + accumulation[4] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[4][iChannelIn]; + accumulation[5] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[5][iChannelIn]; + } + + pFramesOut[iFrame*6 + 0] = accumulation[0]; + pFramesOut[iFrame*6 + 1] = accumulation[1]; + pFramesOut[iFrame*6 + 2] = accumulation[2]; + pFramesOut[iFrame*6 + 3] = accumulation[3]; + pFramesOut[iFrame*6 + 4] = accumulation[4]; + pFramesOut[iFrame*6 + 5] = accumulation[5]; + } + } + + /* Leftover frames. */ + for (; iFrame < frameCount; iFrame += 1) { + for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) { + float accumulation = 0; + + for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) { + accumulation += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[iChannelOut][iChannelIn]; + } + + pFramesOut[iFrame*channelsOut + iChannelOut] = accumulation; + } + } + } else { + /* Cannot pre-compute weights because not enough room in stack-allocated buffer. */ + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) { + float accumulation = 0; + ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut); + + for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) { + ma_channel channelIn = ma_channel_map_get_channel(pChannelMapIn, channelsIn, iChannelIn); + accumulation += pFramesIn[iFrame*channelsIn + iChannelIn] * ma_calculate_channel_position_rectangular_weight(channelOut, channelIn); + } + + pFramesOut[iFrame*channelsOut + iChannelOut] = accumulation; + } + } + } + } + } else { + /* Fall back to silence. If you hit this, what are you doing with so many channels?! */ + ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, channelsOut); + } +} + + +typedef struct +{ + size_t sizeInBytes; + size_t channelMapInOffset; + size_t channelMapOutOffset; + size_t shuffleTableOffset; + size_t weightsOffset; +} ma_channel_converter_heap_layout; + +static ma_channel_conversion_path ma_channel_converter_config_get_conversion_path(const ma_channel_converter_config* pConfig) +{ + return ma_channel_map_get_conversion_path(pConfig->pChannelMapIn, pConfig->channelsIn, pConfig->pChannelMapOut, pConfig->channelsOut, pConfig->mixingMode); +} + +static ma_result ma_channel_converter_get_heap_layout(const ma_channel_converter_config* pConfig, ma_channel_converter_heap_layout* pHeapLayout) +{ + ma_channel_conversion_path conversionPath; + + MA_ASSERT(pHeapLayout != NULL); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->channelsIn == 0 || pConfig->channelsOut == 0) { + return MA_INVALID_ARGS; + } + + if (!ma_channel_map_is_valid(pConfig->pChannelMapIn, pConfig->channelsIn)) { + return MA_INVALID_ARGS; + } + + if (!ma_channel_map_is_valid(pConfig->pChannelMapOut, pConfig->channelsOut)) { + return MA_INVALID_ARGS; + } + + pHeapLayout->sizeInBytes = 0; + + /* Input channel map. Only need to allocate this if we have an input channel map (otherwise default channel map is assumed). */ + pHeapLayout->channelMapInOffset = pHeapLayout->sizeInBytes; + if (pConfig->pChannelMapIn != NULL) { + pHeapLayout->sizeInBytes += sizeof(ma_channel) * pConfig->channelsIn; + } + + /* Output channel map. Only need to allocate this if we have an output channel map (otherwise default channel map is assumed). */ + pHeapLayout->channelMapOutOffset = pHeapLayout->sizeInBytes; + if (pConfig->pChannelMapOut != NULL) { + pHeapLayout->sizeInBytes += sizeof(ma_channel) * pConfig->channelsOut; + } + + /* Alignment for the next section. */ + pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes); + + /* Whether or not we use weights of a shuffle table depends on the channel map themselves and the algorithm we've chosen. */ + conversionPath = ma_channel_converter_config_get_conversion_path(pConfig); + + /* Shuffle table */ + pHeapLayout->shuffleTableOffset = pHeapLayout->sizeInBytes; + if (conversionPath == ma_channel_conversion_path_shuffle) { + pHeapLayout->sizeInBytes += sizeof(ma_uint8) * pConfig->channelsOut; + } + + /* Weights */ + pHeapLayout->weightsOffset = pHeapLayout->sizeInBytes; + if (conversionPath == ma_channel_conversion_path_weights) { + pHeapLayout->sizeInBytes += sizeof(float*) * pConfig->channelsIn; + pHeapLayout->sizeInBytes += sizeof(float ) * pConfig->channelsIn * pConfig->channelsOut; + } + + /* Make sure allocation size is aligned. */ + pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes); + + return MA_SUCCESS; +} + +MA_API ma_result ma_channel_converter_get_heap_size(const ma_channel_converter_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_result result; + ma_channel_converter_heap_layout heapLayout; + + if (pHeapSizeInBytes == NULL) { + return MA_INVALID_ARGS; + } + + *pHeapSizeInBytes = 0; + + result = ma_channel_converter_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + *pHeapSizeInBytes = heapLayout.sizeInBytes; + + return MA_SUCCESS; +} + +MA_API ma_result ma_channel_converter_init_preallocated(const ma_channel_converter_config* pConfig, void* pHeap, ma_channel_converter* pConverter) +{ + ma_result result; + ma_channel_converter_heap_layout heapLayout; + + if (pConverter == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pConverter); + + result = ma_channel_converter_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + pConverter->_pHeap = pHeap; + MA_ZERO_MEMORY(pConverter->_pHeap, heapLayout.sizeInBytes); + + pConverter->format = pConfig->format; + pConverter->channelsIn = pConfig->channelsIn; + pConverter->channelsOut = pConfig->channelsOut; + pConverter->mixingMode = pConfig->mixingMode; + + if (pConfig->pChannelMapIn != NULL) { + pConverter->pChannelMapIn = (ma_channel*)ma_offset_ptr(pHeap, heapLayout.channelMapInOffset); + ma_channel_map_copy_or_default(pConverter->pChannelMapIn, pConfig->channelsIn, pConfig->pChannelMapIn, pConfig->channelsIn); + } else { + pConverter->pChannelMapIn = NULL; /* Use default channel map. */ + } + + if (pConfig->pChannelMapOut != NULL) { + pConverter->pChannelMapOut = (ma_channel*)ma_offset_ptr(pHeap, heapLayout.channelMapOutOffset); + ma_channel_map_copy_or_default(pConverter->pChannelMapOut, pConfig->channelsOut, pConfig->pChannelMapOut, pConfig->channelsOut); + } else { + pConverter->pChannelMapOut = NULL; /* Use default channel map. */ + } + + pConverter->conversionPath = ma_channel_converter_config_get_conversion_path(pConfig); + + if (pConverter->conversionPath == ma_channel_conversion_path_shuffle) { + pConverter->pShuffleTable = (ma_uint8*)ma_offset_ptr(pHeap, heapLayout.shuffleTableOffset); + ma_channel_map_build_shuffle_table(pConverter->pChannelMapIn, pConverter->channelsIn, pConverter->pChannelMapOut, pConverter->channelsOut, pConverter->pShuffleTable); + } + + if (pConverter->conversionPath == ma_channel_conversion_path_weights) { + ma_uint32 iChannelIn; + ma_uint32 iChannelOut; + + if (pConverter->format == ma_format_f32) { + pConverter->weights.f32 = (float** )ma_offset_ptr(pHeap, heapLayout.weightsOffset); + for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; iChannelIn += 1) { + pConverter->weights.f32[iChannelIn] = (float*)ma_offset_ptr(pHeap, heapLayout.weightsOffset + ((sizeof(float*) * pConverter->channelsIn) + (sizeof(float) * pConverter->channelsOut * iChannelIn))); + } + } else { + pConverter->weights.s16 = (ma_int32**)ma_offset_ptr(pHeap, heapLayout.weightsOffset); + for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; iChannelIn += 1) { + pConverter->weights.s16[iChannelIn] = (ma_int32*)ma_offset_ptr(pHeap, heapLayout.weightsOffset + ((sizeof(ma_int32*) * pConverter->channelsIn) + (sizeof(ma_int32) * pConverter->channelsOut * iChannelIn))); + } + } + + /* Silence our weights by default. */ + for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; iChannelIn += 1) { + for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; iChannelOut += 1) { + if (pConverter->format == ma_format_f32) { + pConverter->weights.f32[iChannelIn][iChannelOut] = 0.0f; + } else { + pConverter->weights.s16[iChannelIn][iChannelOut] = 0; + } + } + } + + /* + We now need to fill out our weights table. This is determined by the mixing mode. + */ + + /* 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 < pConverter->channelsIn; ++iChannelIn) { + ma_channel channelPosIn = ma_channel_map_get_channel(pConverter->pChannelMapIn, pConverter->channelsIn, iChannelIn); + + for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) { + ma_channel channelPosOut = ma_channel_map_get_channel(pConverter->pChannelMapOut, pConverter->channelsOut, iChannelOut); + + if (channelPosIn == channelPosOut) { + float weight = 1; + + if (pConverter->format == ma_format_f32) { + pConverter->weights.f32[iChannelIn][iChannelOut] = weight; + } else { + pConverter->weights.s16[iChannelIn][iChannelOut] = ma_channel_converter_float_to_fixed(weight); + } + } + } + } + + switch (pConverter->mixingMode) + { + case ma_channel_mix_mode_custom_weights: + { + if (pConfig->ppWeights == NULL) { + return MA_INVALID_ARGS; /* Config specified a custom weights mixing mode, but no custom weights have been specified. */ + } + + for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; iChannelIn += 1) { + for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; iChannelOut += 1) { + float weight = pConfig->ppWeights[iChannelIn][iChannelOut]; + + if (pConverter->format == ma_format_f32) { + pConverter->weights.f32[iChannelIn][iChannelOut] = weight; + } else { + pConverter->weights.s16[iChannelIn][iChannelOut] = ma_channel_converter_float_to_fixed(weight); + } + } + } + } break; + + case ma_channel_mix_mode_simple: + { + /* + In simple mode, only set weights for channels that have exactly matching types, leave the rest at + zero. The 1:1 mappings have already been covered before this switch statement. + */ + } break; + + case ma_channel_mix_mode_rectangular: + default: + { + /* Unmapped input channels. */ + for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) { + ma_channel channelPosIn = ma_channel_map_get_channel(pConverter->pChannelMapIn, pConverter->channelsIn, iChannelIn); + + if (ma_is_spatial_channel_position(channelPosIn)) { + if (!ma_channel_map_contains_channel_position(pConverter->channelsOut, pConverter->pChannelMapOut, channelPosIn)) { + for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) { + ma_channel channelPosOut = ma_channel_map_get_channel(pConverter->pChannelMapOut, pConverter->channelsOut, iChannelOut); + + if (ma_is_spatial_channel_position(channelPosOut)) { + float weight = 0; + if (pConverter->mixingMode == ma_channel_mix_mode_rectangular) { + weight = ma_calculate_channel_position_rectangular_weight(channelPosIn, channelPosOut); + } + + /* Only apply the weight if we haven't already got some contribution from the respective channels. */ + if (pConverter->format == ma_format_f32) { + if (pConverter->weights.f32[iChannelIn][iChannelOut] == 0) { + pConverter->weights.f32[iChannelIn][iChannelOut] = weight; + } + } else { + if (pConverter->weights.s16[iChannelIn][iChannelOut] == 0) { + pConverter->weights.s16[iChannelIn][iChannelOut] = ma_channel_converter_float_to_fixed(weight); + } + } + } + } + } + } + } + + /* Unmapped output channels. */ + for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) { + ma_channel channelPosOut = ma_channel_map_get_channel(pConverter->pChannelMapOut, pConverter->channelsOut, iChannelOut); + + if (ma_is_spatial_channel_position(channelPosOut)) { + if (!ma_channel_map_contains_channel_position(pConverter->channelsIn, pConverter->pChannelMapIn, channelPosOut)) { + for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) { + ma_channel channelPosIn = ma_channel_map_get_channel(pConverter->pChannelMapIn, pConverter->channelsIn, iChannelIn); + + if (ma_is_spatial_channel_position(channelPosIn)) { + float weight = 0; + if (pConverter->mixingMode == ma_channel_mix_mode_rectangular) { + weight = ma_calculate_channel_position_rectangular_weight(channelPosIn, channelPosOut); + } + + /* Only apply the weight if we haven't already got some contribution from the respective channels. */ + if (pConverter->format == ma_format_f32) { + if (pConverter->weights.f32[iChannelIn][iChannelOut] == 0) { + pConverter->weights.f32[iChannelIn][iChannelOut] = weight; + } + } else { + if (pConverter->weights.s16[iChannelIn][iChannelOut] == 0) { + pConverter->weights.s16[iChannelIn][iChannelOut] = ma_channel_converter_float_to_fixed(weight); + } + } + } + } + } + } + } + + /* If LFE is in the output channel map but was not present in the input channel map, configure its weight now */ + if (pConfig->calculateLFEFromSpatialChannels) { + if (!ma_channel_map_contains_channel_position(pConverter->channelsIn, pConverter->pChannelMapIn, MA_CHANNEL_LFE)) { + ma_uint32 spatialChannelCount = ma_channel_map_get_spatial_channel_count(pConverter->pChannelMapIn, pConverter->channelsIn); + ma_uint32 iChannelOutLFE; + + if (spatialChannelCount > 0 && ma_channel_map_find_channel_position(pConverter->channelsOut, pConverter->pChannelMapOut, MA_CHANNEL_LFE, &iChannelOutLFE)) { + const float weightForLFE = 1.0f / spatialChannelCount; + for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) { + const ma_channel channelPosIn = ma_channel_map_get_channel(pConverter->pChannelMapIn, pConverter->channelsIn, iChannelIn); + if (ma_is_spatial_channel_position(channelPosIn)) { + if (pConverter->format == ma_format_f32) { + if (pConverter->weights.f32[iChannelIn][iChannelOutLFE] == 0) { + pConverter->weights.f32[iChannelIn][iChannelOutLFE] = weightForLFE; + } + } else { + if (pConverter->weights.s16[iChannelIn][iChannelOutLFE] == 0) { + pConverter->weights.s16[iChannelIn][iChannelOutLFE] = ma_channel_converter_float_to_fixed(weightForLFE); + } + } + } + } + } + } + } + } break; + } + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_channel_converter_init(const ma_channel_converter_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_channel_converter* pConverter) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_channel_converter_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_channel_converter_init_preallocated(pConfig, pHeap, pConverter); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pConverter->_ownsHeap = MA_TRUE; + return MA_SUCCESS; +} + +MA_API void ma_channel_converter_uninit(ma_channel_converter* pConverter, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pConverter == NULL) { + return; + } + + if (pConverter->_ownsHeap) { + ma_free(pConverter->_pHeap, pAllocationCallbacks); + } +} + +static ma_result ma_channel_converter_process_pcm_frames__passthrough(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + MA_ASSERT(pConverter != NULL); + MA_ASSERT(pFramesOut != NULL); + MA_ASSERT(pFramesIn != NULL); + + ma_copy_memory_64(pFramesOut, pFramesIn, frameCount * ma_get_bytes_per_frame(pConverter->format, pConverter->channelsOut)); + return MA_SUCCESS; +} + +static ma_result ma_channel_converter_process_pcm_frames__shuffle(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + MA_ASSERT(pConverter != NULL); + MA_ASSERT(pFramesOut != NULL); + MA_ASSERT(pFramesIn != NULL); + MA_ASSERT(pConverter->channelsIn == pConverter->channelsOut); + + return ma_channel_map_apply_shuffle_table(pFramesOut, pConverter->channelsOut, pFramesIn, pConverter->channelsIn, frameCount, pConverter->pShuffleTable, pConverter->format); +} + +static ma_result ma_channel_converter_process_pcm_frames__mono_in(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + ma_uint64 iFrame; + + MA_ASSERT(pConverter != NULL); + MA_ASSERT(pFramesOut != NULL); + MA_ASSERT(pFramesIn != NULL); + MA_ASSERT(pConverter->channelsIn == 1); + + switch (pConverter->format) + { + case ma_format_u8: + { + /* */ ma_uint8* pFramesOutU8 = ( ma_uint8*)pFramesOut; + const ma_uint8* pFramesInU8 = (const ma_uint8*)pFramesIn; + + for (iFrame = 0; iFrame < frameCount; ++iFrame) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) { + pFramesOutU8[iFrame*pConverter->channelsOut + iChannel] = pFramesInU8[iFrame]; + } + } + } break; + + case ma_format_s16: + { + /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut; + const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn; + + if (pConverter->channelsOut == 2) { + for (iFrame = 0; iFrame < frameCount; ++iFrame) { + pFramesOutS16[iFrame*2 + 0] = pFramesInS16[iFrame]; + pFramesOutS16[iFrame*2 + 1] = pFramesInS16[iFrame]; + } + } else { + for (iFrame = 0; iFrame < frameCount; ++iFrame) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) { + pFramesOutS16[iFrame*pConverter->channelsOut + iChannel] = pFramesInS16[iFrame]; + } + } + } + } break; + + case ma_format_s24: + { + /* */ ma_uint8* pFramesOutS24 = ( ma_uint8*)pFramesOut; + const ma_uint8* pFramesInS24 = (const ma_uint8*)pFramesIn; + + for (iFrame = 0; iFrame < frameCount; ++iFrame) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) { + ma_uint64 iSampleOut = iFrame*pConverter->channelsOut + iChannel; + ma_uint64 iSampleIn = iFrame; + pFramesOutS24[iSampleOut*3 + 0] = pFramesInS24[iSampleIn*3 + 0]; + pFramesOutS24[iSampleOut*3 + 1] = pFramesInS24[iSampleIn*3 + 1]; + pFramesOutS24[iSampleOut*3 + 2] = pFramesInS24[iSampleIn*3 + 2]; + } + } + } break; + + case ma_format_s32: + { + /* */ ma_int32* pFramesOutS32 = ( ma_int32*)pFramesOut; + const ma_int32* pFramesInS32 = (const ma_int32*)pFramesIn; + + for (iFrame = 0; iFrame < frameCount; ++iFrame) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) { + pFramesOutS32[iFrame*pConverter->channelsOut + iChannel] = pFramesInS32[iFrame]; + } + } + } break; + + case ma_format_f32: + { + /* */ float* pFramesOutF32 = ( float*)pFramesOut; + const float* pFramesInF32 = (const float*)pFramesIn; + + if (pConverter->channelsOut == 2) { + for (iFrame = 0; iFrame < frameCount; ++iFrame) { + pFramesOutF32[iFrame*2 + 0] = pFramesInF32[iFrame]; + pFramesOutF32[iFrame*2 + 1] = pFramesInF32[iFrame]; + } + } else { + for (iFrame = 0; iFrame < frameCount; ++iFrame) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) { + pFramesOutF32[iFrame*pConverter->channelsOut + iChannel] = pFramesInF32[iFrame]; + } + } + } + } break; + + default: return MA_INVALID_OPERATION; /* Unknown format. */ + } + + return MA_SUCCESS; +} + +static ma_result ma_channel_converter_process_pcm_frames__mono_out(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + ma_uint64 iFrame; + ma_uint32 iChannel; + + MA_ASSERT(pConverter != NULL); + MA_ASSERT(pFramesOut != NULL); + MA_ASSERT(pFramesIn != NULL); + MA_ASSERT(pConverter->channelsOut == 1); + + switch (pConverter->format) + { + case ma_format_u8: + { + /* */ ma_uint8* pFramesOutU8 = ( ma_uint8*)pFramesOut; + const ma_uint8* pFramesInU8 = (const ma_uint8*)pFramesIn; + + for (iFrame = 0; iFrame < frameCount; ++iFrame) { + ma_int32 t = 0; + for (iChannel = 0; iChannel < pConverter->channelsIn; iChannel += 1) { + t += ma_pcm_sample_u8_to_s16_no_scale(pFramesInU8[iFrame*pConverter->channelsIn + iChannel]); + } + + pFramesOutU8[iFrame] = ma_clip_u8(t / pConverter->channelsOut); + } + } break; + + case ma_format_s16: + { + /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut; + const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn; + + for (iFrame = 0; iFrame < frameCount; ++iFrame) { + ma_int32 t = 0; + for (iChannel = 0; iChannel < pConverter->channelsIn; iChannel += 1) { + t += pFramesInS16[iFrame*pConverter->channelsIn + iChannel]; + } + + pFramesOutS16[iFrame] = (ma_int16)(t / pConverter->channelsIn); + } + } break; + + case ma_format_s24: + { + /* */ ma_uint8* pFramesOutS24 = ( ma_uint8*)pFramesOut; + const ma_uint8* pFramesInS24 = (const ma_uint8*)pFramesIn; + + for (iFrame = 0; iFrame < frameCount; ++iFrame) { + ma_int64 t = 0; + for (iChannel = 0; iChannel < pConverter->channelsIn; iChannel += 1) { + t += ma_pcm_sample_s24_to_s32_no_scale(&pFramesInS24[(iFrame*pConverter->channelsIn + iChannel)*3]); + } + + ma_pcm_sample_s32_to_s24_no_scale(t / pConverter->channelsIn, &pFramesOutS24[iFrame*3]); + } + } break; + + case ma_format_s32: + { + /* */ ma_int32* pFramesOutS32 = ( ma_int32*)pFramesOut; + const ma_int32* pFramesInS32 = (const ma_int32*)pFramesIn; + + for (iFrame = 0; iFrame < frameCount; ++iFrame) { + ma_int64 t = 0; + for (iChannel = 0; iChannel < pConverter->channelsIn; iChannel += 1) { + t += pFramesInS32[iFrame*pConverter->channelsIn + iChannel]; + } + + pFramesOutS32[iFrame] = (ma_int32)(t / pConverter->channelsIn); + } + } break; + + case ma_format_f32: + { + /* */ float* pFramesOutF32 = ( float*)pFramesOut; + const float* pFramesInF32 = (const float*)pFramesIn; + + for (iFrame = 0; iFrame < frameCount; ++iFrame) { + float t = 0; + for (iChannel = 0; iChannel < pConverter->channelsIn; iChannel += 1) { + t += pFramesInF32[iFrame*pConverter->channelsIn + iChannel]; + } + + pFramesOutF32[iFrame] = t / pConverter->channelsIn; + } + } break; + + default: return MA_INVALID_OPERATION; /* Unknown format. */ + } + + return MA_SUCCESS; +} + +static ma_result ma_channel_converter_process_pcm_frames__weights(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + ma_uint32 iFrame; + ma_uint32 iChannelIn; + ma_uint32 iChannelOut; + + MA_ASSERT(pConverter != NULL); + MA_ASSERT(pFramesOut != NULL); + MA_ASSERT(pFramesIn != NULL); + + /* This is the more complicated case. Each of the output channels is accumulated with 0 or more input channels. */ + + /* Clear. */ + ma_zero_memory_64(pFramesOut, frameCount * ma_get_bytes_per_frame(pConverter->format, pConverter->channelsOut)); + + /* Accumulate. */ + switch (pConverter->format) + { + case ma_format_u8: + { + /* */ ma_uint8* pFramesOutU8 = ( ma_uint8*)pFramesOut; + const ma_uint8* pFramesInU8 = (const ma_uint8*)pFramesIn; + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) { + for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) { + ma_int16 u8_O = ma_pcm_sample_u8_to_s16_no_scale(pFramesOutU8[iFrame*pConverter->channelsOut + iChannelOut]); + ma_int16 u8_I = ma_pcm_sample_u8_to_s16_no_scale(pFramesInU8 [iFrame*pConverter->channelsIn + iChannelIn ]); + ma_int32 s = (ma_int32)ma_clamp(u8_O + ((u8_I * pConverter->weights.s16[iChannelIn][iChannelOut]) >> MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT), -128, 127); + pFramesOutU8[iFrame*pConverter->channelsOut + iChannelOut] = ma_clip_u8((ma_int16)s); + } + } + } + } break; + + case ma_format_s16: + { + /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut; + const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn; + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) { + for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) { + ma_int32 s = pFramesOutS16[iFrame*pConverter->channelsOut + iChannelOut]; + s += (pFramesInS16[iFrame*pConverter->channelsIn + iChannelIn] * pConverter->weights.s16[iChannelIn][iChannelOut]) >> MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT; + + pFramesOutS16[iFrame*pConverter->channelsOut + iChannelOut] = (ma_int16)ma_clamp(s, -32768, 32767); + } + } + } + } break; + + case ma_format_s24: + { + /* */ ma_uint8* pFramesOutS24 = ( ma_uint8*)pFramesOut; + const ma_uint8* pFramesInS24 = (const ma_uint8*)pFramesIn; + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) { + for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) { + ma_int64 s24_O = ma_pcm_sample_s24_to_s32_no_scale(&pFramesOutS24[(iFrame*pConverter->channelsOut + iChannelOut)*3]); + ma_int64 s24_I = ma_pcm_sample_s24_to_s32_no_scale(&pFramesInS24 [(iFrame*pConverter->channelsIn + iChannelIn )*3]); + ma_int64 s24 = (ma_int32)ma_clamp(s24_O + ((s24_I * pConverter->weights.s16[iChannelIn][iChannelOut]) >> MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT), -8388608, 8388607); + ma_pcm_sample_s32_to_s24_no_scale(s24, &pFramesOutS24[(iFrame*pConverter->channelsOut + iChannelOut)*3]); + } + } + } + } break; + + case ma_format_s32: + { + /* */ ma_int32* pFramesOutS32 = ( ma_int32*)pFramesOut; + const ma_int32* pFramesInS32 = (const ma_int32*)pFramesIn; + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) { + for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) { + ma_int64 s = pFramesOutS32[iFrame*pConverter->channelsOut + iChannelOut]; + s += ((ma_int64)pFramesInS32[iFrame*pConverter->channelsIn + iChannelIn] * pConverter->weights.s16[iChannelIn][iChannelOut]) >> MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT; + + pFramesOutS32[iFrame*pConverter->channelsOut + iChannelOut] = ma_clip_s32(s); + } + } + } + } break; + + case ma_format_f32: + { + /* */ float* pFramesOutF32 = ( float*)pFramesOut; + const float* pFramesInF32 = (const float*)pFramesIn; + + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) { + for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) { + pFramesOutF32[iFrame*pConverter->channelsOut + iChannelOut] += pFramesInF32[iFrame*pConverter->channelsIn + iChannelIn] * pConverter->weights.f32[iChannelIn][iChannelOut]; + } + } + } + } break; + + default: return MA_INVALID_OPERATION; /* Unknown format. */ + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_channel_converter_process_pcm_frames(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount) +{ + if (pConverter == NULL) { + return MA_INVALID_ARGS; + } + + if (pFramesOut == NULL) { + return MA_INVALID_ARGS; + } + + if (pFramesIn == NULL) { + ma_zero_memory_64(pFramesOut, frameCount * ma_get_bytes_per_frame(pConverter->format, pConverter->channelsOut)); + return MA_SUCCESS; + } + + switch (pConverter->conversionPath) + { + case ma_channel_conversion_path_passthrough: return ma_channel_converter_process_pcm_frames__passthrough(pConverter, pFramesOut, pFramesIn, frameCount); + case ma_channel_conversion_path_mono_out: return ma_channel_converter_process_pcm_frames__mono_out(pConverter, pFramesOut, pFramesIn, frameCount); + case ma_channel_conversion_path_mono_in: return ma_channel_converter_process_pcm_frames__mono_in(pConverter, pFramesOut, pFramesIn, frameCount); + case ma_channel_conversion_path_shuffle: return ma_channel_converter_process_pcm_frames__shuffle(pConverter, pFramesOut, pFramesIn, frameCount); + case ma_channel_conversion_path_weights: + default: + { + return ma_channel_converter_process_pcm_frames__weights(pConverter, pFramesOut, pFramesIn, frameCount); + } + } +} + +MA_API ma_result ma_channel_converter_get_input_channel_map(const ma_channel_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap) +{ + if (pConverter == NULL || pChannelMap == NULL) { + return MA_INVALID_ARGS; + } + + ma_channel_map_copy_or_default(pChannelMap, channelMapCap, pConverter->pChannelMapIn, pConverter->channelsIn); + + return MA_SUCCESS; +} + +MA_API ma_result ma_channel_converter_get_output_channel_map(const ma_channel_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap) +{ + if (pConverter == NULL || pChannelMap == NULL) { + return MA_INVALID_ARGS; + } + + ma_channel_map_copy_or_default(pChannelMap, channelMapCap, pConverter->pChannelMapOut, pConverter->channelsOut); + + return MA_SUCCESS; +} + + +/************************************************************************************************************************************************************** + +Data Conversion + +**************************************************************************************************************************************************************/ +MA_API ma_data_converter_config ma_data_converter_config_init_default(void) +{ + ma_data_converter_config config; + MA_ZERO_OBJECT(&config); + + config.ditherMode = ma_dither_mode_none; + config.resampling.algorithm = ma_resample_algorithm_linear; + config.allowDynamicSampleRate = MA_FALSE; /* Disable dynamic sample rates by default because dynamic rate adjustments should be quite rare and it allows an optimization for cases when the in and out sample rates are the same. */ + + /* Linear resampling defaults. */ + config.resampling.linear.lpfOrder = 1; + + return config; +} + +MA_API ma_data_converter_config ma_data_converter_config_init(ma_format formatIn, ma_format formatOut, ma_uint32 channelsIn, ma_uint32 channelsOut, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut) +{ + ma_data_converter_config config = ma_data_converter_config_init_default(); + config.formatIn = formatIn; + config.formatOut = formatOut; + config.channelsIn = channelsIn; + config.channelsOut = channelsOut; + config.sampleRateIn = sampleRateIn; + config.sampleRateOut = sampleRateOut; + + return config; +} + + +typedef struct +{ + size_t sizeInBytes; + size_t channelConverterOffset; + size_t resamplerOffset; +} ma_data_converter_heap_layout; + +static ma_bool32 ma_data_converter_config_is_resampler_required(const ma_data_converter_config* pConfig) +{ + MA_ASSERT(pConfig != NULL); + + return pConfig->allowDynamicSampleRate || pConfig->sampleRateIn != pConfig->sampleRateOut; +} + +static ma_format ma_data_converter_config_get_mid_format(const ma_data_converter_config* pConfig) +{ + MA_ASSERT(pConfig != NULL); + + /* + We want to avoid as much data conversion as possible. The channel converter and linear + resampler both support s16 and f32 natively. We need to decide on the format to use for this + stage. We call this the mid format because it's used in the middle stage of the conversion + pipeline. If the output format is either s16 or f32 we use that one. If that is not the case it + will do the same thing for the input format. If it's neither we just use f32. If we are using a + custom resampling backend, we can only guarantee that f32 will be supported so we'll be forced + to use that if resampling is required. + */ + if (ma_data_converter_config_is_resampler_required(pConfig) && pConfig->resampling.algorithm != ma_resample_algorithm_linear) { + return ma_format_f32; /* <-- Force f32 since that is the only one we can guarantee will be supported by the resampler. */ + } else { + /* */ if (pConfig->formatOut == ma_format_s16 || pConfig->formatOut == ma_format_f32) { + return pConfig->formatOut; + } else if (pConfig->formatIn == ma_format_s16 || pConfig->formatIn == ma_format_f32) { + return pConfig->formatIn; + } else { + return ma_format_f32; + } + } +} + +static ma_channel_converter_config ma_channel_converter_config_init_from_data_converter_config(const ma_data_converter_config* pConfig) +{ + ma_channel_converter_config channelConverterConfig; + + MA_ASSERT(pConfig != NULL); + + channelConverterConfig = ma_channel_converter_config_init(ma_data_converter_config_get_mid_format(pConfig), pConfig->channelsIn, pConfig->pChannelMapIn, pConfig->channelsOut, pConfig->pChannelMapOut, pConfig->channelMixMode); + channelConverterConfig.ppWeights = pConfig->ppChannelWeights; + channelConverterConfig.calculateLFEFromSpatialChannels = pConfig->calculateLFEFromSpatialChannels; + + return channelConverterConfig; +} + +static ma_resampler_config ma_resampler_config_init_from_data_converter_config(const ma_data_converter_config* pConfig) +{ + ma_resampler_config resamplerConfig; + ma_uint32 resamplerChannels; + + MA_ASSERT(pConfig != NULL); + + /* The resampler is the most expensive part of the conversion process, so we need to do it at the stage where the channel count is at it's lowest. */ + if (pConfig->channelsIn < pConfig->channelsOut) { + resamplerChannels = pConfig->channelsIn; + } else { + resamplerChannels = pConfig->channelsOut; + } + + resamplerConfig = ma_resampler_config_init(ma_data_converter_config_get_mid_format(pConfig), resamplerChannels, pConfig->sampleRateIn, pConfig->sampleRateOut, pConfig->resampling.algorithm); + resamplerConfig.linear = pConfig->resampling.linear; + resamplerConfig.pBackendVTable = pConfig->resampling.pBackendVTable; + resamplerConfig.pBackendUserData = pConfig->resampling.pBackendUserData; + + return resamplerConfig; +} + +static ma_result ma_data_converter_get_heap_layout(const ma_data_converter_config* pConfig, ma_data_converter_heap_layout* pHeapLayout) +{ + ma_result result; + + MA_ASSERT(pHeapLayout != NULL); + + MA_ZERO_OBJECT(pHeapLayout); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->channelsIn == 0 || pConfig->channelsOut == 0) { + return MA_INVALID_ARGS; + } + + pHeapLayout->sizeInBytes = 0; + + /* Channel converter. */ + pHeapLayout->channelConverterOffset = pHeapLayout->sizeInBytes; + { + size_t heapSizeInBytes; + ma_channel_converter_config channelConverterConfig = ma_channel_converter_config_init_from_data_converter_config(pConfig); + + result = ma_channel_converter_get_heap_size(&channelConverterConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + pHeapLayout->sizeInBytes += heapSizeInBytes; + } + + /* Resampler. */ + pHeapLayout->resamplerOffset = pHeapLayout->sizeInBytes; + if (ma_data_converter_config_is_resampler_required(pConfig)) { + size_t heapSizeInBytes; + ma_resampler_config resamplerConfig = ma_resampler_config_init_from_data_converter_config(pConfig); + + result = ma_resampler_get_heap_size(&resamplerConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + pHeapLayout->sizeInBytes += heapSizeInBytes; + } + + /* Make sure allocation size is aligned. */ + pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes); + + return MA_SUCCESS; +} + +MA_API ma_result ma_data_converter_get_heap_size(const ma_data_converter_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_result result; + ma_data_converter_heap_layout heapLayout; + + if (pHeapSizeInBytes == NULL) { + return MA_INVALID_ARGS; + } + + *pHeapSizeInBytes = 0; + + result = ma_data_converter_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + *pHeapSizeInBytes = heapLayout.sizeInBytes; + + return MA_SUCCESS; +} + +MA_API ma_result ma_data_converter_init_preallocated(const ma_data_converter_config* pConfig, void* pHeap, ma_data_converter* pConverter) +{ + ma_result result; + ma_data_converter_heap_layout heapLayout; + ma_format midFormat; + ma_bool32 isResamplingRequired; + + if (pConverter == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pConverter); + + result = ma_data_converter_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + pConverter->_pHeap = pHeap; + MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes); + + pConverter->formatIn = pConfig->formatIn; + pConverter->formatOut = pConfig->formatOut; + pConverter->channelsIn = pConfig->channelsIn; + pConverter->channelsOut = pConfig->channelsOut; + pConverter->sampleRateIn = pConfig->sampleRateIn; + pConverter->sampleRateOut = pConfig->sampleRateOut; + pConverter->ditherMode = pConfig->ditherMode; + + /* + Determine if resampling is required. We need to do this so we can determine an appropriate + mid format to use. If resampling is required, the mid format must be ma_format_f32 since + that is the only one that is guaranteed to supported by custom resampling backends. + */ + isResamplingRequired = ma_data_converter_config_is_resampler_required(pConfig); + midFormat = ma_data_converter_config_get_mid_format(pConfig); + + + /* Channel converter. We always initialize this, but we check if it configures itself as a passthrough to determine whether or not it's needed. */ + { + ma_channel_converter_config channelConverterConfig = ma_channel_converter_config_init_from_data_converter_config(pConfig); + + result = ma_channel_converter_init_preallocated(&channelConverterConfig, ma_offset_ptr(pHeap, heapLayout.channelConverterOffset), &pConverter->channelConverter); + if (result != MA_SUCCESS) { + return result; + } + + /* If the channel converter is not a passthrough we need to enable it. Otherwise we can skip it. */ + if (pConverter->channelConverter.conversionPath != ma_channel_conversion_path_passthrough) { + pConverter->hasChannelConverter = MA_TRUE; + } + } + + + /* Resampler. */ + if (isResamplingRequired) { + ma_resampler_config resamplerConfig = ma_resampler_config_init_from_data_converter_config(pConfig); + + result = ma_resampler_init_preallocated(&resamplerConfig, ma_offset_ptr(pHeap, heapLayout.resamplerOffset), &pConverter->resampler); + if (result != MA_SUCCESS) { + return result; + } + + pConverter->hasResampler = MA_TRUE; + } + + + /* We can simplify pre- and post-format conversion if we have neither channel conversion nor resampling. */ + if (pConverter->hasChannelConverter == MA_FALSE && pConverter->hasResampler == MA_FALSE) { + /* We have neither channel conversion nor resampling so we'll only need one of pre- or post-format conversion, or none if the input and output formats are the same. */ + if (pConverter->formatIn == pConverter->formatOut) { + /* The formats are the same so we can just pass through. */ + pConverter->hasPreFormatConversion = MA_FALSE; + pConverter->hasPostFormatConversion = MA_FALSE; + } else { + /* The formats are different so we need to do either pre- or post-format conversion. It doesn't matter which. */ + pConverter->hasPreFormatConversion = MA_FALSE; + pConverter->hasPostFormatConversion = MA_TRUE; + } + } else { + /* We have a channel converter and/or resampler so we'll need channel conversion based on the mid format. */ + if (pConverter->formatIn != midFormat) { + pConverter->hasPreFormatConversion = MA_TRUE; + } + if (pConverter->formatOut != midFormat) { + pConverter->hasPostFormatConversion = MA_TRUE; + } + } + + /* We can enable passthrough optimizations if applicable. Note that we'll only be able to do this if the sample rate is static. */ + if (pConverter->hasPreFormatConversion == MA_FALSE && + pConverter->hasPostFormatConversion == MA_FALSE && + pConverter->hasChannelConverter == MA_FALSE && + pConverter->hasResampler == MA_FALSE) { + pConverter->isPassthrough = MA_TRUE; + } + + + /* We now need to determine our execution path. */ + if (pConverter->isPassthrough) { + pConverter->executionPath = ma_data_converter_execution_path_passthrough; + } else { + if (pConverter->channelsIn < pConverter->channelsOut) { + /* Do resampling first, if necessary. */ + MA_ASSERT(pConverter->hasChannelConverter == MA_TRUE); + + if (pConverter->hasResampler) { + pConverter->executionPath = ma_data_converter_execution_path_resample_first; + } else { + pConverter->executionPath = ma_data_converter_execution_path_channels_only; + } + } else { + /* Do channel conversion first, if necessary. */ + if (pConverter->hasChannelConverter) { + if (pConverter->hasResampler) { + pConverter->executionPath = ma_data_converter_execution_path_channels_first; + } else { + pConverter->executionPath = ma_data_converter_execution_path_channels_only; + } + } else { + /* Channel routing not required. */ + if (pConverter->hasResampler) { + pConverter->executionPath = ma_data_converter_execution_path_resample_only; + } else { + pConverter->executionPath = ma_data_converter_execution_path_format_only; + } + } + } + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_data_converter_init(const ma_data_converter_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_converter* pConverter) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_data_converter_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_data_converter_init_preallocated(pConfig, pHeap, pConverter); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pConverter->_ownsHeap = MA_TRUE; + return MA_SUCCESS; +} + +MA_API void ma_data_converter_uninit(ma_data_converter* pConverter, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pConverter == NULL) { + return; + } + + if (pConverter->hasResampler) { + ma_resampler_uninit(&pConverter->resampler, pAllocationCallbacks); + } + + ma_channel_converter_uninit(&pConverter->channelConverter, pAllocationCallbacks); + + if (pConverter->_ownsHeap) { + ma_free(pConverter->_pHeap, pAllocationCallbacks); + } +} + +static ma_result ma_data_converter_process_pcm_frames__passthrough(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut) +{ + ma_uint64 frameCountIn; + ma_uint64 frameCountOut; + ma_uint64 frameCount; + + MA_ASSERT(pConverter != NULL); + + frameCountIn = 0; + if (pFrameCountIn != NULL) { + frameCountIn = *pFrameCountIn; + } + + frameCountOut = 0; + if (pFrameCountOut != NULL) { + frameCountOut = *pFrameCountOut; + } + + frameCount = ma_min(frameCountIn, frameCountOut); + + if (pFramesOut != NULL) { + if (pFramesIn != NULL) { + ma_copy_memory_64(pFramesOut, pFramesIn, frameCount * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut)); + } else { + ma_zero_memory_64(pFramesOut, frameCount * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut)); + } + } + + if (pFrameCountIn != NULL) { + *pFrameCountIn = frameCount; + } + if (pFrameCountOut != NULL) { + *pFrameCountOut = frameCount; + } + + return MA_SUCCESS; +} + +static ma_result ma_data_converter_process_pcm_frames__format_only(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut) +{ + ma_uint64 frameCountIn; + ma_uint64 frameCountOut; + ma_uint64 frameCount; + + MA_ASSERT(pConverter != NULL); + + frameCountIn = 0; + if (pFrameCountIn != NULL) { + frameCountIn = *pFrameCountIn; + } + + frameCountOut = 0; + if (pFrameCountOut != NULL) { + frameCountOut = *pFrameCountOut; + } + + frameCount = ma_min(frameCountIn, frameCountOut); + + if (pFramesOut != NULL) { + if (pFramesIn != NULL) { + ma_convert_pcm_frames_format(pFramesOut, pConverter->formatOut, pFramesIn, pConverter->formatIn, frameCount, pConverter->channelsIn, pConverter->ditherMode); + } else { + ma_zero_memory_64(pFramesOut, frameCount * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut)); + } + } + + if (pFrameCountIn != NULL) { + *pFrameCountIn = frameCount; + } + if (pFrameCountOut != NULL) { + *pFrameCountOut = frameCount; + } + + return MA_SUCCESS; +} + + +static ma_result ma_data_converter_process_pcm_frames__resample_with_format_conversion(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut) +{ + ma_result result = MA_SUCCESS; + ma_uint64 frameCountIn; + ma_uint64 frameCountOut; + ma_uint64 framesProcessedIn; + ma_uint64 framesProcessedOut; + + MA_ASSERT(pConverter != NULL); + + frameCountIn = 0; + if (pFrameCountIn != NULL) { + frameCountIn = *pFrameCountIn; + } + + frameCountOut = 0; + if (pFrameCountOut != NULL) { + frameCountOut = *pFrameCountOut; + } + + framesProcessedIn = 0; + framesProcessedOut = 0; + + while (framesProcessedOut < frameCountOut) { + ma_uint8 pTempBufferOut[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; + const ma_uint32 tempBufferOutCap = sizeof(pTempBufferOut) / ma_get_bytes_per_frame(pConverter->resampler.format, pConverter->resampler.channels); + const void* pFramesInThisIteration; + /* */ void* pFramesOutThisIteration; + ma_uint64 frameCountInThisIteration; + ma_uint64 frameCountOutThisIteration; + + if (pFramesIn != NULL) { + pFramesInThisIteration = ma_offset_ptr(pFramesIn, framesProcessedIn * ma_get_bytes_per_frame(pConverter->formatIn, pConverter->channelsIn)); + } else { + pFramesInThisIteration = NULL; + } + + if (pFramesOut != NULL) { + pFramesOutThisIteration = ma_offset_ptr(pFramesOut, framesProcessedOut * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut)); + } else { + pFramesOutThisIteration = NULL; + } + + /* Do a pre format conversion if necessary. */ + if (pConverter->hasPreFormatConversion) { + ma_uint8 pTempBufferIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; + const ma_uint32 tempBufferInCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->resampler.format, pConverter->resampler.channels); + + frameCountInThisIteration = (frameCountIn - framesProcessedIn); + if (frameCountInThisIteration > tempBufferInCap) { + frameCountInThisIteration = tempBufferInCap; + } + + if (pConverter->hasPostFormatConversion) { + if (frameCountInThisIteration > tempBufferOutCap) { + frameCountInThisIteration = tempBufferOutCap; + } + } + + if (pFramesInThisIteration != NULL) { + ma_convert_pcm_frames_format(pTempBufferIn, pConverter->resampler.format, pFramesInThisIteration, pConverter->formatIn, frameCountInThisIteration, pConverter->channelsIn, pConverter->ditherMode); + } else { + MA_ZERO_MEMORY(pTempBufferIn, sizeof(pTempBufferIn)); + } + + frameCountOutThisIteration = (frameCountOut - framesProcessedOut); + + if (pConverter->hasPostFormatConversion) { + /* Both input and output conversion required. Output to the temp buffer. */ + if (frameCountOutThisIteration > tempBufferOutCap) { + frameCountOutThisIteration = tempBufferOutCap; + } + + result = ma_resampler_process_pcm_frames(&pConverter->resampler, pTempBufferIn, &frameCountInThisIteration, pTempBufferOut, &frameCountOutThisIteration); + } else { + /* Only pre-format required. Output straight to the output buffer. */ + result = ma_resampler_process_pcm_frames(&pConverter->resampler, pTempBufferIn, &frameCountInThisIteration, pFramesOutThisIteration, &frameCountOutThisIteration); + } + + if (result != MA_SUCCESS) { + break; + } + } else { + /* No pre-format required. Just read straight from the input buffer. */ + MA_ASSERT(pConverter->hasPostFormatConversion == MA_TRUE); + + frameCountInThisIteration = (frameCountIn - framesProcessedIn); + frameCountOutThisIteration = (frameCountOut - framesProcessedOut); + if (frameCountOutThisIteration > tempBufferOutCap) { + frameCountOutThisIteration = tempBufferOutCap; + } + + result = ma_resampler_process_pcm_frames(&pConverter->resampler, pFramesInThisIteration, &frameCountInThisIteration, pTempBufferOut, &frameCountOutThisIteration); + if (result != MA_SUCCESS) { + break; + } + } + + /* If we are doing a post format conversion we need to do that now. */ + if (pConverter->hasPostFormatConversion) { + if (pFramesOutThisIteration != NULL) { + ma_convert_pcm_frames_format(pFramesOutThisIteration, pConverter->formatOut, pTempBufferOut, pConverter->resampler.format, frameCountOutThisIteration, pConverter->resampler.channels, pConverter->ditherMode); + } + } + + framesProcessedIn += frameCountInThisIteration; + framesProcessedOut += frameCountOutThisIteration; + + MA_ASSERT(framesProcessedIn <= frameCountIn); + MA_ASSERT(framesProcessedOut <= frameCountOut); + + if (frameCountOutThisIteration == 0) { + break; /* Consumed all of our input data. */ + } + } + + if (pFrameCountIn != NULL) { + *pFrameCountIn = framesProcessedIn; + } + if (pFrameCountOut != NULL) { + *pFrameCountOut = framesProcessedOut; + } + + return result; +} + +static ma_result ma_data_converter_process_pcm_frames__resample_only(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut) +{ + MA_ASSERT(pConverter != NULL); + + if (pConverter->hasPreFormatConversion == MA_FALSE && pConverter->hasPostFormatConversion == MA_FALSE) { + /* Neither pre- nor post-format required. This is simple case where only resampling is required. */ + return ma_resampler_process_pcm_frames(&pConverter->resampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut); + } else { + /* Format conversion required. */ + return ma_data_converter_process_pcm_frames__resample_with_format_conversion(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut); + } +} + +static ma_result ma_data_converter_process_pcm_frames__channels_only(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut) +{ + ma_result result; + ma_uint64 frameCountIn; + ma_uint64 frameCountOut; + ma_uint64 frameCount; + + MA_ASSERT(pConverter != NULL); + + frameCountIn = 0; + if (pFrameCountIn != NULL) { + frameCountIn = *pFrameCountIn; + } + + frameCountOut = 0; + if (pFrameCountOut != NULL) { + frameCountOut = *pFrameCountOut; + } + + frameCount = ma_min(frameCountIn, frameCountOut); + + if (pConverter->hasPreFormatConversion == MA_FALSE && pConverter->hasPostFormatConversion == MA_FALSE) { + /* No format conversion required. */ + result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pFramesOut, pFramesIn, frameCount); + if (result != MA_SUCCESS) { + return result; + } + } else { + /* Format conversion required. */ + ma_uint64 framesProcessed = 0; + + while (framesProcessed < frameCount) { + ma_uint8 pTempBufferOut[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; + const ma_uint32 tempBufferOutCap = sizeof(pTempBufferOut) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsOut); + const void* pFramesInThisIteration; + /* */ void* pFramesOutThisIteration; + ma_uint64 frameCountThisIteration; + + if (pFramesIn != NULL) { + pFramesInThisIteration = ma_offset_ptr(pFramesIn, framesProcessed * ma_get_bytes_per_frame(pConverter->formatIn, pConverter->channelsIn)); + } else { + pFramesInThisIteration = NULL; + } + + if (pFramesOut != NULL) { + pFramesOutThisIteration = ma_offset_ptr(pFramesOut, framesProcessed * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut)); + } else { + pFramesOutThisIteration = NULL; + } + + /* Do a pre format conversion if necessary. */ + if (pConverter->hasPreFormatConversion) { + ma_uint8 pTempBufferIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; + const ma_uint32 tempBufferInCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsIn); + + frameCountThisIteration = (frameCount - framesProcessed); + if (frameCountThisIteration > tempBufferInCap) { + frameCountThisIteration = tempBufferInCap; + } + + if (pConverter->hasPostFormatConversion) { + if (frameCountThisIteration > tempBufferOutCap) { + frameCountThisIteration = tempBufferOutCap; + } + } + + if (pFramesInThisIteration != NULL) { + ma_convert_pcm_frames_format(pTempBufferIn, pConverter->channelConverter.format, pFramesInThisIteration, pConverter->formatIn, frameCountThisIteration, pConverter->channelsIn, pConverter->ditherMode); + } else { + MA_ZERO_MEMORY(pTempBufferIn, sizeof(pTempBufferIn)); + } + + if (pConverter->hasPostFormatConversion) { + /* Both input and output conversion required. Output to the temp buffer. */ + result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pTempBufferOut, pTempBufferIn, frameCountThisIteration); + } else { + /* Only pre-format required. Output straight to the output buffer. */ + result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pFramesOutThisIteration, pTempBufferIn, frameCountThisIteration); + } + + if (result != MA_SUCCESS) { + break; + } + } else { + /* No pre-format required. Just read straight from the input buffer. */ + MA_ASSERT(pConverter->hasPostFormatConversion == MA_TRUE); + + frameCountThisIteration = (frameCount - framesProcessed); + if (frameCountThisIteration > tempBufferOutCap) { + frameCountThisIteration = tempBufferOutCap; + } + + result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pTempBufferOut, pFramesInThisIteration, frameCountThisIteration); + if (result != MA_SUCCESS) { + break; + } + } + + /* If we are doing a post format conversion we need to do that now. */ + if (pConverter->hasPostFormatConversion) { + if (pFramesOutThisIteration != NULL) { + ma_convert_pcm_frames_format(pFramesOutThisIteration, pConverter->formatOut, pTempBufferOut, pConverter->channelConverter.format, frameCountThisIteration, pConverter->channelConverter.channelsOut, pConverter->ditherMode); + } + } + + framesProcessed += frameCountThisIteration; + } + } + + if (pFrameCountIn != NULL) { + *pFrameCountIn = frameCount; + } + if (pFrameCountOut != NULL) { + *pFrameCountOut = frameCount; + } + + return MA_SUCCESS; +} + +static ma_result ma_data_converter_process_pcm_frames__resample_first(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut) +{ + ma_result result; + ma_uint64 frameCountIn; + ma_uint64 frameCountOut; + ma_uint64 framesProcessedIn; + ma_uint64 framesProcessedOut; + ma_uint8 pTempBufferIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In resampler format. */ + ma_uint64 tempBufferInCap; + ma_uint8 pTempBufferMid[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In resampler format, channel converter input format. */ + ma_uint64 tempBufferMidCap; + ma_uint8 pTempBufferOut[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In channel converter output format. */ + ma_uint64 tempBufferOutCap; + + MA_ASSERT(pConverter != NULL); + MA_ASSERT(pConverter->resampler.format == pConverter->channelConverter.format); + MA_ASSERT(pConverter->resampler.channels == pConverter->channelConverter.channelsIn); + MA_ASSERT(pConverter->resampler.channels < pConverter->channelConverter.channelsOut); + + frameCountIn = 0; + if (pFrameCountIn != NULL) { + frameCountIn = *pFrameCountIn; + } + + frameCountOut = 0; + if (pFrameCountOut != NULL) { + frameCountOut = *pFrameCountOut; + } + + framesProcessedIn = 0; + framesProcessedOut = 0; + + tempBufferInCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->resampler.format, pConverter->resampler.channels); + tempBufferMidCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->resampler.format, pConverter->resampler.channels); + tempBufferOutCap = sizeof(pTempBufferOut) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsOut); + + while (framesProcessedOut < frameCountOut) { + ma_uint64 frameCountInThisIteration; + ma_uint64 frameCountOutThisIteration; + const void* pRunningFramesIn = NULL; + void* pRunningFramesOut = NULL; + const void* pResampleBufferIn; + void* pChannelsBufferOut; + + if (pFramesIn != NULL) { + pRunningFramesIn = ma_offset_ptr(pFramesIn, framesProcessedIn * ma_get_bytes_per_frame(pConverter->formatIn, pConverter->channelsIn)); + } + if (pFramesOut != NULL) { + pRunningFramesOut = ma_offset_ptr(pFramesOut, framesProcessedOut * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut)); + } + + /* Run input data through the resampler and output it to the temporary buffer. */ + frameCountInThisIteration = (frameCountIn - framesProcessedIn); + + if (pConverter->hasPreFormatConversion) { + if (frameCountInThisIteration > tempBufferInCap) { + frameCountInThisIteration = tempBufferInCap; + } + } + + frameCountOutThisIteration = (frameCountOut - framesProcessedOut); + if (frameCountOutThisIteration > tempBufferMidCap) { + frameCountOutThisIteration = tempBufferMidCap; + } + + /* We can't read more frames than can fit in the output buffer. */ + if (pConverter->hasPostFormatConversion) { + if (frameCountOutThisIteration > tempBufferOutCap) { + frameCountOutThisIteration = tempBufferOutCap; + } + } + + /* We need to ensure we don't try to process too many input frames that we run out of room in the output buffer. If this happens we'll end up glitching. */ + + /* + We need to try to predict how many input frames will be required for the resampler. If the + resampler can tell us, we'll use that. Otherwise we'll need to make a best guess. The further + off we are from this, the more wasted format conversions we'll end up doing. + */ + #if 1 + { + ma_uint64 requiredInputFrameCount; + + result = ma_resampler_get_required_input_frame_count(&pConverter->resampler, frameCountOutThisIteration, &requiredInputFrameCount); + if (result != MA_SUCCESS) { + /* Fall back to a best guess. */ + requiredInputFrameCount = (frameCountOutThisIteration * pConverter->resampler.sampleRateIn) / pConverter->resampler.sampleRateOut; + } + + if (frameCountInThisIteration > requiredInputFrameCount) { + frameCountInThisIteration = requiredInputFrameCount; + } + } + #endif + + if (pConverter->hasPreFormatConversion) { + if (pFramesIn != NULL) { + ma_convert_pcm_frames_format(pTempBufferIn, pConverter->resampler.format, pRunningFramesIn, pConverter->formatIn, frameCountInThisIteration, pConverter->channelsIn, pConverter->ditherMode); + pResampleBufferIn = pTempBufferIn; + } else { + pResampleBufferIn = NULL; + } + } else { + pResampleBufferIn = pRunningFramesIn; + } + + result = ma_resampler_process_pcm_frames(&pConverter->resampler, pResampleBufferIn, &frameCountInThisIteration, pTempBufferMid, &frameCountOutThisIteration); + if (result != MA_SUCCESS) { + return result; + } + + + /* + The input data has been resampled so now we need to run it through the channel converter. The input data is always contained in pTempBufferMid. We only need to do + this part if we have an output buffer. + */ + if (pFramesOut != NULL) { + if (pConverter->hasPostFormatConversion) { + pChannelsBufferOut = pTempBufferOut; + } else { + pChannelsBufferOut = pRunningFramesOut; + } + + result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pChannelsBufferOut, pTempBufferMid, frameCountOutThisIteration); + if (result != MA_SUCCESS) { + return result; + } + + /* Finally we do post format conversion. */ + if (pConverter->hasPostFormatConversion) { + ma_convert_pcm_frames_format(pRunningFramesOut, pConverter->formatOut, pChannelsBufferOut, pConverter->channelConverter.format, frameCountOutThisIteration, pConverter->channelConverter.channelsOut, pConverter->ditherMode); + } + } + + + framesProcessedIn += frameCountInThisIteration; + framesProcessedOut += frameCountOutThisIteration; + + MA_ASSERT(framesProcessedIn <= frameCountIn); + MA_ASSERT(framesProcessedOut <= frameCountOut); + + if (frameCountOutThisIteration == 0) { + break; /* Consumed all of our input data. */ + } + } + + if (pFrameCountIn != NULL) { + *pFrameCountIn = framesProcessedIn; + } + if (pFrameCountOut != NULL) { + *pFrameCountOut = framesProcessedOut; + } + + return MA_SUCCESS; +} + +static ma_result ma_data_converter_process_pcm_frames__channels_first(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut) +{ + ma_result result; + ma_uint64 frameCountIn; + ma_uint64 frameCountOut; + ma_uint64 framesProcessedIn; + ma_uint64 framesProcessedOut; + ma_uint8 pTempBufferIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In resampler format. */ + ma_uint64 tempBufferInCap; + ma_uint8 pTempBufferMid[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In resampler format, channel converter input format. */ + ma_uint64 tempBufferMidCap; + ma_uint8 pTempBufferOut[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In channel converter output format. */ + ma_uint64 tempBufferOutCap; + + MA_ASSERT(pConverter != NULL); + MA_ASSERT(pConverter->resampler.format == pConverter->channelConverter.format); + MA_ASSERT(pConverter->resampler.channels == pConverter->channelConverter.channelsOut); + MA_ASSERT(pConverter->resampler.channels <= pConverter->channelConverter.channelsIn); + + frameCountIn = 0; + if (pFrameCountIn != NULL) { + frameCountIn = *pFrameCountIn; + } + + frameCountOut = 0; + if (pFrameCountOut != NULL) { + frameCountOut = *pFrameCountOut; + } + + framesProcessedIn = 0; + framesProcessedOut = 0; + + tempBufferInCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsIn); + tempBufferMidCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsOut); + tempBufferOutCap = sizeof(pTempBufferOut) / ma_get_bytes_per_frame(pConverter->resampler.format, pConverter->resampler.channels); + + while (framesProcessedOut < frameCountOut) { + ma_uint64 frameCountInThisIteration; + ma_uint64 frameCountOutThisIteration; + const void* pRunningFramesIn = NULL; + void* pRunningFramesOut = NULL; + const void* pChannelsBufferIn; + void* pResampleBufferOut; + + if (pFramesIn != NULL) { + pRunningFramesIn = ma_offset_ptr(pFramesIn, framesProcessedIn * ma_get_bytes_per_frame(pConverter->formatIn, pConverter->channelsIn)); + } + if (pFramesOut != NULL) { + pRunningFramesOut = ma_offset_ptr(pFramesOut, framesProcessedOut * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut)); + } + + /* + Before doing any processing we need to determine how many frames we should try processing + this iteration, for both input and output. The resampler requires us to perform format and + channel conversion before passing any data into it. If we get our input count wrong, we'll + end up peforming redundant pre-processing. This isn't the end of the world, but it does + result in some inefficiencies proportionate to how far our estimates are off. + + If the resampler has a means to calculate exactly how much we'll need, we'll use that. + Otherwise we'll make a best guess. In order to do this, we'll need to calculate the output + frame count first. + */ + frameCountOutThisIteration = (frameCountOut - framesProcessedOut); + if (frameCountOutThisIteration > tempBufferMidCap) { + frameCountOutThisIteration = tempBufferMidCap; + } + + if (pConverter->hasPostFormatConversion) { + if (frameCountOutThisIteration > tempBufferOutCap) { + frameCountOutThisIteration = tempBufferOutCap; + } + } + + /* Now that we have the output frame count we can determine the input frame count. */ + frameCountInThisIteration = (frameCountIn - framesProcessedIn); + if (pConverter->hasPreFormatConversion) { + if (frameCountInThisIteration > tempBufferInCap) { + frameCountInThisIteration = tempBufferInCap; + } + } + + if (frameCountInThisIteration > tempBufferMidCap) { + frameCountInThisIteration = tempBufferMidCap; + } + + #if 1 + { + ma_uint64 requiredInputFrameCount; + + result = ma_resampler_get_required_input_frame_count(&pConverter->resampler, frameCountOutThisIteration, &requiredInputFrameCount); + if (result != MA_SUCCESS) { + /* Fall back to a best guess. */ + requiredInputFrameCount = (frameCountOutThisIteration * pConverter->resampler.sampleRateIn) / pConverter->resampler.sampleRateOut; + } + + if (frameCountInThisIteration > requiredInputFrameCount) { + frameCountInThisIteration = requiredInputFrameCount; + } + } + #endif + + + /* Pre format conversion. */ + if (pConverter->hasPreFormatConversion) { + if (pRunningFramesIn != NULL) { + ma_convert_pcm_frames_format(pTempBufferIn, pConverter->channelConverter.format, pRunningFramesIn, pConverter->formatIn, frameCountInThisIteration, pConverter->channelsIn, pConverter->ditherMode); + pChannelsBufferIn = pTempBufferIn; + } else { + pChannelsBufferIn = NULL; + } + } else { + pChannelsBufferIn = pRunningFramesIn; + } + + + /* Channel conversion. */ + result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pTempBufferMid, pChannelsBufferIn, frameCountInThisIteration); + if (result != MA_SUCCESS) { + return result; + } + + + /* Resampling. */ + if (pConverter->hasPostFormatConversion) { + pResampleBufferOut = pTempBufferOut; + } else { + pResampleBufferOut = pRunningFramesOut; + } + + result = ma_resampler_process_pcm_frames(&pConverter->resampler, pTempBufferMid, &frameCountInThisIteration, pResampleBufferOut, &frameCountOutThisIteration); + if (result != MA_SUCCESS) { + return result; + } + + + /* Post format conversion. */ + if (pConverter->hasPostFormatConversion) { + if (pRunningFramesOut != NULL) { + ma_convert_pcm_frames_format(pRunningFramesOut, pConverter->formatOut, pResampleBufferOut, pConverter->resampler.format, frameCountOutThisIteration, pConverter->channelsOut, pConverter->ditherMode); + } + } + + + framesProcessedIn += frameCountInThisIteration; + framesProcessedOut += frameCountOutThisIteration; + + MA_ASSERT(framesProcessedIn <= frameCountIn); + MA_ASSERT(framesProcessedOut <= frameCountOut); + + if (frameCountOutThisIteration == 0) { + break; /* Consumed all of our input data. */ + } + } + + if (pFrameCountIn != NULL) { + *pFrameCountIn = framesProcessedIn; + } + if (pFrameCountOut != NULL) { + *pFrameCountOut = framesProcessedOut; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_data_converter_process_pcm_frames(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut) +{ + if (pConverter == NULL) { + return MA_INVALID_ARGS; + } + + switch (pConverter->executionPath) + { + case ma_data_converter_execution_path_passthrough: return ma_data_converter_process_pcm_frames__passthrough(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut); + case ma_data_converter_execution_path_format_only: return ma_data_converter_process_pcm_frames__format_only(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut); + case ma_data_converter_execution_path_channels_only: return ma_data_converter_process_pcm_frames__channels_only(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut); + case ma_data_converter_execution_path_resample_only: return ma_data_converter_process_pcm_frames__resample_only(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut); + case ma_data_converter_execution_path_resample_first: return ma_data_converter_process_pcm_frames__resample_first(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut); + case ma_data_converter_execution_path_channels_first: return ma_data_converter_process_pcm_frames__channels_first(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut); + default: return MA_INVALID_OPERATION; /* Should never hit this. */ + } +} + +MA_API ma_result ma_data_converter_set_rate(ma_data_converter* pConverter, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut) +{ + if (pConverter == NULL) { + return MA_INVALID_ARGS; + } + + if (pConverter->hasResampler == MA_FALSE) { + return MA_INVALID_OPERATION; /* Dynamic resampling not enabled. */ + } + + return ma_resampler_set_rate(&pConverter->resampler, sampleRateIn, sampleRateOut); +} + +MA_API ma_result ma_data_converter_set_rate_ratio(ma_data_converter* pConverter, float ratioInOut) +{ + if (pConverter == NULL) { + return MA_INVALID_ARGS; + } + + if (pConverter->hasResampler == MA_FALSE) { + return MA_INVALID_OPERATION; /* Dynamic resampling not enabled. */ + } + + return ma_resampler_set_rate_ratio(&pConverter->resampler, ratioInOut); +} + +MA_API ma_uint64 ma_data_converter_get_input_latency(const ma_data_converter* pConverter) +{ + if (pConverter == NULL) { + return 0; + } + + if (pConverter->hasResampler) { + return ma_resampler_get_input_latency(&pConverter->resampler); + } + + return 0; /* No latency without a resampler. */ +} + +MA_API ma_uint64 ma_data_converter_get_output_latency(const ma_data_converter* pConverter) +{ + if (pConverter == NULL) { + return 0; + } + + if (pConverter->hasResampler) { + return ma_resampler_get_output_latency(&pConverter->resampler); + } + + return 0; /* No latency without a resampler. */ +} + +MA_API ma_result ma_data_converter_get_required_input_frame_count(const ma_data_converter* pConverter, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount) +{ + if (pInputFrameCount == NULL) { + return MA_INVALID_ARGS; + } + + *pInputFrameCount = 0; + + if (pConverter == NULL) { + return MA_INVALID_ARGS; + } + + if (pConverter->hasResampler) { + return ma_resampler_get_required_input_frame_count(&pConverter->resampler, outputFrameCount, pInputFrameCount); + } else { + *pInputFrameCount = outputFrameCount; /* 1:1 */ + return MA_SUCCESS; + } +} + +MA_API ma_result ma_data_converter_get_expected_output_frame_count(const ma_data_converter* pConverter, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount) +{ + if (pOutputFrameCount == NULL) { + return MA_INVALID_ARGS; + } + + *pOutputFrameCount = 0; + + if (pConverter == NULL) { + return MA_INVALID_ARGS; + } + + if (pConverter->hasResampler) { + return ma_resampler_get_expected_output_frame_count(&pConverter->resampler, inputFrameCount, pOutputFrameCount); + } else { + *pOutputFrameCount = inputFrameCount; /* 1:1 */ + return MA_SUCCESS; + } +} + +MA_API ma_result ma_data_converter_get_input_channel_map(const ma_data_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap) +{ + if (pConverter == NULL || pChannelMap == NULL) { + return MA_INVALID_ARGS; + } + + if (pConverter->hasChannelConverter) { + ma_channel_converter_get_output_channel_map(&pConverter->channelConverter, pChannelMap, channelMapCap); + } else { + ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pConverter->channelsOut); + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_data_converter_get_output_channel_map(const ma_data_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap) +{ + if (pConverter == NULL || pChannelMap == NULL) { + return MA_INVALID_ARGS; + } + + if (pConverter->hasChannelConverter) { + ma_channel_converter_get_input_channel_map(&pConverter->channelConverter, pChannelMap, channelMapCap); + } else { + ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pConverter->channelsIn); + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_data_converter_reset(ma_data_converter* pConverter) +{ + if (pConverter == NULL) { + return MA_INVALID_ARGS; + } + + /* There's nothing to do if we're not resampling. */ + if (pConverter->hasResampler == MA_FALSE) { + return MA_SUCCESS; + } + + return ma_resampler_reset(&pConverter->resampler); +} + + + +/************************************************************************************************************************************************************** + +Channel Maps + +**************************************************************************************************************************************************************/ +static ma_channel ma_channel_map_init_standard_channel(ma_standard_channel_map standardChannelMap, ma_uint32 channelCount, ma_uint32 channelIndex); + +MA_API ma_channel ma_channel_map_get_channel(const ma_channel* pChannelMap, ma_uint32 channelCount, ma_uint32 channelIndex) +{ + if (pChannelMap == NULL) { + return ma_channel_map_init_standard_channel(ma_standard_channel_map_default, channelCount, channelIndex); + } else { + if (channelIndex >= channelCount) { + return MA_CHANNEL_NONE; + } + + return pChannelMap[channelIndex]; + } +} + +MA_API void ma_channel_map_init_blank(ma_channel* pChannelMap, ma_uint32 channels) +{ + if (pChannelMap == NULL) { + return; + } + + MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channels); +} + + +static ma_channel ma_channel_map_init_standard_channel_microsoft(ma_uint32 channelCount, ma_uint32 channelIndex) +{ + if (channelCount == 0 || channelIndex >= channelCount) { + return MA_CHANNEL_NONE; + } + + /* This is the Microsoft channel map. 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 (channelCount) + { + case 0: return MA_CHANNEL_NONE; + + case 1: + { + return MA_CHANNEL_MONO; + } break; + + case 2: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + } + } break; + + case 3: /* No defined, but best guess. */ + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_FRONT_CENTER; + } + } break; + + case 4: + { + switch (channelIndex) { + #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. */ + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_FRONT_CENTER; + case 3: return MA_CHANNEL_BACK_CENTER; + #else + /* Quad. */ + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_BACK_LEFT; + case 3: return MA_CHANNEL_BACK_RIGHT; + #endif + } + } break; + + case 5: /* Not defined, but best guess. */ + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_FRONT_CENTER; + case 3: return MA_CHANNEL_BACK_LEFT; + case 4: return MA_CHANNEL_BACK_RIGHT; + } + } break; + + case 6: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_FRONT_CENTER; + case 3: return MA_CHANNEL_LFE; + case 4: return MA_CHANNEL_SIDE_LEFT; + case 5: return MA_CHANNEL_SIDE_RIGHT; + } + } break; + + case 7: /* Not defined, but best guess. */ + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_FRONT_CENTER; + case 3: return MA_CHANNEL_LFE; + case 4: return MA_CHANNEL_BACK_CENTER; + case 5: return MA_CHANNEL_SIDE_LEFT; + case 6: return MA_CHANNEL_SIDE_RIGHT; + } + } break; + + case 8: + default: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_FRONT_CENTER; + case 3: return MA_CHANNEL_LFE; + case 4: return MA_CHANNEL_BACK_LEFT; + case 5: return MA_CHANNEL_BACK_RIGHT; + case 6: return MA_CHANNEL_SIDE_LEFT; + case 7: return MA_CHANNEL_SIDE_RIGHT; + } + } break; + } + + if (channelCount > 8) { + if (channelIndex < 32) { /* We have 32 AUX channels. */ + return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 8)); + } + } + + /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */ + return MA_CHANNEL_NONE; +} + +static ma_channel ma_channel_map_init_standard_channel_alsa(ma_uint32 channelCount, ma_uint32 channelIndex) +{ + switch (channelCount) + { + case 0: return MA_CHANNEL_NONE; + + case 1: + { + return MA_CHANNEL_MONO; + } break; + + case 2: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + } + } break; + + case 3: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_FRONT_CENTER; + } + } break; + + case 4: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_BACK_LEFT; + case 3: return MA_CHANNEL_BACK_RIGHT; + } + } break; + + case 5: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_BACK_LEFT; + case 3: return MA_CHANNEL_BACK_RIGHT; + case 4: return MA_CHANNEL_FRONT_CENTER; + } + } break; + + case 6: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_BACK_LEFT; + case 3: return MA_CHANNEL_BACK_RIGHT; + case 4: return MA_CHANNEL_FRONT_CENTER; + case 5: return MA_CHANNEL_LFE; + } + } break; + + case 7: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_BACK_LEFT; + case 3: return MA_CHANNEL_BACK_RIGHT; + case 4: return MA_CHANNEL_FRONT_CENTER; + case 5: return MA_CHANNEL_LFE; + case 6: return MA_CHANNEL_BACK_CENTER; + } + } break; + + case 8: + default: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_BACK_LEFT; + case 3: return MA_CHANNEL_BACK_RIGHT; + case 4: return MA_CHANNEL_FRONT_CENTER; + case 5: return MA_CHANNEL_LFE; + case 6: return MA_CHANNEL_SIDE_LEFT; + case 7: return MA_CHANNEL_SIDE_RIGHT; + } + } break; + } + + if (channelCount > 8) { + if (channelIndex < 32) { /* We have 32 AUX channels. */ + return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 8)); + } + } + + /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */ + return MA_CHANNEL_NONE; +} + +static ma_channel ma_channel_map_init_standard_channel_rfc3551(ma_uint32 channelCount, ma_uint32 channelIndex) +{ + switch (channelCount) + { + case 0: return MA_CHANNEL_NONE; + + case 1: + { + return MA_CHANNEL_MONO; + } break; + + case 2: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + } + } break; + + case 3: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_FRONT_CENTER; + } + } break; + + case 4: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 2: return MA_CHANNEL_FRONT_CENTER; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 3: return MA_CHANNEL_BACK_CENTER; + } + } break; + + case 5: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_FRONT_CENTER; + case 3: return MA_CHANNEL_BACK_LEFT; + case 4: return MA_CHANNEL_BACK_RIGHT; + } + } break; + + case 6: + default: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_SIDE_LEFT; + case 2: return MA_CHANNEL_FRONT_CENTER; + case 3: return MA_CHANNEL_FRONT_RIGHT; + case 4: return MA_CHANNEL_SIDE_RIGHT; + case 5: return MA_CHANNEL_BACK_CENTER; + } + } break; + } + + if (channelCount > 6) { + if (channelIndex < 32) { /* We have 32 AUX channels. */ + return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 6)); + } + } + + /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */ + return MA_CHANNEL_NONE; +} + +static ma_channel ma_channel_map_init_standard_channel_flac(ma_uint32 channelCount, ma_uint32 channelIndex) +{ + switch (channelCount) + { + case 0: return MA_CHANNEL_NONE; + + case 1: + { + return MA_CHANNEL_MONO; + } break; + + case 2: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + } + } break; + + case 3: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_FRONT_CENTER; + } + } break; + + case 4: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_BACK_LEFT; + case 3: return MA_CHANNEL_BACK_RIGHT; + } + } break; + + case 5: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_FRONT_CENTER; + case 3: return MA_CHANNEL_BACK_LEFT; + case 4: return MA_CHANNEL_BACK_RIGHT; + } + } break; + + case 6: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_FRONT_CENTER; + case 3: return MA_CHANNEL_LFE; + case 4: return MA_CHANNEL_BACK_LEFT; + case 5: return MA_CHANNEL_BACK_RIGHT; + } + } break; + + case 7: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_FRONT_CENTER; + case 3: return MA_CHANNEL_LFE; + case 4: return MA_CHANNEL_BACK_CENTER; + case 5: return MA_CHANNEL_SIDE_LEFT; + case 6: return MA_CHANNEL_SIDE_RIGHT; + } + } break; + + case 8: + default: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_FRONT_CENTER; + case 3: return MA_CHANNEL_LFE; + case 4: return MA_CHANNEL_BACK_LEFT; + case 5: return MA_CHANNEL_BACK_RIGHT; + case 6: return MA_CHANNEL_SIDE_LEFT; + case 7: return MA_CHANNEL_SIDE_RIGHT; + } + } break; + } + + if (channelCount > 8) { + if (channelIndex < 32) { /* We have 32 AUX channels. */ + return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 8)); + } + } + + /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */ + return MA_CHANNEL_NONE; +} + +static ma_channel ma_channel_map_init_standard_channel_vorbis(ma_uint32 channelCount, ma_uint32 channelIndex) +{ + switch (channelCount) + { + case 0: return MA_CHANNEL_NONE; + + case 1: + { + return MA_CHANNEL_MONO; + } break; + + case 2: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + } + } break; + + case 3: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_CENTER; + case 2: return MA_CHANNEL_FRONT_RIGHT; + } + } break; + + case 4: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_BACK_LEFT; + case 3: return MA_CHANNEL_BACK_RIGHT; + } + } break; + + case 5: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_CENTER; + case 2: return MA_CHANNEL_FRONT_RIGHT; + case 3: return MA_CHANNEL_BACK_LEFT; + case 4: return MA_CHANNEL_BACK_RIGHT; + } + } break; + + case 6: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_CENTER; + case 2: return MA_CHANNEL_FRONT_RIGHT; + case 3: return MA_CHANNEL_BACK_LEFT; + case 4: return MA_CHANNEL_BACK_RIGHT; + case 5: return MA_CHANNEL_LFE; + } + } break; + + case 7: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_CENTER; + case 2: return MA_CHANNEL_FRONT_RIGHT; + case 3: return MA_CHANNEL_SIDE_LEFT; + case 4: return MA_CHANNEL_SIDE_RIGHT; + case 5: return MA_CHANNEL_BACK_CENTER; + case 6: return MA_CHANNEL_LFE; + } + } break; + + case 8: + default: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_CENTER; + case 2: return MA_CHANNEL_FRONT_RIGHT; + case 3: return MA_CHANNEL_SIDE_LEFT; + case 4: return MA_CHANNEL_SIDE_RIGHT; + case 5: return MA_CHANNEL_BACK_LEFT; + case 6: return MA_CHANNEL_BACK_RIGHT; + case 7: return MA_CHANNEL_LFE; + } + } break; + } + + if (channelCount > 8) { + if (channelIndex < 32) { /* We have 32 AUX channels. */ + return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 8)); + } + } + + /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */ + return MA_CHANNEL_NONE; +} + +static ma_channel ma_channel_map_init_standard_channel_sound4(ma_uint32 channelCount, ma_uint32 channelIndex) +{ + switch (channelCount) + { + case 0: return MA_CHANNEL_NONE; + + case 1: + { + return MA_CHANNEL_MONO; + } break; + + case 2: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + } + } break; + + case 3: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_FRONT_CENTER; + } + } break; + + case 4: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_BACK_LEFT; + case 3: return MA_CHANNEL_BACK_RIGHT; + } + } break; + + case 5: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_FRONT_CENTER; + case 3: return MA_CHANNEL_BACK_LEFT; + case 4: return MA_CHANNEL_BACK_RIGHT; + } + } break; + + case 6: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_CENTER; + case 2: return MA_CHANNEL_FRONT_RIGHT; + case 3: return MA_CHANNEL_BACK_LEFT; + case 4: return MA_CHANNEL_BACK_RIGHT; + case 5: return MA_CHANNEL_LFE; + } + } break; + + case 7: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_CENTER; + case 2: return MA_CHANNEL_FRONT_RIGHT; + case 3: return MA_CHANNEL_SIDE_LEFT; + case 4: return MA_CHANNEL_SIDE_RIGHT; + case 5: return MA_CHANNEL_BACK_CENTER; + case 6: return MA_CHANNEL_LFE; + } + } break; + + case 8: + default: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_CENTER; + case 2: return MA_CHANNEL_FRONT_RIGHT; + case 3: return MA_CHANNEL_SIDE_LEFT; + case 4: return MA_CHANNEL_SIDE_RIGHT; + case 5: return MA_CHANNEL_BACK_LEFT; + case 6: return MA_CHANNEL_BACK_RIGHT; + case 7: return MA_CHANNEL_LFE; + } + } break; + } + + if (channelCount > 8) { + if (channelIndex < 32) { /* We have 32 AUX channels. */ + return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 8)); + } + } + + /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */ + return MA_CHANNEL_NONE; +} + +static ma_channel ma_channel_map_init_standard_channel_sndio(ma_uint32 channelCount, ma_uint32 channelIndex) +{ + switch (channelCount) + { + case 0: return MA_CHANNEL_NONE; + + case 1: + { + return MA_CHANNEL_MONO; + } break; + + case 2: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + } + } break; + + case 3: /* No defined, but best guess. */ + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_FRONT_CENTER; + } + } break; + + case 4: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_BACK_LEFT; + case 3: return MA_CHANNEL_BACK_RIGHT; + } + } break; + + case 5: /* Not defined, but best guess. */ + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_BACK_LEFT; + case 3: return MA_CHANNEL_BACK_RIGHT; + case 4: return MA_CHANNEL_FRONT_CENTER; + } + } break; + + case 6: + default: + { + switch (channelIndex) { + case 0: return MA_CHANNEL_FRONT_LEFT; + case 1: return MA_CHANNEL_FRONT_RIGHT; + case 2: return MA_CHANNEL_BACK_LEFT; + case 3: return MA_CHANNEL_BACK_RIGHT; + case 4: return MA_CHANNEL_FRONT_CENTER; + case 5: return MA_CHANNEL_LFE; + } + } break; + } + + if (channelCount > 6) { + if (channelIndex < 32) { /* We have 32 AUX channels. */ + return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 6)); + } + } + + /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */ + return MA_CHANNEL_NONE; +} + + +static ma_channel ma_channel_map_init_standard_channel(ma_standard_channel_map standardChannelMap, ma_uint32 channelCount, ma_uint32 channelIndex) +{ + if (channelCount == 0 || channelIndex >= channelCount) { + return MA_CHANNEL_NONE; + } + + switch (standardChannelMap) + { + case ma_standard_channel_map_alsa: + { + return ma_channel_map_init_standard_channel_alsa(channelCount, channelIndex); + } break; + + case ma_standard_channel_map_rfc3551: + { + return ma_channel_map_init_standard_channel_rfc3551(channelCount, channelIndex); + } break; + + case ma_standard_channel_map_flac: + { + return ma_channel_map_init_standard_channel_flac(channelCount, channelIndex); + } break; + + case ma_standard_channel_map_vorbis: + { + return ma_channel_map_init_standard_channel_vorbis(channelCount, channelIndex); + } break; + + case ma_standard_channel_map_sound4: + { + return ma_channel_map_init_standard_channel_sound4(channelCount, channelIndex); + } break; + + case ma_standard_channel_map_sndio: + { + return ma_channel_map_init_standard_channel_sndio(channelCount, channelIndex); + } break; + + case ma_standard_channel_map_microsoft: /* Also default. */ + /*case ma_standard_channel_map_default;*/ + default: + { + return ma_channel_map_init_standard_channel_microsoft(channelCount, channelIndex); + } break; + } +} + +MA_API void ma_channel_map_init_standard(ma_standard_channel_map standardChannelMap, ma_channel* pChannelMap, size_t channelMapCap, ma_uint32 channels) +{ + ma_uint32 iChannel; + + if (pChannelMap == NULL || channelMapCap == 0 || channels == 0) { + return; + } + + for (iChannel = 0; iChannel < channels; iChannel += 1) { + if (channelMapCap == 0) { + break; /* Ran out of room. */ + } + + pChannelMap[0] = ma_channel_map_init_standard_channel(standardChannelMap, channels, iChannel); + pChannelMap += 1; + channelMapCap -= 1; + } +} + +MA_API 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_API void ma_channel_map_copy_or_default(ma_channel* pOut, size_t channelMapCapOut, const ma_channel* pIn, ma_uint32 channels) +{ + if (pOut == NULL || channels == 0) { + return; + } + + if (pIn != NULL) { + ma_channel_map_copy(pOut, pIn, channels); + } else { + ma_channel_map_init_standard(ma_standard_channel_map_default, pOut, channelMapCapOut, channels); + } +} + +MA_API ma_bool32 ma_channel_map_is_valid(const ma_channel* pChannelMap, ma_uint32 channels) +{ + /* 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) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; ++iChannel) { + if (ma_channel_map_get_channel(pChannelMap, channels, iChannel) == MA_CHANNEL_MONO) { + return MA_FALSE; + } + } + } + + return MA_TRUE; +} + +MA_API ma_bool32 ma_channel_map_is_equal(const ma_channel* pChannelMapA, const ma_channel* pChannelMapB, ma_uint32 channels) +{ + ma_uint32 iChannel; + + if (pChannelMapA == pChannelMapB) { + return MA_TRUE; + } + + for (iChannel = 0; iChannel < channels; ++iChannel) { + if (ma_channel_map_get_channel(pChannelMapA, channels, iChannel) != ma_channel_map_get_channel(pChannelMapB, channels, iChannel)) { + return MA_FALSE; + } + } + + return MA_TRUE; +} + +MA_API ma_bool32 ma_channel_map_is_blank(const ma_channel* pChannelMap, ma_uint32 channels) +{ + ma_uint32 iChannel; + + /* A null channel map is equivalent to the default channel map. */ + if (pChannelMap == NULL) { + return MA_FALSE; + } + + for (iChannel = 0; iChannel < channels; ++iChannel) { + if (pChannelMap[iChannel] != MA_CHANNEL_NONE) { + return MA_FALSE; + } + } + + return MA_TRUE; +} + +MA_API ma_bool32 ma_channel_map_contains_channel_position(ma_uint32 channels, const ma_channel* pChannelMap, ma_channel channelPosition) +{ + return ma_channel_map_find_channel_position(channels, pChannelMap, channelPosition, NULL); +} + +MA_API ma_bool32 ma_channel_map_find_channel_position(ma_uint32 channels, const ma_channel* pChannelMap, ma_channel channelPosition, ma_uint32* pChannelIndex) +{ + ma_uint32 iChannel; + + if (pChannelIndex != NULL) { + *pChannelIndex = (ma_uint32)-1; + } + + for (iChannel = 0; iChannel < channels; ++iChannel) { + if (ma_channel_map_get_channel(pChannelMap, channels, iChannel) == channelPosition) { + if (pChannelIndex != NULL) { + *pChannelIndex = iChannel; + } + + return MA_TRUE; + } + } + + /* Getting here means the channel position was not found. */ + return MA_FALSE; +} + +MA_API size_t ma_channel_map_to_string(const ma_channel* pChannelMap, ma_uint32 channels, char* pBufferOut, size_t bufferCap) +{ + size_t len; + ma_uint32 iChannel; + + len = 0; + + for (iChannel = 0; iChannel < channels; iChannel += 1) { + const char* pChannelStr = ma_channel_position_to_string(ma_channel_map_get_channel(pChannelMap, channels, iChannel)); + size_t channelStrLen = strlen(pChannelStr); + + /* Append the string if necessary. */ + if (pBufferOut != NULL && bufferCap > len + channelStrLen) { + MA_COPY_MEMORY(pBufferOut + len, pChannelStr, channelStrLen); + } + len += channelStrLen; + + /* Append a space if it's not the last item. */ + if (iChannel+1 < channels) { + if (pBufferOut != NULL && bufferCap > len + 1) { + pBufferOut[len] = ' '; + } + len += 1; + } + } + + /* Null terminate. Don't increment the length here. */ + if (pBufferOut != NULL && bufferCap > len + 1) { + pBufferOut[len] = '\0'; + } + + return len; +} + +MA_API const char* ma_channel_position_to_string(ma_channel channel) +{ + switch (channel) + { + case MA_CHANNEL_NONE : return "CHANNEL_NONE"; + case MA_CHANNEL_MONO : return "CHANNEL_MONO"; + case MA_CHANNEL_FRONT_LEFT : return "CHANNEL_FRONT_LEFT"; + case MA_CHANNEL_FRONT_RIGHT : return "CHANNEL_FRONT_RIGHT"; + case MA_CHANNEL_FRONT_CENTER : return "CHANNEL_FRONT_CENTER"; + case MA_CHANNEL_LFE : return "CHANNEL_LFE"; + case MA_CHANNEL_BACK_LEFT : return "CHANNEL_BACK_LEFT"; + case MA_CHANNEL_BACK_RIGHT : return "CHANNEL_BACK_RIGHT"; + case MA_CHANNEL_FRONT_LEFT_CENTER : return "CHANNEL_FRONT_LEFT_CENTER "; + case MA_CHANNEL_FRONT_RIGHT_CENTER: return "CHANNEL_FRONT_RIGHT_CENTER"; + case MA_CHANNEL_BACK_CENTER : return "CHANNEL_BACK_CENTER"; + case MA_CHANNEL_SIDE_LEFT : return "CHANNEL_SIDE_LEFT"; + case MA_CHANNEL_SIDE_RIGHT : return "CHANNEL_SIDE_RIGHT"; + case MA_CHANNEL_TOP_CENTER : return "CHANNEL_TOP_CENTER"; + case MA_CHANNEL_TOP_FRONT_LEFT : return "CHANNEL_TOP_FRONT_LEFT"; + case MA_CHANNEL_TOP_FRONT_CENTER : return "CHANNEL_TOP_FRONT_CENTER"; + case MA_CHANNEL_TOP_FRONT_RIGHT : return "CHANNEL_TOP_FRONT_RIGHT"; + case MA_CHANNEL_TOP_BACK_LEFT : return "CHANNEL_TOP_BACK_LEFT"; + case MA_CHANNEL_TOP_BACK_CENTER : return "CHANNEL_TOP_BACK_CENTER"; + case MA_CHANNEL_TOP_BACK_RIGHT : return "CHANNEL_TOP_BACK_RIGHT"; + case MA_CHANNEL_AUX_0 : return "CHANNEL_AUX_0"; + case MA_CHANNEL_AUX_1 : return "CHANNEL_AUX_1"; + case MA_CHANNEL_AUX_2 : return "CHANNEL_AUX_2"; + case MA_CHANNEL_AUX_3 : return "CHANNEL_AUX_3"; + case MA_CHANNEL_AUX_4 : return "CHANNEL_AUX_4"; + case MA_CHANNEL_AUX_5 : return "CHANNEL_AUX_5"; + case MA_CHANNEL_AUX_6 : return "CHANNEL_AUX_6"; + case MA_CHANNEL_AUX_7 : return "CHANNEL_AUX_7"; + case MA_CHANNEL_AUX_8 : return "CHANNEL_AUX_8"; + case MA_CHANNEL_AUX_9 : return "CHANNEL_AUX_9"; + case MA_CHANNEL_AUX_10 : return "CHANNEL_AUX_10"; + case MA_CHANNEL_AUX_11 : return "CHANNEL_AUX_11"; + case MA_CHANNEL_AUX_12 : return "CHANNEL_AUX_12"; + case MA_CHANNEL_AUX_13 : return "CHANNEL_AUX_13"; + case MA_CHANNEL_AUX_14 : return "CHANNEL_AUX_14"; + case MA_CHANNEL_AUX_15 : return "CHANNEL_AUX_15"; + case MA_CHANNEL_AUX_16 : return "CHANNEL_AUX_16"; + case MA_CHANNEL_AUX_17 : return "CHANNEL_AUX_17"; + case MA_CHANNEL_AUX_18 : return "CHANNEL_AUX_18"; + case MA_CHANNEL_AUX_19 : return "CHANNEL_AUX_19"; + case MA_CHANNEL_AUX_20 : return "CHANNEL_AUX_20"; + case MA_CHANNEL_AUX_21 : return "CHANNEL_AUX_21"; + case MA_CHANNEL_AUX_22 : return "CHANNEL_AUX_22"; + case MA_CHANNEL_AUX_23 : return "CHANNEL_AUX_23"; + case MA_CHANNEL_AUX_24 : return "CHANNEL_AUX_24"; + case MA_CHANNEL_AUX_25 : return "CHANNEL_AUX_25"; + case MA_CHANNEL_AUX_26 : return "CHANNEL_AUX_26"; + case MA_CHANNEL_AUX_27 : return "CHANNEL_AUX_27"; + case MA_CHANNEL_AUX_28 : return "CHANNEL_AUX_28"; + case MA_CHANNEL_AUX_29 : return "CHANNEL_AUX_29"; + case MA_CHANNEL_AUX_30 : return "CHANNEL_AUX_30"; + case MA_CHANNEL_AUX_31 : return "CHANNEL_AUX_31"; + default: break; + } + + return "UNKNOWN"; +} + + + +/************************************************************************************************************************************************************** + +Conversion Helpers + +**************************************************************************************************************************************************************/ +MA_API ma_uint64 ma_convert_frames(void* pOut, ma_uint64 frameCountOut, ma_format formatOut, ma_uint32 channelsOut, ma_uint32 sampleRateOut, const void* pIn, ma_uint64 frameCountIn, ma_format formatIn, ma_uint32 channelsIn, ma_uint32 sampleRateIn) +{ + ma_data_converter_config config; + + config = ma_data_converter_config_init(formatIn, formatOut, channelsIn, channelsOut, sampleRateIn, sampleRateOut); + config.resampling.linear.lpfOrder = ma_min(MA_DEFAULT_RESAMPLER_LPF_ORDER, MA_MAX_FILTER_ORDER); + + return ma_convert_frames_ex(pOut, frameCountOut, pIn, frameCountIn, &config); +} + +MA_API ma_uint64 ma_convert_frames_ex(void* pOut, ma_uint64 frameCountOut, const void* pIn, ma_uint64 frameCountIn, const ma_data_converter_config* pConfig) +{ + ma_result result; + ma_data_converter converter; + + if (frameCountIn == 0 || pConfig == NULL) { + return 0; + } + + result = ma_data_converter_init(pConfig, NULL, &converter); + if (result != MA_SUCCESS) { + return 0; /* Failed to initialize the data converter. */ + } + + if (pOut == NULL) { + result = ma_data_converter_get_expected_output_frame_count(&converter, frameCountIn, &frameCountOut); + if (result != MA_SUCCESS) { + if (result == MA_NOT_IMPLEMENTED) { + /* No way to calculate the number of frames, so we'll need to brute force it and loop. */ + frameCountOut = 0; + + while (frameCountIn > 0) { + ma_uint64 framesProcessedIn = frameCountIn; + ma_uint64 framesProcessedOut = 0xFFFFFFFF; + + result = ma_data_converter_process_pcm_frames(&converter, pIn, &framesProcessedIn, NULL, &framesProcessedOut); + if (result != MA_SUCCESS) { + break; + } + + frameCountIn -= framesProcessedIn; + } + } + } + } else { + result = ma_data_converter_process_pcm_frames(&converter, pIn, &frameCountIn, pOut, &frameCountOut); + if (result != MA_SUCCESS) { + frameCountOut = 0; + } + } + + ma_data_converter_uninit(&converter, NULL); + return frameCountOut; +} + + +/************************************************************************************************************************************************************** + +Ring Buffer + +**************************************************************************************************************************************************************/ +static MA_INLINE ma_uint32 ma_rb__extract_offset_in_bytes(ma_uint32 encodedOffset) +{ + return encodedOffset & 0x7FFFFFFF; +} + +static MA_INLINE ma_uint32 ma_rb__extract_offset_loop_flag(ma_uint32 encodedOffset) +{ + return encodedOffset & 0x80000000; +} + +static 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(ma_atomic_load_32(&pRB->encodedReadOffset))); +} + +static 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(ma_atomic_load_32(&pRB->encodedWriteOffset))); +} + +static MA_INLINE ma_uint32 ma_rb__construct_offset(ma_uint32 offsetInBytes, ma_uint32 offsetLoopFlag) +{ + return offsetLoopFlag | offsetInBytes; +} + +static 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_API ma_result ma_rb_init_ex(size_t subbufferSizeInBytes, size_t subbufferCount, size_t subbufferStrideInBytes, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_rb* pRB) +{ + ma_result result; + const ma_uint32 maxSubBufferSize = 0x7FFFFFFF - (MA_SIMD_ALIGNMENT-1); + + if (pRB == NULL) { + return MA_INVALID_ARGS; + } + + if (subbufferSizeInBytes == 0 || subbufferCount == 0) { + return MA_INVALID_ARGS; + } + + 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); + + result = ma_allocation_callbacks_init_copy(&pRB->allocationCallbacks, pAllocationCallbacks); + if (result != MA_SUCCESS) { + return result; + } + + pRB->subbufferSizeInBytes = (ma_uint32)subbufferSizeInBytes; + pRB->subbufferCount = (ma_uint32)subbufferCount; + + if (pOptionalPreallocatedBuffer != NULL) { + pRB->subbufferStrideInBytes = (ma_uint32)subbufferStrideInBytes; + pRB->pBuffer = pOptionalPreallocatedBuffer; + } else { + 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; + + bufferSizeInBytes = (size_t)pRB->subbufferCount*pRB->subbufferStrideInBytes; + pRB->pBuffer = ma_aligned_malloc(bufferSizeInBytes, MA_SIMD_ALIGNMENT, &pRB->allocationCallbacks); + if (pRB->pBuffer == NULL) { + return MA_OUT_OF_MEMORY; + } + + MA_ZERO_MEMORY(pRB->pBuffer, bufferSizeInBytes); + pRB->ownsBuffer = MA_TRUE; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_rb_init(size_t bufferSizeInBytes, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_rb* pRB) +{ + return ma_rb_init_ex(bufferSizeInBytes, 1, 0, pOptionalPreallocatedBuffer, pAllocationCallbacks, pRB); +} + +MA_API void ma_rb_uninit(ma_rb* pRB) +{ + if (pRB == NULL) { + return; + } + + if (pRB->ownsBuffer) { + ma_aligned_free(pRB->pBuffer, &pRB->allocationCallbacks); + } +} + +MA_API void ma_rb_reset(ma_rb* pRB) +{ + if (pRB == NULL) { + return; + } + + ma_atomic_exchange_32(&pRB->encodedReadOffset, 0); + ma_atomic_exchange_32(&pRB->encodedWriteOffset, 0); +} + +MA_API 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. */ + writeOffset = ma_atomic_load_32(&pRB->encodedWriteOffset); + ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag); + + readOffset = ma_atomic_load_32(&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. + */ + if (readOffsetLoopFlag == writeOffsetLoopFlag) { + bytesAvailable = writeOffsetInBytes - readOffsetInBytes; + } else { + bytesAvailable = pRB->subbufferSizeInBytes - readOffsetInBytes; + } + + bytesRequested = *pSizeInBytes; + if (bytesRequested > bytesAvailable) { + bytesRequested = bytesAvailable; + } + + *pSizeInBytes = bytesRequested; + (*ppBufferOut) = ma_rb__get_read_ptr(pRB); + + return MA_SUCCESS; +} + +MA_API ma_result ma_rb_commit_read(ma_rb* pRB, size_t sizeInBytes) +{ + ma_uint32 readOffset; + ma_uint32 readOffsetInBytes; + ma_uint32 readOffsetLoopFlag; + ma_uint32 newReadOffsetInBytes; + ma_uint32 newReadOffsetLoopFlag; + + if (pRB == NULL) { + return MA_INVALID_ARGS; + } + + readOffset = ma_atomic_load_32(&pRB->encodedReadOffset); + ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag); + + /* 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. */ + } + + /* Move the read pointer back to the start if necessary. */ + newReadOffsetLoopFlag = readOffsetLoopFlag; + if (newReadOffsetInBytes == pRB->subbufferSizeInBytes) { + newReadOffsetInBytes = 0; + newReadOffsetLoopFlag ^= 0x80000000; + } + + ma_atomic_exchange_32(&pRB->encodedReadOffset, ma_rb__construct_offset(newReadOffsetLoopFlag, newReadOffsetInBytes)); + + if (ma_rb_pointer_distance(pRB) == 0) { + return MA_AT_END; + } else { + return MA_SUCCESS; + } +} + +MA_API 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. */ + readOffset = ma_atomic_load_32(&pRB->encodedReadOffset); + ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag); + + writeOffset = ma_atomic_load_32(&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. + */ + if (writeOffsetLoopFlag == readOffsetLoopFlag) { + bytesAvailable = pRB->subbufferSizeInBytes - writeOffsetInBytes; + } else { + bytesAvailable = readOffsetInBytes - writeOffsetInBytes; + } + + 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_API ma_result ma_rb_commit_write(ma_rb* pRB, size_t sizeInBytes) +{ + ma_uint32 writeOffset; + ma_uint32 writeOffsetInBytes; + ma_uint32 writeOffsetLoopFlag; + ma_uint32 newWriteOffsetInBytes; + ma_uint32 newWriteOffsetLoopFlag; + + if (pRB == NULL) { + return MA_INVALID_ARGS; + } + + writeOffset = ma_atomic_load_32(&pRB->encodedWriteOffset); + ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag); + + /* 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. */ + } + + /* Move the read pointer back to the start if necessary. */ + newWriteOffsetLoopFlag = writeOffsetLoopFlag; + if (newWriteOffsetInBytes == pRB->subbufferSizeInBytes) { + newWriteOffsetInBytes = 0; + newWriteOffsetLoopFlag ^= 0x80000000; + } + + ma_atomic_exchange_32(&pRB->encodedWriteOffset, ma_rb__construct_offset(newWriteOffsetLoopFlag, newWriteOffsetInBytes)); + + if (ma_rb_pointer_distance(pRB) == 0) { + return MA_AT_END; + } else { + return MA_SUCCESS; + } +} + +MA_API 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; + } + + readOffset = ma_atomic_load_32(&pRB->encodedReadOffset); + ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag); + + writeOffset = ma_atomic_load_32(&pRB->encodedWriteOffset); + ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag); + + 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_API 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; + } + + readOffset = ma_atomic_load_32(&pRB->encodedReadOffset); + ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag); + + writeOffset = ma_atomic_load_32(&pRB->encodedWriteOffset); + ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag); + + 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_API 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; + } + + readOffset = ma_atomic_load_32(&pRB->encodedReadOffset); + ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag); + + writeOffset = ma_atomic_load_32(&pRB->encodedWriteOffset); + ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag); + + if (readOffsetLoopFlag == writeOffsetLoopFlag) { + return writeOffsetInBytes - readOffsetInBytes; + } else { + return writeOffsetInBytes + (pRB->subbufferSizeInBytes - readOffsetInBytes); + } +} + +MA_API ma_uint32 ma_rb_available_read(ma_rb* pRB) +{ + ma_int32 dist; + + if (pRB == NULL) { + return 0; + } + + dist = ma_rb_pointer_distance(pRB); + if (dist < 0) { + return 0; + } + + return dist; +} + +MA_API ma_uint32 ma_rb_available_write(ma_rb* pRB) +{ + if (pRB == NULL) { + return 0; + } + + return (ma_uint32)(ma_rb_get_subbuffer_size(pRB) - ma_rb_pointer_distance(pRB)); +} + +MA_API size_t ma_rb_get_subbuffer_size(ma_rb* pRB) +{ + if (pRB == NULL) { + return 0; + } + + return pRB->subbufferSizeInBytes; +} + +MA_API 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; +} + +MA_API 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); +} + +MA_API 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_result ma_pcm_rb_data_source__on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + /* Since there's no notion of an end, we don't ever want to return MA_AT_END here. But it is possible to return 0. */ + ma_pcm_rb* pRB = (ma_pcm_rb*)pDataSource; + ma_result result; + ma_uint64 totalFramesRead; + + MA_ASSERT(pRB != NULL); + + /* We need to run this in a loop since the ring buffer itself may loop. */ + totalFramesRead = 0; + while (totalFramesRead < frameCount) { + void* pMappedBuffer; + ma_uint32 mappedFrameCount; + ma_uint64 framesToRead = frameCount - totalFramesRead; + if (framesToRead > 0xFFFFFFFF) { + framesToRead = 0xFFFFFFFF; + } + + mappedFrameCount = (ma_uint32)framesToRead; + result = ma_pcm_rb_acquire_read(pRB, &mappedFrameCount, &pMappedBuffer); + if (result != MA_SUCCESS) { + break; + } + + if (mappedFrameCount == 0) { + break; /* <-- End of ring buffer. */ + } + + ma_copy_pcm_frames(ma_offset_pcm_frames_ptr(pFramesOut, totalFramesRead, pRB->format, pRB->channels), pMappedBuffer, mappedFrameCount, pRB->format, pRB->channels); + + result = ma_pcm_rb_commit_read(pRB, mappedFrameCount); + if (result != MA_SUCCESS) { + break; + } + + totalFramesRead += mappedFrameCount; + } + + *pFramesRead = totalFramesRead; + return MA_SUCCESS; +} + +static ma_result ma_pcm_rb_data_source__on_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + ma_pcm_rb* pRB = (ma_pcm_rb*)pDataSource; + MA_ASSERT(pRB != NULL); + + if (pFormat != NULL) { + *pFormat = pRB->format; + } + + if (pChannels != NULL) { + *pChannels = pRB->channels; + } + + if (pSampleRate != NULL) { + *pSampleRate = pRB->sampleRate; + } + + /* Just assume the default channel map. */ + if (pChannelMap != NULL) { + ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pRB->channels); + } + + return MA_SUCCESS; +} + +static ma_data_source_vtable ma_gRBDataSourceVTable = +{ + ma_pcm_rb_data_source__on_read, + NULL, /* onSeek */ + ma_pcm_rb_data_source__on_get_data_format, + NULL, /* onGetCursor */ + NULL, /* onGetLength */ + NULL, /* onSetLooping */ + 0 +}; + +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_API ma_result ma_pcm_rb_init_ex(ma_format format, ma_uint32 channels, ma_uint32 subbufferSizeInFrames, ma_uint32 subbufferCount, ma_uint32 subbufferStrideInFrames, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_pcm_rb* pRB) +{ + ma_uint32 bpf; + ma_result result; + + if (pRB == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pRB); + + bpf = ma_get_bytes_per_frame(format, channels); + if (bpf == 0) { + return MA_INVALID_ARGS; + } + + result = ma_rb_init_ex(subbufferSizeInFrames*bpf, subbufferCount, subbufferStrideInFrames*bpf, pOptionalPreallocatedBuffer, pAllocationCallbacks, &pRB->rb); + if (result != MA_SUCCESS) { + return result; + } + + pRB->format = format; + pRB->channels = channels; + pRB->sampleRate = 0; /* The sample rate is not passed in as a parameter. */ + + /* The PCM ring buffer is a data source. We need to get that set up as well. */ + { + ma_data_source_config dataSourceConfig = ma_data_source_config_init(); + dataSourceConfig.vtable = &ma_gRBDataSourceVTable; + + result = ma_data_source_init(&dataSourceConfig, &pRB->ds); + if (result != MA_SUCCESS) { + ma_rb_uninit(&pRB->rb); + return result; + } + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_pcm_rb_init(ma_format format, ma_uint32 channels, ma_uint32 bufferSizeInFrames, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_pcm_rb* pRB) +{ + return ma_pcm_rb_init_ex(format, channels, bufferSizeInFrames, 1, 0, pOptionalPreallocatedBuffer, pAllocationCallbacks, pRB); +} + +MA_API void ma_pcm_rb_uninit(ma_pcm_rb* pRB) +{ + if (pRB == NULL) { + return; + } + + ma_data_source_uninit(&pRB->ds); + ma_rb_uninit(&pRB->rb); +} + +MA_API void ma_pcm_rb_reset(ma_pcm_rb* pRB) +{ + if (pRB == NULL) { + return; + } + + ma_rb_reset(&pRB->rb); +} + +MA_API 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_API ma_result ma_pcm_rb_commit_read(ma_pcm_rb* pRB, ma_uint32 sizeInFrames) +{ + if (pRB == NULL) { + return MA_INVALID_ARGS; + } + + return ma_rb_commit_read(&pRB->rb, sizeInFrames * ma_pcm_rb_get_bpf(pRB)); +} + +MA_API 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_API ma_result ma_pcm_rb_commit_write(ma_pcm_rb* pRB, ma_uint32 sizeInFrames) +{ + if (pRB == NULL) { + return MA_INVALID_ARGS; + } + + return ma_rb_commit_write(&pRB->rb, sizeInFrames * ma_pcm_rb_get_bpf(pRB)); +} + +MA_API 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_API 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_API ma_int32 ma_pcm_rb_pointer_distance(ma_pcm_rb* pRB) +{ + if (pRB == NULL) { + return 0; + } + + return ma_rb_pointer_distance(&pRB->rb) / ma_pcm_rb_get_bpf(pRB); +} + +MA_API ma_uint32 ma_pcm_rb_available_read(ma_pcm_rb* pRB) +{ + if (pRB == NULL) { + return 0; + } + + return ma_rb_available_read(&pRB->rb) / ma_pcm_rb_get_bpf(pRB); +} + +MA_API ma_uint32 ma_pcm_rb_available_write(ma_pcm_rb* pRB) +{ + if (pRB == NULL) { + return 0; + } + + return ma_rb_available_write(&pRB->rb) / ma_pcm_rb_get_bpf(pRB); +} + +MA_API 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_API 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_API 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)); +} + +MA_API 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); +} + +MA_API ma_format ma_pcm_rb_get_format(const ma_pcm_rb* pRB) +{ + if (pRB == NULL) { + return ma_format_unknown; + } + + return pRB->format; +} + +MA_API ma_uint32 ma_pcm_rb_get_channels(const ma_pcm_rb* pRB) +{ + if (pRB == NULL) { + return 0; + } + + return pRB->channels; +} + +MA_API ma_uint32 ma_pcm_rb_get_sample_rate(const ma_pcm_rb* pRB) +{ + if (pRB == NULL) { + return 0; + } + + return pRB->sampleRate; +} + +MA_API void ma_pcm_rb_set_sample_rate(ma_pcm_rb* pRB, ma_uint32 sampleRate) +{ + if (pRB == NULL) { + return; + } + + pRB->sampleRate = sampleRate; +} + + + +MA_API ma_result ma_duplex_rb_init(ma_format captureFormat, ma_uint32 captureChannels, ma_uint32 sampleRate, ma_uint32 captureInternalSampleRate, ma_uint32 captureInternalPeriodSizeInFrames, const ma_allocation_callbacks* pAllocationCallbacks, ma_duplex_rb* pRB) +{ + ma_result result; + ma_uint32 sizeInFrames; + + sizeInFrames = (ma_uint32)ma_calculate_frame_count_after_resampling(sampleRate, captureInternalSampleRate, captureInternalPeriodSizeInFrames * 5); + if (sizeInFrames == 0) { + return MA_INVALID_ARGS; + } + + result = ma_pcm_rb_init(captureFormat, captureChannels, sizeInFrames, NULL, pAllocationCallbacks, &pRB->rb); + if (result != MA_SUCCESS) { + return result; + } + + /* Seek forward a bit so we have a bit of a buffer in case of desyncs. */ + ma_pcm_rb_seek_write((ma_pcm_rb*)pRB, captureInternalPeriodSizeInFrames * 2); + + return MA_SUCCESS; +} + +MA_API ma_result ma_duplex_rb_uninit(ma_duplex_rb* pRB) +{ + ma_pcm_rb_uninit((ma_pcm_rb*)pRB); + return MA_SUCCESS; +} + + + +/************************************************************************************************************************************************************** + +Miscellaneous Helpers + +**************************************************************************************************************************************************************/ +MA_API const char* ma_result_description(ma_result result) +{ + switch (result) + { + case MA_SUCCESS: return "No error"; + case MA_ERROR: return "Unknown error"; + case MA_INVALID_ARGS: return "Invalid argument"; + case MA_INVALID_OPERATION: return "Invalid operation"; + case MA_OUT_OF_MEMORY: return "Out of memory"; + case MA_OUT_OF_RANGE: return "Out of range"; + case MA_ACCESS_DENIED: return "Permission denied"; + case MA_DOES_NOT_EXIST: return "Resource does not exist"; + case MA_ALREADY_EXISTS: return "Resource already exists"; + case MA_TOO_MANY_OPEN_FILES: return "Too many open files"; + case MA_INVALID_FILE: return "Invalid file"; + case MA_TOO_BIG: return "Too large"; + case MA_PATH_TOO_LONG: return "Path too long"; + case MA_NAME_TOO_LONG: return "Name too long"; + case MA_NOT_DIRECTORY: return "Not a directory"; + case MA_IS_DIRECTORY: return "Is a directory"; + case MA_DIRECTORY_NOT_EMPTY: return "Directory not empty"; + case MA_AT_END: return "At end"; + case MA_NO_SPACE: return "No space available"; + case MA_BUSY: return "Device or resource busy"; + case MA_IO_ERROR: return "Input/output error"; + case MA_INTERRUPT: return "Interrupted"; + case MA_UNAVAILABLE: return "Resource unavailable"; + case MA_ALREADY_IN_USE: return "Resource already in use"; + case MA_BAD_ADDRESS: return "Bad address"; + case MA_BAD_SEEK: return "Illegal seek"; + case MA_BAD_PIPE: return "Broken pipe"; + case MA_DEADLOCK: return "Deadlock"; + case MA_TOO_MANY_LINKS: return "Too many links"; + case MA_NOT_IMPLEMENTED: return "Not implemented"; + case MA_NO_MESSAGE: return "No message of desired type"; + case MA_BAD_MESSAGE: return "Invalid message"; + case MA_NO_DATA_AVAILABLE: return "No data available"; + case MA_INVALID_DATA: return "Invalid data"; + case MA_TIMEOUT: return "Timeout"; + case MA_NO_NETWORK: return "Network unavailable"; + case MA_NOT_UNIQUE: return "Not unique"; + case MA_NOT_SOCKET: return "Socket operation on non-socket"; + case MA_NO_ADDRESS: return "Destination address required"; + case MA_BAD_PROTOCOL: return "Protocol wrong type for socket"; + case MA_PROTOCOL_UNAVAILABLE: return "Protocol not available"; + case MA_PROTOCOL_NOT_SUPPORTED: return "Protocol not supported"; + case MA_PROTOCOL_FAMILY_NOT_SUPPORTED: return "Protocol family not supported"; + case MA_ADDRESS_FAMILY_NOT_SUPPORTED: return "Address family not supported"; + case MA_SOCKET_NOT_SUPPORTED: return "Socket type not supported"; + case MA_CONNECTION_RESET: return "Connection reset"; + case MA_ALREADY_CONNECTED: return "Already connected"; + case MA_NOT_CONNECTED: return "Not connected"; + case MA_CONNECTION_REFUSED: return "Connection refused"; + case MA_NO_HOST: return "No host"; + case MA_IN_PROGRESS: return "Operation in progress"; + case MA_CANCELLED: return "Operation cancelled"; + case MA_MEMORY_ALREADY_MAPPED: return "Memory already mapped"; + + case MA_FORMAT_NOT_SUPPORTED: return "Format not supported"; + case MA_DEVICE_TYPE_NOT_SUPPORTED: return "Device type not supported"; + case MA_SHARE_MODE_NOT_SUPPORTED: return "Share mode not supported"; + case MA_NO_BACKEND: return "No backend"; + case MA_NO_DEVICE: return "No device"; + case MA_API_NOT_FOUND: return "API not found"; + case MA_INVALID_DEVICE_CONFIG: return "Invalid device config"; + + case MA_DEVICE_NOT_INITIALIZED: return "Device not initialized"; + case MA_DEVICE_NOT_STARTED: return "Device not started"; + + case MA_FAILED_TO_INIT_BACKEND: return "Failed to initialize backend"; + case MA_FAILED_TO_OPEN_BACKEND_DEVICE: return "Failed to open backend device"; + case MA_FAILED_TO_START_BACKEND_DEVICE: return "Failed to start backend device"; + case MA_FAILED_TO_STOP_BACKEND_DEVICE: return "Failed to stop backend device"; + + default: return "Unknown error"; + } +} + +MA_API void* ma_malloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pAllocationCallbacks != NULL) { + if (pAllocationCallbacks->onMalloc != NULL) { + return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData); + } else { + return NULL; /* Do not fall back to the default implementation. */ + } + } else { + return ma__malloc_default(sz, NULL); + } +} + +MA_API void* ma_calloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks) +{ + void* p = ma_malloc(sz, pAllocationCallbacks); + if (p != NULL) { + MA_ZERO_MEMORY(p, sz); + } + + return p; +} + +MA_API void* ma_realloc(void* p, size_t sz, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pAllocationCallbacks != NULL) { + if (pAllocationCallbacks->onRealloc != NULL) { + return pAllocationCallbacks->onRealloc(p, sz, pAllocationCallbacks->pUserData); + } else { + return NULL; /* Do not fall back to the default implementation. */ + } + } else { + return ma__realloc_default(p, sz, NULL); + } +} + +MA_API void ma_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (p == NULL) { + return; + } + + if (pAllocationCallbacks != NULL) { + if (pAllocationCallbacks->onFree != NULL) { + pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData); + } else { + return; /* Do no fall back to the default implementation. */ + } + } else { + ma__free_default(p, NULL); + } +} + +MA_API void* ma_aligned_malloc(size_t sz, size_t alignment, const ma_allocation_callbacks* pAllocationCallbacks) +{ + size_t extraBytes; + void* pUnaligned; + void* pAligned; + + if (alignment == 0) { + return 0; + } + + extraBytes = alignment-1 + sizeof(void*); + + pUnaligned = ma_malloc(sz + extraBytes, pAllocationCallbacks); + if (pUnaligned == NULL) { + return NULL; + } + + pAligned = (void*)(((ma_uintptr)pUnaligned + extraBytes) & ~((ma_uintptr)(alignment-1))); + ((void**)pAligned)[-1] = pUnaligned; + + return pAligned; +} + +MA_API void ma_aligned_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_free(((void**)p)[-1], pAllocationCallbacks); +} + +MA_API 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"; + } +} + +MA_API void ma_blend_f32(float* pOut, float* pInA, float* pInB, float factor, ma_uint32 channels) +{ + ma_uint32 i; + for (i = 0; i < channels; ++i) { + pOut[i] = ma_mix_f32(pInA[i], pInB[i], factor); + } +} + + +MA_API 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]; +} + + + +#define MA_DATA_SOURCE_DEFAULT_RANGE_BEG 0 +#define MA_DATA_SOURCE_DEFAULT_RANGE_END ~((ma_uint64)0) +#define MA_DATA_SOURCE_DEFAULT_LOOP_POINT_BEG 0 +#define MA_DATA_SOURCE_DEFAULT_LOOP_POINT_END ~((ma_uint64)0) + +MA_API ma_data_source_config ma_data_source_config_init(void) +{ + ma_data_source_config config; + + MA_ZERO_OBJECT(&config); + + return config; +} + + +MA_API ma_result ma_data_source_init(const ma_data_source_config* pConfig, ma_data_source* pDataSource) +{ + ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource; + + if (pDataSource == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pDataSourceBase); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + pDataSourceBase->vtable = pConfig->vtable; + pDataSourceBase->rangeBegInFrames = MA_DATA_SOURCE_DEFAULT_RANGE_BEG; + pDataSourceBase->rangeEndInFrames = MA_DATA_SOURCE_DEFAULT_RANGE_END; + pDataSourceBase->loopBegInFrames = MA_DATA_SOURCE_DEFAULT_LOOP_POINT_BEG; + pDataSourceBase->loopEndInFrames = MA_DATA_SOURCE_DEFAULT_LOOP_POINT_END; + pDataSourceBase->pCurrent = pDataSource; /* Always read from ourself by default. */ + pDataSourceBase->pNext = NULL; + pDataSourceBase->onGetNext = NULL; + + return MA_SUCCESS; +} + +MA_API void ma_data_source_uninit(ma_data_source* pDataSource) +{ + if (pDataSource == NULL) { + return; + } + + /* + This is placeholder in case we need this later. Data sources need to call this in their + uninitialization routine to ensure things work later on if something is added here. + */ +} + +static ma_result ma_data_source_resolve_current(ma_data_source* pDataSource, ma_data_source** ppCurrentDataSource) +{ + ma_data_source_base* pCurrentDataSource = (ma_data_source_base*)pDataSource; + + MA_ASSERT(pDataSource != NULL); + MA_ASSERT(ppCurrentDataSource != NULL); + + if (pCurrentDataSource->pCurrent == NULL) { + /* + The current data source is NULL. If we're using this in the context of a chain we need to return NULL + here so that we don't end up looping. Otherwise we just return the data source itself. + */ + if (pCurrentDataSource->pNext != NULL || pCurrentDataSource->onGetNext != NULL) { + pCurrentDataSource = NULL; + } else { + pCurrentDataSource = (ma_data_source_base*)pDataSource; /* Not being used in a chain. Make sure we just always read from the data source itself at all times. */ + } + } else { + pCurrentDataSource = (ma_data_source_base*)pCurrentDataSource->pCurrent; + } + + *ppCurrentDataSource = pCurrentDataSource; + + return MA_SUCCESS; +} + +static ma_result ma_data_source_read_pcm_frames_within_range(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource; + ma_result result; + ma_uint64 framesRead = 0; + ma_bool32 loop = ma_data_source_is_looping(pDataSource); + + if (pDataSourceBase == NULL) { + return MA_AT_END; + } + + if (frameCount == 0) { + return MA_INVALID_ARGS; + } + + if ((pDataSourceBase->vtable->flags & MA_DATA_SOURCE_SELF_MANAGED_RANGE_AND_LOOP_POINT) != 0 || (pDataSourceBase->rangeEndInFrames == ~((ma_uint64)0) && (pDataSourceBase->loopEndInFrames == ~((ma_uint64)0) || loop == MA_FALSE))) { + /* Either the data source is self-managing the range, or no range is set - just read like normal. The data source itself will tell us when the end is reached. */ + result = pDataSourceBase->vtable->onRead(pDataSourceBase, pFramesOut, frameCount, &framesRead); + } else { + /* Need to clamp to within the range. */ + ma_uint64 relativeCursor; + ma_uint64 absoluteCursor; + + result = ma_data_source_get_cursor_in_pcm_frames(pDataSourceBase, &relativeCursor); + if (result != MA_SUCCESS) { + /* Failed to retrieve the cursor. Cannot read within a range or loop points. Just read like normal - this may happen for things like noise data sources where it doesn't really matter. */ + result = pDataSourceBase->vtable->onRead(pDataSourceBase, pFramesOut, frameCount, &framesRead); + } else { + ma_uint64 rangeBeg; + ma_uint64 rangeEnd; + + /* We have the cursor. We need to make sure we don't read beyond our range. */ + rangeBeg = pDataSourceBase->rangeBegInFrames; + rangeEnd = pDataSourceBase->rangeEndInFrames; + + absoluteCursor = rangeBeg + relativeCursor; + + /* If looping, make sure we're within range. */ + if (loop) { + if (pDataSourceBase->loopEndInFrames != ~((ma_uint64)0)) { + rangeEnd = ma_min(rangeEnd, pDataSourceBase->rangeBegInFrames + pDataSourceBase->loopEndInFrames); + } + } + + if (frameCount > (rangeEnd - absoluteCursor) && rangeEnd != ~((ma_uint64)0)) { + frameCount = (rangeEnd - absoluteCursor); + } + + /* + If the cursor is sitting on the end of the range the frame count will be set to 0 which can + result in MA_INVALID_ARGS. In this case, we don't want to try reading, but instead return + MA_AT_END so the higher level function can know about it. + */ + if (frameCount > 0) { + result = pDataSourceBase->vtable->onRead(pDataSourceBase, pFramesOut, frameCount, &framesRead); + } else { + result = MA_AT_END; /* The cursor is sitting on the end of the range which means we're at the end. */ + } + } + } + + if (pFramesRead != NULL) { + *pFramesRead = framesRead; + } + + /* We need to make sure MA_AT_END is returned if we hit the end of the range. */ + if (result == MA_SUCCESS && framesRead == 0) { + result = MA_AT_END; + } + + return result; +} + +MA_API ma_result ma_data_source_read_pcm_frames(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + ma_result result = MA_SUCCESS; + ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource; + ma_data_source_base* pCurrentDataSource; + void* pRunningFramesOut = pFramesOut; + ma_uint64 totalFramesProcessed = 0; + ma_format format; + ma_uint32 channels; + ma_uint32 emptyLoopCounter = 0; /* Keeps track of how many times 0 frames have been read. For infinite loop detection of sounds with no audio data. */ + ma_bool32 loop; + + if (pFramesRead != NULL) { + *pFramesRead = 0; + } + + if (frameCount == 0) { + return MA_INVALID_ARGS; + } + + if (pDataSourceBase == NULL) { + return MA_INVALID_ARGS; + } + + loop = ma_data_source_is_looping(pDataSource); + + /* + We need to know the data format so we can advance the output buffer as we read frames. If this + fails, chaining will not work and we'll just read as much as we can from the current source. + */ + if (ma_data_source_get_data_format(pDataSource, &format, &channels, NULL, NULL, 0) != MA_SUCCESS) { + result = ma_data_source_resolve_current(pDataSource, (ma_data_source**)&pCurrentDataSource); + if (result != MA_SUCCESS) { + return result; + } + + return ma_data_source_read_pcm_frames_within_range(pCurrentDataSource, pFramesOut, frameCount, pFramesRead); + } + + /* + Looping is a bit of a special case. When the `loop` argument is true, chaining will not work and + only the current data source will be read from. + */ + + /* Keep reading until we've read as many frames as possible. */ + while (totalFramesProcessed < frameCount) { + ma_uint64 framesProcessed; + ma_uint64 framesRemaining = frameCount - totalFramesProcessed; + + /* We need to resolve the data source that we'll actually be reading from. */ + result = ma_data_source_resolve_current(pDataSource, (ma_data_source**)&pCurrentDataSource); + if (result != MA_SUCCESS) { + break; + } + + if (pCurrentDataSource == NULL) { + break; + } + + result = ma_data_source_read_pcm_frames_within_range(pCurrentDataSource, pRunningFramesOut, framesRemaining, &framesProcessed); + totalFramesProcessed += framesProcessed; + + /* + If we encounted an error from the read callback, make sure it's propagated to the caller. The caller may need to know whether or not MA_BUSY is returned which is + not necessarily considered an error. + */ + if (result != MA_SUCCESS && result != MA_AT_END) { + break; + } + + /* + We can determine if we've reached the end by checking if ma_data_source_read_pcm_frames_within_range() returned + MA_AT_END. To loop back to the start, all we need to do is seek back to the first frame. + */ + if (result == MA_AT_END) { + /* + The result needs to be reset back to MA_SUCCESS (from MA_AT_END) so that we don't + accidentally return MA_AT_END when data has been read in prior loop iterations. at the + end of this function, the result will be checked for MA_SUCCESS, and if the total + number of frames processed is 0, will be explicitly set to MA_AT_END. + */ + result = MA_SUCCESS; + + /* + We reached the end. If we're looping, we just loop back to the start of the current + data source. If we're not looping we need to check if we have another in the chain, and + if so, switch to it. + */ + if (loop) { + if (framesProcessed == 0) { + emptyLoopCounter += 1; + if (emptyLoopCounter > 1) { + break; /* Infinite loop detected. Get out. */ + } + } else { + emptyLoopCounter = 0; + } + + result = ma_data_source_seek_to_pcm_frame(pCurrentDataSource, pCurrentDataSource->loopBegInFrames); + if (result != MA_SUCCESS) { + break; /* Failed to loop. Abort. */ + } + + /* Don't return MA_AT_END for looping sounds. */ + result = MA_SUCCESS; + } else { + if (pCurrentDataSource->pNext != NULL) { + pDataSourceBase->pCurrent = pCurrentDataSource->pNext; + } else if (pCurrentDataSource->onGetNext != NULL) { + pDataSourceBase->pCurrent = pCurrentDataSource->onGetNext(pCurrentDataSource); + if (pDataSourceBase->pCurrent == NULL) { + break; /* Our callback did not return a next data source. We're done. */ + } + } else { + /* Reached the end of the chain. We're done. */ + break; + } + + /* The next data source needs to be rewound to ensure data is read in looping scenarios. */ + result = ma_data_source_seek_to_pcm_frame(pDataSourceBase->pCurrent, 0); + if (result != MA_SUCCESS) { + break; + } + } + } + + if (pRunningFramesOut != NULL) { + pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesProcessed * ma_get_bytes_per_frame(format, channels)); + } + } + + if (pFramesRead != NULL) { + *pFramesRead = totalFramesProcessed; + } + + MA_ASSERT(!(result == MA_AT_END && totalFramesProcessed > 0)); /* We should never be returning MA_AT_END if we read some data. */ + + if (result == MA_SUCCESS && totalFramesProcessed == 0) { + result = MA_AT_END; + } + + return result; +} + +MA_API ma_result ma_data_source_seek_pcm_frames(ma_data_source* pDataSource, ma_uint64 frameCount, ma_uint64* pFramesSeeked) +{ + return ma_data_source_read_pcm_frames(pDataSource, NULL, frameCount, pFramesSeeked); +} + +MA_API ma_result ma_data_source_seek_to_pcm_frame(ma_data_source* pDataSource, ma_uint64 frameIndex) +{ + ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource; + + if (pDataSourceBase == NULL) { + return MA_SUCCESS; + } + + if (pDataSourceBase->vtable->onSeek == NULL) { + return MA_NOT_IMPLEMENTED; + } + + if (frameIndex > pDataSourceBase->rangeEndInFrames) { + return MA_INVALID_OPERATION; /* Trying to seek to far forward. */ + } + + return pDataSourceBase->vtable->onSeek(pDataSource, pDataSourceBase->rangeBegInFrames + frameIndex); +} + +MA_API ma_result ma_data_source_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource; + ma_result result; + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + + /* Initialize to defaults for safety just in case the data source does not implement this callback. */ + if (pFormat != NULL) { + *pFormat = ma_format_unknown; + } + if (pChannels != NULL) { + *pChannels = 0; + } + if (pSampleRate != NULL) { + *pSampleRate = 0; + } + if (pChannelMap != NULL) { + MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap); + } + + if (pDataSourceBase == NULL) { + return MA_INVALID_ARGS; + } + + if (pDataSourceBase->vtable->onGetDataFormat == NULL) { + return MA_NOT_IMPLEMENTED; + } + + result = pDataSourceBase->vtable->onGetDataFormat(pDataSource, &format, &channels, &sampleRate, pChannelMap, channelMapCap); + if (result != MA_SUCCESS) { + return result; + } + + if (pFormat != NULL) { + *pFormat = format; + } + if (pChannels != NULL) { + *pChannels = channels; + } + if (pSampleRate != NULL) { + *pSampleRate = sampleRate; + } + + /* Channel map was passed in directly to the callback. This is safe due to the channelMapCap parameter. */ + + return MA_SUCCESS; +} + +MA_API ma_result ma_data_source_get_cursor_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pCursor) +{ + ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource; + ma_result result; + ma_uint64 cursor; + + if (pCursor == NULL) { + return MA_INVALID_ARGS; + } + + *pCursor = 0; + + if (pDataSourceBase == NULL) { + return MA_SUCCESS; + } + + if (pDataSourceBase->vtable->onGetCursor == NULL) { + return MA_NOT_IMPLEMENTED; + } + + result = pDataSourceBase->vtable->onGetCursor(pDataSourceBase, &cursor); + if (result != MA_SUCCESS) { + return result; + } + + /* The cursor needs to be made relative to the start of the range. */ + if (cursor < pDataSourceBase->rangeBegInFrames) { /* Safety check so we don't return some huge number. */ + *pCursor = 0; + } else { + *pCursor = cursor - pDataSourceBase->rangeBegInFrames; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_data_source_get_length_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pLength) +{ + ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource; + + if (pLength == NULL) { + return MA_INVALID_ARGS; + } + + *pLength = 0; + + if (pDataSourceBase == NULL) { + return MA_INVALID_ARGS; + } + + /* + If we have a range defined we'll use that to determine the length. This is one of rare times + where we'll actually trust the caller. If they've set the range, I think it's mostly safe to + assume they've set it based on some higher level knowledge of the structure of the sound bank. + */ + if (pDataSourceBase->rangeEndInFrames != ~((ma_uint64)0)) { + *pLength = pDataSourceBase->rangeEndInFrames - pDataSourceBase->rangeBegInFrames; + return MA_SUCCESS; + } + + /* + Getting here means a range is not defined so we'll need to get the data source itself to tell + us the length. + */ + if (pDataSourceBase->vtable->onGetLength == NULL) { + return MA_NOT_IMPLEMENTED; + } + + return pDataSourceBase->vtable->onGetLength(pDataSource, pLength); +} + +MA_API ma_result ma_data_source_get_cursor_in_seconds(ma_data_source* pDataSource, float* pCursor) +{ + ma_result result; + ma_uint64 cursorInPCMFrames; + ma_uint32 sampleRate; + + if (pCursor == NULL) { + return MA_INVALID_ARGS; + } + + *pCursor = 0; + + result = ma_data_source_get_cursor_in_pcm_frames(pDataSource, &cursorInPCMFrames); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_data_source_get_data_format(pDataSource, NULL, NULL, &sampleRate, NULL, 0); + if (result != MA_SUCCESS) { + return result; + } + + /* VC6 does not support division of unsigned 64-bit integers with floating point numbers. Need to use a signed number. This shouldn't effect anything in practice. */ + *pCursor = (ma_int64)cursorInPCMFrames / (float)sampleRate; + + return MA_SUCCESS; +} + +MA_API ma_result ma_data_source_get_length_in_seconds(ma_data_source* pDataSource, float* pLength) +{ + ma_result result; + ma_uint64 lengthInPCMFrames; + ma_uint32 sampleRate; + + if (pLength == NULL) { + return MA_INVALID_ARGS; + } + + *pLength = 0; + + result = ma_data_source_get_length_in_pcm_frames(pDataSource, &lengthInPCMFrames); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_data_source_get_data_format(pDataSource, NULL, NULL, &sampleRate, NULL, 0); + if (result != MA_SUCCESS) { + return result; + } + + /* VC6 does not support division of unsigned 64-bit integers with floating point numbers. Need to use a signed number. This shouldn't effect anything in practice. */ + *pLength = (ma_int64)lengthInPCMFrames / (float)sampleRate; + + return MA_SUCCESS; +} + +MA_API ma_result ma_data_source_set_looping(ma_data_source* pDataSource, ma_bool32 isLooping) +{ + ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource; + + if (pDataSource == NULL) { + return MA_INVALID_ARGS; + } + + ma_atomic_exchange_32(&pDataSourceBase->isLooping, isLooping); + + /* If there's no callback for this just treat it as a successful no-op. */ + if (pDataSourceBase->vtable->onSetLooping == NULL) { + return MA_SUCCESS; + } + + return pDataSourceBase->vtable->onSetLooping(pDataSource, isLooping); +} + +MA_API ma_bool32 ma_data_source_is_looping(const ma_data_source* pDataSource) +{ + const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource; + + if (pDataSource == NULL) { + return MA_FALSE; + } + + return ma_atomic_load_32(&pDataSourceBase->isLooping); +} + +MA_API ma_result ma_data_source_set_range_in_pcm_frames(ma_data_source* pDataSource, ma_uint64 rangeBegInFrames, ma_uint64 rangeEndInFrames) +{ + ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource; + ma_result result; + ma_uint64 relativeCursor; + ma_uint64 absoluteCursor; + ma_bool32 doSeekAdjustment = MA_FALSE; + + if (pDataSource == NULL) { + return MA_INVALID_ARGS; + } + + if (rangeEndInFrames < rangeBegInFrames) { + return MA_INVALID_ARGS; /* The end of the range must come after the beginning. */ + } + + /* + We may need to adjust the position of the cursor to ensure it's clamped to the range. Grab it now + so we can calculate it's absolute position before we change the range. + */ + result = ma_data_source_get_cursor_in_pcm_frames(pDataSource, &relativeCursor); + if (result == MA_SUCCESS) { + doSeekAdjustment = MA_TRUE; + absoluteCursor = relativeCursor + pDataSourceBase->rangeBegInFrames; + } else { + /* + We couldn't get the position of the cursor. It probably means the data source has no notion + of a cursor. We'll just leave it at position 0. Don't treat this as an error. + */ + doSeekAdjustment = MA_FALSE; + relativeCursor = 0; + absoluteCursor = 0; + } + + pDataSourceBase->rangeBegInFrames = rangeBegInFrames; + pDataSourceBase->rangeEndInFrames = rangeEndInFrames; + + /* + The commented out logic below was intended to maintain loop points in response to a change in the + range. However, this is not useful because it results in the sound breaking when you move the range + outside of the old loop points. I'm simplifying this by simply resetting the loop points. The + caller is expected to update their loop points if they change the range. + + In practice this should be mostly a non-issue because the majority of the time the range will be + set once right after initialization. + */ + pDataSourceBase->loopBegInFrames = 0; + pDataSourceBase->loopEndInFrames = ~((ma_uint64)0); + + + /* + Seek to within range. Note that our seek positions here are relative to the new range. We don't want + do do this if we failed to retrieve the cursor earlier on because it probably means the data source + has no notion of a cursor. In practice the seek would probably fail (which we silently ignore), but + I'm just not even going to attempt it. + */ + if (doSeekAdjustment) { + if (absoluteCursor < rangeBegInFrames) { + ma_data_source_seek_to_pcm_frame(pDataSource, 0); + } else if (absoluteCursor > rangeEndInFrames) { + ma_data_source_seek_to_pcm_frame(pDataSource, rangeEndInFrames - rangeBegInFrames); + } + } + + return MA_SUCCESS; +} + +MA_API void ma_data_source_get_range_in_pcm_frames(const ma_data_source* pDataSource, ma_uint64* pRangeBegInFrames, ma_uint64* pRangeEndInFrames) +{ + const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource; + + if (pDataSource == NULL) { + return; + } + + if (pRangeBegInFrames != NULL) { + *pRangeBegInFrames = pDataSourceBase->rangeBegInFrames; + } + + if (pRangeEndInFrames != NULL) { + *pRangeEndInFrames = pDataSourceBase->rangeEndInFrames; + } +} + +MA_API ma_result ma_data_source_set_loop_point_in_pcm_frames(ma_data_source* pDataSource, ma_uint64 loopBegInFrames, ma_uint64 loopEndInFrames) +{ + ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource; + + if (pDataSource == NULL) { + return MA_INVALID_ARGS; + } + + if (loopEndInFrames < loopBegInFrames) { + return MA_INVALID_ARGS; /* The end of the loop point must come after the beginning. */ + } + + if (loopEndInFrames > pDataSourceBase->rangeEndInFrames && loopEndInFrames != ~((ma_uint64)0)) { + return MA_INVALID_ARGS; /* The end of the loop point must not go beyond the range. */ + } + + pDataSourceBase->loopBegInFrames = loopBegInFrames; + pDataSourceBase->loopEndInFrames = loopEndInFrames; + + /* The end cannot exceed the range. */ + if (pDataSourceBase->loopEndInFrames > (pDataSourceBase->rangeEndInFrames - pDataSourceBase->rangeBegInFrames) && pDataSourceBase->loopEndInFrames != ~((ma_uint64)0)) { + pDataSourceBase->loopEndInFrames = (pDataSourceBase->rangeEndInFrames - pDataSourceBase->rangeBegInFrames); + } + + return MA_SUCCESS; +} + +MA_API void ma_data_source_get_loop_point_in_pcm_frames(const ma_data_source* pDataSource, ma_uint64* pLoopBegInFrames, ma_uint64* pLoopEndInFrames) +{ + const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource; + + if (pDataSource == NULL) { + return; + } + + if (pLoopBegInFrames != NULL) { + *pLoopBegInFrames = pDataSourceBase->loopBegInFrames; + } + + if (pLoopEndInFrames != NULL) { + *pLoopEndInFrames = pDataSourceBase->loopEndInFrames; + } +} + +MA_API ma_result ma_data_source_set_current(ma_data_source* pDataSource, ma_data_source* pCurrentDataSource) +{ + ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource; + + if (pDataSource == NULL) { + return MA_INVALID_ARGS; + } + + pDataSourceBase->pCurrent = pCurrentDataSource; + + return MA_SUCCESS; +} + +MA_API ma_data_source* ma_data_source_get_current(const ma_data_source* pDataSource) +{ + const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource; + + if (pDataSource == NULL) { + return NULL; + } + + return pDataSourceBase->pCurrent; +} + +MA_API ma_result ma_data_source_set_next(ma_data_source* pDataSource, ma_data_source* pNextDataSource) +{ + ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource; + + if (pDataSource == NULL) { + return MA_INVALID_ARGS; + } + + pDataSourceBase->pNext = pNextDataSource; + + return MA_SUCCESS; +} + +MA_API ma_data_source* ma_data_source_get_next(const ma_data_source* pDataSource) +{ + const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource; + + if (pDataSource == NULL) { + return NULL; + } + + return pDataSourceBase->pNext; +} + +MA_API ma_result ma_data_source_set_next_callback(ma_data_source* pDataSource, ma_data_source_get_next_proc onGetNext) +{ + ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource; + + if (pDataSource == NULL) { + return MA_INVALID_ARGS; + } + + pDataSourceBase->onGetNext = onGetNext; + + return MA_SUCCESS; +} + +MA_API ma_data_source_get_next_proc ma_data_source_get_next_callback(const ma_data_source* pDataSource) +{ + const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource; + + if (pDataSource == NULL) { + return NULL; + } + + return pDataSourceBase->onGetNext; +} + + +static ma_result ma_audio_buffer_ref__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + ma_audio_buffer_ref* pAudioBufferRef = (ma_audio_buffer_ref*)pDataSource; + ma_uint64 framesRead = ma_audio_buffer_ref_read_pcm_frames(pAudioBufferRef, pFramesOut, frameCount, MA_FALSE); + + if (pFramesRead != NULL) { + *pFramesRead = framesRead; + } + + if (framesRead < frameCount || framesRead == 0) { + return MA_AT_END; + } + + return MA_SUCCESS; +} + +static ma_result ma_audio_buffer_ref__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex) +{ + return ma_audio_buffer_ref_seek_to_pcm_frame((ma_audio_buffer_ref*)pDataSource, frameIndex); +} + +static ma_result ma_audio_buffer_ref__data_source_on_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + ma_audio_buffer_ref* pAudioBufferRef = (ma_audio_buffer_ref*)pDataSource; + + *pFormat = pAudioBufferRef->format; + *pChannels = pAudioBufferRef->channels; + *pSampleRate = pAudioBufferRef->sampleRate; + ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pAudioBufferRef->channels); + + return MA_SUCCESS; +} + +static ma_result ma_audio_buffer_ref__data_source_on_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor) +{ + ma_audio_buffer_ref* pAudioBufferRef = (ma_audio_buffer_ref*)pDataSource; + + *pCursor = pAudioBufferRef->cursor; + + return MA_SUCCESS; +} + +static ma_result ma_audio_buffer_ref__data_source_on_get_length(ma_data_source* pDataSource, ma_uint64* pLength) +{ + ma_audio_buffer_ref* pAudioBufferRef = (ma_audio_buffer_ref*)pDataSource; + + *pLength = pAudioBufferRef->sizeInFrames; + + return MA_SUCCESS; +} + +static ma_data_source_vtable g_ma_audio_buffer_ref_data_source_vtable = +{ + ma_audio_buffer_ref__data_source_on_read, + ma_audio_buffer_ref__data_source_on_seek, + ma_audio_buffer_ref__data_source_on_get_data_format, + ma_audio_buffer_ref__data_source_on_get_cursor, + ma_audio_buffer_ref__data_source_on_get_length, + NULL, /* onSetLooping */ + 0 +}; + +MA_API ma_result ma_audio_buffer_ref_init(ma_format format, ma_uint32 channels, const void* pData, ma_uint64 sizeInFrames, ma_audio_buffer_ref* pAudioBufferRef) +{ + ma_result result; + ma_data_source_config dataSourceConfig; + + if (pAudioBufferRef == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pAudioBufferRef); + + dataSourceConfig = ma_data_source_config_init(); + dataSourceConfig.vtable = &g_ma_audio_buffer_ref_data_source_vtable; + + result = ma_data_source_init(&dataSourceConfig, &pAudioBufferRef->ds); + if (result != MA_SUCCESS) { + return result; + } + + pAudioBufferRef->format = format; + pAudioBufferRef->channels = channels; + pAudioBufferRef->sampleRate = 0; /* TODO: Version 0.12. Set this to sampleRate. */ + pAudioBufferRef->cursor = 0; + pAudioBufferRef->sizeInFrames = sizeInFrames; + pAudioBufferRef->pData = pData; + + return MA_SUCCESS; +} + +MA_API void ma_audio_buffer_ref_uninit(ma_audio_buffer_ref* pAudioBufferRef) +{ + if (pAudioBufferRef == NULL) { + return; + } + + ma_data_source_uninit(&pAudioBufferRef->ds); +} + +MA_API ma_result ma_audio_buffer_ref_set_data(ma_audio_buffer_ref* pAudioBufferRef, const void* pData, ma_uint64 sizeInFrames) +{ + if (pAudioBufferRef == NULL) { + return MA_INVALID_ARGS; + } + + pAudioBufferRef->cursor = 0; + pAudioBufferRef->sizeInFrames = sizeInFrames; + pAudioBufferRef->pData = pData; + + return MA_SUCCESS; +} + +MA_API ma_uint64 ma_audio_buffer_ref_read_pcm_frames(ma_audio_buffer_ref* pAudioBufferRef, void* pFramesOut, ma_uint64 frameCount, ma_bool32 loop) +{ + ma_uint64 totalFramesRead = 0; + + if (pAudioBufferRef == NULL) { + return 0; + } + + if (frameCount == 0) { + return 0; + } + + while (totalFramesRead < frameCount) { + ma_uint64 framesAvailable = pAudioBufferRef->sizeInFrames - pAudioBufferRef->cursor; + ma_uint64 framesRemaining = frameCount - totalFramesRead; + ma_uint64 framesToRead; + + framesToRead = framesRemaining; + if (framesToRead > framesAvailable) { + framesToRead = framesAvailable; + } + + if (pFramesOut != NULL) { + ma_copy_pcm_frames(ma_offset_ptr(pFramesOut, totalFramesRead * ma_get_bytes_per_frame(pAudioBufferRef->format, pAudioBufferRef->channels)), ma_offset_ptr(pAudioBufferRef->pData, pAudioBufferRef->cursor * ma_get_bytes_per_frame(pAudioBufferRef->format, pAudioBufferRef->channels)), framesToRead, pAudioBufferRef->format, pAudioBufferRef->channels); + } + + totalFramesRead += framesToRead; + + pAudioBufferRef->cursor += framesToRead; + if (pAudioBufferRef->cursor == pAudioBufferRef->sizeInFrames) { + if (loop) { + pAudioBufferRef->cursor = 0; + } else { + break; /* We've reached the end and we're not looping. Done. */ + } + } + + MA_ASSERT(pAudioBufferRef->cursor < pAudioBufferRef->sizeInFrames); + } + + return totalFramesRead; +} + +MA_API ma_result ma_audio_buffer_ref_seek_to_pcm_frame(ma_audio_buffer_ref* pAudioBufferRef, ma_uint64 frameIndex) +{ + if (pAudioBufferRef == NULL) { + return MA_INVALID_ARGS; + } + + if (frameIndex > pAudioBufferRef->sizeInFrames) { + return MA_INVALID_ARGS; + } + + pAudioBufferRef->cursor = (size_t)frameIndex; + + return MA_SUCCESS; +} + +MA_API ma_result ma_audio_buffer_ref_map(ma_audio_buffer_ref* pAudioBufferRef, void** ppFramesOut, ma_uint64* pFrameCount) +{ + ma_uint64 framesAvailable; + ma_uint64 frameCount = 0; + + if (ppFramesOut != NULL) { + *ppFramesOut = NULL; /* Safety. */ + } + + if (pFrameCount != NULL) { + frameCount = *pFrameCount; + *pFrameCount = 0; /* Safety. */ + } + + if (pAudioBufferRef == NULL || ppFramesOut == NULL || pFrameCount == NULL) { + return MA_INVALID_ARGS; + } + + framesAvailable = pAudioBufferRef->sizeInFrames - pAudioBufferRef->cursor; + if (frameCount > framesAvailable) { + frameCount = framesAvailable; + } + + *ppFramesOut = ma_offset_ptr(pAudioBufferRef->pData, pAudioBufferRef->cursor * ma_get_bytes_per_frame(pAudioBufferRef->format, pAudioBufferRef->channels)); + *pFrameCount = frameCount; + + return MA_SUCCESS; +} + +MA_API ma_result ma_audio_buffer_ref_unmap(ma_audio_buffer_ref* pAudioBufferRef, ma_uint64 frameCount) +{ + ma_uint64 framesAvailable; + + if (pAudioBufferRef == NULL) { + return MA_INVALID_ARGS; + } + + framesAvailable = pAudioBufferRef->sizeInFrames - pAudioBufferRef->cursor; + if (frameCount > framesAvailable) { + return MA_INVALID_ARGS; /* The frame count was too big. This should never happen in an unmapping. Need to make sure the caller is aware of this. */ + } + + pAudioBufferRef->cursor += frameCount; + + if (pAudioBufferRef->cursor == pAudioBufferRef->sizeInFrames) { + return MA_AT_END; /* Successful. Need to tell the caller that the end has been reached so that it can loop if desired. */ + } else { + return MA_SUCCESS; + } +} + +MA_API ma_bool32 ma_audio_buffer_ref_at_end(const ma_audio_buffer_ref* pAudioBufferRef) +{ + if (pAudioBufferRef == NULL) { + return MA_FALSE; + } + + return pAudioBufferRef->cursor == pAudioBufferRef->sizeInFrames; +} + +MA_API ma_result ma_audio_buffer_ref_get_cursor_in_pcm_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pCursor) +{ + if (pCursor == NULL) { + return MA_INVALID_ARGS; + } + + *pCursor = 0; + + if (pAudioBufferRef == NULL) { + return MA_INVALID_ARGS; + } + + *pCursor = pAudioBufferRef->cursor; + + return MA_SUCCESS; +} + +MA_API ma_result ma_audio_buffer_ref_get_length_in_pcm_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pLength) +{ + if (pLength == NULL) { + return MA_INVALID_ARGS; + } + + *pLength = 0; + + if (pAudioBufferRef == NULL) { + return MA_INVALID_ARGS; + } + + *pLength = pAudioBufferRef->sizeInFrames; + + return MA_SUCCESS; +} + +MA_API ma_result ma_audio_buffer_ref_get_available_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pAvailableFrames) +{ + if (pAvailableFrames == NULL) { + return MA_INVALID_ARGS; + } + + *pAvailableFrames = 0; + + if (pAudioBufferRef == NULL) { + return MA_INVALID_ARGS; + } + + if (pAudioBufferRef->sizeInFrames <= pAudioBufferRef->cursor) { + *pAvailableFrames = 0; + } else { + *pAvailableFrames = pAudioBufferRef->sizeInFrames - pAudioBufferRef->cursor; + } + + return MA_SUCCESS; +} + + + + +MA_API ma_audio_buffer_config ma_audio_buffer_config_init(ma_format format, ma_uint32 channels, ma_uint64 sizeInFrames, const void* pData, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_audio_buffer_config config; + + MA_ZERO_OBJECT(&config); + config.format = format; + config.channels = channels; + config.sampleRate = 0; /* TODO: Version 0.12. Set this to sampleRate. */ + config.sizeInFrames = sizeInFrames; + config.pData = pData; + ma_allocation_callbacks_init_copy(&config.allocationCallbacks, pAllocationCallbacks); + + return config; +} + +static ma_result ma_audio_buffer_init_ex(const ma_audio_buffer_config* pConfig, ma_bool32 doCopy, ma_audio_buffer* pAudioBuffer) +{ + ma_result result; + + if (pAudioBuffer == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_MEMORY(pAudioBuffer, sizeof(*pAudioBuffer) - sizeof(pAudioBuffer->_pExtraData)); /* Safety. Don't overwrite the extra data. */ + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->sizeInFrames == 0) { + return MA_INVALID_ARGS; /* Not allowing buffer sizes of 0 frames. */ + } + + result = ma_audio_buffer_ref_init(pConfig->format, pConfig->channels, NULL, 0, &pAudioBuffer->ref); + if (result != MA_SUCCESS) { + return result; + } + + /* TODO: Version 0.12. Set this in ma_audio_buffer_ref_init() instead of here. */ + pAudioBuffer->ref.sampleRate = pConfig->sampleRate; + + ma_allocation_callbacks_init_copy(&pAudioBuffer->allocationCallbacks, &pConfig->allocationCallbacks); + + if (doCopy) { + ma_uint64 allocationSizeInBytes; + void* pData; + + allocationSizeInBytes = pConfig->sizeInFrames * ma_get_bytes_per_frame(pConfig->format, pConfig->channels); + if (allocationSizeInBytes > MA_SIZE_MAX) { + return MA_OUT_OF_MEMORY; /* Too big. */ + } + + pData = ma_malloc((size_t)allocationSizeInBytes, &pAudioBuffer->allocationCallbacks); /* Safe cast to size_t. */ + if (pData == NULL) { + return MA_OUT_OF_MEMORY; + } + + if (pConfig->pData != NULL) { + ma_copy_pcm_frames(pData, pConfig->pData, pConfig->sizeInFrames, pConfig->format, pConfig->channels); + } else { + ma_silence_pcm_frames(pData, pConfig->sizeInFrames, pConfig->format, pConfig->channels); + } + + ma_audio_buffer_ref_set_data(&pAudioBuffer->ref, pData, pConfig->sizeInFrames); + pAudioBuffer->ownsData = MA_TRUE; + } else { + ma_audio_buffer_ref_set_data(&pAudioBuffer->ref, pConfig->pData, pConfig->sizeInFrames); + pAudioBuffer->ownsData = MA_FALSE; + } + + return MA_SUCCESS; +} + +static void ma_audio_buffer_uninit_ex(ma_audio_buffer* pAudioBuffer, ma_bool32 doFree) +{ + if (pAudioBuffer == NULL) { + return; + } + + if (pAudioBuffer->ownsData && pAudioBuffer->ref.pData != &pAudioBuffer->_pExtraData[0]) { + ma_free((void*)pAudioBuffer->ref.pData, &pAudioBuffer->allocationCallbacks); /* Naugty const cast, but OK in this case since we've guarded it with the ownsData check. */ + } + + if (doFree) { + ma_free(pAudioBuffer, &pAudioBuffer->allocationCallbacks); + } + + ma_audio_buffer_ref_uninit(&pAudioBuffer->ref); +} + +MA_API ma_result ma_audio_buffer_init(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer) +{ + return ma_audio_buffer_init_ex(pConfig, MA_FALSE, pAudioBuffer); +} + +MA_API ma_result ma_audio_buffer_init_copy(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer) +{ + return ma_audio_buffer_init_ex(pConfig, MA_TRUE, pAudioBuffer); +} + +MA_API ma_result ma_audio_buffer_alloc_and_init(const ma_audio_buffer_config* pConfig, ma_audio_buffer** ppAudioBuffer) +{ + ma_result result; + ma_audio_buffer* pAudioBuffer; + ma_audio_buffer_config innerConfig; /* We'll be making some changes to the config, so need to make a copy. */ + ma_uint64 allocationSizeInBytes; + + if (ppAudioBuffer == NULL) { + return MA_INVALID_ARGS; + } + + *ppAudioBuffer = NULL; /* Safety. */ + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + innerConfig = *pConfig; + ma_allocation_callbacks_init_copy(&innerConfig.allocationCallbacks, &pConfig->allocationCallbacks); + + allocationSizeInBytes = sizeof(*pAudioBuffer) - sizeof(pAudioBuffer->_pExtraData) + (pConfig->sizeInFrames * ma_get_bytes_per_frame(pConfig->format, pConfig->channels)); + if (allocationSizeInBytes > MA_SIZE_MAX) { + return MA_OUT_OF_MEMORY; /* Too big. */ + } + + pAudioBuffer = (ma_audio_buffer*)ma_malloc((size_t)allocationSizeInBytes, &innerConfig.allocationCallbacks); /* Safe cast to size_t. */ + if (pAudioBuffer == NULL) { + return MA_OUT_OF_MEMORY; + } + + if (pConfig->pData != NULL) { + ma_copy_pcm_frames(&pAudioBuffer->_pExtraData[0], pConfig->pData, pConfig->sizeInFrames, pConfig->format, pConfig->channels); + } else { + ma_silence_pcm_frames(&pAudioBuffer->_pExtraData[0], pConfig->sizeInFrames, pConfig->format, pConfig->channels); + } + + innerConfig.pData = &pAudioBuffer->_pExtraData[0]; + + result = ma_audio_buffer_init_ex(&innerConfig, MA_FALSE, pAudioBuffer); + if (result != MA_SUCCESS) { + ma_free(pAudioBuffer, &innerConfig.allocationCallbacks); + return result; + } + + *ppAudioBuffer = pAudioBuffer; + + return MA_SUCCESS; +} + +MA_API void ma_audio_buffer_uninit(ma_audio_buffer* pAudioBuffer) +{ + ma_audio_buffer_uninit_ex(pAudioBuffer, MA_FALSE); +} + +MA_API void ma_audio_buffer_uninit_and_free(ma_audio_buffer* pAudioBuffer) +{ + ma_audio_buffer_uninit_ex(pAudioBuffer, MA_TRUE); +} + +MA_API ma_uint64 ma_audio_buffer_read_pcm_frames(ma_audio_buffer* pAudioBuffer, void* pFramesOut, ma_uint64 frameCount, ma_bool32 loop) +{ + if (pAudioBuffer == NULL) { + return 0; + } + + return ma_audio_buffer_ref_read_pcm_frames(&pAudioBuffer->ref, pFramesOut, frameCount, loop); +} + +MA_API ma_result ma_audio_buffer_seek_to_pcm_frame(ma_audio_buffer* pAudioBuffer, ma_uint64 frameIndex) +{ + if (pAudioBuffer == NULL) { + return MA_INVALID_ARGS; + } + + return ma_audio_buffer_ref_seek_to_pcm_frame(&pAudioBuffer->ref, frameIndex); +} + +MA_API ma_result ma_audio_buffer_map(ma_audio_buffer* pAudioBuffer, void** ppFramesOut, ma_uint64* pFrameCount) +{ + if (ppFramesOut != NULL) { + *ppFramesOut = NULL; /* Safety. */ + } + + if (pAudioBuffer == NULL) { + if (pFrameCount != NULL) { + *pFrameCount = 0; + } + + return MA_INVALID_ARGS; + } + + return ma_audio_buffer_ref_map(&pAudioBuffer->ref, ppFramesOut, pFrameCount); +} + +MA_API ma_result ma_audio_buffer_unmap(ma_audio_buffer* pAudioBuffer, ma_uint64 frameCount) +{ + if (pAudioBuffer == NULL) { + return MA_INVALID_ARGS; + } + + return ma_audio_buffer_ref_unmap(&pAudioBuffer->ref, frameCount); +} + +MA_API ma_bool32 ma_audio_buffer_at_end(const ma_audio_buffer* pAudioBuffer) +{ + if (pAudioBuffer == NULL) { + return MA_FALSE; + } + + return ma_audio_buffer_ref_at_end(&pAudioBuffer->ref); +} + +MA_API ma_result ma_audio_buffer_get_cursor_in_pcm_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pCursor) +{ + if (pAudioBuffer == NULL) { + return MA_INVALID_ARGS; + } + + return ma_audio_buffer_ref_get_cursor_in_pcm_frames(&pAudioBuffer->ref, pCursor); +} + +MA_API ma_result ma_audio_buffer_get_length_in_pcm_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pLength) +{ + if (pAudioBuffer == NULL) { + return MA_INVALID_ARGS; + } + + return ma_audio_buffer_ref_get_length_in_pcm_frames(&pAudioBuffer->ref, pLength); +} + +MA_API ma_result ma_audio_buffer_get_available_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pAvailableFrames) +{ + if (pAvailableFrames == NULL) { + return MA_INVALID_ARGS; + } + + *pAvailableFrames = 0; + + if (pAudioBuffer == NULL) { + return MA_INVALID_ARGS; + } + + return ma_audio_buffer_ref_get_available_frames(&pAudioBuffer->ref, pAvailableFrames); +} + + + + + +MA_API ma_result ma_paged_audio_buffer_data_init(ma_format format, ma_uint32 channels, ma_paged_audio_buffer_data* pData) +{ + if (pData == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pData); + + pData->format = format; + pData->channels = channels; + pData->pTail = &pData->head; + + return MA_SUCCESS; +} + +MA_API void ma_paged_audio_buffer_data_uninit(ma_paged_audio_buffer_data* pData, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_paged_audio_buffer_page* pPage; + + if (pData == NULL) { + return; + } + + /* All pages need to be freed. */ + pPage = (ma_paged_audio_buffer_page*)ma_atomic_load_ptr(&pData->head.pNext); + while (pPage != NULL) { + ma_paged_audio_buffer_page* pNext = (ma_paged_audio_buffer_page*)ma_atomic_load_ptr(&pPage->pNext); + + ma_free(pPage, pAllocationCallbacks); + pPage = pNext; + } +} + +MA_API ma_paged_audio_buffer_page* ma_paged_audio_buffer_data_get_head(ma_paged_audio_buffer_data* pData) +{ + if (pData == NULL) { + return NULL; + } + + return &pData->head; +} + +MA_API ma_paged_audio_buffer_page* ma_paged_audio_buffer_data_get_tail(ma_paged_audio_buffer_data* pData) +{ + if (pData == NULL) { + return NULL; + } + + return pData->pTail; +} + +MA_API ma_result ma_paged_audio_buffer_data_get_length_in_pcm_frames(ma_paged_audio_buffer_data* pData, ma_uint64* pLength) +{ + ma_paged_audio_buffer_page* pPage; + + if (pLength == NULL) { + return MA_INVALID_ARGS; + } + + *pLength = 0; + + if (pData == NULL) { + return MA_INVALID_ARGS; + } + + /* Calculate the length from the linked list. */ + for (pPage = (ma_paged_audio_buffer_page*)ma_atomic_load_ptr(&pData->head.pNext); pPage != NULL; pPage = (ma_paged_audio_buffer_page*)ma_atomic_load_ptr(&pPage->pNext)) { + *pLength += pPage->sizeInFrames; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_paged_audio_buffer_data_allocate_page(ma_paged_audio_buffer_data* pData, ma_uint64 pageSizeInFrames, const void* pInitialData, const ma_allocation_callbacks* pAllocationCallbacks, ma_paged_audio_buffer_page** ppPage) +{ + ma_paged_audio_buffer_page* pPage; + ma_uint64 allocationSize; + + if (ppPage == NULL) { + return MA_INVALID_ARGS; + } + + *ppPage = NULL; + + if (pData == NULL) { + return MA_INVALID_ARGS; + } + + allocationSize = sizeof(*pPage) + (pageSizeInFrames * ma_get_bytes_per_frame(pData->format, pData->channels)); + if (allocationSize > MA_SIZE_MAX) { + return MA_OUT_OF_MEMORY; /* Too big. */ + } + + pPage = (ma_paged_audio_buffer_page*)ma_malloc((size_t)allocationSize, pAllocationCallbacks); /* Safe cast to size_t. */ + if (pPage == NULL) { + return MA_OUT_OF_MEMORY; + } + + pPage->pNext = NULL; + pPage->sizeInFrames = pageSizeInFrames; + + if (pInitialData != NULL) { + ma_copy_pcm_frames(pPage->pAudioData, pInitialData, pageSizeInFrames, pData->format, pData->channels); + } + + *ppPage = pPage; + + return MA_SUCCESS; +} + +MA_API ma_result ma_paged_audio_buffer_data_free_page(ma_paged_audio_buffer_data* pData, ma_paged_audio_buffer_page* pPage, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pData == NULL || pPage == NULL) { + return MA_INVALID_ARGS; + } + + /* It's assumed the page is not attached to the list. */ + ma_free(pPage, pAllocationCallbacks); + + return MA_SUCCESS; +} + +MA_API ma_result ma_paged_audio_buffer_data_append_page(ma_paged_audio_buffer_data* pData, ma_paged_audio_buffer_page* pPage) +{ + if (pData == NULL || pPage == NULL) { + return MA_INVALID_ARGS; + } + + /* This function assumes the page has been filled with audio data by this point. As soon as we append, the page will be available for reading. */ + + /* First thing to do is update the tail. */ + for (;;) { + ma_paged_audio_buffer_page* pOldTail = (ma_paged_audio_buffer_page*)ma_atomic_load_ptr(&pData->pTail); + ma_paged_audio_buffer_page* pNewTail = pPage; + + if (ma_atomic_compare_exchange_weak_ptr((volatile void**)&pData->pTail, (void**)&pOldTail, pNewTail)) { + /* Here is where we append the page to the list. After this, the page is attached to the list and ready to be read from. */ + ma_atomic_exchange_ptr(&pOldTail->pNext, pPage); + break; /* Done. */ + } + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_paged_audio_buffer_data_allocate_and_append_page(ma_paged_audio_buffer_data* pData, ma_uint32 pageSizeInFrames, const void* pInitialData, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_result result; + ma_paged_audio_buffer_page* pPage; + + result = ma_paged_audio_buffer_data_allocate_page(pData, pageSizeInFrames, pInitialData, pAllocationCallbacks, &pPage); + if (result != MA_SUCCESS) { + return result; + } + + return ma_paged_audio_buffer_data_append_page(pData, pPage); /* <-- Should never fail. */ +} + + +MA_API ma_paged_audio_buffer_config ma_paged_audio_buffer_config_init(ma_paged_audio_buffer_data* pData) +{ + ma_paged_audio_buffer_config config; + + MA_ZERO_OBJECT(&config); + config.pData = pData; + + return config; +} + + +static ma_result ma_paged_audio_buffer__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + return ma_paged_audio_buffer_read_pcm_frames((ma_paged_audio_buffer*)pDataSource, pFramesOut, frameCount, pFramesRead); +} + +static ma_result ma_paged_audio_buffer__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex) +{ + return ma_paged_audio_buffer_seek_to_pcm_frame((ma_paged_audio_buffer*)pDataSource, frameIndex); +} + +static ma_result ma_paged_audio_buffer__data_source_on_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + ma_paged_audio_buffer* pPagedAudioBuffer = (ma_paged_audio_buffer*)pDataSource; + + *pFormat = pPagedAudioBuffer->pData->format; + *pChannels = pPagedAudioBuffer->pData->channels; + *pSampleRate = 0; /* There is no notion of a sample rate with audio buffers. */ + ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pPagedAudioBuffer->pData->channels); + + return MA_SUCCESS; +} + +static ma_result ma_paged_audio_buffer__data_source_on_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor) +{ + return ma_paged_audio_buffer_get_cursor_in_pcm_frames((ma_paged_audio_buffer*)pDataSource, pCursor); +} + +static ma_result ma_paged_audio_buffer__data_source_on_get_length(ma_data_source* pDataSource, ma_uint64* pLength) +{ + return ma_paged_audio_buffer_get_length_in_pcm_frames((ma_paged_audio_buffer*)pDataSource, pLength); +} + +static ma_data_source_vtable g_ma_paged_audio_buffer_data_source_vtable = +{ + ma_paged_audio_buffer__data_source_on_read, + ma_paged_audio_buffer__data_source_on_seek, + ma_paged_audio_buffer__data_source_on_get_data_format, + ma_paged_audio_buffer__data_source_on_get_cursor, + ma_paged_audio_buffer__data_source_on_get_length, + NULL, /* onSetLooping */ + 0 +}; + +MA_API ma_result ma_paged_audio_buffer_init(const ma_paged_audio_buffer_config* pConfig, ma_paged_audio_buffer* pPagedAudioBuffer) +{ + ma_result result; + ma_data_source_config dataSourceConfig; + + if (pPagedAudioBuffer == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pPagedAudioBuffer); + + /* A config is required for the format and channel count. */ + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->pData == NULL) { + return MA_INVALID_ARGS; /* No underlying data specified. */ + } + + dataSourceConfig = ma_data_source_config_init(); + dataSourceConfig.vtable = &g_ma_paged_audio_buffer_data_source_vtable; + + result = ma_data_source_init(&dataSourceConfig, &pPagedAudioBuffer->ds); + if (result != MA_SUCCESS) { + return result; + } + + pPagedAudioBuffer->pData = pConfig->pData; + pPagedAudioBuffer->pCurrent = ma_paged_audio_buffer_data_get_head(pConfig->pData); + pPagedAudioBuffer->relativeCursor = 0; + pPagedAudioBuffer->absoluteCursor = 0; + + return MA_SUCCESS; +} + +MA_API void ma_paged_audio_buffer_uninit(ma_paged_audio_buffer* pPagedAudioBuffer) +{ + if (pPagedAudioBuffer == NULL) { + return; + } + + /* Nothing to do. The data needs to be deleted separately. */ +} + +MA_API ma_result ma_paged_audio_buffer_read_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + ma_result result = MA_SUCCESS; + ma_uint64 totalFramesRead = 0; + ma_format format; + ma_uint32 channels; + + if (pPagedAudioBuffer == NULL) { + return MA_INVALID_ARGS; + } + + format = pPagedAudioBuffer->pData->format; + channels = pPagedAudioBuffer->pData->channels; + + while (totalFramesRead < frameCount) { + /* Read from the current page. The buffer should never be in a state where this is NULL. */ + ma_uint64 framesRemainingInCurrentPage; + ma_uint64 framesRemainingToRead = frameCount - totalFramesRead; + ma_uint64 framesToReadThisIteration; + + MA_ASSERT(pPagedAudioBuffer->pCurrent != NULL); + + framesRemainingInCurrentPage = pPagedAudioBuffer->pCurrent->sizeInFrames - pPagedAudioBuffer->relativeCursor; + + framesToReadThisIteration = ma_min(framesRemainingInCurrentPage, framesRemainingToRead); + ma_copy_pcm_frames(ma_offset_pcm_frames_ptr(pFramesOut, totalFramesRead, format, channels), ma_offset_pcm_frames_ptr(pPagedAudioBuffer->pCurrent->pAudioData, pPagedAudioBuffer->relativeCursor, format, channels), framesToReadThisIteration, format, channels); + totalFramesRead += framesToReadThisIteration; + + pPagedAudioBuffer->absoluteCursor += framesToReadThisIteration; + pPagedAudioBuffer->relativeCursor += framesToReadThisIteration; + + /* Move to the next page if necessary. If there's no more pages, we need to return MA_AT_END. */ + MA_ASSERT(pPagedAudioBuffer->relativeCursor <= pPagedAudioBuffer->pCurrent->sizeInFrames); + + if (pPagedAudioBuffer->relativeCursor == pPagedAudioBuffer->pCurrent->sizeInFrames) { + /* We reached the end of the page. Need to move to the next. If there's no more pages, we're done. */ + ma_paged_audio_buffer_page* pNext = (ma_paged_audio_buffer_page*)ma_atomic_load_ptr(&pPagedAudioBuffer->pCurrent->pNext); + if (pNext == NULL) { + result = MA_AT_END; + break; /* We've reached the end. */ + } else { + pPagedAudioBuffer->pCurrent = pNext; + pPagedAudioBuffer->relativeCursor = 0; + } + } + } + + if (pFramesRead != NULL) { + *pFramesRead = totalFramesRead; + } + + return result; +} + +MA_API ma_result ma_paged_audio_buffer_seek_to_pcm_frame(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64 frameIndex) +{ + if (pPagedAudioBuffer == NULL) { + return MA_INVALID_ARGS; + } + + if (frameIndex == pPagedAudioBuffer->absoluteCursor) { + return MA_SUCCESS; /* Nothing to do. */ + } + + if (frameIndex < pPagedAudioBuffer->absoluteCursor) { + /* Moving backwards. Need to move the cursor back to the start, and then move forward. */ + pPagedAudioBuffer->pCurrent = ma_paged_audio_buffer_data_get_head(pPagedAudioBuffer->pData); + pPagedAudioBuffer->absoluteCursor = 0; + pPagedAudioBuffer->relativeCursor = 0; + + /* Fall through to the forward seeking section below. */ + } + + if (frameIndex > pPagedAudioBuffer->absoluteCursor) { + /* Moving forward. */ + ma_paged_audio_buffer_page* pPage; + ma_uint64 runningCursor = 0; + + for (pPage = (ma_paged_audio_buffer_page*)ma_atomic_load_ptr(&ma_paged_audio_buffer_data_get_head(pPagedAudioBuffer->pData)->pNext); pPage != NULL; pPage = (ma_paged_audio_buffer_page*)ma_atomic_load_ptr(&pPage->pNext)) { + ma_uint64 pageRangeBeg = runningCursor; + ma_uint64 pageRangeEnd = pageRangeBeg + pPage->sizeInFrames; + + if (frameIndex >= pageRangeBeg) { + if (frameIndex < pageRangeEnd || (frameIndex == pageRangeEnd && pPage == (ma_paged_audio_buffer_page*)ma_atomic_load_ptr(ma_paged_audio_buffer_data_get_tail(pPagedAudioBuffer->pData)))) { /* A small edge case - allow seeking to the very end of the buffer. */ + /* We found the page. */ + pPagedAudioBuffer->pCurrent = pPage; + pPagedAudioBuffer->absoluteCursor = frameIndex; + pPagedAudioBuffer->relativeCursor = frameIndex - pageRangeBeg; + return MA_SUCCESS; + } + } + + runningCursor = pageRangeEnd; + } + + /* Getting here means we tried seeking too far forward. Don't change any state. */ + return MA_BAD_SEEK; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_paged_audio_buffer_get_cursor_in_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64* pCursor) +{ + if (pCursor == NULL) { + return MA_INVALID_ARGS; + } + + *pCursor = 0; /* Safety. */ + + if (pPagedAudioBuffer == NULL) { + return MA_INVALID_ARGS; + } + + *pCursor = pPagedAudioBuffer->absoluteCursor; + + return MA_SUCCESS; +} + +MA_API ma_result ma_paged_audio_buffer_get_length_in_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64* pLength) +{ + return ma_paged_audio_buffer_data_get_length_in_pcm_frames(pPagedAudioBuffer->pData, pLength); +} + + + +/************************************************************************************************************************************************************** + +VFS + +**************************************************************************************************************************************************************/ +MA_API ma_result ma_vfs_open(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile) +{ + ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS; + + if (pFile == NULL) { + return MA_INVALID_ARGS; + } + + *pFile = NULL; + + if (pVFS == NULL || pFilePath == NULL || openMode == 0) { + return MA_INVALID_ARGS; + } + + if (pCallbacks->onOpen == NULL) { + return MA_NOT_IMPLEMENTED; + } + + return pCallbacks->onOpen(pVFS, pFilePath, openMode, pFile); +} + +MA_API ma_result ma_vfs_open_w(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile) +{ + ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS; + + if (pFile == NULL) { + return MA_INVALID_ARGS; + } + + *pFile = NULL; + + if (pVFS == NULL || pFilePath == NULL || openMode == 0) { + return MA_INVALID_ARGS; + } + + if (pCallbacks->onOpenW == NULL) { + return MA_NOT_IMPLEMENTED; + } + + return pCallbacks->onOpenW(pVFS, pFilePath, openMode, pFile); +} + +MA_API ma_result ma_vfs_close(ma_vfs* pVFS, ma_vfs_file file) +{ + ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS; + + if (pVFS == NULL || file == NULL) { + return MA_INVALID_ARGS; + } + + if (pCallbacks->onClose == NULL) { + return MA_NOT_IMPLEMENTED; + } + + return pCallbacks->onClose(pVFS, file); +} + +MA_API ma_result ma_vfs_read(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead) +{ + ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS; + ma_result result; + size_t bytesRead = 0; + + if (pBytesRead != NULL) { + *pBytesRead = 0; + } + + if (pVFS == NULL || file == NULL || pDst == NULL) { + return MA_INVALID_ARGS; + } + + if (pCallbacks->onRead == NULL) { + return MA_NOT_IMPLEMENTED; + } + + result = pCallbacks->onRead(pVFS, file, pDst, sizeInBytes, &bytesRead); + + if (pBytesRead != NULL) { + *pBytesRead = bytesRead; + } + + if (result == MA_SUCCESS && bytesRead == 0 && sizeInBytes > 0) { + result = MA_AT_END; + } + + return result; +} + +MA_API ma_result ma_vfs_write(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten) +{ + ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS; + + if (pBytesWritten != NULL) { + *pBytesWritten = 0; + } + + if (pVFS == NULL || file == NULL || pSrc == NULL) { + return MA_INVALID_ARGS; + } + + if (pCallbacks->onWrite == NULL) { + return MA_NOT_IMPLEMENTED; + } + + return pCallbacks->onWrite(pVFS, file, pSrc, sizeInBytes, pBytesWritten); +} + +MA_API ma_result ma_vfs_seek(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin) +{ + ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS; + + if (pVFS == NULL || file == NULL) { + return MA_INVALID_ARGS; + } + + if (pCallbacks->onSeek == NULL) { + return MA_NOT_IMPLEMENTED; + } + + return pCallbacks->onSeek(pVFS, file, offset, origin); +} + +MA_API ma_result ma_vfs_tell(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor) +{ + ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS; + + if (pCursor == NULL) { + return MA_INVALID_ARGS; + } + + *pCursor = 0; + + if (pVFS == NULL || file == NULL) { + return MA_INVALID_ARGS; + } + + if (pCallbacks->onTell == NULL) { + return MA_NOT_IMPLEMENTED; + } + + return pCallbacks->onTell(pVFS, file, pCursor); +} + +MA_API ma_result ma_vfs_info(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo) +{ + ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS; + + if (pInfo == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pInfo); + + if (pVFS == NULL || file == NULL) { + return MA_INVALID_ARGS; + } + + if (pCallbacks->onInfo == NULL) { + return MA_NOT_IMPLEMENTED; + } + + return pCallbacks->onInfo(pVFS, file, pInfo); +} + + +#if !defined(MA_USE_WIN32_FILEIO) && (defined(MA_WIN32) && defined(MA_WIN32_DESKTOP) && !defined(MA_NO_WIN32_FILEIO) && !defined(MA_POSIX)) + #define MA_USE_WIN32_FILEIO +#endif + +#if defined(MA_USE_WIN32_FILEIO) +/* +We need to dynamically load SetFilePointer or SetFilePointerEx because older versions of Windows do +not have the Ex version. We therefore need to do some dynamic branching depending on what's available. + +We load these when we load our first file from the default VFS. It's left open for the life of the +program and is left to the OS to uninitialize when the program terminates. +*/ +typedef DWORD (__stdcall * ma_SetFilePointer_proc)(HANDLE hFile, LONG lDistanceToMove, LONG* lpDistanceToMoveHigh, DWORD dwMoveMethod); +typedef BOOL (__stdcall * ma_SetFilePointerEx_proc)(HANDLE hFile, LARGE_INTEGER liDistanceToMove, LARGE_INTEGER* lpNewFilePointer, DWORD dwMoveMethod); + +static ma_handle hKernel32DLL = NULL; +static ma_SetFilePointer_proc ma_SetFilePointer = NULL; +static ma_SetFilePointerEx_proc ma_SetFilePointerEx = NULL; + +static void ma_win32_fileio_init(void) +{ + if (hKernel32DLL == NULL) { + hKernel32DLL = ma_dlopen(NULL, "kernel32.dll"); + if (hKernel32DLL != NULL) { + ma_SetFilePointer = (ma_SetFilePointer_proc) ma_dlsym(NULL, hKernel32DLL, "SetFilePointer"); + ma_SetFilePointerEx = (ma_SetFilePointerEx_proc)ma_dlsym(NULL, hKernel32DLL, "SetFilePointerEx"); + } + } +} + +static void ma_default_vfs__get_open_settings_win32(ma_uint32 openMode, DWORD* pDesiredAccess, DWORD* pShareMode, DWORD* pCreationDisposition) +{ + *pDesiredAccess = 0; + if ((openMode & MA_OPEN_MODE_READ) != 0) { + *pDesiredAccess |= GENERIC_READ; + } + if ((openMode & MA_OPEN_MODE_WRITE) != 0) { + *pDesiredAccess |= GENERIC_WRITE; + } + + *pShareMode = 0; + if ((openMode & MA_OPEN_MODE_READ) != 0) { + *pShareMode |= FILE_SHARE_READ; + } + + if ((openMode & MA_OPEN_MODE_WRITE) != 0) { + *pCreationDisposition = CREATE_ALWAYS; /* Opening in write mode. Truncate. */ + } else { + *pCreationDisposition = OPEN_EXISTING; /* Opening in read mode. File must exist. */ + } +} + +static ma_result ma_default_vfs_open__win32(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile) +{ + HANDLE hFile; + DWORD dwDesiredAccess; + DWORD dwShareMode; + DWORD dwCreationDisposition; + + (void)pVFS; + + /* Load some Win32 symbols dynamically so we can dynamically check for the existence of SetFilePointerEx. */ + ma_win32_fileio_init(); + + ma_default_vfs__get_open_settings_win32(openMode, &dwDesiredAccess, &dwShareMode, &dwCreationDisposition); + + hFile = CreateFileA(pFilePath, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL); + if (hFile == INVALID_HANDLE_VALUE) { + return ma_result_from_GetLastError(GetLastError()); + } + + *pFile = hFile; + return MA_SUCCESS; +} + +static ma_result ma_default_vfs_open_w__win32(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile) +{ + HANDLE hFile; + DWORD dwDesiredAccess; + DWORD dwShareMode; + DWORD dwCreationDisposition; + + (void)pVFS; + + /* Load some Win32 symbols dynamically so we can dynamically check for the existence of SetFilePointerEx. */ + ma_win32_fileio_init(); + + ma_default_vfs__get_open_settings_win32(openMode, &dwDesiredAccess, &dwShareMode, &dwCreationDisposition); + + hFile = CreateFileW(pFilePath, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL); + if (hFile == INVALID_HANDLE_VALUE) { + return ma_result_from_GetLastError(GetLastError()); + } + + *pFile = hFile; + return MA_SUCCESS; +} + +static ma_result ma_default_vfs_close__win32(ma_vfs* pVFS, ma_vfs_file file) +{ + (void)pVFS; + + if (CloseHandle((HANDLE)file) == 0) { + return ma_result_from_GetLastError(GetLastError()); + } + + return MA_SUCCESS; +} + + +static ma_result ma_default_vfs_read__win32(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead) +{ + ma_result result = MA_SUCCESS; + size_t totalBytesRead; + + (void)pVFS; + + totalBytesRead = 0; + while (totalBytesRead < sizeInBytes) { + size_t bytesRemaining; + DWORD bytesToRead; + DWORD bytesRead; + BOOL readResult; + + bytesRemaining = sizeInBytes - totalBytesRead; + if (bytesRemaining >= 0xFFFFFFFF) { + bytesToRead = 0xFFFFFFFF; + } else { + bytesToRead = (DWORD)bytesRemaining; + } + + readResult = ReadFile((HANDLE)file, ma_offset_ptr(pDst, totalBytesRead), bytesToRead, &bytesRead, NULL); + if (readResult == 1 && bytesRead == 0) { + result = MA_AT_END; + break; /* EOF */ + } + + totalBytesRead += bytesRead; + + if (bytesRead < bytesToRead) { + break; /* EOF */ + } + + if (readResult == 0) { + result = ma_result_from_GetLastError(GetLastError()); + break; + } + } + + if (pBytesRead != NULL) { + *pBytesRead = totalBytesRead; + } + + return result; +} + +static ma_result ma_default_vfs_write__win32(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten) +{ + ma_result result = MA_SUCCESS; + size_t totalBytesWritten; + + (void)pVFS; + + totalBytesWritten = 0; + while (totalBytesWritten < sizeInBytes) { + size_t bytesRemaining; + DWORD bytesToWrite; + DWORD bytesWritten; + BOOL writeResult; + + bytesRemaining = sizeInBytes - totalBytesWritten; + if (bytesRemaining >= 0xFFFFFFFF) { + bytesToWrite = 0xFFFFFFFF; + } else { + bytesToWrite = (DWORD)bytesRemaining; + } + + writeResult = WriteFile((HANDLE)file, ma_offset_ptr(pSrc, totalBytesWritten), bytesToWrite, &bytesWritten, NULL); + totalBytesWritten += bytesWritten; + + if (writeResult == 0) { + result = ma_result_from_GetLastError(GetLastError()); + break; + } + } + + if (pBytesWritten != NULL) { + *pBytesWritten = totalBytesWritten; + } + + return result; +} + + +static ma_result ma_default_vfs_seek__win32(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin) +{ + LARGE_INTEGER liDistanceToMove; + DWORD dwMoveMethod; + BOOL result; + + (void)pVFS; + + liDistanceToMove.QuadPart = offset; + + /* */ if (origin == ma_seek_origin_current) { + dwMoveMethod = FILE_CURRENT; + } else if (origin == ma_seek_origin_end) { + dwMoveMethod = FILE_END; + } else { + dwMoveMethod = FILE_BEGIN; + } + + if (ma_SetFilePointerEx != NULL) { + result = ma_SetFilePointerEx((HANDLE)file, liDistanceToMove, NULL, dwMoveMethod); + } else if (ma_SetFilePointer != NULL) { + /* No SetFilePointerEx() so restrict to 31 bits. */ + if (origin > 0x7FFFFFFF) { + return MA_OUT_OF_RANGE; + } + + result = ma_SetFilePointer((HANDLE)file, (LONG)liDistanceToMove.QuadPart, NULL, dwMoveMethod); + } else { + return MA_NOT_IMPLEMENTED; + } + + if (result == 0) { + return ma_result_from_GetLastError(GetLastError()); + } + + return MA_SUCCESS; +} + +static ma_result ma_default_vfs_tell__win32(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor) +{ + LARGE_INTEGER liZero; + LARGE_INTEGER liTell; + BOOL result; + + (void)pVFS; + + liZero.QuadPart = 0; + + if (ma_SetFilePointerEx != NULL) { + result = ma_SetFilePointerEx((HANDLE)file, liZero, &liTell, FILE_CURRENT); + } else if (ma_SetFilePointer != NULL) { + LONG tell; + + result = ma_SetFilePointer((HANDLE)file, (LONG)liZero.QuadPart, &tell, FILE_CURRENT); + liTell.QuadPart = tell; + } else { + return MA_NOT_IMPLEMENTED; + } + + if (result == 0) { + return ma_result_from_GetLastError(GetLastError()); + } + + if (pCursor != NULL) { + *pCursor = liTell.QuadPart; + } + + return MA_SUCCESS; +} + +static ma_result ma_default_vfs_info__win32(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo) +{ + BY_HANDLE_FILE_INFORMATION fi; + BOOL result; + + (void)pVFS; + + result = GetFileInformationByHandle((HANDLE)file, &fi); + if (result == 0) { + return ma_result_from_GetLastError(GetLastError()); + } + + pInfo->sizeInBytes = ((ma_uint64)fi.nFileSizeHigh << 32) | ((ma_uint64)fi.nFileSizeLow); + + return MA_SUCCESS; +} +#else +static ma_result ma_default_vfs_open__stdio(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile) +{ + ma_result result; + FILE* pFileStd; + const char* pOpenModeStr; + + MA_ASSERT(pFilePath != NULL); + MA_ASSERT(openMode != 0); + MA_ASSERT(pFile != NULL); + + (void)pVFS; + + if ((openMode & MA_OPEN_MODE_READ) != 0) { + if ((openMode & MA_OPEN_MODE_WRITE) != 0) { + pOpenModeStr = "r+"; + } else { + pOpenModeStr = "rb"; + } + } else { + pOpenModeStr = "wb"; + } + + result = ma_fopen(&pFileStd, pFilePath, pOpenModeStr); + if (result != MA_SUCCESS) { + return result; + } + + *pFile = pFileStd; + + return MA_SUCCESS; +} + +static ma_result ma_default_vfs_open_w__stdio(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile) +{ + ma_result result; + FILE* pFileStd; + const wchar_t* pOpenModeStr; + + MA_ASSERT(pFilePath != NULL); + MA_ASSERT(openMode != 0); + MA_ASSERT(pFile != NULL); + + (void)pVFS; + + if ((openMode & MA_OPEN_MODE_READ) != 0) { + if ((openMode & MA_OPEN_MODE_WRITE) != 0) { + pOpenModeStr = L"r+"; + } else { + pOpenModeStr = L"rb"; + } + } else { + pOpenModeStr = L"wb"; + } + + result = ma_wfopen(&pFileStd, pFilePath, pOpenModeStr, (pVFS != NULL) ? &((ma_default_vfs*)pVFS)->allocationCallbacks : NULL); + if (result != MA_SUCCESS) { + return result; + } + + *pFile = pFileStd; + + return MA_SUCCESS; +} + +static ma_result ma_default_vfs_close__stdio(ma_vfs* pVFS, ma_vfs_file file) +{ + MA_ASSERT(file != NULL); + + (void)pVFS; + + fclose((FILE*)file); + + return MA_SUCCESS; +} + +static ma_result ma_default_vfs_read__stdio(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead) +{ + size_t result; + + MA_ASSERT(file != NULL); + MA_ASSERT(pDst != NULL); + + (void)pVFS; + + result = fread(pDst, 1, sizeInBytes, (FILE*)file); + + if (pBytesRead != NULL) { + *pBytesRead = result; + } + + if (result != sizeInBytes) { + if (result == 0 && feof((FILE*)file)) { + return MA_AT_END; + } else { + return ma_result_from_errno(ferror((FILE*)file)); + } + } + + return MA_SUCCESS; +} + +static ma_result ma_default_vfs_write__stdio(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten) +{ + size_t result; + + MA_ASSERT(file != NULL); + MA_ASSERT(pSrc != NULL); + + (void)pVFS; + + result = fwrite(pSrc, 1, sizeInBytes, (FILE*)file); + + if (pBytesWritten != NULL) { + *pBytesWritten = result; + } + + if (result != sizeInBytes) { + return ma_result_from_errno(ferror((FILE*)file)); + } + + return MA_SUCCESS; +} + +static ma_result ma_default_vfs_seek__stdio(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin) +{ + int result; + int whence; + + MA_ASSERT(file != NULL); + + (void)pVFS; + + if (origin == ma_seek_origin_start) { + whence = SEEK_SET; + } else if (origin == ma_seek_origin_end) { + whence = SEEK_END; + } else { + whence = SEEK_CUR; + } + +#if defined(_WIN32) + #if defined(_MSC_VER) && _MSC_VER > 1200 + result = _fseeki64((FILE*)file, offset, whence); + #else + /* No _fseeki64() so restrict to 31 bits. */ + if (origin > 0x7FFFFFFF) { + return MA_OUT_OF_RANGE; + } + + result = fseek((FILE*)file, (int)offset, whence); + #endif +#else + result = fseek((FILE*)file, (long int)offset, whence); +#endif + if (result != 0) { + return MA_ERROR; + } + + return MA_SUCCESS; +} + +static ma_result ma_default_vfs_tell__stdio(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor) +{ + ma_int64 result; + + MA_ASSERT(file != NULL); + MA_ASSERT(pCursor != NULL); + + (void)pVFS; + +#if defined(_WIN32) + #if defined(_MSC_VER) && _MSC_VER > 1200 + result = _ftelli64((FILE*)file); + #else + result = ftell((FILE*)file); + #endif +#else + result = ftell((FILE*)file); +#endif + + *pCursor = result; + + return MA_SUCCESS; +} + +#if !defined(_MSC_VER) && !((defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 1) || defined(_XOPEN_SOURCE) || defined(_POSIX_SOURCE)) && !defined(MA_BSD) +int fileno(FILE *stream); +#endif + +static ma_result ma_default_vfs_info__stdio(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo) +{ + int fd; + struct stat info; + + MA_ASSERT(file != NULL); + MA_ASSERT(pInfo != NULL); + + (void)pVFS; + +#if defined(_MSC_VER) + fd = _fileno((FILE*)file); +#else + fd = fileno((FILE*)file); +#endif + + if (fstat(fd, &info) != 0) { + return ma_result_from_errno(errno); + } + + pInfo->sizeInBytes = info.st_size; + + return MA_SUCCESS; +} +#endif + + +static ma_result ma_default_vfs_open(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile) +{ + if (pFile == NULL) { + return MA_INVALID_ARGS; + } + + *pFile = NULL; + + if (pFilePath == NULL || openMode == 0) { + return MA_INVALID_ARGS; + } + +#if defined(MA_USE_WIN32_FILEIO) + return ma_default_vfs_open__win32(pVFS, pFilePath, openMode, pFile); +#else + return ma_default_vfs_open__stdio(pVFS, pFilePath, openMode, pFile); +#endif +} + +static ma_result ma_default_vfs_open_w(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile) +{ + if (pFile == NULL) { + return MA_INVALID_ARGS; + } + + *pFile = NULL; + + if (pFilePath == NULL || openMode == 0) { + return MA_INVALID_ARGS; + } + +#if defined(MA_USE_WIN32_FILEIO) + return ma_default_vfs_open_w__win32(pVFS, pFilePath, openMode, pFile); +#else + return ma_default_vfs_open_w__stdio(pVFS, pFilePath, openMode, pFile); +#endif +} + +static ma_result ma_default_vfs_close(ma_vfs* pVFS, ma_vfs_file file) +{ + if (file == NULL) { + return MA_INVALID_ARGS; + } + +#if defined(MA_USE_WIN32_FILEIO) + return ma_default_vfs_close__win32(pVFS, file); +#else + return ma_default_vfs_close__stdio(pVFS, file); +#endif +} + +static ma_result ma_default_vfs_read(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead) +{ + if (pBytesRead != NULL) { + *pBytesRead = 0; + } + + if (file == NULL || pDst == NULL) { + return MA_INVALID_ARGS; + } + +#if defined(MA_USE_WIN32_FILEIO) + return ma_default_vfs_read__win32(pVFS, file, pDst, sizeInBytes, pBytesRead); +#else + return ma_default_vfs_read__stdio(pVFS, file, pDst, sizeInBytes, pBytesRead); +#endif +} + +static ma_result ma_default_vfs_write(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten) +{ + if (pBytesWritten != NULL) { + *pBytesWritten = 0; + } + + if (file == NULL || pSrc == NULL) { + return MA_INVALID_ARGS; + } + +#if defined(MA_USE_WIN32_FILEIO) + return ma_default_vfs_write__win32(pVFS, file, pSrc, sizeInBytes, pBytesWritten); +#else + return ma_default_vfs_write__stdio(pVFS, file, pSrc, sizeInBytes, pBytesWritten); +#endif +} + +static ma_result ma_default_vfs_seek(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin) +{ + if (file == NULL) { + return MA_INVALID_ARGS; + } + +#if defined(MA_USE_WIN32_FILEIO) + return ma_default_vfs_seek__win32(pVFS, file, offset, origin); +#else + return ma_default_vfs_seek__stdio(pVFS, file, offset, origin); +#endif +} + +static ma_result ma_default_vfs_tell(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor) +{ + if (pCursor == NULL) { + return MA_INVALID_ARGS; + } + + *pCursor = 0; + + if (file == NULL) { + return MA_INVALID_ARGS; + } + +#if defined(MA_USE_WIN32_FILEIO) + return ma_default_vfs_tell__win32(pVFS, file, pCursor); +#else + return ma_default_vfs_tell__stdio(pVFS, file, pCursor); +#endif +} + +static ma_result ma_default_vfs_info(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo) +{ + if (pInfo == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pInfo); + + if (file == NULL) { + return MA_INVALID_ARGS; + } + +#if defined(MA_USE_WIN32_FILEIO) + return ma_default_vfs_info__win32(pVFS, file, pInfo); +#else + return ma_default_vfs_info__stdio(pVFS, file, pInfo); +#endif +} + + +MA_API ma_result ma_default_vfs_init(ma_default_vfs* pVFS, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pVFS == NULL) { + return MA_INVALID_ARGS; + } + + pVFS->cb.onOpen = ma_default_vfs_open; + pVFS->cb.onOpenW = ma_default_vfs_open_w; + pVFS->cb.onClose = ma_default_vfs_close; + pVFS->cb.onRead = ma_default_vfs_read; + pVFS->cb.onWrite = ma_default_vfs_write; + pVFS->cb.onSeek = ma_default_vfs_seek; + pVFS->cb.onTell = ma_default_vfs_tell; + pVFS->cb.onInfo = ma_default_vfs_info; + ma_allocation_callbacks_init_copy(&pVFS->allocationCallbacks, pAllocationCallbacks); + + return MA_SUCCESS; +} + + +MA_API ma_result ma_vfs_or_default_open(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile) +{ + if (pVFS != NULL) { + return ma_vfs_open(pVFS, pFilePath, openMode, pFile); + } else { + return ma_default_vfs_open(pVFS, pFilePath, openMode, pFile); + } +} + +MA_API ma_result ma_vfs_or_default_open_w(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile) +{ + if (pVFS != NULL) { + return ma_vfs_open_w(pVFS, pFilePath, openMode, pFile); + } else { + return ma_default_vfs_open_w(pVFS, pFilePath, openMode, pFile); + } +} + +MA_API ma_result ma_vfs_or_default_close(ma_vfs* pVFS, ma_vfs_file file) +{ + if (pVFS != NULL) { + return ma_vfs_close(pVFS, file); + } else { + return ma_default_vfs_close(pVFS, file); + } +} + +MA_API ma_result ma_vfs_or_default_read(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead) +{ + if (pVFS != NULL) { + return ma_vfs_read(pVFS, file, pDst, sizeInBytes, pBytesRead); + } else { + return ma_default_vfs_read(pVFS, file, pDst, sizeInBytes, pBytesRead); + } +} + +MA_API ma_result ma_vfs_or_default_write(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten) +{ + if (pVFS != NULL) { + return ma_vfs_write(pVFS, file, pSrc, sizeInBytes, pBytesWritten); + } else { + return ma_default_vfs_write(pVFS, file, pSrc, sizeInBytes, pBytesWritten); + } +} + +MA_API ma_result ma_vfs_or_default_seek(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin) +{ + if (pVFS != NULL) { + return ma_vfs_seek(pVFS, file, offset, origin); + } else { + return ma_default_vfs_seek(pVFS, file, offset, origin); + } +} + +MA_API ma_result ma_vfs_or_default_tell(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor) +{ + if (pVFS != NULL) { + return ma_vfs_tell(pVFS, file, pCursor); + } else { + return ma_default_vfs_tell(pVFS, file, pCursor); + } +} + +MA_API ma_result ma_vfs_or_default_info(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo) +{ + if (pVFS != NULL) { + return ma_vfs_info(pVFS, file, pInfo); + } else { + return ma_default_vfs_info(pVFS, file, pInfo); + } +} + + + +static ma_result ma_vfs_open_and_read_file_ex(ma_vfs* pVFS, const char* pFilePath, const wchar_t* pFilePathW, void** ppData, size_t* pSize, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_result result; + ma_vfs_file file; + ma_file_info info; + void* pData; + size_t bytesRead; + + if (ppData != NULL) { + *ppData = NULL; + } + if (pSize != NULL) { + *pSize = 0; + } + + if (ppData == NULL) { + return MA_INVALID_ARGS; + } + + if (pFilePath != NULL) { + result = ma_vfs_or_default_open(pVFS, pFilePath, MA_OPEN_MODE_READ, &file); + } else { + result = ma_vfs_or_default_open_w(pVFS, pFilePathW, MA_OPEN_MODE_READ, &file); + } + if (result != MA_SUCCESS) { + return result; + } + + result = ma_vfs_or_default_info(pVFS, file, &info); + if (result != MA_SUCCESS) { + ma_vfs_or_default_close(pVFS, file); + return result; + } + + if (info.sizeInBytes > MA_SIZE_MAX) { + ma_vfs_or_default_close(pVFS, file); + return MA_TOO_BIG; + } + + pData = ma_malloc((size_t)info.sizeInBytes, pAllocationCallbacks); /* Safe cast. */ + if (pData == NULL) { + ma_vfs_or_default_close(pVFS, file); + return result; + } + + result = ma_vfs_or_default_read(pVFS, file, pData, (size_t)info.sizeInBytes, &bytesRead); /* Safe cast. */ + ma_vfs_or_default_close(pVFS, file); + + if (result != MA_SUCCESS) { + ma_free(pData, pAllocationCallbacks); + return result; + } + + if (pSize != NULL) { + *pSize = bytesRead; + } + + MA_ASSERT(ppData != NULL); + *ppData = pData; + + return MA_SUCCESS; +} + +MA_API ma_result ma_vfs_open_and_read_file(ma_vfs* pVFS, const char* pFilePath, void** ppData, size_t* pSize, const ma_allocation_callbacks* pAllocationCallbacks) +{ + return ma_vfs_open_and_read_file_ex(pVFS, pFilePath, NULL, ppData, pSize, pAllocationCallbacks); +} + +MA_API ma_result ma_vfs_open_and_read_file_w(ma_vfs* pVFS, const wchar_t* pFilePath, void** ppData, size_t* pSize, const ma_allocation_callbacks* pAllocationCallbacks) +{ + return ma_vfs_open_and_read_file_ex(pVFS, NULL, pFilePath, ppData, pSize, pAllocationCallbacks); +} + + + +/************************************************************************************************************************************************************** + +Decoding and Encoding Headers. These are auto-generated from a tool. + +**************************************************************************************************************************************************************/ +#if !defined(MA_NO_WAV) && (!defined(MA_NO_DECODING) || !defined(MA_NO_ENCODING)) +/* dr_wav_h begin */ +#ifndef ma_dr_wav_h +#define ma_dr_wav_h +#ifdef __cplusplus +extern "C" { +#endif +#define MA_DR_WAV_STRINGIFY(x) #x +#define MA_DR_WAV_XSTRINGIFY(x) MA_DR_WAV_STRINGIFY(x) +#define MA_DR_WAV_VERSION_MAJOR 0 +#define MA_DR_WAV_VERSION_MINOR 13 +#define MA_DR_WAV_VERSION_REVISION 13 +#define MA_DR_WAV_VERSION_STRING MA_DR_WAV_XSTRINGIFY(MA_DR_WAV_VERSION_MAJOR) "." MA_DR_WAV_XSTRINGIFY(MA_DR_WAV_VERSION_MINOR) "." MA_DR_WAV_XSTRINGIFY(MA_DR_WAV_VERSION_REVISION) +#include +#define MA_DR_WAVE_FORMAT_PCM 0x1 +#define MA_DR_WAVE_FORMAT_ADPCM 0x2 +#define MA_DR_WAVE_FORMAT_IEEE_FLOAT 0x3 +#define MA_DR_WAVE_FORMAT_ALAW 0x6 +#define MA_DR_WAVE_FORMAT_MULAW 0x7 +#define MA_DR_WAVE_FORMAT_DVI_ADPCM 0x11 +#define MA_DR_WAVE_FORMAT_EXTENSIBLE 0xFFFE +#define MA_DR_WAV_SEQUENTIAL 0x00000001 +#define MA_DR_WAV_WITH_METADATA 0x00000002 +MA_API void ma_dr_wav_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision); +MA_API const char* ma_dr_wav_version_string(void); +typedef enum +{ + ma_dr_wav_seek_origin_start, + ma_dr_wav_seek_origin_current +} ma_dr_wav_seek_origin; +typedef enum +{ + ma_dr_wav_container_riff, + ma_dr_wav_container_rifx, + ma_dr_wav_container_w64, + ma_dr_wav_container_rf64, + ma_dr_wav_container_aiff +} ma_dr_wav_container; +typedef struct +{ + union + { + ma_uint8 fourcc[4]; + ma_uint8 guid[16]; + } id; + ma_uint64 sizeInBytes; + unsigned int paddingSize; +} ma_dr_wav_chunk_header; +typedef struct +{ + ma_uint16 formatTag; + ma_uint16 channels; + ma_uint32 sampleRate; + ma_uint32 avgBytesPerSec; + ma_uint16 blockAlign; + ma_uint16 bitsPerSample; + ma_uint16 extendedSize; + ma_uint16 validBitsPerSample; + ma_uint32 channelMask; + ma_uint8 subFormat[16]; +} ma_dr_wav_fmt; +MA_API ma_uint16 ma_dr_wav_fmt_get_format(const ma_dr_wav_fmt* pFMT); +typedef size_t (* ma_dr_wav_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead); +typedef size_t (* ma_dr_wav_write_proc)(void* pUserData, const void* pData, size_t bytesToWrite); +typedef ma_bool32 (* ma_dr_wav_seek_proc)(void* pUserData, int offset, ma_dr_wav_seek_origin origin); +typedef ma_uint64 (* ma_dr_wav_chunk_proc)(void* pChunkUserData, ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pReadSeekUserData, const ma_dr_wav_chunk_header* pChunkHeader, ma_dr_wav_container container, const ma_dr_wav_fmt* pFMT); +typedef struct +{ + const ma_uint8* data; + size_t dataSize; + size_t currentReadPos; +} ma_dr_wav__memory_stream; +typedef struct +{ + void** ppData; + size_t* pDataSize; + size_t dataSize; + size_t dataCapacity; + size_t currentWritePos; +} ma_dr_wav__memory_stream_write; +typedef struct +{ + ma_dr_wav_container container; + ma_uint32 format; + ma_uint32 channels; + ma_uint32 sampleRate; + ma_uint32 bitsPerSample; +} ma_dr_wav_data_format; +typedef enum +{ + ma_dr_wav_metadata_type_none = 0, + ma_dr_wav_metadata_type_unknown = 1 << 0, + ma_dr_wav_metadata_type_smpl = 1 << 1, + ma_dr_wav_metadata_type_inst = 1 << 2, + ma_dr_wav_metadata_type_cue = 1 << 3, + ma_dr_wav_metadata_type_acid = 1 << 4, + ma_dr_wav_metadata_type_bext = 1 << 5, + ma_dr_wav_metadata_type_list_label = 1 << 6, + ma_dr_wav_metadata_type_list_note = 1 << 7, + ma_dr_wav_metadata_type_list_labelled_cue_region = 1 << 8, + ma_dr_wav_metadata_type_list_info_software = 1 << 9, + ma_dr_wav_metadata_type_list_info_copyright = 1 << 10, + ma_dr_wav_metadata_type_list_info_title = 1 << 11, + ma_dr_wav_metadata_type_list_info_artist = 1 << 12, + ma_dr_wav_metadata_type_list_info_comment = 1 << 13, + ma_dr_wav_metadata_type_list_info_date = 1 << 14, + ma_dr_wav_metadata_type_list_info_genre = 1 << 15, + ma_dr_wav_metadata_type_list_info_album = 1 << 16, + ma_dr_wav_metadata_type_list_info_tracknumber = 1 << 17, + ma_dr_wav_metadata_type_list_all_info_strings = ma_dr_wav_metadata_type_list_info_software + | ma_dr_wav_metadata_type_list_info_copyright + | ma_dr_wav_metadata_type_list_info_title + | ma_dr_wav_metadata_type_list_info_artist + | ma_dr_wav_metadata_type_list_info_comment + | ma_dr_wav_metadata_type_list_info_date + | ma_dr_wav_metadata_type_list_info_genre + | ma_dr_wav_metadata_type_list_info_album + | ma_dr_wav_metadata_type_list_info_tracknumber, + ma_dr_wav_metadata_type_list_all_adtl = ma_dr_wav_metadata_type_list_label + | ma_dr_wav_metadata_type_list_note + | ma_dr_wav_metadata_type_list_labelled_cue_region, + ma_dr_wav_metadata_type_all = -2, + ma_dr_wav_metadata_type_all_including_unknown = -1 +} ma_dr_wav_metadata_type; +typedef enum +{ + ma_dr_wav_smpl_loop_type_forward = 0, + ma_dr_wav_smpl_loop_type_pingpong = 1, + ma_dr_wav_smpl_loop_type_backward = 2 +} ma_dr_wav_smpl_loop_type; +typedef struct +{ + ma_uint32 cuePointId; + ma_uint32 type; + ma_uint32 firstSampleByteOffset; + ma_uint32 lastSampleByteOffset; + ma_uint32 sampleFraction; + ma_uint32 playCount; +} ma_dr_wav_smpl_loop; +typedef struct +{ + ma_uint32 manufacturerId; + ma_uint32 productId; + ma_uint32 samplePeriodNanoseconds; + ma_uint32 midiUnityNote; + ma_uint32 midiPitchFraction; + ma_uint32 smpteFormat; + ma_uint32 smpteOffset; + ma_uint32 sampleLoopCount; + ma_uint32 samplerSpecificDataSizeInBytes; + ma_dr_wav_smpl_loop* pLoops; + ma_uint8* pSamplerSpecificData; +} ma_dr_wav_smpl; +typedef struct +{ + ma_int8 midiUnityNote; + ma_int8 fineTuneCents; + ma_int8 gainDecibels; + ma_int8 lowNote; + ma_int8 highNote; + ma_int8 lowVelocity; + ma_int8 highVelocity; +} ma_dr_wav_inst; +typedef struct +{ + ma_uint32 id; + ma_uint32 playOrderPosition; + ma_uint8 dataChunkId[4]; + ma_uint32 chunkStart; + ma_uint32 blockStart; + ma_uint32 sampleByteOffset; +} ma_dr_wav_cue_point; +typedef struct +{ + ma_uint32 cuePointCount; + ma_dr_wav_cue_point *pCuePoints; +} ma_dr_wav_cue; +typedef enum +{ + ma_dr_wav_acid_flag_one_shot = 1, + ma_dr_wav_acid_flag_root_note_set = 2, + ma_dr_wav_acid_flag_stretch = 4, + ma_dr_wav_acid_flag_disk_based = 8, + ma_dr_wav_acid_flag_acidizer = 16 +} ma_dr_wav_acid_flag; +typedef struct +{ + ma_uint32 flags; + ma_uint16 midiUnityNote; + ma_uint16 reserved1; + float reserved2; + ma_uint32 numBeats; + ma_uint16 meterDenominator; + ma_uint16 meterNumerator; + float tempo; +} ma_dr_wav_acid; +typedef struct +{ + ma_uint32 cuePointId; + ma_uint32 stringLength; + char* pString; +} ma_dr_wav_list_label_or_note; +typedef struct +{ + char* pDescription; + char* pOriginatorName; + char* pOriginatorReference; + char pOriginationDate[10]; + char pOriginationTime[8]; + ma_uint64 timeReference; + ma_uint16 version; + char* pCodingHistory; + ma_uint32 codingHistorySize; + ma_uint8* pUMID; + ma_uint16 loudnessValue; + ma_uint16 loudnessRange; + ma_uint16 maxTruePeakLevel; + ma_uint16 maxMomentaryLoudness; + ma_uint16 maxShortTermLoudness; +} ma_dr_wav_bext; +typedef struct +{ + ma_uint32 stringLength; + char* pString; +} ma_dr_wav_list_info_text; +typedef struct +{ + ma_uint32 cuePointId; + ma_uint32 sampleLength; + ma_uint8 purposeId[4]; + ma_uint16 country; + ma_uint16 language; + ma_uint16 dialect; + ma_uint16 codePage; + ma_uint32 stringLength; + char* pString; +} ma_dr_wav_list_labelled_cue_region; +typedef enum +{ + ma_dr_wav_metadata_location_invalid, + ma_dr_wav_metadata_location_top_level, + ma_dr_wav_metadata_location_inside_info_list, + ma_dr_wav_metadata_location_inside_adtl_list +} ma_dr_wav_metadata_location; +typedef struct +{ + ma_uint8 id[4]; + ma_dr_wav_metadata_location chunkLocation; + ma_uint32 dataSizeInBytes; + ma_uint8* pData; +} ma_dr_wav_unknown_metadata; +typedef struct +{ + ma_dr_wav_metadata_type type; + union + { + ma_dr_wav_cue cue; + ma_dr_wav_smpl smpl; + ma_dr_wav_acid acid; + ma_dr_wav_inst inst; + ma_dr_wav_bext bext; + ma_dr_wav_list_label_or_note labelOrNote; + ma_dr_wav_list_labelled_cue_region labelledCueRegion; + ma_dr_wav_list_info_text infoText; + ma_dr_wav_unknown_metadata unknown; + } data; +} ma_dr_wav_metadata; +typedef struct +{ + ma_dr_wav_read_proc onRead; + ma_dr_wav_write_proc onWrite; + ma_dr_wav_seek_proc onSeek; + void* pUserData; + ma_allocation_callbacks allocationCallbacks; + ma_dr_wav_container container; + ma_dr_wav_fmt fmt; + ma_uint32 sampleRate; + ma_uint16 channels; + ma_uint16 bitsPerSample; + ma_uint16 translatedFormatTag; + ma_uint64 totalPCMFrameCount; + ma_uint64 dataChunkDataSize; + ma_uint64 dataChunkDataPos; + ma_uint64 bytesRemaining; + ma_uint64 readCursorInPCMFrames; + ma_uint64 dataChunkDataSizeTargetWrite; + ma_bool32 isSequentialWrite; + ma_dr_wav_metadata* pMetadata; + ma_uint32 metadataCount; + ma_dr_wav__memory_stream memoryStream; + ma_dr_wav__memory_stream_write memoryStreamWrite; + struct + { + ma_uint32 bytesRemainingInBlock; + ma_uint16 predictor[2]; + ma_int32 delta[2]; + ma_int32 cachedFrames[4]; + ma_uint32 cachedFrameCount; + ma_int32 prevFrames[2][2]; + } msadpcm; + struct + { + ma_uint32 bytesRemainingInBlock; + ma_int32 predictor[2]; + ma_int32 stepIndex[2]; + ma_int32 cachedFrames[16]; + ma_uint32 cachedFrameCount; + } ima; + struct + { + ma_bool8 isLE; + ma_bool8 isUnsigned; + } aiff; +} ma_dr_wav; +MA_API ma_bool32 ma_dr_wav_init(ma_dr_wav* pWav, ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_ex(ma_dr_wav* pWav, ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, ma_dr_wav_chunk_proc onChunk, void* pReadSeekUserData, void* pChunkUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_with_metadata(ma_dr_wav* pWav, ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_write(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_dr_wav_write_proc onWrite, ma_dr_wav_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_write_sequential(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, ma_dr_wav_write_proc onWrite, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_write_sequential_pcm_frames(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_uint64 totalPCMFrameCount, ma_dr_wav_write_proc onWrite, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_write_with_metadata(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_dr_wav_write_proc onWrite, ma_dr_wav_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks, ma_dr_wav_metadata* pMetadata, ma_uint32 metadataCount); +MA_API ma_uint64 ma_dr_wav_target_write_size_bytes(const ma_dr_wav_data_format* pFormat, ma_uint64 totalFrameCount, ma_dr_wav_metadata* pMetadata, ma_uint32 metadataCount); +MA_API ma_dr_wav_metadata* ma_dr_wav_take_ownership_of_metadata(ma_dr_wav* pWav); +MA_API ma_result ma_dr_wav_uninit(ma_dr_wav* pWav); +MA_API size_t ma_dr_wav_read_raw(ma_dr_wav* pWav, size_t bytesToRead, void* pBufferOut); +MA_API ma_uint64 ma_dr_wav_read_pcm_frames(ma_dr_wav* pWav, ma_uint64 framesToRead, void* pBufferOut); +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_le(ma_dr_wav* pWav, ma_uint64 framesToRead, void* pBufferOut); +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_be(ma_dr_wav* pWav, ma_uint64 framesToRead, void* pBufferOut); +MA_API ma_bool32 ma_dr_wav_seek_to_pcm_frame(ma_dr_wav* pWav, ma_uint64 targetFrameIndex); +MA_API ma_result ma_dr_wav_get_cursor_in_pcm_frames(ma_dr_wav* pWav, ma_uint64* pCursor); +MA_API ma_result ma_dr_wav_get_length_in_pcm_frames(ma_dr_wav* pWav, ma_uint64* pLength); +MA_API size_t ma_dr_wav_write_raw(ma_dr_wav* pWav, size_t bytesToWrite, const void* pData); +MA_API ma_uint64 ma_dr_wav_write_pcm_frames(ma_dr_wav* pWav, ma_uint64 framesToWrite, const void* pData); +MA_API ma_uint64 ma_dr_wav_write_pcm_frames_le(ma_dr_wav* pWav, ma_uint64 framesToWrite, const void* pData); +MA_API ma_uint64 ma_dr_wav_write_pcm_frames_be(ma_dr_wav* pWav, ma_uint64 framesToWrite, const void* pData); +#ifndef MA_DR_WAV_NO_CONVERSION_API +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s16(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut); +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s16le(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut); +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s16be(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut); +MA_API void ma_dr_wav_u8_to_s16(ma_int16* pOut, const ma_uint8* pIn, size_t sampleCount); +MA_API void ma_dr_wav_s24_to_s16(ma_int16* pOut, const ma_uint8* pIn, size_t sampleCount); +MA_API void ma_dr_wav_s32_to_s16(ma_int16* pOut, const ma_int32* pIn, size_t sampleCount); +MA_API void ma_dr_wav_f32_to_s16(ma_int16* pOut, const float* pIn, size_t sampleCount); +MA_API void ma_dr_wav_f64_to_s16(ma_int16* pOut, const double* pIn, size_t sampleCount); +MA_API void ma_dr_wav_alaw_to_s16(ma_int16* pOut, const ma_uint8* pIn, size_t sampleCount); +MA_API void ma_dr_wav_mulaw_to_s16(ma_int16* pOut, const ma_uint8* pIn, size_t sampleCount); +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_f32(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut); +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_f32le(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut); +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_f32be(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut); +MA_API void ma_dr_wav_u8_to_f32(float* pOut, const ma_uint8* pIn, size_t sampleCount); +MA_API void ma_dr_wav_s16_to_f32(float* pOut, const ma_int16* pIn, size_t sampleCount); +MA_API void ma_dr_wav_s24_to_f32(float* pOut, const ma_uint8* pIn, size_t sampleCount); +MA_API void ma_dr_wav_s32_to_f32(float* pOut, const ma_int32* pIn, size_t sampleCount); +MA_API void ma_dr_wav_f64_to_f32(float* pOut, const double* pIn, size_t sampleCount); +MA_API void ma_dr_wav_alaw_to_f32(float* pOut, const ma_uint8* pIn, size_t sampleCount); +MA_API void ma_dr_wav_mulaw_to_f32(float* pOut, const ma_uint8* pIn, size_t sampleCount); +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s32(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut); +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s32le(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut); +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s32be(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut); +MA_API void ma_dr_wav_u8_to_s32(ma_int32* pOut, const ma_uint8* pIn, size_t sampleCount); +MA_API void ma_dr_wav_s16_to_s32(ma_int32* pOut, const ma_int16* pIn, size_t sampleCount); +MA_API void ma_dr_wav_s24_to_s32(ma_int32* pOut, const ma_uint8* pIn, size_t sampleCount); +MA_API void ma_dr_wav_f32_to_s32(ma_int32* pOut, const float* pIn, size_t sampleCount); +MA_API void ma_dr_wav_f64_to_s32(ma_int32* pOut, const double* pIn, size_t sampleCount); +MA_API void ma_dr_wav_alaw_to_s32(ma_int32* pOut, const ma_uint8* pIn, size_t sampleCount); +MA_API void ma_dr_wav_mulaw_to_s32(ma_int32* pOut, const ma_uint8* pIn, size_t sampleCount); +#endif +#ifndef MA_DR_WAV_NO_STDIO +MA_API ma_bool32 ma_dr_wav_init_file(ma_dr_wav* pWav, const char* filename, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_file_ex(ma_dr_wav* pWav, const char* filename, ma_dr_wav_chunk_proc onChunk, void* pChunkUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_file_w(ma_dr_wav* pWav, const wchar_t* filename, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_file_ex_w(ma_dr_wav* pWav, const wchar_t* filename, ma_dr_wav_chunk_proc onChunk, void* pChunkUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_file_with_metadata(ma_dr_wav* pWav, const char* filename, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_file_with_metadata_w(ma_dr_wav* pWav, const wchar_t* filename, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_file_write(ma_dr_wav* pWav, const char* filename, const ma_dr_wav_data_format* pFormat, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_file_write_sequential(ma_dr_wav* pWav, const char* filename, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_file_write_sequential_pcm_frames(ma_dr_wav* pWav, const char* filename, const ma_dr_wav_data_format* pFormat, ma_uint64 totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_file_write_w(ma_dr_wav* pWav, const wchar_t* filename, const ma_dr_wav_data_format* pFormat, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_file_write_sequential_w(ma_dr_wav* pWav, const wchar_t* filename, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_file_write_sequential_pcm_frames_w(ma_dr_wav* pWav, const wchar_t* filename, const ma_dr_wav_data_format* pFormat, ma_uint64 totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks); +#endif +MA_API ma_bool32 ma_dr_wav_init_memory(ma_dr_wav* pWav, const void* data, size_t dataSize, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_memory_ex(ma_dr_wav* pWav, const void* data, size_t dataSize, ma_dr_wav_chunk_proc onChunk, void* pChunkUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_memory_with_metadata(ma_dr_wav* pWav, const void* data, size_t dataSize, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_memory_write(ma_dr_wav* pWav, void** ppData, size_t* pDataSize, const ma_dr_wav_data_format* pFormat, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_memory_write_sequential(ma_dr_wav* pWav, void** ppData, size_t* pDataSize, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_wav_init_memory_write_sequential_pcm_frames(ma_dr_wav* pWav, void** ppData, size_t* pDataSize, const ma_dr_wav_data_format* pFormat, ma_uint64 totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks); +#ifndef MA_DR_WAV_NO_CONVERSION_API +MA_API ma_int16* ma_dr_wav_open_and_read_pcm_frames_s16(ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API float* ma_dr_wav_open_and_read_pcm_frames_f32(ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_int32* ma_dr_wav_open_and_read_pcm_frames_s32(ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks); +#ifndef MA_DR_WAV_NO_STDIO +MA_API ma_int16* ma_dr_wav_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API float* ma_dr_wav_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_int32* ma_dr_wav_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_int16* ma_dr_wav_open_file_and_read_pcm_frames_s16_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API float* ma_dr_wav_open_file_and_read_pcm_frames_f32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_int32* ma_dr_wav_open_file_and_read_pcm_frames_s32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks); +#endif +MA_API ma_int16* ma_dr_wav_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API float* ma_dr_wav_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_int32* ma_dr_wav_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks); +#endif +MA_API void ma_dr_wav_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_uint16 ma_dr_wav_bytes_to_u16(const ma_uint8* data); +MA_API ma_int16 ma_dr_wav_bytes_to_s16(const ma_uint8* data); +MA_API ma_uint32 ma_dr_wav_bytes_to_u32(const ma_uint8* data); +MA_API ma_int32 ma_dr_wav_bytes_to_s32(const ma_uint8* data); +MA_API ma_uint64 ma_dr_wav_bytes_to_u64(const ma_uint8* data); +MA_API ma_int64 ma_dr_wav_bytes_to_s64(const ma_uint8* data); +MA_API float ma_dr_wav_bytes_to_f32(const ma_uint8* data); +MA_API ma_bool32 ma_dr_wav_guid_equal(const ma_uint8 a[16], const ma_uint8 b[16]); +MA_API ma_bool32 ma_dr_wav_fourcc_equal(const ma_uint8* a, const char* b); +#ifdef __cplusplus +} +#endif +#endif +/* dr_wav_h end */ +#endif /* MA_NO_WAV */ + +#if !defined(MA_NO_FLAC) && !defined(MA_NO_DECODING) +/* dr_flac_h begin */ +#ifndef ma_dr_flac_h +#define ma_dr_flac_h +#ifdef __cplusplus +extern "C" { +#endif +#define MA_DR_FLAC_STRINGIFY(x) #x +#define MA_DR_FLAC_XSTRINGIFY(x) MA_DR_FLAC_STRINGIFY(x) +#define MA_DR_FLAC_VERSION_MAJOR 0 +#define MA_DR_FLAC_VERSION_MINOR 12 +#define MA_DR_FLAC_VERSION_REVISION 42 +#define MA_DR_FLAC_VERSION_STRING MA_DR_FLAC_XSTRINGIFY(MA_DR_FLAC_VERSION_MAJOR) "." MA_DR_FLAC_XSTRINGIFY(MA_DR_FLAC_VERSION_MINOR) "." MA_DR_FLAC_XSTRINGIFY(MA_DR_FLAC_VERSION_REVISION) +#include +#if defined(_MSC_VER) && _MSC_VER >= 1700 + #define MA_DR_FLAC_DEPRECATED __declspec(deprecated) +#elif (defined(__GNUC__) && __GNUC__ >= 4) + #define MA_DR_FLAC_DEPRECATED __attribute__((deprecated)) +#elif defined(__has_feature) + #if __has_feature(attribute_deprecated) + #define MA_DR_FLAC_DEPRECATED __attribute__((deprecated)) + #else + #define MA_DR_FLAC_DEPRECATED + #endif +#else + #define MA_DR_FLAC_DEPRECATED +#endif +MA_API void ma_dr_flac_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision); +MA_API const char* ma_dr_flac_version_string(void); +#ifndef MA_DR_FLAC_BUFFER_SIZE +#define MA_DR_FLAC_BUFFER_SIZE 4096 +#endif +#ifdef MA_64BIT +typedef ma_uint64 ma_dr_flac_cache_t; +#else +typedef ma_uint32 ma_dr_flac_cache_t; +#endif +#define MA_DR_FLAC_METADATA_BLOCK_TYPE_STREAMINFO 0 +#define MA_DR_FLAC_METADATA_BLOCK_TYPE_PADDING 1 +#define MA_DR_FLAC_METADATA_BLOCK_TYPE_APPLICATION 2 +#define MA_DR_FLAC_METADATA_BLOCK_TYPE_SEEKTABLE 3 +#define MA_DR_FLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT 4 +#define MA_DR_FLAC_METADATA_BLOCK_TYPE_CUESHEET 5 +#define MA_DR_FLAC_METADATA_BLOCK_TYPE_PICTURE 6 +#define MA_DR_FLAC_METADATA_BLOCK_TYPE_INVALID 127 +#define MA_DR_FLAC_PICTURE_TYPE_OTHER 0 +#define MA_DR_FLAC_PICTURE_TYPE_FILE_ICON 1 +#define MA_DR_FLAC_PICTURE_TYPE_OTHER_FILE_ICON 2 +#define MA_DR_FLAC_PICTURE_TYPE_COVER_FRONT 3 +#define MA_DR_FLAC_PICTURE_TYPE_COVER_BACK 4 +#define MA_DR_FLAC_PICTURE_TYPE_LEAFLET_PAGE 5 +#define MA_DR_FLAC_PICTURE_TYPE_MEDIA 6 +#define MA_DR_FLAC_PICTURE_TYPE_LEAD_ARTIST 7 +#define MA_DR_FLAC_PICTURE_TYPE_ARTIST 8 +#define MA_DR_FLAC_PICTURE_TYPE_CONDUCTOR 9 +#define MA_DR_FLAC_PICTURE_TYPE_BAND 10 +#define MA_DR_FLAC_PICTURE_TYPE_COMPOSER 11 +#define MA_DR_FLAC_PICTURE_TYPE_LYRICIST 12 +#define MA_DR_FLAC_PICTURE_TYPE_RECORDING_LOCATION 13 +#define MA_DR_FLAC_PICTURE_TYPE_DURING_RECORDING 14 +#define MA_DR_FLAC_PICTURE_TYPE_DURING_PERFORMANCE 15 +#define MA_DR_FLAC_PICTURE_TYPE_SCREEN_CAPTURE 16 +#define MA_DR_FLAC_PICTURE_TYPE_BRIGHT_COLORED_FISH 17 +#define MA_DR_FLAC_PICTURE_TYPE_ILLUSTRATION 18 +#define MA_DR_FLAC_PICTURE_TYPE_BAND_LOGOTYPE 19 +#define MA_DR_FLAC_PICTURE_TYPE_PUBLISHER_LOGOTYPE 20 +typedef enum +{ + ma_dr_flac_container_native, + ma_dr_flac_container_ogg, + ma_dr_flac_container_unknown +} ma_dr_flac_container; +typedef enum +{ + ma_dr_flac_seek_origin_start, + ma_dr_flac_seek_origin_current +} ma_dr_flac_seek_origin; +typedef struct +{ + ma_uint64 firstPCMFrame; + ma_uint64 flacFrameOffset; + ma_uint16 pcmFrameCount; +} ma_dr_flac_seekpoint; +typedef struct +{ + ma_uint16 minBlockSizeInPCMFrames; + ma_uint16 maxBlockSizeInPCMFrames; + ma_uint32 minFrameSizeInPCMFrames; + ma_uint32 maxFrameSizeInPCMFrames; + ma_uint32 sampleRate; + ma_uint8 channels; + ma_uint8 bitsPerSample; + ma_uint64 totalPCMFrameCount; + ma_uint8 md5[16]; +} ma_dr_flac_streaminfo; +typedef struct +{ + ma_uint32 type; + const void* pRawData; + ma_uint32 rawDataSize; + union + { + ma_dr_flac_streaminfo streaminfo; + struct + { + int unused; + } padding; + struct + { + ma_uint32 id; + const void* pData; + ma_uint32 dataSize; + } application; + struct + { + ma_uint32 seekpointCount; + const ma_dr_flac_seekpoint* pSeekpoints; + } seektable; + struct + { + ma_uint32 vendorLength; + const char* vendor; + ma_uint32 commentCount; + const void* pComments; + } vorbis_comment; + struct + { + char catalog[128]; + ma_uint64 leadInSampleCount; + ma_bool32 isCD; + ma_uint8 trackCount; + const void* pTrackData; + } cuesheet; + struct + { + ma_uint32 type; + ma_uint32 mimeLength; + const char* mime; + ma_uint32 descriptionLength; + const char* description; + ma_uint32 width; + ma_uint32 height; + ma_uint32 colorDepth; + ma_uint32 indexColorCount; + ma_uint32 pictureDataSize; + const ma_uint8* pPictureData; + } picture; + } data; +} ma_dr_flac_metadata; +typedef size_t (* ma_dr_flac_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead); +typedef ma_bool32 (* ma_dr_flac_seek_proc)(void* pUserData, int offset, ma_dr_flac_seek_origin origin); +typedef void (* ma_dr_flac_meta_proc)(void* pUserData, ma_dr_flac_metadata* pMetadata); +typedef struct +{ + const ma_uint8* data; + size_t dataSize; + size_t currentReadPos; +} ma_dr_flac__memory_stream; +typedef struct +{ + ma_dr_flac_read_proc onRead; + ma_dr_flac_seek_proc onSeek; + void* pUserData; + size_t unalignedByteCount; + ma_dr_flac_cache_t unalignedCache; + ma_uint32 nextL2Line; + ma_uint32 consumedBits; + ma_dr_flac_cache_t cacheL2[MA_DR_FLAC_BUFFER_SIZE/sizeof(ma_dr_flac_cache_t)]; + ma_dr_flac_cache_t cache; + ma_uint16 crc16; + ma_dr_flac_cache_t crc16Cache; + ma_uint32 crc16CacheIgnoredBytes; +} ma_dr_flac_bs; +typedef struct +{ + ma_uint8 subframeType; + ma_uint8 wastedBitsPerSample; + ma_uint8 lpcOrder; + ma_int32* pSamplesS32; +} ma_dr_flac_subframe; +typedef struct +{ + ma_uint64 pcmFrameNumber; + ma_uint32 flacFrameNumber; + ma_uint32 sampleRate; + ma_uint16 blockSizeInPCMFrames; + ma_uint8 channelAssignment; + ma_uint8 bitsPerSample; + ma_uint8 crc8; +} ma_dr_flac_frame_header; +typedef struct +{ + ma_dr_flac_frame_header header; + ma_uint32 pcmFramesRemaining; + ma_dr_flac_subframe subframes[8]; +} ma_dr_flac_frame; +typedef struct +{ + ma_dr_flac_meta_proc onMeta; + void* pUserDataMD; + ma_allocation_callbacks allocationCallbacks; + ma_uint32 sampleRate; + ma_uint8 channels; + ma_uint8 bitsPerSample; + ma_uint16 maxBlockSizeInPCMFrames; + ma_uint64 totalPCMFrameCount; + ma_dr_flac_container container; + ma_uint32 seekpointCount; + ma_dr_flac_frame currentFLACFrame; + ma_uint64 currentPCMFrame; + ma_uint64 firstFLACFramePosInBytes; + ma_dr_flac__memory_stream memoryStream; + ma_int32* pDecodedSamples; + ma_dr_flac_seekpoint* pSeekpoints; + void* _oggbs; + ma_bool32 _noSeekTableSeek : 1; + ma_bool32 _noBinarySearchSeek : 1; + ma_bool32 _noBruteForceSeek : 1; + ma_dr_flac_bs bs; + ma_uint8 pExtraData[1]; +} ma_dr_flac; +MA_API ma_dr_flac* ma_dr_flac_open(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_dr_flac* ma_dr_flac_open_relaxed(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_container container, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_dr_flac* ma_dr_flac_open_with_metadata(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_meta_proc onMeta, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_dr_flac* ma_dr_flac_open_with_metadata_relaxed(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_meta_proc onMeta, ma_dr_flac_container container, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API void ma_dr_flac_close(ma_dr_flac* pFlac); +MA_API ma_uint64 ma_dr_flac_read_pcm_frames_s32(ma_dr_flac* pFlac, ma_uint64 framesToRead, ma_int32* pBufferOut); +MA_API ma_uint64 ma_dr_flac_read_pcm_frames_s16(ma_dr_flac* pFlac, ma_uint64 framesToRead, ma_int16* pBufferOut); +MA_API ma_uint64 ma_dr_flac_read_pcm_frames_f32(ma_dr_flac* pFlac, ma_uint64 framesToRead, float* pBufferOut); +MA_API ma_bool32 ma_dr_flac_seek_to_pcm_frame(ma_dr_flac* pFlac, ma_uint64 pcmFrameIndex); +#ifndef MA_DR_FLAC_NO_STDIO +MA_API ma_dr_flac* ma_dr_flac_open_file(const char* pFileName, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_dr_flac* ma_dr_flac_open_file_w(const wchar_t* pFileName, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_dr_flac* ma_dr_flac_open_file_with_metadata(const char* pFileName, ma_dr_flac_meta_proc onMeta, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_dr_flac* ma_dr_flac_open_file_with_metadata_w(const wchar_t* pFileName, ma_dr_flac_meta_proc onMeta, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks); +#endif +MA_API ma_dr_flac* ma_dr_flac_open_memory(const void* pData, size_t dataSize, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_dr_flac* ma_dr_flac_open_memory_with_metadata(const void* pData, size_t dataSize, ma_dr_flac_meta_proc onMeta, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_int32* ma_dr_flac_open_and_read_pcm_frames_s32(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_int16* ma_dr_flac_open_and_read_pcm_frames_s16(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API float* ma_dr_flac_open_and_read_pcm_frames_f32(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks); +#ifndef MA_DR_FLAC_NO_STDIO +MA_API ma_int32* ma_dr_flac_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_int16* ma_dr_flac_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API float* ma_dr_flac_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks); +#endif +MA_API ma_int32* ma_dr_flac_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_int16* ma_dr_flac_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API float* ma_dr_flac_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API void ma_dr_flac_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks); +typedef struct +{ + ma_uint32 countRemaining; + const char* pRunningData; +} ma_dr_flac_vorbis_comment_iterator; +MA_API void ma_dr_flac_init_vorbis_comment_iterator(ma_dr_flac_vorbis_comment_iterator* pIter, ma_uint32 commentCount, const void* pComments); +MA_API const char* ma_dr_flac_next_vorbis_comment(ma_dr_flac_vorbis_comment_iterator* pIter, ma_uint32* pCommentLengthOut); +typedef struct +{ + ma_uint32 countRemaining; + const char* pRunningData; +} ma_dr_flac_cuesheet_track_iterator; +typedef struct +{ + ma_uint64 offset; + ma_uint8 index; + ma_uint8 reserved[3]; +} ma_dr_flac_cuesheet_track_index; +typedef struct +{ + ma_uint64 offset; + ma_uint8 trackNumber; + char ISRC[12]; + ma_bool8 isAudio; + ma_bool8 preEmphasis; + ma_uint8 indexCount; + const ma_dr_flac_cuesheet_track_index* pIndexPoints; +} ma_dr_flac_cuesheet_track; +MA_API void ma_dr_flac_init_cuesheet_track_iterator(ma_dr_flac_cuesheet_track_iterator* pIter, ma_uint32 trackCount, const void* pTrackData); +MA_API ma_bool32 ma_dr_flac_next_cuesheet_track(ma_dr_flac_cuesheet_track_iterator* pIter, ma_dr_flac_cuesheet_track* pCuesheetTrack); +#ifdef __cplusplus +} +#endif +#endif +/* dr_flac_h end */ +#endif /* MA_NO_FLAC */ + +#if !defined(MA_NO_MP3) && !defined(MA_NO_DECODING) +/* dr_mp3_h begin */ +#ifndef ma_dr_mp3_h +#define ma_dr_mp3_h +#ifdef __cplusplus +extern "C" { +#endif +#define MA_DR_MP3_STRINGIFY(x) #x +#define MA_DR_MP3_XSTRINGIFY(x) MA_DR_MP3_STRINGIFY(x) +#define MA_DR_MP3_VERSION_MAJOR 0 +#define MA_DR_MP3_VERSION_MINOR 6 +#define MA_DR_MP3_VERSION_REVISION 38 +#define MA_DR_MP3_VERSION_STRING MA_DR_MP3_XSTRINGIFY(MA_DR_MP3_VERSION_MAJOR) "." MA_DR_MP3_XSTRINGIFY(MA_DR_MP3_VERSION_MINOR) "." MA_DR_MP3_XSTRINGIFY(MA_DR_MP3_VERSION_REVISION) +#include +#define MA_DR_MP3_MAX_PCM_FRAMES_PER_MP3_FRAME 1152 +#define MA_DR_MP3_MAX_SAMPLES_PER_FRAME (MA_DR_MP3_MAX_PCM_FRAMES_PER_MP3_FRAME*2) +MA_API void ma_dr_mp3_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision); +MA_API const char* ma_dr_mp3_version_string(void); +typedef struct +{ + int frame_bytes, channels, hz, layer, bitrate_kbps; +} ma_dr_mp3dec_frame_info; +typedef struct +{ + float mdct_overlap[2][9*32], qmf_state[15*2*32]; + int reserv, free_format_bytes; + ma_uint8 header[4], reserv_buf[511]; +} ma_dr_mp3dec; +MA_API void ma_dr_mp3dec_init(ma_dr_mp3dec *dec); +MA_API int ma_dr_mp3dec_decode_frame(ma_dr_mp3dec *dec, const ma_uint8 *mp3, int mp3_bytes, void *pcm, ma_dr_mp3dec_frame_info *info); +MA_API void ma_dr_mp3dec_f32_to_s16(const float *in, ma_int16 *out, size_t num_samples); +typedef enum +{ + ma_dr_mp3_seek_origin_start, + ma_dr_mp3_seek_origin_current +} ma_dr_mp3_seek_origin; +typedef struct +{ + ma_uint64 seekPosInBytes; + ma_uint64 pcmFrameIndex; + ma_uint16 mp3FramesToDiscard; + ma_uint16 pcmFramesToDiscard; +} ma_dr_mp3_seek_point; +typedef size_t (* ma_dr_mp3_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead); +typedef ma_bool32 (* ma_dr_mp3_seek_proc)(void* pUserData, int offset, ma_dr_mp3_seek_origin origin); +typedef struct +{ + ma_uint32 channels; + ma_uint32 sampleRate; +} ma_dr_mp3_config; +typedef struct +{ + ma_dr_mp3dec decoder; + ma_uint32 channels; + ma_uint32 sampleRate; + ma_dr_mp3_read_proc onRead; + ma_dr_mp3_seek_proc onSeek; + void* pUserData; + ma_allocation_callbacks allocationCallbacks; + ma_uint32 mp3FrameChannels; + ma_uint32 mp3FrameSampleRate; + ma_uint32 pcmFramesConsumedInMP3Frame; + ma_uint32 pcmFramesRemainingInMP3Frame; + ma_uint8 pcmFrames[sizeof(float)*MA_DR_MP3_MAX_SAMPLES_PER_FRAME]; + ma_uint64 currentPCMFrame; + ma_uint64 streamCursor; + ma_dr_mp3_seek_point* pSeekPoints; + ma_uint32 seekPointCount; + size_t dataSize; + size_t dataCapacity; + size_t dataConsumed; + ma_uint8* pData; + ma_bool32 atEnd : 1; + struct + { + const ma_uint8* pData; + size_t dataSize; + size_t currentReadPos; + } memory; +} ma_dr_mp3; +MA_API ma_bool32 ma_dr_mp3_init(ma_dr_mp3* pMP3, ma_dr_mp3_read_proc onRead, ma_dr_mp3_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_mp3_init_memory(ma_dr_mp3* pMP3, const void* pData, size_t dataSize, const ma_allocation_callbacks* pAllocationCallbacks); +#ifndef MA_DR_MP3_NO_STDIO +MA_API ma_bool32 ma_dr_mp3_init_file(ma_dr_mp3* pMP3, const char* pFilePath, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_bool32 ma_dr_mp3_init_file_w(ma_dr_mp3* pMP3, const wchar_t* pFilePath, const ma_allocation_callbacks* pAllocationCallbacks); +#endif +MA_API void ma_dr_mp3_uninit(ma_dr_mp3* pMP3); +MA_API ma_uint64 ma_dr_mp3_read_pcm_frames_f32(ma_dr_mp3* pMP3, ma_uint64 framesToRead, float* pBufferOut); +MA_API ma_uint64 ma_dr_mp3_read_pcm_frames_s16(ma_dr_mp3* pMP3, ma_uint64 framesToRead, ma_int16* pBufferOut); +MA_API ma_bool32 ma_dr_mp3_seek_to_pcm_frame(ma_dr_mp3* pMP3, ma_uint64 frameIndex); +MA_API ma_uint64 ma_dr_mp3_get_pcm_frame_count(ma_dr_mp3* pMP3); +MA_API ma_uint64 ma_dr_mp3_get_mp3_frame_count(ma_dr_mp3* pMP3); +MA_API ma_bool32 ma_dr_mp3_get_mp3_and_pcm_frame_count(ma_dr_mp3* pMP3, ma_uint64* pMP3FrameCount, ma_uint64* pPCMFrameCount); +MA_API ma_bool32 ma_dr_mp3_calculate_seek_points(ma_dr_mp3* pMP3, ma_uint32* pSeekPointCount, ma_dr_mp3_seek_point* pSeekPoints); +MA_API ma_bool32 ma_dr_mp3_bind_seek_table(ma_dr_mp3* pMP3, ma_uint32 seekPointCount, ma_dr_mp3_seek_point* pSeekPoints); +MA_API float* ma_dr_mp3_open_and_read_pcm_frames_f32(ma_dr_mp3_read_proc onRead, ma_dr_mp3_seek_proc onSeek, void* pUserData, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_int16* ma_dr_mp3_open_and_read_pcm_frames_s16(ma_dr_mp3_read_proc onRead, ma_dr_mp3_seek_proc onSeek, void* pUserData, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API float* ma_dr_mp3_open_memory_and_read_pcm_frames_f32(const void* pData, size_t dataSize, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_int16* ma_dr_mp3_open_memory_and_read_pcm_frames_s16(const void* pData, size_t dataSize, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks); +#ifndef MA_DR_MP3_NO_STDIO +MA_API float* ma_dr_mp3_open_file_and_read_pcm_frames_f32(const char* filePath, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_int16* ma_dr_mp3_open_file_and_read_pcm_frames_s16(const char* filePath, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks); +#endif +MA_API void* ma_dr_mp3_malloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API void ma_dr_mp3_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks); +#ifdef __cplusplus +} +#endif +#endif +/* dr_mp3_h end */ +#endif /* MA_NO_MP3 */ + + +/************************************************************************************************************************************************************** + +Decoding + +**************************************************************************************************************************************************************/ +#ifndef MA_NO_DECODING + +static ma_result ma_decoder_read_bytes(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead) +{ + MA_ASSERT(pDecoder != NULL); + + return pDecoder->onRead(pDecoder, pBufferOut, bytesToRead, pBytesRead); +} + +static ma_result ma_decoder_seek_bytes(ma_decoder* pDecoder, ma_int64 byteOffset, ma_seek_origin origin) +{ + MA_ASSERT(pDecoder != NULL); + + return pDecoder->onSeek(pDecoder, byteOffset, origin); +} + +static ma_result ma_decoder_tell_bytes(ma_decoder* pDecoder, ma_int64* pCursor) +{ + MA_ASSERT(pDecoder != NULL); + + if (pDecoder->onTell == NULL) { + return MA_NOT_IMPLEMENTED; + } + + return pDecoder->onTell(pDecoder, pCursor); +} + + +MA_API ma_decoding_backend_config ma_decoding_backend_config_init(ma_format preferredFormat, ma_uint32 seekPointCount) +{ + ma_decoding_backend_config config; + + MA_ZERO_OBJECT(&config); + config.preferredFormat = preferredFormat; + config.seekPointCount = seekPointCount; + + return config; +} + + +MA_API 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; + config.resampling = ma_resampler_config_init(ma_format_unknown, 0, 0, 0, ma_resample_algorithm_linear); /* Format/channels/rate doesn't matter here. */ + config.encodingFormat = ma_encoding_format_unknown; + + /* Note that we are intentionally leaving the channel map empty here which will cause the default channel map to be used. */ + + return config; +} + +MA_API ma_decoder_config ma_decoder_config_init_default() +{ + return ma_decoder_config_init(ma_format_unknown, 0, 0); +} + +MA_API 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; +} + +static ma_result ma_decoder__init_data_converter(ma_decoder* pDecoder, const ma_decoder_config* pConfig) +{ + ma_result result; + ma_data_converter_config converterConfig; + ma_format internalFormat; + ma_uint32 internalChannels; + ma_uint32 internalSampleRate; + ma_channel internalChannelMap[MA_MAX_CHANNELS]; + + MA_ASSERT(pDecoder != NULL); + MA_ASSERT(pConfig != NULL); + + result = ma_data_source_get_data_format(pDecoder->pBackend, &internalFormat, &internalChannels, &internalSampleRate, internalChannelMap, ma_countof(internalChannelMap)); + if (result != MA_SUCCESS) { + return result; /* Failed to retrieve the internal data format. */ + } + + + /* Make sure we're not asking for too many channels. */ + if (pConfig->channels > MA_MAX_CHANNELS) { + return MA_INVALID_ARGS; + } + + /* The internal channels should have already been validated at a higher level, but we'll do it again explicitly here for safety. */ + if (internalChannels > MA_MAX_CHANNELS) { + return MA_INVALID_ARGS; + } + + + /* Output format. */ + if (pConfig->format == ma_format_unknown) { + pDecoder->outputFormat = internalFormat; + } else { + pDecoder->outputFormat = pConfig->format; + } + + if (pConfig->channels == 0) { + pDecoder->outputChannels = internalChannels; + } else { + pDecoder->outputChannels = pConfig->channels; + } + + if (pConfig->sampleRate == 0) { + pDecoder->outputSampleRate = internalSampleRate; + } else { + pDecoder->outputSampleRate = pConfig->sampleRate; + } + + converterConfig = ma_data_converter_config_init( + internalFormat, pDecoder->outputFormat, + internalChannels, pDecoder->outputChannels, + internalSampleRate, pDecoder->outputSampleRate + ); + converterConfig.pChannelMapIn = internalChannelMap; + converterConfig.pChannelMapOut = pConfig->pChannelMap; + converterConfig.channelMixMode = pConfig->channelMixMode; + converterConfig.ditherMode = pConfig->ditherMode; + converterConfig.allowDynamicSampleRate = MA_FALSE; /* Never allow dynamic sample rate conversion. Setting this to true will disable passthrough optimizations. */ + converterConfig.resampling = pConfig->resampling; + + result = ma_data_converter_init(&converterConfig, &pDecoder->allocationCallbacks, &pDecoder->converter); + if (result != MA_SUCCESS) { + return result; + } + + /* + Now that we have the decoder we need to determine whether or not we need a heap-allocated cache. We'll + need this if the data converter does not support calculation of the required input frame count. To + determine support for this we'll just run a test. + */ + { + ma_uint64 unused; + + result = ma_data_converter_get_required_input_frame_count(&pDecoder->converter, 1, &unused); + if (result != MA_SUCCESS) { + /* + We were unable to calculate the required input frame count which means we'll need to use + a heap-allocated cache. + */ + ma_uint64 inputCacheCapSizeInBytes; + + pDecoder->inputCacheCap = MA_DATA_CONVERTER_STACK_BUFFER_SIZE / ma_get_bytes_per_frame(internalFormat, internalChannels); + + /* Not strictly necessary, but keeping here for safety in case we change the default value of pDecoder->inputCacheCap. */ + inputCacheCapSizeInBytes = pDecoder->inputCacheCap * ma_get_bytes_per_frame(internalFormat, internalChannels); + if (inputCacheCapSizeInBytes > MA_SIZE_MAX) { + ma_data_converter_uninit(&pDecoder->converter, &pDecoder->allocationCallbacks); + return MA_OUT_OF_MEMORY; + } + + pDecoder->pInputCache = ma_malloc((size_t)inputCacheCapSizeInBytes, &pDecoder->allocationCallbacks); /* Safe cast to size_t. */ + if (pDecoder->pInputCache == NULL) { + ma_data_converter_uninit(&pDecoder->converter, &pDecoder->allocationCallbacks); + return MA_OUT_OF_MEMORY; + } + } + } + + return MA_SUCCESS; +} + + + +static ma_result ma_decoder_internal_on_read__custom(void* pUserData, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead) +{ + ma_decoder* pDecoder = (ma_decoder*)pUserData; + MA_ASSERT(pDecoder != NULL); + + return ma_decoder_read_bytes(pDecoder, pBufferOut, bytesToRead, pBytesRead); +} + +static ma_result ma_decoder_internal_on_seek__custom(void* pUserData, ma_int64 offset, ma_seek_origin origin) +{ + ma_decoder* pDecoder = (ma_decoder*)pUserData; + MA_ASSERT(pDecoder != NULL); + + return ma_decoder_seek_bytes(pDecoder, offset, origin); +} + +static ma_result ma_decoder_internal_on_tell__custom(void* pUserData, ma_int64* pCursor) +{ + ma_decoder* pDecoder = (ma_decoder*)pUserData; + MA_ASSERT(pDecoder != NULL); + + return ma_decoder_tell_bytes(pDecoder, pCursor); +} + + +static ma_result ma_decoder_init_from_vtable__internal(const ma_decoding_backend_vtable* pVTable, void* pVTableUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result; + ma_decoding_backend_config backendConfig; + ma_data_source* pBackend; + + MA_ASSERT(pVTable != NULL); + MA_ASSERT(pConfig != NULL); + MA_ASSERT(pDecoder != NULL); + + if (pVTable->onInit == NULL) { + return MA_NOT_IMPLEMENTED; + } + + backendConfig = ma_decoding_backend_config_init(pConfig->format, pConfig->seekPointCount); + + result = pVTable->onInit(pVTableUserData, ma_decoder_internal_on_read__custom, ma_decoder_internal_on_seek__custom, ma_decoder_internal_on_tell__custom, pDecoder, &backendConfig, &pDecoder->allocationCallbacks, &pBackend); + if (result != MA_SUCCESS) { + return result; /* Failed to initialize the backend from this vtable. */ + } + + /* Getting here means we were able to initialize the backend so we can now initialize the decoder. */ + pDecoder->pBackend = pBackend; + pDecoder->pBackendVTable = pVTable; + pDecoder->pBackendUserData = pConfig->pCustomBackendUserData; + + return MA_SUCCESS; +} + +static ma_result ma_decoder_init_from_file__internal(const ma_decoding_backend_vtable* pVTable, void* pVTableUserData, const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result; + ma_decoding_backend_config backendConfig; + ma_data_source* pBackend; + + MA_ASSERT(pVTable != NULL); + MA_ASSERT(pConfig != NULL); + MA_ASSERT(pDecoder != NULL); + + if (pVTable->onInitFile == NULL) { + return MA_NOT_IMPLEMENTED; + } + + backendConfig = ma_decoding_backend_config_init(pConfig->format, pConfig->seekPointCount); + + result = pVTable->onInitFile(pVTableUserData, pFilePath, &backendConfig, &pDecoder->allocationCallbacks, &pBackend); + if (result != MA_SUCCESS) { + return result; /* Failed to initialize the backend from this vtable. */ + } + + /* Getting here means we were able to initialize the backend so we can now initialize the decoder. */ + pDecoder->pBackend = pBackend; + pDecoder->pBackendVTable = pVTable; + pDecoder->pBackendUserData = pConfig->pCustomBackendUserData; + + return MA_SUCCESS; +} + +static ma_result ma_decoder_init_from_file_w__internal(const ma_decoding_backend_vtable* pVTable, void* pVTableUserData, const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result; + ma_decoding_backend_config backendConfig; + ma_data_source* pBackend; + + MA_ASSERT(pVTable != NULL); + MA_ASSERT(pConfig != NULL); + MA_ASSERT(pDecoder != NULL); + + if (pVTable->onInitFileW == NULL) { + return MA_NOT_IMPLEMENTED; + } + + backendConfig = ma_decoding_backend_config_init(pConfig->format, pConfig->seekPointCount); + + result = pVTable->onInitFileW(pVTableUserData, pFilePath, &backendConfig, &pDecoder->allocationCallbacks, &pBackend); + if (result != MA_SUCCESS) { + return result; /* Failed to initialize the backend from this vtable. */ + } + + /* Getting here means we were able to initialize the backend so we can now initialize the decoder. */ + pDecoder->pBackend = pBackend; + pDecoder->pBackendVTable = pVTable; + pDecoder->pBackendUserData = pConfig->pCustomBackendUserData; + + return MA_SUCCESS; +} + +static ma_result ma_decoder_init_from_memory__internal(const ma_decoding_backend_vtable* pVTable, void* pVTableUserData, const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result; + ma_decoding_backend_config backendConfig; + ma_data_source* pBackend; + + MA_ASSERT(pVTable != NULL); + MA_ASSERT(pConfig != NULL); + MA_ASSERT(pDecoder != NULL); + + if (pVTable->onInitMemory == NULL) { + return MA_NOT_IMPLEMENTED; + } + + backendConfig = ma_decoding_backend_config_init(pConfig->format, pConfig->seekPointCount); + + result = pVTable->onInitMemory(pVTableUserData, pData, dataSize, &backendConfig, &pDecoder->allocationCallbacks, &pBackend); + if (result != MA_SUCCESS) { + return result; /* Failed to initialize the backend from this vtable. */ + } + + /* Getting here means we were able to initialize the backend so we can now initialize the decoder. */ + pDecoder->pBackend = pBackend; + pDecoder->pBackendVTable = pVTable; + pDecoder->pBackendUserData = pConfig->pCustomBackendUserData; + + return MA_SUCCESS; +} + + + +static ma_result ma_decoder_init_custom__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result = MA_NO_BACKEND; + size_t ivtable; + + MA_ASSERT(pConfig != NULL); + MA_ASSERT(pDecoder != NULL); + + if (pConfig->ppCustomBackendVTables == NULL) { + return MA_NO_BACKEND; + } + + /* The order each backend is listed is what defines the priority. */ + for (ivtable = 0; ivtable < pConfig->customBackendCount; ivtable += 1) { + const ma_decoding_backend_vtable* pVTable = pConfig->ppCustomBackendVTables[ivtable]; + if (pVTable != NULL) { + result = ma_decoder_init_from_vtable__internal(pVTable, pConfig->pCustomBackendUserData, pConfig, pDecoder); + if (result == MA_SUCCESS) { + return MA_SUCCESS; + } else { + /* Initialization failed. Move on to the next one, but seek back to the start first so the next vtable starts from the first byte of the file. */ + result = ma_decoder_seek_bytes(pDecoder, 0, ma_seek_origin_start); + if (result != MA_SUCCESS) { + return result; /* Failed to seek back to the start. */ + } + } + } else { + /* No vtable. */ + } + } + + /* Getting here means we couldn't find a backend. */ + return MA_NO_BACKEND; +} + +static ma_result ma_decoder_init_custom_from_file__internal(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result = MA_NO_BACKEND; + size_t ivtable; + + MA_ASSERT(pConfig != NULL); + MA_ASSERT(pDecoder != NULL); + + if (pConfig->ppCustomBackendVTables == NULL) { + return MA_NO_BACKEND; + } + + /* The order each backend is listed is what defines the priority. */ + for (ivtable = 0; ivtable < pConfig->customBackendCount; ivtable += 1) { + const ma_decoding_backend_vtable* pVTable = pConfig->ppCustomBackendVTables[ivtable]; + if (pVTable != NULL) { + result = ma_decoder_init_from_file__internal(pVTable, pConfig->pCustomBackendUserData, pFilePath, pConfig, pDecoder); + if (result == MA_SUCCESS) { + return MA_SUCCESS; + } + } else { + /* No vtable. */ + } + } + + /* Getting here means we couldn't find a backend. */ + return MA_NO_BACKEND; +} + +static ma_result ma_decoder_init_custom_from_file_w__internal(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result = MA_NO_BACKEND; + size_t ivtable; + + MA_ASSERT(pConfig != NULL); + MA_ASSERT(pDecoder != NULL); + + if (pConfig->ppCustomBackendVTables == NULL) { + return MA_NO_BACKEND; + } + + /* The order each backend is listed is what defines the priority. */ + for (ivtable = 0; ivtable < pConfig->customBackendCount; ivtable += 1) { + const ma_decoding_backend_vtable* pVTable = pConfig->ppCustomBackendVTables[ivtable]; + if (pVTable != NULL) { + result = ma_decoder_init_from_file_w__internal(pVTable, pConfig->pCustomBackendUserData, pFilePath, pConfig, pDecoder); + if (result == MA_SUCCESS) { + return MA_SUCCESS; + } + } else { + /* No vtable. */ + } + } + + /* Getting here means we couldn't find a backend. */ + return MA_NO_BACKEND; +} + +static ma_result ma_decoder_init_custom_from_memory__internal(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result = MA_NO_BACKEND; + size_t ivtable; + + MA_ASSERT(pConfig != NULL); + MA_ASSERT(pDecoder != NULL); + + if (pConfig->ppCustomBackendVTables == NULL) { + return MA_NO_BACKEND; + } + + /* The order each backend is listed is what defines the priority. */ + for (ivtable = 0; ivtable < pConfig->customBackendCount; ivtable += 1) { + const ma_decoding_backend_vtable* pVTable = pConfig->ppCustomBackendVTables[ivtable]; + if (pVTable != NULL) { + result = ma_decoder_init_from_memory__internal(pVTable, pConfig->pCustomBackendUserData, pData, dataSize, pConfig, pDecoder); + if (result == MA_SUCCESS) { + return MA_SUCCESS; + } + } else { + /* No vtable. */ + } + } + + /* Getting here means we couldn't find a backend. */ + return MA_NO_BACKEND; +} + + +/* WAV */ +#ifdef ma_dr_wav_h +#define MA_HAS_WAV + +typedef struct +{ + ma_data_source_base ds; + ma_read_proc onRead; + ma_seek_proc onSeek; + ma_tell_proc onTell; + void* pReadSeekTellUserData; + ma_format format; /* Can be f32, s16 or s32. */ +#if !defined(MA_NO_WAV) + ma_dr_wav dr; +#endif +} ma_wav; + +MA_API ma_result ma_wav_init(ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_wav* pWav); +MA_API ma_result ma_wav_init_file(const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_wav* pWav); +MA_API ma_result ma_wav_init_file_w(const wchar_t* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_wav* pWav); +MA_API ma_result ma_wav_init_memory(const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_wav* pWav); +MA_API void ma_wav_uninit(ma_wav* pWav, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_wav_read_pcm_frames(ma_wav* pWav, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead); +MA_API ma_result ma_wav_seek_to_pcm_frame(ma_wav* pWav, ma_uint64 frameIndex); +MA_API ma_result ma_wav_get_data_format(ma_wav* pWav, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap); +MA_API ma_result ma_wav_get_cursor_in_pcm_frames(ma_wav* pWav, ma_uint64* pCursor); +MA_API ma_result ma_wav_get_length_in_pcm_frames(ma_wav* pWav, ma_uint64* pLength); + + +static ma_result ma_wav_ds_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + return ma_wav_read_pcm_frames((ma_wav*)pDataSource, pFramesOut, frameCount, pFramesRead); +} + +static ma_result ma_wav_ds_seek(ma_data_source* pDataSource, ma_uint64 frameIndex) +{ + return ma_wav_seek_to_pcm_frame((ma_wav*)pDataSource, frameIndex); +} + +static ma_result ma_wav_ds_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + return ma_wav_get_data_format((ma_wav*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap); +} + +static ma_result ma_wav_ds_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor) +{ + return ma_wav_get_cursor_in_pcm_frames((ma_wav*)pDataSource, pCursor); +} + +static ma_result ma_wav_ds_get_length(ma_data_source* pDataSource, ma_uint64* pLength) +{ + return ma_wav_get_length_in_pcm_frames((ma_wav*)pDataSource, pLength); +} + +static ma_data_source_vtable g_ma_wav_ds_vtable = +{ + ma_wav_ds_read, + ma_wav_ds_seek, + ma_wav_ds_get_data_format, + ma_wav_ds_get_cursor, + ma_wav_ds_get_length, + NULL, /* onSetLooping */ + 0 +}; + + +#if !defined(MA_NO_WAV) +static size_t ma_wav_dr_callback__read(void* pUserData, void* pBufferOut, size_t bytesToRead) +{ + ma_wav* pWav = (ma_wav*)pUserData; + ma_result result; + size_t bytesRead; + + MA_ASSERT(pWav != NULL); + + result = pWav->onRead(pWav->pReadSeekTellUserData, pBufferOut, bytesToRead, &bytesRead); + (void)result; + + return bytesRead; +} + +static ma_bool32 ma_wav_dr_callback__seek(void* pUserData, int offset, ma_dr_wav_seek_origin origin) +{ + ma_wav* pWav = (ma_wav*)pUserData; + ma_result result; + ma_seek_origin maSeekOrigin; + + MA_ASSERT(pWav != NULL); + + maSeekOrigin = ma_seek_origin_start; + if (origin == ma_dr_wav_seek_origin_current) { + maSeekOrigin = ma_seek_origin_current; + } + + result = pWav->onSeek(pWav->pReadSeekTellUserData, offset, maSeekOrigin); + if (result != MA_SUCCESS) { + return MA_FALSE; + } + + return MA_TRUE; +} +#endif + +static ma_result ma_wav_init_internal(const ma_decoding_backend_config* pConfig, ma_wav* pWav) +{ + ma_result result; + ma_data_source_config dataSourceConfig; + + if (pWav == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pWav); + pWav->format = ma_format_unknown; /* Use closest match to source file by default. */ + + if (pConfig != NULL && (pConfig->preferredFormat == ma_format_f32 || pConfig->preferredFormat == ma_format_s16 || pConfig->preferredFormat == ma_format_s32)) { + pWav->format = pConfig->preferredFormat; + } else { + /* Getting here means something other than f32 and s16 was specified. Just leave this unset to use the default format. */ + } + + dataSourceConfig = ma_data_source_config_init(); + dataSourceConfig.vtable = &g_ma_wav_ds_vtable; + + result = ma_data_source_init(&dataSourceConfig, &pWav->ds); + if (result != MA_SUCCESS) { + return result; /* Failed to initialize the base data source. */ + } + + return MA_SUCCESS; +} + +static ma_result ma_wav_post_init(ma_wav* pWav) +{ + /* + If an explicit format was not specified, try picking the closest match based on the internal + format. The format needs to be supported by miniaudio. + */ + if (pWav->format == ma_format_unknown) { + switch (pWav->dr.translatedFormatTag) + { + case MA_DR_WAVE_FORMAT_PCM: + { + if (pWav->dr.bitsPerSample == 8) { + pWav->format = ma_format_u8; + } else if (pWav->dr.bitsPerSample == 16) { + pWav->format = ma_format_s16; + } else if (pWav->dr.bitsPerSample == 24) { + pWav->format = ma_format_s24; + } else if (pWav->dr.bitsPerSample == 32) { + pWav->format = ma_format_s32; + } + } break; + + case MA_DR_WAVE_FORMAT_IEEE_FLOAT: + { + if (pWav->dr.bitsPerSample == 32) { + pWav->format = ma_format_f32; + } + } break; + + default: break; + } + + /* Fall back to f32 if we couldn't find anything. */ + if (pWav->format == ma_format_unknown) { + pWav->format = ma_format_f32; + } + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_wav_init(ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_wav* pWav) +{ + ma_result result; + + result = ma_wav_init_internal(pConfig, pWav); + if (result != MA_SUCCESS) { + return result; + } + + if (onRead == NULL || onSeek == NULL) { + return MA_INVALID_ARGS; /* onRead and onSeek are mandatory. */ + } + + pWav->onRead = onRead; + pWav->onSeek = onSeek; + pWav->onTell = onTell; + pWav->pReadSeekTellUserData = pReadSeekTellUserData; + + #if !defined(MA_NO_WAV) + { + ma_bool32 wavResult; + + wavResult = ma_dr_wav_init(&pWav->dr, ma_wav_dr_callback__read, ma_wav_dr_callback__seek, pWav, pAllocationCallbacks); + if (wavResult != MA_TRUE) { + return MA_INVALID_FILE; + } + + ma_wav_post_init(pWav); + + return MA_SUCCESS; + } + #else + { + /* wav is disabled. */ + (void)pAllocationCallbacks; + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_wav_init_file(const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_wav* pWav) +{ + ma_result result; + + result = ma_wav_init_internal(pConfig, pWav); + if (result != MA_SUCCESS) { + return result; + } + + #if !defined(MA_NO_WAV) + { + ma_bool32 wavResult; + + wavResult = ma_dr_wav_init_file(&pWav->dr, pFilePath, pAllocationCallbacks); + if (wavResult != MA_TRUE) { + return MA_INVALID_FILE; + } + + ma_wav_post_init(pWav); + + return MA_SUCCESS; + } + #else + { + /* wav is disabled. */ + (void)pFilePath; + (void)pAllocationCallbacks; + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_wav_init_file_w(const wchar_t* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_wav* pWav) +{ + ma_result result; + + result = ma_wav_init_internal(pConfig, pWav); + if (result != MA_SUCCESS) { + return result; + } + + #if !defined(MA_NO_WAV) + { + ma_bool32 wavResult; + + wavResult = ma_dr_wav_init_file_w(&pWav->dr, pFilePath, pAllocationCallbacks); + if (wavResult != MA_TRUE) { + return MA_INVALID_FILE; + } + + ma_wav_post_init(pWav); + + return MA_SUCCESS; + } + #else + { + /* wav is disabled. */ + (void)pFilePath; + (void)pAllocationCallbacks; + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_wav_init_memory(const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_wav* pWav) +{ + ma_result result; + + result = ma_wav_init_internal(pConfig, pWav); + if (result != MA_SUCCESS) { + return result; + } + + #if !defined(MA_NO_WAV) + { + ma_bool32 wavResult; + + wavResult = ma_dr_wav_init_memory(&pWav->dr, pData, dataSize, pAllocationCallbacks); + if (wavResult != MA_TRUE) { + return MA_INVALID_FILE; + } + + ma_wav_post_init(pWav); + + return MA_SUCCESS; + } + #else + { + /* wav is disabled. */ + (void)pData; + (void)dataSize; + (void)pAllocationCallbacks; + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API void ma_wav_uninit(ma_wav* pWav, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pWav == NULL) { + return; + } + + (void)pAllocationCallbacks; + + #if !defined(MA_NO_WAV) + { + ma_dr_wav_uninit(&pWav->dr); + } + #else + { + /* wav is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + } + #endif + + ma_data_source_uninit(&pWav->ds); +} + +MA_API ma_result ma_wav_read_pcm_frames(ma_wav* pWav, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + if (pFramesRead != NULL) { + *pFramesRead = 0; + } + + if (frameCount == 0) { + return MA_INVALID_ARGS; + } + + if (pWav == NULL) { + return MA_INVALID_ARGS; + } + + #if !defined(MA_NO_WAV) + { + /* We always use floating point format. */ + ma_result result = MA_SUCCESS; /* Must be initialized to MA_SUCCESS. */ + ma_uint64 totalFramesRead = 0; + ma_format format; + + ma_wav_get_data_format(pWav, &format, NULL, NULL, NULL, 0); + + switch (format) + { + case ma_format_f32: + { + totalFramesRead = ma_dr_wav_read_pcm_frames_f32(&pWav->dr, frameCount, (float*)pFramesOut); + } break; + + case ma_format_s16: + { + totalFramesRead = ma_dr_wav_read_pcm_frames_s16(&pWav->dr, frameCount, (ma_int16*)pFramesOut); + } break; + + case ma_format_s32: + { + totalFramesRead = ma_dr_wav_read_pcm_frames_s32(&pWav->dr, frameCount, (ma_int32*)pFramesOut); + } break; + + /* Fallback to a raw read. */ + case ma_format_unknown: return MA_INVALID_OPERATION; /* <-- this should never be hit because initialization would just fall back to a supported format. */ + default: + { + totalFramesRead = ma_dr_wav_read_pcm_frames(&pWav->dr, frameCount, pFramesOut); + } break; + } + + /* In the future we'll update ma_dr_wav to return MA_AT_END for us. */ + if (totalFramesRead == 0) { + result = MA_AT_END; + } + + if (pFramesRead != NULL) { + *pFramesRead = totalFramesRead; + } + + if (result == MA_SUCCESS && totalFramesRead == 0) { + result = MA_AT_END; + } + + return result; + } + #else + { + /* wav is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + + (void)pFramesOut; + (void)frameCount; + (void)pFramesRead; + + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_wav_seek_to_pcm_frame(ma_wav* pWav, ma_uint64 frameIndex) +{ + if (pWav == NULL) { + return MA_INVALID_ARGS; + } + + #if !defined(MA_NO_WAV) + { + ma_bool32 wavResult; + + wavResult = ma_dr_wav_seek_to_pcm_frame(&pWav->dr, frameIndex); + if (wavResult != MA_TRUE) { + return MA_ERROR; + } + + return MA_SUCCESS; + } + #else + { + /* wav is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + + (void)frameIndex; + + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_wav_get_data_format(ma_wav* pWav, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + /* Defaults for safety. */ + if (pFormat != NULL) { + *pFormat = ma_format_unknown; + } + if (pChannels != NULL) { + *pChannels = 0; + } + if (pSampleRate != NULL) { + *pSampleRate = 0; + } + if (pChannelMap != NULL) { + MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap); + } + + if (pWav == NULL) { + return MA_INVALID_OPERATION; + } + + if (pFormat != NULL) { + *pFormat = pWav->format; + } + + #if !defined(MA_NO_WAV) + { + if (pChannels != NULL) { + *pChannels = pWav->dr.channels; + } + + if (pSampleRate != NULL) { + *pSampleRate = pWav->dr.sampleRate; + } + + if (pChannelMap != NULL) { + ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pChannelMap, channelMapCap, pWav->dr.channels); + } + + return MA_SUCCESS; + } + #else + { + /* wav is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_wav_get_cursor_in_pcm_frames(ma_wav* pWav, ma_uint64* pCursor) +{ + if (pCursor == NULL) { + return MA_INVALID_ARGS; + } + + *pCursor = 0; /* Safety. */ + + if (pWav == NULL) { + return MA_INVALID_ARGS; + } + + #if !defined(MA_NO_WAV) + { + ma_result wavResult = ma_dr_wav_get_cursor_in_pcm_frames(&pWav->dr, pCursor); + if (wavResult != MA_SUCCESS) { + return (ma_result)wavResult; /* ma_dr_wav result codes map to miniaudio's. */ + } + + return MA_SUCCESS; + } + #else + { + /* wav is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_wav_get_length_in_pcm_frames(ma_wav* pWav, ma_uint64* pLength) +{ + if (pLength == NULL) { + return MA_INVALID_ARGS; + } + + *pLength = 0; /* Safety. */ + + if (pWav == NULL) { + return MA_INVALID_ARGS; + } + + #if !defined(MA_NO_WAV) + { + ma_result wavResult = ma_dr_wav_get_length_in_pcm_frames(&pWav->dr, pLength); + if (wavResult != MA_SUCCESS) { + return (ma_result)wavResult; /* ma_dr_wav result codes map to miniaudio's. */ + } + + return MA_SUCCESS; + } + #else + { + /* wav is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + return MA_NOT_IMPLEMENTED; + } + #endif +} + + +static ma_result ma_decoding_backend_init__wav(void* pUserData, ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend) +{ + ma_result result; + ma_wav* pWav; + + (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */ + + /* For now we're just allocating the decoder backend on the heap. */ + pWav = (ma_wav*)ma_malloc(sizeof(*pWav), pAllocationCallbacks); + if (pWav == NULL) { + return MA_OUT_OF_MEMORY; + } + + result = ma_wav_init(onRead, onSeek, onTell, pReadSeekTellUserData, pConfig, pAllocationCallbacks, pWav); + if (result != MA_SUCCESS) { + ma_free(pWav, pAllocationCallbacks); + return result; + } + + *ppBackend = pWav; + + return MA_SUCCESS; +} + +static ma_result ma_decoding_backend_init_file__wav(void* pUserData, const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend) +{ + ma_result result; + ma_wav* pWav; + + (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */ + + /* For now we're just allocating the decoder backend on the heap. */ + pWav = (ma_wav*)ma_malloc(sizeof(*pWav), pAllocationCallbacks); + if (pWav == NULL) { + return MA_OUT_OF_MEMORY; + } + + result = ma_wav_init_file(pFilePath, pConfig, pAllocationCallbacks, pWav); + if (result != MA_SUCCESS) { + ma_free(pWav, pAllocationCallbacks); + return result; + } + + *ppBackend = pWav; + + return MA_SUCCESS; +} + +static ma_result ma_decoding_backend_init_file_w__wav(void* pUserData, const wchar_t* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend) +{ + ma_result result; + ma_wav* pWav; + + (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */ + + /* For now we're just allocating the decoder backend on the heap. */ + pWav = (ma_wav*)ma_malloc(sizeof(*pWav), pAllocationCallbacks); + if (pWav == NULL) { + return MA_OUT_OF_MEMORY; + } + + result = ma_wav_init_file_w(pFilePath, pConfig, pAllocationCallbacks, pWav); + if (result != MA_SUCCESS) { + ma_free(pWav, pAllocationCallbacks); + return result; + } + + *ppBackend = pWav; + + return MA_SUCCESS; +} + +static ma_result ma_decoding_backend_init_memory__wav(void* pUserData, const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend) +{ + ma_result result; + ma_wav* pWav; + + (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */ + + /* For now we're just allocating the decoder backend on the heap. */ + pWav = (ma_wav*)ma_malloc(sizeof(*pWav), pAllocationCallbacks); + if (pWav == NULL) { + return MA_OUT_OF_MEMORY; + } + + result = ma_wav_init_memory(pData, dataSize, pConfig, pAllocationCallbacks, pWav); + if (result != MA_SUCCESS) { + ma_free(pWav, pAllocationCallbacks); + return result; + } + + *ppBackend = pWav; + + return MA_SUCCESS; +} + +static void ma_decoding_backend_uninit__wav(void* pUserData, ma_data_source* pBackend, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_wav* pWav = (ma_wav*)pBackend; + + (void)pUserData; + + ma_wav_uninit(pWav, pAllocationCallbacks); + ma_free(pWav, pAllocationCallbacks); +} + +static ma_decoding_backend_vtable g_ma_decoding_backend_vtable_wav = +{ + ma_decoding_backend_init__wav, + ma_decoding_backend_init_file__wav, + ma_decoding_backend_init_file_w__wav, + ma_decoding_backend_init_memory__wav, + ma_decoding_backend_uninit__wav +}; + +static ma_result ma_decoder_init_wav__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + return ma_decoder_init_from_vtable__internal(&g_ma_decoding_backend_vtable_wav, NULL, pConfig, pDecoder); +} + +static ma_result ma_decoder_init_wav_from_file__internal(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + return ma_decoder_init_from_file__internal(&g_ma_decoding_backend_vtable_wav, NULL, pFilePath, pConfig, pDecoder); +} + +static ma_result ma_decoder_init_wav_from_file_w__internal(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + return ma_decoder_init_from_file_w__internal(&g_ma_decoding_backend_vtable_wav, NULL, pFilePath, pConfig, pDecoder); +} + +static ma_result ma_decoder_init_wav_from_memory__internal(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + return ma_decoder_init_from_memory__internal(&g_ma_decoding_backend_vtable_wav, NULL, pData, dataSize, pConfig, pDecoder); +} +#endif /* ma_dr_wav_h */ + +/* FLAC */ +#ifdef ma_dr_flac_h +#define MA_HAS_FLAC + +typedef struct +{ + ma_data_source_base ds; + ma_read_proc onRead; + ma_seek_proc onSeek; + ma_tell_proc onTell; + void* pReadSeekTellUserData; + ma_format format; /* Can be f32, s16 or s32. */ +#if !defined(MA_NO_FLAC) + ma_dr_flac* dr; +#endif +} ma_flac; + +MA_API ma_result ma_flac_init(ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_flac* pFlac); +MA_API ma_result ma_flac_init_file(const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_flac* pFlac); +MA_API ma_result ma_flac_init_file_w(const wchar_t* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_flac* pFlac); +MA_API ma_result ma_flac_init_memory(const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_flac* pFlac); +MA_API void ma_flac_uninit(ma_flac* pFlac, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_flac_read_pcm_frames(ma_flac* pFlac, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead); +MA_API ma_result ma_flac_seek_to_pcm_frame(ma_flac* pFlac, ma_uint64 frameIndex); +MA_API ma_result ma_flac_get_data_format(ma_flac* pFlac, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap); +MA_API ma_result ma_flac_get_cursor_in_pcm_frames(ma_flac* pFlac, ma_uint64* pCursor); +MA_API ma_result ma_flac_get_length_in_pcm_frames(ma_flac* pFlac, ma_uint64* pLength); + + +static ma_result ma_flac_ds_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + return ma_flac_read_pcm_frames((ma_flac*)pDataSource, pFramesOut, frameCount, pFramesRead); +} + +static ma_result ma_flac_ds_seek(ma_data_source* pDataSource, ma_uint64 frameIndex) +{ + return ma_flac_seek_to_pcm_frame((ma_flac*)pDataSource, frameIndex); +} + +static ma_result ma_flac_ds_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + return ma_flac_get_data_format((ma_flac*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap); +} + +static ma_result ma_flac_ds_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor) +{ + return ma_flac_get_cursor_in_pcm_frames((ma_flac*)pDataSource, pCursor); +} + +static ma_result ma_flac_ds_get_length(ma_data_source* pDataSource, ma_uint64* pLength) +{ + return ma_flac_get_length_in_pcm_frames((ma_flac*)pDataSource, pLength); +} + +static ma_data_source_vtable g_ma_flac_ds_vtable = +{ + ma_flac_ds_read, + ma_flac_ds_seek, + ma_flac_ds_get_data_format, + ma_flac_ds_get_cursor, + ma_flac_ds_get_length, + NULL, /* onSetLooping */ + 0 +}; + + +#if !defined(MA_NO_FLAC) +static size_t ma_flac_dr_callback__read(void* pUserData, void* pBufferOut, size_t bytesToRead) +{ + ma_flac* pFlac = (ma_flac*)pUserData; + ma_result result; + size_t bytesRead; + + MA_ASSERT(pFlac != NULL); + + result = pFlac->onRead(pFlac->pReadSeekTellUserData, pBufferOut, bytesToRead, &bytesRead); + (void)result; + + return bytesRead; +} + +static ma_bool32 ma_flac_dr_callback__seek(void* pUserData, int offset, ma_dr_flac_seek_origin origin) +{ + ma_flac* pFlac = (ma_flac*)pUserData; + ma_result result; + ma_seek_origin maSeekOrigin; + + MA_ASSERT(pFlac != NULL); + + maSeekOrigin = ma_seek_origin_start; + if (origin == ma_dr_flac_seek_origin_current) { + maSeekOrigin = ma_seek_origin_current; + } + + result = pFlac->onSeek(pFlac->pReadSeekTellUserData, offset, maSeekOrigin); + if (result != MA_SUCCESS) { + return MA_FALSE; + } + + return MA_TRUE; +} +#endif + +static ma_result ma_flac_init_internal(const ma_decoding_backend_config* pConfig, ma_flac* pFlac) +{ + ma_result result; + ma_data_source_config dataSourceConfig; + + if (pFlac == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pFlac); + pFlac->format = ma_format_f32; /* f32 by default. */ + + if (pConfig != NULL && (pConfig->preferredFormat == ma_format_f32 || pConfig->preferredFormat == ma_format_s16 || pConfig->preferredFormat == ma_format_s32)) { + pFlac->format = pConfig->preferredFormat; + } else { + /* Getting here means something other than f32 and s16 was specified. Just leave this unset to use the default format. */ + } + + dataSourceConfig = ma_data_source_config_init(); + dataSourceConfig.vtable = &g_ma_flac_ds_vtable; + + result = ma_data_source_init(&dataSourceConfig, &pFlac->ds); + if (result != MA_SUCCESS) { + return result; /* Failed to initialize the base data source. */ + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_flac_init(ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_flac* pFlac) +{ + ma_result result; + + result = ma_flac_init_internal(pConfig, pFlac); + if (result != MA_SUCCESS) { + return result; + } + + if (onRead == NULL || onSeek == NULL) { + return MA_INVALID_ARGS; /* onRead and onSeek are mandatory. */ + } + + pFlac->onRead = onRead; + pFlac->onSeek = onSeek; + pFlac->onTell = onTell; + pFlac->pReadSeekTellUserData = pReadSeekTellUserData; + + #if !defined(MA_NO_FLAC) + { + pFlac->dr = ma_dr_flac_open(ma_flac_dr_callback__read, ma_flac_dr_callback__seek, pFlac, pAllocationCallbacks); + if (pFlac->dr == NULL) { + return MA_INVALID_FILE; + } + + return MA_SUCCESS; + } + #else + { + /* flac is disabled. */ + (void)pAllocationCallbacks; + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_flac_init_file(const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_flac* pFlac) +{ + ma_result result; + + result = ma_flac_init_internal(pConfig, pFlac); + if (result != MA_SUCCESS) { + return result; + } + + #if !defined(MA_NO_FLAC) + { + pFlac->dr = ma_dr_flac_open_file(pFilePath, pAllocationCallbacks); + if (pFlac->dr == NULL) { + return MA_INVALID_FILE; + } + + return MA_SUCCESS; + } + #else + { + /* flac is disabled. */ + (void)pFilePath; + (void)pAllocationCallbacks; + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_flac_init_file_w(const wchar_t* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_flac* pFlac) +{ + ma_result result; + + result = ma_flac_init_internal(pConfig, pFlac); + if (result != MA_SUCCESS) { + return result; + } + + #if !defined(MA_NO_FLAC) + { + pFlac->dr = ma_dr_flac_open_file_w(pFilePath, pAllocationCallbacks); + if (pFlac->dr == NULL) { + return MA_INVALID_FILE; + } + + return MA_SUCCESS; + } + #else + { + /* flac is disabled. */ + (void)pFilePath; + (void)pAllocationCallbacks; + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_flac_init_memory(const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_flac* pFlac) +{ + ma_result result; + + result = ma_flac_init_internal(pConfig, pFlac); + if (result != MA_SUCCESS) { + return result; + } + + #if !defined(MA_NO_FLAC) + { + pFlac->dr = ma_dr_flac_open_memory(pData, dataSize, pAllocationCallbacks); + if (pFlac->dr == NULL) { + return MA_INVALID_FILE; + } + + return MA_SUCCESS; + } + #else + { + /* flac is disabled. */ + (void)pData; + (void)dataSize; + (void)pAllocationCallbacks; + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API void ma_flac_uninit(ma_flac* pFlac, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pFlac == NULL) { + return; + } + + (void)pAllocationCallbacks; + + #if !defined(MA_NO_FLAC) + { + ma_dr_flac_close(pFlac->dr); + } + #else + { + /* flac is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + } + #endif + + ma_data_source_uninit(&pFlac->ds); +} + +MA_API ma_result ma_flac_read_pcm_frames(ma_flac* pFlac, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + if (pFramesRead != NULL) { + *pFramesRead = 0; + } + + if (frameCount == 0) { + return MA_INVALID_ARGS; + } + + if (pFlac == NULL) { + return MA_INVALID_ARGS; + } + + #if !defined(MA_NO_FLAC) + { + /* We always use floating point format. */ + ma_result result = MA_SUCCESS; /* Must be initialized to MA_SUCCESS. */ + ma_uint64 totalFramesRead = 0; + ma_format format; + + ma_flac_get_data_format(pFlac, &format, NULL, NULL, NULL, 0); + + switch (format) + { + case ma_format_f32: + { + totalFramesRead = ma_dr_flac_read_pcm_frames_f32(pFlac->dr, frameCount, (float*)pFramesOut); + } break; + + case ma_format_s16: + { + totalFramesRead = ma_dr_flac_read_pcm_frames_s16(pFlac->dr, frameCount, (ma_int16*)pFramesOut); + } break; + + case ma_format_s32: + { + totalFramesRead = ma_dr_flac_read_pcm_frames_s32(pFlac->dr, frameCount, (ma_int32*)pFramesOut); + } break; + + case ma_format_u8: + case ma_format_s24: + case ma_format_unknown: + default: + { + return MA_INVALID_OPERATION; + }; + } + + /* In the future we'll update ma_dr_flac to return MA_AT_END for us. */ + if (totalFramesRead == 0) { + result = MA_AT_END; + } + + if (pFramesRead != NULL) { + *pFramesRead = totalFramesRead; + } + + if (result == MA_SUCCESS && totalFramesRead == 0) { + result = MA_AT_END; + } + + return result; + } + #else + { + /* flac is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + + (void)pFramesOut; + (void)frameCount; + (void)pFramesRead; + + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_flac_seek_to_pcm_frame(ma_flac* pFlac, ma_uint64 frameIndex) +{ + if (pFlac == NULL) { + return MA_INVALID_ARGS; + } + + #if !defined(MA_NO_FLAC) + { + ma_bool32 flacResult; + + flacResult = ma_dr_flac_seek_to_pcm_frame(pFlac->dr, frameIndex); + if (flacResult != MA_TRUE) { + return MA_ERROR; + } + + return MA_SUCCESS; + } + #else + { + /* flac is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + + (void)frameIndex; + + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_flac_get_data_format(ma_flac* pFlac, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + /* Defaults for safety. */ + if (pFormat != NULL) { + *pFormat = ma_format_unknown; + } + if (pChannels != NULL) { + *pChannels = 0; + } + if (pSampleRate != NULL) { + *pSampleRate = 0; + } + if (pChannelMap != NULL) { + MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap); + } + + if (pFlac == NULL) { + return MA_INVALID_OPERATION; + } + + if (pFormat != NULL) { + *pFormat = pFlac->format; + } + + #if !defined(MA_NO_FLAC) + { + if (pChannels != NULL) { + *pChannels = pFlac->dr->channels; + } + + if (pSampleRate != NULL) { + *pSampleRate = pFlac->dr->sampleRate; + } + + if (pChannelMap != NULL) { + ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pChannelMap, channelMapCap, pFlac->dr->channels); + } + + return MA_SUCCESS; + } + #else + { + /* flac is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_flac_get_cursor_in_pcm_frames(ma_flac* pFlac, ma_uint64* pCursor) +{ + if (pCursor == NULL) { + return MA_INVALID_ARGS; + } + + *pCursor = 0; /* Safety. */ + + if (pFlac == NULL) { + return MA_INVALID_ARGS; + } + + #if !defined(MA_NO_FLAC) + { + *pCursor = pFlac->dr->currentPCMFrame; + + return MA_SUCCESS; + } + #else + { + /* flac is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_flac_get_length_in_pcm_frames(ma_flac* pFlac, ma_uint64* pLength) +{ + if (pLength == NULL) { + return MA_INVALID_ARGS; + } + + *pLength = 0; /* Safety. */ + + if (pFlac == NULL) { + return MA_INVALID_ARGS; + } + + #if !defined(MA_NO_FLAC) + { + *pLength = pFlac->dr->totalPCMFrameCount; + + return MA_SUCCESS; + } + #else + { + /* flac is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + return MA_NOT_IMPLEMENTED; + } + #endif +} + + +static ma_result ma_decoding_backend_init__flac(void* pUserData, ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend) +{ + ma_result result; + ma_flac* pFlac; + + (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */ + + /* For now we're just allocating the decoder backend on the heap. */ + pFlac = (ma_flac*)ma_malloc(sizeof(*pFlac), pAllocationCallbacks); + if (pFlac == NULL) { + return MA_OUT_OF_MEMORY; + } + + result = ma_flac_init(onRead, onSeek, onTell, pReadSeekTellUserData, pConfig, pAllocationCallbacks, pFlac); + if (result != MA_SUCCESS) { + ma_free(pFlac, pAllocationCallbacks); + return result; + } + + *ppBackend = pFlac; + + return MA_SUCCESS; +} + +static ma_result ma_decoding_backend_init_file__flac(void* pUserData, const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend) +{ + ma_result result; + ma_flac* pFlac; + + (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */ + + /* For now we're just allocating the decoder backend on the heap. */ + pFlac = (ma_flac*)ma_malloc(sizeof(*pFlac), pAllocationCallbacks); + if (pFlac == NULL) { + return MA_OUT_OF_MEMORY; + } + + result = ma_flac_init_file(pFilePath, pConfig, pAllocationCallbacks, pFlac); + if (result != MA_SUCCESS) { + ma_free(pFlac, pAllocationCallbacks); + return result; + } + + *ppBackend = pFlac; + + return MA_SUCCESS; +} + +static ma_result ma_decoding_backend_init_file_w__flac(void* pUserData, const wchar_t* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend) +{ + ma_result result; + ma_flac* pFlac; + + (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */ + + /* For now we're just allocating the decoder backend on the heap. */ + pFlac = (ma_flac*)ma_malloc(sizeof(*pFlac), pAllocationCallbacks); + if (pFlac == NULL) { + return MA_OUT_OF_MEMORY; + } + + result = ma_flac_init_file_w(pFilePath, pConfig, pAllocationCallbacks, pFlac); + if (result != MA_SUCCESS) { + ma_free(pFlac, pAllocationCallbacks); + return result; + } + + *ppBackend = pFlac; + + return MA_SUCCESS; +} + +static ma_result ma_decoding_backend_init_memory__flac(void* pUserData, const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend) +{ + ma_result result; + ma_flac* pFlac; + + (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */ + + /* For now we're just allocating the decoder backend on the heap. */ + pFlac = (ma_flac*)ma_malloc(sizeof(*pFlac), pAllocationCallbacks); + if (pFlac == NULL) { + return MA_OUT_OF_MEMORY; + } + + result = ma_flac_init_memory(pData, dataSize, pConfig, pAllocationCallbacks, pFlac); + if (result != MA_SUCCESS) { + ma_free(pFlac, pAllocationCallbacks); + return result; + } + + *ppBackend = pFlac; + + return MA_SUCCESS; +} + +static void ma_decoding_backend_uninit__flac(void* pUserData, ma_data_source* pBackend, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_flac* pFlac = (ma_flac*)pBackend; + + (void)pUserData; + + ma_flac_uninit(pFlac, pAllocationCallbacks); + ma_free(pFlac, pAllocationCallbacks); +} + +static ma_decoding_backend_vtable g_ma_decoding_backend_vtable_flac = +{ + ma_decoding_backend_init__flac, + ma_decoding_backend_init_file__flac, + ma_decoding_backend_init_file_w__flac, + ma_decoding_backend_init_memory__flac, + ma_decoding_backend_uninit__flac +}; + +static ma_result ma_decoder_init_flac__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + return ma_decoder_init_from_vtable__internal(&g_ma_decoding_backend_vtable_flac, NULL, pConfig, pDecoder); +} + +static ma_result ma_decoder_init_flac_from_file__internal(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + return ma_decoder_init_from_file__internal(&g_ma_decoding_backend_vtable_flac, NULL, pFilePath, pConfig, pDecoder); +} + +static ma_result ma_decoder_init_flac_from_file_w__internal(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + return ma_decoder_init_from_file_w__internal(&g_ma_decoding_backend_vtable_flac, NULL, pFilePath, pConfig, pDecoder); +} + +static ma_result ma_decoder_init_flac_from_memory__internal(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + return ma_decoder_init_from_memory__internal(&g_ma_decoding_backend_vtable_flac, NULL, pData, dataSize, pConfig, pDecoder); +} +#endif /* ma_dr_flac_h */ + +/* MP3 */ +#ifdef ma_dr_mp3_h +#define MA_HAS_MP3 + +typedef struct +{ + ma_data_source_base ds; + ma_read_proc onRead; + ma_seek_proc onSeek; + ma_tell_proc onTell; + void* pReadSeekTellUserData; + ma_format format; /* Can be f32 or s16. */ +#if !defined(MA_NO_MP3) + ma_dr_mp3 dr; + ma_uint32 seekPointCount; + ma_dr_mp3_seek_point* pSeekPoints; /* Only used if seek table generation is used. */ +#endif +} ma_mp3; + +MA_API ma_result ma_mp3_init(ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_mp3* pMP3); +MA_API ma_result ma_mp3_init_file(const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_mp3* pMP3); +MA_API ma_result ma_mp3_init_file_w(const wchar_t* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_mp3* pMP3); +MA_API ma_result ma_mp3_init_memory(const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_mp3* pMP3); +MA_API void ma_mp3_uninit(ma_mp3* pMP3, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_mp3_read_pcm_frames(ma_mp3* pMP3, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead); +MA_API ma_result ma_mp3_seek_to_pcm_frame(ma_mp3* pMP3, ma_uint64 frameIndex); +MA_API ma_result ma_mp3_get_data_format(ma_mp3* pMP3, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap); +MA_API ma_result ma_mp3_get_cursor_in_pcm_frames(ma_mp3* pMP3, ma_uint64* pCursor); +MA_API ma_result ma_mp3_get_length_in_pcm_frames(ma_mp3* pMP3, ma_uint64* pLength); + + +static ma_result ma_mp3_ds_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + return ma_mp3_read_pcm_frames((ma_mp3*)pDataSource, pFramesOut, frameCount, pFramesRead); +} + +static ma_result ma_mp3_ds_seek(ma_data_source* pDataSource, ma_uint64 frameIndex) +{ + return ma_mp3_seek_to_pcm_frame((ma_mp3*)pDataSource, frameIndex); +} + +static ma_result ma_mp3_ds_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + return ma_mp3_get_data_format((ma_mp3*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap); +} + +static ma_result ma_mp3_ds_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor) +{ + return ma_mp3_get_cursor_in_pcm_frames((ma_mp3*)pDataSource, pCursor); +} + +static ma_result ma_mp3_ds_get_length(ma_data_source* pDataSource, ma_uint64* pLength) +{ + return ma_mp3_get_length_in_pcm_frames((ma_mp3*)pDataSource, pLength); +} + +static ma_data_source_vtable g_ma_mp3_ds_vtable = +{ + ma_mp3_ds_read, + ma_mp3_ds_seek, + ma_mp3_ds_get_data_format, + ma_mp3_ds_get_cursor, + ma_mp3_ds_get_length, + NULL, /* onSetLooping */ + 0 +}; + + +#if !defined(MA_NO_MP3) +static size_t ma_mp3_dr_callback__read(void* pUserData, void* pBufferOut, size_t bytesToRead) +{ + ma_mp3* pMP3 = (ma_mp3*)pUserData; + ma_result result; + size_t bytesRead; + + MA_ASSERT(pMP3 != NULL); + + result = pMP3->onRead(pMP3->pReadSeekTellUserData, pBufferOut, bytesToRead, &bytesRead); + (void)result; + + return bytesRead; +} + +static ma_bool32 ma_mp3_dr_callback__seek(void* pUserData, int offset, ma_dr_mp3_seek_origin origin) +{ + ma_mp3* pMP3 = (ma_mp3*)pUserData; + ma_result result; + ma_seek_origin maSeekOrigin; + + MA_ASSERT(pMP3 != NULL); + + maSeekOrigin = ma_seek_origin_start; + if (origin == ma_dr_mp3_seek_origin_current) { + maSeekOrigin = ma_seek_origin_current; + } + + result = pMP3->onSeek(pMP3->pReadSeekTellUserData, offset, maSeekOrigin); + if (result != MA_SUCCESS) { + return MA_FALSE; + } + + return MA_TRUE; +} +#endif + +static ma_result ma_mp3_init_internal(const ma_decoding_backend_config* pConfig, ma_mp3* pMP3) +{ + ma_result result; + ma_data_source_config dataSourceConfig; + + if (pMP3 == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pMP3); + pMP3->format = ma_format_f32; /* f32 by default. */ + + if (pConfig != NULL && (pConfig->preferredFormat == ma_format_f32 || pConfig->preferredFormat == ma_format_s16)) { + pMP3->format = pConfig->preferredFormat; + } else { + /* Getting here means something other than f32 and s16 was specified. Just leave this unset to use the default format. */ + } + + dataSourceConfig = ma_data_source_config_init(); + dataSourceConfig.vtable = &g_ma_mp3_ds_vtable; + + result = ma_data_source_init(&dataSourceConfig, &pMP3->ds); + if (result != MA_SUCCESS) { + return result; /* Failed to initialize the base data source. */ + } + + return MA_SUCCESS; +} + +static ma_result ma_mp3_generate_seek_table(ma_mp3* pMP3, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_bool32 mp3Result; + ma_uint32 seekPointCount = 0; + ma_dr_mp3_seek_point* pSeekPoints = NULL; + + MA_ASSERT(pMP3 != NULL); + MA_ASSERT(pConfig != NULL); + + seekPointCount = pConfig->seekPointCount; + if (seekPointCount > 0) { + pSeekPoints = (ma_dr_mp3_seek_point*)ma_malloc(sizeof(*pMP3->pSeekPoints) * seekPointCount, pAllocationCallbacks); + if (pSeekPoints == NULL) { + return MA_OUT_OF_MEMORY; + } + } + + mp3Result = ma_dr_mp3_calculate_seek_points(&pMP3->dr, &seekPointCount, pSeekPoints); + if (mp3Result != MA_TRUE) { + ma_free(pSeekPoints, pAllocationCallbacks); + return MA_ERROR; + } + + mp3Result = ma_dr_mp3_bind_seek_table(&pMP3->dr, seekPointCount, pSeekPoints); + if (mp3Result != MA_TRUE) { + ma_free(pSeekPoints, pAllocationCallbacks); + return MA_ERROR; + } + + pMP3->seekPointCount = seekPointCount; + pMP3->pSeekPoints = pSeekPoints; + + return MA_SUCCESS; +} + +static ma_result ma_mp3_post_init(ma_mp3* pMP3, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_result result; + + result = ma_mp3_generate_seek_table(pMP3, pConfig, pAllocationCallbacks); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_mp3_init(ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_mp3* pMP3) +{ + ma_result result; + + result = ma_mp3_init_internal(pConfig, pMP3); + if (result != MA_SUCCESS) { + return result; + } + + if (onRead == NULL || onSeek == NULL) { + return MA_INVALID_ARGS; /* onRead and onSeek are mandatory. */ + } + + pMP3->onRead = onRead; + pMP3->onSeek = onSeek; + pMP3->onTell = onTell; + pMP3->pReadSeekTellUserData = pReadSeekTellUserData; + + #if !defined(MA_NO_MP3) + { + ma_bool32 mp3Result; + + mp3Result = ma_dr_mp3_init(&pMP3->dr, ma_mp3_dr_callback__read, ma_mp3_dr_callback__seek, pMP3, pAllocationCallbacks); + if (mp3Result != MA_TRUE) { + return MA_INVALID_FILE; + } + + ma_mp3_post_init(pMP3, pConfig, pAllocationCallbacks); + + return MA_SUCCESS; + } + #else + { + /* mp3 is disabled. */ + (void)pAllocationCallbacks; + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_mp3_init_file(const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_mp3* pMP3) +{ + ma_result result; + + result = ma_mp3_init_internal(pConfig, pMP3); + if (result != MA_SUCCESS) { + return result; + } + + #if !defined(MA_NO_MP3) + { + ma_bool32 mp3Result; + + mp3Result = ma_dr_mp3_init_file(&pMP3->dr, pFilePath, pAllocationCallbacks); + if (mp3Result != MA_TRUE) { + return MA_INVALID_FILE; + } + + ma_mp3_post_init(pMP3, pConfig, pAllocationCallbacks); + + return MA_SUCCESS; + } + #else + { + /* mp3 is disabled. */ + (void)pFilePath; + (void)pAllocationCallbacks; + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_mp3_init_file_w(const wchar_t* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_mp3* pMP3) +{ + ma_result result; + + result = ma_mp3_init_internal(pConfig, pMP3); + if (result != MA_SUCCESS) { + return result; + } + + #if !defined(MA_NO_MP3) + { + ma_bool32 mp3Result; + + mp3Result = ma_dr_mp3_init_file_w(&pMP3->dr, pFilePath, pAllocationCallbacks); + if (mp3Result != MA_TRUE) { + return MA_INVALID_FILE; + } + + ma_mp3_post_init(pMP3, pConfig, pAllocationCallbacks); + + return MA_SUCCESS; + } + #else + { + /* mp3 is disabled. */ + (void)pFilePath; + (void)pAllocationCallbacks; + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_mp3_init_memory(const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_mp3* pMP3) +{ + ma_result result; + + result = ma_mp3_init_internal(pConfig, pMP3); + if (result != MA_SUCCESS) { + return result; + } + + #if !defined(MA_NO_MP3) + { + ma_bool32 mp3Result; + + mp3Result = ma_dr_mp3_init_memory(&pMP3->dr, pData, dataSize, pAllocationCallbacks); + if (mp3Result != MA_TRUE) { + return MA_INVALID_FILE; + } + + ma_mp3_post_init(pMP3, pConfig, pAllocationCallbacks); + + return MA_SUCCESS; + } + #else + { + /* mp3 is disabled. */ + (void)pData; + (void)dataSize; + (void)pAllocationCallbacks; + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API void ma_mp3_uninit(ma_mp3* pMP3, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pMP3 == NULL) { + return; + } + + #if !defined(MA_NO_MP3) + { + ma_dr_mp3_uninit(&pMP3->dr); + } + #else + { + /* mp3 is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + } + #endif + + /* Seek points need to be freed after the MP3 decoder has been uninitialized to ensure they're no longer being referenced. */ + ma_free(pMP3->pSeekPoints, pAllocationCallbacks); + + ma_data_source_uninit(&pMP3->ds); +} + +MA_API ma_result ma_mp3_read_pcm_frames(ma_mp3* pMP3, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + if (pFramesRead != NULL) { + *pFramesRead = 0; + } + + if (frameCount == 0) { + return MA_INVALID_ARGS; + } + + if (pMP3 == NULL) { + return MA_INVALID_ARGS; + } + + #if !defined(MA_NO_MP3) + { + /* We always use floating point format. */ + ma_result result = MA_SUCCESS; /* Must be initialized to MA_SUCCESS. */ + ma_uint64 totalFramesRead = 0; + ma_format format; + + ma_mp3_get_data_format(pMP3, &format, NULL, NULL, NULL, 0); + + switch (format) + { + case ma_format_f32: + { + totalFramesRead = ma_dr_mp3_read_pcm_frames_f32(&pMP3->dr, frameCount, (float*)pFramesOut); + } break; + + case ma_format_s16: + { + totalFramesRead = ma_dr_mp3_read_pcm_frames_s16(&pMP3->dr, frameCount, (ma_int16*)pFramesOut); + } break; + + case ma_format_u8: + case ma_format_s24: + case ma_format_s32: + case ma_format_unknown: + default: + { + return MA_INVALID_OPERATION; + }; + } + + /* In the future we'll update ma_dr_mp3 to return MA_AT_END for us. */ + if (totalFramesRead == 0) { + result = MA_AT_END; + } + + if (pFramesRead != NULL) { + *pFramesRead = totalFramesRead; + } + + return result; + } + #else + { + /* mp3 is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + + (void)pFramesOut; + (void)frameCount; + (void)pFramesRead; + + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_mp3_seek_to_pcm_frame(ma_mp3* pMP3, ma_uint64 frameIndex) +{ + if (pMP3 == NULL) { + return MA_INVALID_ARGS; + } + + #if !defined(MA_NO_MP3) + { + ma_bool32 mp3Result; + + mp3Result = ma_dr_mp3_seek_to_pcm_frame(&pMP3->dr, frameIndex); + if (mp3Result != MA_TRUE) { + return MA_ERROR; + } + + return MA_SUCCESS; + } + #else + { + /* mp3 is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + + (void)frameIndex; + + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_mp3_get_data_format(ma_mp3* pMP3, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + /* Defaults for safety. */ + if (pFormat != NULL) { + *pFormat = ma_format_unknown; + } + if (pChannels != NULL) { + *pChannels = 0; + } + if (pSampleRate != NULL) { + *pSampleRate = 0; + } + if (pChannelMap != NULL) { + MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap); + } + + if (pMP3 == NULL) { + return MA_INVALID_OPERATION; + } + + if (pFormat != NULL) { + *pFormat = pMP3->format; + } + + #if !defined(MA_NO_MP3) + { + if (pChannels != NULL) { + *pChannels = pMP3->dr.channels; + } + + if (pSampleRate != NULL) { + *pSampleRate = pMP3->dr.sampleRate; + } + + if (pChannelMap != NULL) { + ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pMP3->dr.channels); + } + + return MA_SUCCESS; + } + #else + { + /* mp3 is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_mp3_get_cursor_in_pcm_frames(ma_mp3* pMP3, ma_uint64* pCursor) +{ + if (pCursor == NULL) { + return MA_INVALID_ARGS; + } + + *pCursor = 0; /* Safety. */ + + if (pMP3 == NULL) { + return MA_INVALID_ARGS; + } + + #if !defined(MA_NO_MP3) + { + *pCursor = pMP3->dr.currentPCMFrame; + + return MA_SUCCESS; + } + #else + { + /* mp3 is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_mp3_get_length_in_pcm_frames(ma_mp3* pMP3, ma_uint64* pLength) +{ + if (pLength == NULL) { + return MA_INVALID_ARGS; + } + + *pLength = 0; /* Safety. */ + + if (pMP3 == NULL) { + return MA_INVALID_ARGS; + } + + #if !defined(MA_NO_MP3) + { + *pLength = ma_dr_mp3_get_pcm_frame_count(&pMP3->dr); + + return MA_SUCCESS; + } + #else + { + /* mp3 is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + return MA_NOT_IMPLEMENTED; + } + #endif +} + + +static ma_result ma_decoding_backend_init__mp3(void* pUserData, ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend) +{ + ma_result result; + ma_mp3* pMP3; + + (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */ + + /* For now we're just allocating the decoder backend on the heap. */ + pMP3 = (ma_mp3*)ma_malloc(sizeof(*pMP3), pAllocationCallbacks); + if (pMP3 == NULL) { + return MA_OUT_OF_MEMORY; + } + + result = ma_mp3_init(onRead, onSeek, onTell, pReadSeekTellUserData, pConfig, pAllocationCallbacks, pMP3); + if (result != MA_SUCCESS) { + ma_free(pMP3, pAllocationCallbacks); + return result; + } + + *ppBackend = pMP3; + + return MA_SUCCESS; +} + +static ma_result ma_decoding_backend_init_file__mp3(void* pUserData, const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend) +{ + ma_result result; + ma_mp3* pMP3; + + (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */ + + /* For now we're just allocating the decoder backend on the heap. */ + pMP3 = (ma_mp3*)ma_malloc(sizeof(*pMP3), pAllocationCallbacks); + if (pMP3 == NULL) { + return MA_OUT_OF_MEMORY; + } + + result = ma_mp3_init_file(pFilePath, pConfig, pAllocationCallbacks, pMP3); + if (result != MA_SUCCESS) { + ma_free(pMP3, pAllocationCallbacks); + return result; + } + + *ppBackend = pMP3; + + return MA_SUCCESS; +} + +static ma_result ma_decoding_backend_init_file_w__mp3(void* pUserData, const wchar_t* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend) +{ + ma_result result; + ma_mp3* pMP3; + + (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */ + + /* For now we're just allocating the decoder backend on the heap. */ + pMP3 = (ma_mp3*)ma_malloc(sizeof(*pMP3), pAllocationCallbacks); + if (pMP3 == NULL) { + return MA_OUT_OF_MEMORY; + } + + result = ma_mp3_init_file_w(pFilePath, pConfig, pAllocationCallbacks, pMP3); + if (result != MA_SUCCESS) { + ma_free(pMP3, pAllocationCallbacks); + return result; + } + + *ppBackend = pMP3; + + return MA_SUCCESS; +} + +static ma_result ma_decoding_backend_init_memory__mp3(void* pUserData, const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend) +{ + ma_result result; + ma_mp3* pMP3; + + (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */ + + /* For now we're just allocating the decoder backend on the heap. */ + pMP3 = (ma_mp3*)ma_malloc(sizeof(*pMP3), pAllocationCallbacks); + if (pMP3 == NULL) { + return MA_OUT_OF_MEMORY; + } + + result = ma_mp3_init_memory(pData, dataSize, pConfig, pAllocationCallbacks, pMP3); + if (result != MA_SUCCESS) { + ma_free(pMP3, pAllocationCallbacks); + return result; + } + + *ppBackend = pMP3; + + return MA_SUCCESS; +} + +static void ma_decoding_backend_uninit__mp3(void* pUserData, ma_data_source* pBackend, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_mp3* pMP3 = (ma_mp3*)pBackend; + + (void)pUserData; + + ma_mp3_uninit(pMP3, pAllocationCallbacks); + ma_free(pMP3, pAllocationCallbacks); +} + +static ma_decoding_backend_vtable g_ma_decoding_backend_vtable_mp3 = +{ + ma_decoding_backend_init__mp3, + ma_decoding_backend_init_file__mp3, + ma_decoding_backend_init_file_w__mp3, + ma_decoding_backend_init_memory__mp3, + ma_decoding_backend_uninit__mp3 +}; + +static ma_result ma_decoder_init_mp3__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + return ma_decoder_init_from_vtable__internal(&g_ma_decoding_backend_vtable_mp3, NULL, pConfig, pDecoder); +} + +static ma_result ma_decoder_init_mp3_from_file__internal(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + return ma_decoder_init_from_file__internal(&g_ma_decoding_backend_vtable_mp3, NULL, pFilePath, pConfig, pDecoder); +} + +static ma_result ma_decoder_init_mp3_from_file_w__internal(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + return ma_decoder_init_from_file_w__internal(&g_ma_decoding_backend_vtable_mp3, NULL, pFilePath, pConfig, pDecoder); +} + +static ma_result ma_decoder_init_mp3_from_memory__internal(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + return ma_decoder_init_from_memory__internal(&g_ma_decoding_backend_vtable_mp3, NULL, pData, dataSize, pConfig, pDecoder); +} +#endif /* ma_dr_mp3_h */ + +/* 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 +{ + ma_data_source_base ds; + ma_read_proc onRead; + ma_seek_proc onSeek; + ma_tell_proc onTell; + void* pReadSeekTellUserData; + ma_allocation_callbacks allocationCallbacks; /* Store the allocation callbacks within the structure because we may need to dynamically expand a buffer in ma_stbvorbis_read_pcm_frames() when using push mode. */ + ma_format format; /* Only f32 is allowed with stb_vorbis. */ + ma_uint32 channels; + ma_uint32 sampleRate; + ma_uint64 cursor; +#if !defined(MA_NO_VORBIS) + stb_vorbis* stb; + ma_bool32 usingPushMode; + struct + { + ma_uint8* pData; + size_t dataSize; + size_t dataCapacity; + size_t audioStartOffsetInBytes; + ma_uint32 framesConsumed; /* The number of frames consumed in ppPacketData. */ + ma_uint32 framesRemaining; /* The number of frames remaining in ppPacketData. */ + float** ppPacketData; + } push; +#endif +} ma_stbvorbis; + +MA_API ma_result ma_stbvorbis_init(ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_stbvorbis* pVorbis); +MA_API ma_result ma_stbvorbis_init_file(const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_stbvorbis* pVorbis); +MA_API ma_result ma_stbvorbis_init_memory(const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_stbvorbis* pVorbis); +MA_API void ma_stbvorbis_uninit(ma_stbvorbis* pVorbis, const ma_allocation_callbacks* pAllocationCallbacks); +MA_API ma_result ma_stbvorbis_read_pcm_frames(ma_stbvorbis* pVorbis, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead); +MA_API ma_result ma_stbvorbis_seek_to_pcm_frame(ma_stbvorbis* pVorbis, ma_uint64 frameIndex); +MA_API ma_result ma_stbvorbis_get_data_format(ma_stbvorbis* pVorbis, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap); +MA_API ma_result ma_stbvorbis_get_cursor_in_pcm_frames(ma_stbvorbis* pVorbis, ma_uint64* pCursor); +MA_API ma_result ma_stbvorbis_get_length_in_pcm_frames(ma_stbvorbis* pVorbis, ma_uint64* pLength); + + +static ma_result ma_stbvorbis_ds_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + return ma_stbvorbis_read_pcm_frames((ma_stbvorbis*)pDataSource, pFramesOut, frameCount, pFramesRead); +} + +static ma_result ma_stbvorbis_ds_seek(ma_data_source* pDataSource, ma_uint64 frameIndex) +{ + return ma_stbvorbis_seek_to_pcm_frame((ma_stbvorbis*)pDataSource, frameIndex); +} + +static ma_result ma_stbvorbis_ds_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + return ma_stbvorbis_get_data_format((ma_stbvorbis*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap); +} + +static ma_result ma_stbvorbis_ds_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor) +{ + return ma_stbvorbis_get_cursor_in_pcm_frames((ma_stbvorbis*)pDataSource, pCursor); +} + +static ma_result ma_stbvorbis_ds_get_length(ma_data_source* pDataSource, ma_uint64* pLength) +{ + return ma_stbvorbis_get_length_in_pcm_frames((ma_stbvorbis*)pDataSource, pLength); +} + +static ma_data_source_vtable g_ma_stbvorbis_ds_vtable = +{ + ma_stbvorbis_ds_read, + ma_stbvorbis_ds_seek, + ma_stbvorbis_ds_get_data_format, + ma_stbvorbis_ds_get_cursor, + ma_stbvorbis_ds_get_length, + NULL, /* onSetLooping */ + 0 +}; + + +static ma_result ma_stbvorbis_init_internal(const ma_decoding_backend_config* pConfig, ma_stbvorbis* pVorbis) +{ + ma_result result; + ma_data_source_config dataSourceConfig; + + (void)pConfig; + + if (pVorbis == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pVorbis); + pVorbis->format = ma_format_f32; /* Only supporting f32. */ + + dataSourceConfig = ma_data_source_config_init(); + dataSourceConfig.vtable = &g_ma_stbvorbis_ds_vtable; + + result = ma_data_source_init(&dataSourceConfig, &pVorbis->ds); + if (result != MA_SUCCESS) { + return result; /* Failed to initialize the base data source. */ + } + + return MA_SUCCESS; +} + +#if !defined(MA_NO_VORBIS) +static ma_result ma_stbvorbis_post_init(ma_stbvorbis* pVorbis) +{ + stb_vorbis_info info; + + MA_ASSERT(pVorbis != NULL); + + info = stb_vorbis_get_info(pVorbis->stb); + + pVorbis->channels = info.channels; + pVorbis->sampleRate = info.sample_rate; + + return MA_SUCCESS; +} + +static ma_result ma_stbvorbis_init_internal_decoder_push(ma_stbvorbis* pVorbis) +{ + ma_result result; + stb_vorbis* stb; + size_t dataSize = 0; + size_t dataCapacity = 0; + ma_uint8* pData = NULL; /* <-- Must be initialized to NULL. */ + + for (;;) { + int vorbisError; + int consumedDataSize; /* <-- Fill by stb_vorbis_open_pushdata(). */ + size_t bytesRead; + ma_uint8* pNewData; + + /* Allocate memory for the new chunk. */ + dataCapacity += MA_VORBIS_DATA_CHUNK_SIZE; + pNewData = (ma_uint8*)ma_realloc(pData, dataCapacity, &pVorbis->allocationCallbacks); + if (pNewData == NULL) { + ma_free(pData, &pVorbis->allocationCallbacks); + return MA_OUT_OF_MEMORY; + } + + pData = pNewData; + + /* Read in the next chunk. */ + result = pVorbis->onRead(pVorbis->pReadSeekTellUserData, ma_offset_ptr(pData, dataSize), (dataCapacity - dataSize), &bytesRead); + dataSize += bytesRead; + + if (result != MA_SUCCESS) { + ma_free(pData, &pVorbis->allocationCallbacks); + return result; + } + + /* We have a maximum of 31 bits with stb_vorbis. */ + if (dataSize > INT_MAX) { + ma_free(pData, &pVorbis->allocationCallbacks); + return MA_TOO_BIG; + } + + stb = stb_vorbis_open_pushdata(pData, (int)dataSize, &consumedDataSize, &vorbisError, NULL); + if (stb != NULL) { + /* + Successfully opened the Vorbis decoder. We might have some leftover unprocessed + data so we'll need to move that down to the front. + */ + dataSize -= (size_t)consumedDataSize; /* Consume the data. */ + MA_MOVE_MEMORY(pData, ma_offset_ptr(pData, consumedDataSize), dataSize); + + /* + We need to track the start point so we can seek back to the start of the audio + data when seeking. + */ + pVorbis->push.audioStartOffsetInBytes = consumedDataSize; + + break; + } else { + /* Failed to open the decoder. */ + if (vorbisError == VORBIS_need_more_data) { + continue; + } else { + ma_free(pData, &pVorbis->allocationCallbacks); + return MA_ERROR; /* Failed to open the stb_vorbis decoder. */ + } + } + } + + MA_ASSERT(stb != NULL); + pVorbis->stb = stb; + pVorbis->push.pData = pData; + pVorbis->push.dataSize = dataSize; + pVorbis->push.dataCapacity = dataCapacity; + + return MA_SUCCESS; +} +#endif + +MA_API ma_result ma_stbvorbis_init(ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_stbvorbis* pVorbis) +{ + ma_result result; + + result = ma_stbvorbis_init_internal(pConfig, pVorbis); + if (result != MA_SUCCESS) { + return result; + } + + if (onRead == NULL || onSeek == NULL) { + return MA_INVALID_ARGS; /* onRead and onSeek are mandatory. */ + } + + pVorbis->onRead = onRead; + pVorbis->onSeek = onSeek; + pVorbis->onTell = onTell; + pVorbis->pReadSeekTellUserData = pReadSeekTellUserData; + ma_allocation_callbacks_init_copy(&pVorbis->allocationCallbacks, pAllocationCallbacks); + + #if !defined(MA_NO_VORBIS) + { + /* + stb_vorbis lacks a callback based API for it's pulling API which means we're stuck with the + pushing API. In order for us to be able to successfully initialize the decoder we need to + supply it with enough data. We need to keep loading data until we have enough. + */ + result = ma_stbvorbis_init_internal_decoder_push(pVorbis); + if (result != MA_SUCCESS) { + return result; + } + + pVorbis->usingPushMode = MA_TRUE; + + result = ma_stbvorbis_post_init(pVorbis); + if (result != MA_SUCCESS) { + stb_vorbis_close(pVorbis->stb); + ma_free(pVorbis->push.pData, pAllocationCallbacks); + return result; + } + + return MA_SUCCESS; + } + #else + { + /* vorbis is disabled. */ + (void)pAllocationCallbacks; + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_stbvorbis_init_file(const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_stbvorbis* pVorbis) +{ + ma_result result; + + result = ma_stbvorbis_init_internal(pConfig, pVorbis); + if (result != MA_SUCCESS) { + return result; + } + + #if !defined(MA_NO_VORBIS) + { + (void)pAllocationCallbacks; /* Don't know how to make use of this with stb_vorbis. */ + + /* We can use stb_vorbis' pull mode for file based streams. */ + pVorbis->stb = stb_vorbis_open_filename(pFilePath, NULL, NULL); + if (pVorbis->stb == NULL) { + return MA_INVALID_FILE; + } + + pVorbis->usingPushMode = MA_FALSE; + + result = ma_stbvorbis_post_init(pVorbis); + if (result != MA_SUCCESS) { + stb_vorbis_close(pVorbis->stb); + return result; + } + + return MA_SUCCESS; + } + #else + { + /* vorbis is disabled. */ + (void)pFilePath; + (void)pAllocationCallbacks; + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_stbvorbis_init_memory(const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_stbvorbis* pVorbis) +{ + ma_result result; + + result = ma_stbvorbis_init_internal(pConfig, pVorbis); + if (result != MA_SUCCESS) { + return result; + } + + #if !defined(MA_NO_VORBIS) + { + (void)pAllocationCallbacks; + + /* stb_vorbis uses an int as it's size specifier, restricting it to 32-bit even on 64-bit systems. *sigh*. */ + if (dataSize > INT_MAX) { + return MA_TOO_BIG; + } + + pVorbis->stb = stb_vorbis_open_memory((const unsigned char*)pData, (int)dataSize, NULL, NULL); + if (pVorbis->stb == NULL) { + return MA_INVALID_FILE; + } + + pVorbis->usingPushMode = MA_FALSE; + + result = ma_stbvorbis_post_init(pVorbis); + if (result != MA_SUCCESS) { + stb_vorbis_close(pVorbis->stb); + return result; + } + + return MA_SUCCESS; + } + #else + { + /* vorbis is disabled. */ + (void)pData; + (void)dataSize; + (void)pAllocationCallbacks; + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API void ma_stbvorbis_uninit(ma_stbvorbis* pVorbis, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pVorbis == NULL) { + return; + } + + #if !defined(MA_NO_VORBIS) + { + stb_vorbis_close(pVorbis->stb); + + /* We'll have to clear some memory if we're using push mode. */ + if (pVorbis->usingPushMode) { + ma_free(pVorbis->push.pData, pAllocationCallbacks); + } + } + #else + { + /* vorbis is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + } + #endif + + ma_data_source_uninit(&pVorbis->ds); +} + +MA_API ma_result ma_stbvorbis_read_pcm_frames(ma_stbvorbis* pVorbis, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + if (pFramesRead != NULL) { + *pFramesRead = 0; + } + + if (frameCount == 0) { + return MA_INVALID_ARGS; + } + + if (pVorbis == NULL) { + return MA_INVALID_ARGS; + } + + #if !defined(MA_NO_VORBIS) + { + /* We always use floating point format. */ + ma_result result = MA_SUCCESS; /* Must be initialized to MA_SUCCESS. */ + ma_uint64 totalFramesRead = 0; + ma_format format; + ma_uint32 channels; + + ma_stbvorbis_get_data_format(pVorbis, &format, &channels, NULL, NULL, 0); + + if (format == ma_format_f32) { + /* We read differently depending on whether or not we're using push mode. */ + if (pVorbis->usingPushMode) { + /* Push mode. This is the complex case. */ + float* pFramesOutF32 = (float*)pFramesOut; + + while (totalFramesRead < frameCount) { + /* The first thing to do is read from any already-cached frames. */ + ma_uint32 framesToReadFromCache = (ma_uint32)ma_min(pVorbis->push.framesRemaining, (frameCount - totalFramesRead)); /* Safe cast because pVorbis->framesRemaining is 32-bit. */ + + /* The output pointer can be null in which case we just treate it as a seek. */ + if (pFramesOut != NULL) { + ma_uint64 iFrame; + for (iFrame = 0; iFrame < framesToReadFromCache; iFrame += 1) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < pVorbis->channels; iChannel += 1) { + pFramesOutF32[iChannel] = pVorbis->push.ppPacketData[iChannel][pVorbis->push.framesConsumed + iFrame]; + } + + pFramesOutF32 += pVorbis->channels; + } + } + + /* Update pointers and counters. */ + pVorbis->push.framesConsumed += framesToReadFromCache; + pVorbis->push.framesRemaining -= framesToReadFromCache; + totalFramesRead += framesToReadFromCache; + + /* Don't bother reading any more frames right now if we've just finished loading. */ + if (totalFramesRead == frameCount) { + break; + } + + MA_ASSERT(pVorbis->push.framesRemaining == 0); + + /* Getting here means we've run out of cached frames. We'll need to load some more. */ + for (;;) { + int samplesRead = 0; + int consumedDataSize; + + /* We need to case dataSize to an int, so make sure we can do it safely. */ + if (pVorbis->push.dataSize > INT_MAX) { + break; /* Too big. */ + } + + consumedDataSize = stb_vorbis_decode_frame_pushdata(pVorbis->stb, pVorbis->push.pData, (int)pVorbis->push.dataSize, NULL, &pVorbis->push.ppPacketData, &samplesRead); + if (consumedDataSize != 0) { + /* Successfully decoded a Vorbis frame. Consume the data. */ + pVorbis->push.dataSize -= (size_t)consumedDataSize; + MA_MOVE_MEMORY(pVorbis->push.pData, ma_offset_ptr(pVorbis->push.pData, consumedDataSize), pVorbis->push.dataSize); + + pVorbis->push.framesConsumed = 0; + pVorbis->push.framesRemaining = samplesRead; + + break; + } else { + /* Not enough data. Read more. */ + size_t bytesRead; + + /* Expand the data buffer if necessary. */ + if (pVorbis->push.dataCapacity == pVorbis->push.dataSize) { + size_t newCap = pVorbis->push.dataCapacity + MA_VORBIS_DATA_CHUNK_SIZE; + ma_uint8* pNewData; + + pNewData = (ma_uint8*)ma_realloc(pVorbis->push.pData, newCap, &pVorbis->allocationCallbacks); + if (pNewData == NULL) { + result = MA_OUT_OF_MEMORY; + break; + } + + pVorbis->push.pData = pNewData; + pVorbis->push.dataCapacity = newCap; + } + + /* We should have enough room to load some data. */ + result = pVorbis->onRead(pVorbis->pReadSeekTellUserData, ma_offset_ptr(pVorbis->push.pData, pVorbis->push.dataSize), (pVorbis->push.dataCapacity - pVorbis->push.dataSize), &bytesRead); + pVorbis->push.dataSize += bytesRead; + + if (result != MA_SUCCESS) { + break; /* Failed to read any data. Get out. */ + } + } + } + + /* If we don't have a success code at this point it means we've encounted an error or the end of the file has been reached (probably the latter). */ + if (result != MA_SUCCESS) { + break; + } + } + } else { + /* Pull mode. This is the simple case, but we still need to run in a loop because stb_vorbis loves using 32-bit instead of 64-bit. */ + while (totalFramesRead < frameCount) { + ma_uint64 framesRemaining = (frameCount - totalFramesRead); + int framesRead; + + if (framesRemaining > INT_MAX) { + framesRemaining = INT_MAX; + } + + framesRead = stb_vorbis_get_samples_float_interleaved(pVorbis->stb, channels, (float*)ma_offset_pcm_frames_ptr(pFramesOut, totalFramesRead, format, channels), (int)framesRemaining * channels); /* Safe cast. */ + totalFramesRead += framesRead; + + if (framesRead < (int)framesRemaining) { + break; /* Nothing left to read. Get out. */ + } + } + } + } else { + result = MA_INVALID_ARGS; + } + + pVorbis->cursor += totalFramesRead; + + if (totalFramesRead == 0) { + result = MA_AT_END; + } + + if (pFramesRead != NULL) { + *pFramesRead = totalFramesRead; + } + + if (result == MA_SUCCESS && totalFramesRead == 0) { + result = MA_AT_END; + } + + return result; + } + #else + { + /* vorbis is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + + (void)pFramesOut; + (void)frameCount; + (void)pFramesRead; + + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_stbvorbis_seek_to_pcm_frame(ma_stbvorbis* pVorbis, ma_uint64 frameIndex) +{ + if (pVorbis == NULL) { + return MA_INVALID_ARGS; + } + + #if !defined(MA_NO_VORBIS) + { + /* Different seeking methods depending on whether or not we're using push mode. */ + if (pVorbis->usingPushMode) { + /* Push mode. This is the complex case. */ + ma_result result; + float buffer[4096]; + + /* If we're seeking backwards, we need to seek back to the start and then brute-force forward. */ + if (frameIndex < pVorbis->cursor) { + if (frameIndex > 0x7FFFFFFF) { + return MA_INVALID_ARGS; /* Trying to seek beyond the 32-bit maximum of stb_vorbis. */ + } + + /* + This is wildly inefficient due to me having trouble getting sample exact seeking working + robustly with stb_vorbis_flush_pushdata(). The only way I can think to make this work + perfectly is to reinitialize the decoder. Note that we only enter this path when seeking + backwards. This will hopefully be removed once we get our own Vorbis decoder implemented. + */ + stb_vorbis_close(pVorbis->stb); + ma_free(pVorbis->push.pData, &pVorbis->allocationCallbacks); + + MA_ZERO_OBJECT(&pVorbis->push); + + /* Seek to the start of the file. */ + result = pVorbis->onSeek(pVorbis->pReadSeekTellUserData, 0, ma_seek_origin_start); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_stbvorbis_init_internal_decoder_push(pVorbis); + if (result != MA_SUCCESS) { + return result; + } + + /* At this point we should be sitting on the first frame. */ + pVorbis->cursor = 0; + } + + /* We're just brute-forcing this for now. */ + while (pVorbis->cursor < frameIndex) { + ma_uint64 framesRead; + ma_uint64 framesToRead = ma_countof(buffer)/pVorbis->channels; + if (framesToRead > (frameIndex - pVorbis->cursor)) { + framesToRead = (frameIndex - pVorbis->cursor); + } + + result = ma_stbvorbis_read_pcm_frames(pVorbis, buffer, framesToRead, &framesRead); + if (result != MA_SUCCESS) { + return result; + } + } + } else { + /* Pull mode. This is the simple case. */ + int vorbisResult; + + if (frameIndex > UINT_MAX) { + return MA_INVALID_ARGS; /* Trying to seek beyond the 32-bit maximum of stb_vorbis. */ + } + + vorbisResult = stb_vorbis_seek(pVorbis->stb, (unsigned int)frameIndex); /* Safe cast. */ + if (vorbisResult == 0) { + return MA_ERROR; /* See failed. */ + } + + pVorbis->cursor = frameIndex; + } + + return MA_SUCCESS; + } + #else + { + /* vorbis is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + + (void)frameIndex; + + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_stbvorbis_get_data_format(ma_stbvorbis* pVorbis, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + /* Defaults for safety. */ + if (pFormat != NULL) { + *pFormat = ma_format_unknown; + } + if (pChannels != NULL) { + *pChannels = 0; + } + if (pSampleRate != NULL) { + *pSampleRate = 0; + } + if (pChannelMap != NULL) { + MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap); + } + + if (pVorbis == NULL) { + return MA_INVALID_OPERATION; + } + + if (pFormat != NULL) { + *pFormat = pVorbis->format; + } + + #if !defined(MA_NO_VORBIS) + { + if (pChannels != NULL) { + *pChannels = pVorbis->channels; + } + + if (pSampleRate != NULL) { + *pSampleRate = pVorbis->sampleRate; + } + + if (pChannelMap != NULL) { + ma_channel_map_init_standard(ma_standard_channel_map_vorbis, pChannelMap, channelMapCap, pVorbis->channels); + } + + return MA_SUCCESS; + } + #else + { + /* vorbis is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_stbvorbis_get_cursor_in_pcm_frames(ma_stbvorbis* pVorbis, ma_uint64* pCursor) +{ + if (pCursor == NULL) { + return MA_INVALID_ARGS; + } + + *pCursor = 0; /* Safety. */ + + if (pVorbis == NULL) { + return MA_INVALID_ARGS; + } + + #if !defined(MA_NO_VORBIS) + { + *pCursor = pVorbis->cursor; + + return MA_SUCCESS; + } + #else + { + /* vorbis is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + return MA_NOT_IMPLEMENTED; + } + #endif +} + +MA_API ma_result ma_stbvorbis_get_length_in_pcm_frames(ma_stbvorbis* pVorbis, ma_uint64* pLength) +{ + if (pLength == NULL) { + return MA_INVALID_ARGS; + } + + *pLength = 0; /* Safety. */ + + if (pVorbis == NULL) { + return MA_INVALID_ARGS; + } + + #if !defined(MA_NO_VORBIS) + { + if (pVorbis->usingPushMode) { + *pLength = 0; /* I don't know of a good way to determine this reliably with stb_vorbis and push mode. */ + } else { + *pLength = stb_vorbis_stream_length_in_samples(pVorbis->stb); + } + + return MA_SUCCESS; + } + #else + { + /* vorbis is disabled. Should never hit this since initialization would have failed. */ + MA_ASSERT(MA_FALSE); + return MA_NOT_IMPLEMENTED; + } + #endif +} + + +static ma_result ma_decoding_backend_init__stbvorbis(void* pUserData, ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend) +{ + ma_result result; + ma_stbvorbis* pVorbis; + + (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */ + + /* For now we're just allocating the decoder backend on the heap. */ + pVorbis = (ma_stbvorbis*)ma_malloc(sizeof(*pVorbis), pAllocationCallbacks); + if (pVorbis == NULL) { + return MA_OUT_OF_MEMORY; + } + + result = ma_stbvorbis_init(onRead, onSeek, onTell, pReadSeekTellUserData, pConfig, pAllocationCallbacks, pVorbis); + if (result != MA_SUCCESS) { + ma_free(pVorbis, pAllocationCallbacks); + return result; + } + + *ppBackend = pVorbis; + + return MA_SUCCESS; +} + +static ma_result ma_decoding_backend_init_file__stbvorbis(void* pUserData, const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend) +{ + ma_result result; + ma_stbvorbis* pVorbis; + + (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */ + + /* For now we're just allocating the decoder backend on the heap. */ + pVorbis = (ma_stbvorbis*)ma_malloc(sizeof(*pVorbis), pAllocationCallbacks); + if (pVorbis == NULL) { + return MA_OUT_OF_MEMORY; + } + + result = ma_stbvorbis_init_file(pFilePath, pConfig, pAllocationCallbacks, pVorbis); + if (result != MA_SUCCESS) { + ma_free(pVorbis, pAllocationCallbacks); + return result; + } + + *ppBackend = pVorbis; + + return MA_SUCCESS; +} + +static ma_result ma_decoding_backend_init_memory__stbvorbis(void* pUserData, const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend) +{ + ma_result result; + ma_stbvorbis* pVorbis; + + (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */ + + /* For now we're just allocating the decoder backend on the heap. */ + pVorbis = (ma_stbvorbis*)ma_malloc(sizeof(*pVorbis), pAllocationCallbacks); + if (pVorbis == NULL) { + return MA_OUT_OF_MEMORY; + } + + result = ma_stbvorbis_init_memory(pData, dataSize, pConfig, pAllocationCallbacks, pVorbis); + if (result != MA_SUCCESS) { + ma_free(pVorbis, pAllocationCallbacks); + return result; + } + + *ppBackend = pVorbis; + + return MA_SUCCESS; +} + +static void ma_decoding_backend_uninit__stbvorbis(void* pUserData, ma_data_source* pBackend, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_stbvorbis* pVorbis = (ma_stbvorbis*)pBackend; + + (void)pUserData; + + ma_stbvorbis_uninit(pVorbis, pAllocationCallbacks); + ma_free(pVorbis, pAllocationCallbacks); +} + +static ma_decoding_backend_vtable g_ma_decoding_backend_vtable_stbvorbis = +{ + ma_decoding_backend_init__stbvorbis, + ma_decoding_backend_init_file__stbvorbis, + NULL, /* onInitFileW() */ + ma_decoding_backend_init_memory__stbvorbis, + ma_decoding_backend_uninit__stbvorbis +}; + +static ma_result ma_decoder_init_vorbis__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + return ma_decoder_init_from_vtable__internal(&g_ma_decoding_backend_vtable_stbvorbis, NULL, pConfig, pDecoder); +} + +static ma_result ma_decoder_init_vorbis_from_file__internal(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + return ma_decoder_init_from_file__internal(&g_ma_decoding_backend_vtable_stbvorbis, NULL, pFilePath, pConfig, pDecoder); +} + +static ma_result ma_decoder_init_vorbis_from_file_w__internal(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + return ma_decoder_init_from_file_w__internal(&g_ma_decoding_backend_vtable_stbvorbis, NULL, pFilePath, pConfig, pDecoder); +} + +static ma_result ma_decoder_init_vorbis_from_memory__internal(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + return ma_decoder_init_from_memory__internal(&g_ma_decoding_backend_vtable_stbvorbis, NULL, pData, dataSize, pConfig, pDecoder); +} +#endif /* STB_VORBIS_INCLUDE_STB_VORBIS_H */ + + + +static ma_result ma_decoder__init_allocation_callbacks(const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + MA_ASSERT(pDecoder != NULL); + + if (pConfig != NULL) { + return ma_allocation_callbacks_init_copy(&pDecoder->allocationCallbacks, &pConfig->allocationCallbacks); + } else { + pDecoder->allocationCallbacks = ma_allocation_callbacks_init_default(); + return MA_SUCCESS; + } +} + +static ma_result ma_decoder__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + return ma_decoder_read_pcm_frames((ma_decoder*)pDataSource, pFramesOut, frameCount, pFramesRead); +} + +static ma_result ma_decoder__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex) +{ + return ma_decoder_seek_to_pcm_frame((ma_decoder*)pDataSource, frameIndex); +} + +static ma_result ma_decoder__data_source_on_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + return ma_decoder_get_data_format((ma_decoder*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap); +} + +static ma_result ma_decoder__data_source_on_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor) +{ + return ma_decoder_get_cursor_in_pcm_frames((ma_decoder*)pDataSource, pCursor); +} + +static ma_result ma_decoder__data_source_on_get_length(ma_data_source* pDataSource, ma_uint64* pLength) +{ + return ma_decoder_get_length_in_pcm_frames((ma_decoder*)pDataSource, pLength); +} + +static ma_data_source_vtable g_ma_decoder_data_source_vtable = +{ + ma_decoder__data_source_on_read, + ma_decoder__data_source_on_seek, + ma_decoder__data_source_on_get_data_format, + ma_decoder__data_source_on_get_cursor, + ma_decoder__data_source_on_get_length, + NULL, /* onSetLooping */ + 0 +}; + +static ma_result ma_decoder__preinit(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, ma_decoder_tell_proc onTell, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result; + ma_data_source_config dataSourceConfig; + + MA_ASSERT(pConfig != NULL); + + if (pDecoder == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pDecoder); + + dataSourceConfig = ma_data_source_config_init(); + dataSourceConfig.vtable = &g_ma_decoder_data_source_vtable; + + result = ma_data_source_init(&dataSourceConfig, &pDecoder->ds); + if (result != MA_SUCCESS) { + return result; + } + + pDecoder->onRead = onRead; + pDecoder->onSeek = onSeek; + pDecoder->onTell = onTell; + pDecoder->pUserData = pUserData; + + result = ma_decoder__init_allocation_callbacks(pConfig, pDecoder); + if (result != MA_SUCCESS) { + ma_data_source_uninit(&pDecoder->ds); + return result; + } + + return MA_SUCCESS; +} + +static ma_result ma_decoder__postinit(const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result; + + result = ma_decoder__init_data_converter(pDecoder, pConfig); + + /* If we failed post initialization we need to uninitialize the decoder before returning to prevent a memory leak. */ + if (result != MA_SUCCESS) { + ma_decoder_uninit(pDecoder); + return result; + } + + return result; +} + + +static 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. */ + (void)onRead; + (void)onSeek; + (void)pUserData; + + + /* If we've specified a specific encoding type, try that first. */ + if (pConfig->encodingFormat != ma_encoding_format_unknown) { + #ifdef MA_HAS_WAV + if (pConfig->encodingFormat == ma_encoding_format_wav) { + result = ma_decoder_init_wav__internal(pConfig, pDecoder); + } + #endif + #ifdef MA_HAS_FLAC + if (pConfig->encodingFormat == ma_encoding_format_flac) { + result = ma_decoder_init_flac__internal(pConfig, pDecoder); + } + #endif + #ifdef MA_HAS_MP3 + if (pConfig->encodingFormat == ma_encoding_format_mp3) { + result = ma_decoder_init_mp3__internal(pConfig, pDecoder); + } + #endif + #ifdef MA_HAS_VORBIS + if (pConfig->encodingFormat == ma_encoding_format_vorbis) { + result = ma_decoder_init_vorbis__internal(pConfig, pDecoder); + } + #endif + + /* If we weren't able to initialize the decoder, seek back to the start to give the next attempts a clean start. */ + if (result != MA_SUCCESS) { + onSeek(pDecoder, 0, ma_seek_origin_start); + } + } + + if (result != MA_SUCCESS) { + /* Getting here means we couldn't load a specific decoding backend based on the encoding format. */ + + /* + We use trial and error to open a decoder. We prioritize custom decoders so that if they + implement the same encoding format they take priority over the built-in decoders. + */ + if (result != MA_SUCCESS) { + result = ma_decoder_init_custom__internal(pConfig, pDecoder); + if (result != MA_SUCCESS) { + onSeek(pDecoder, 0, ma_seek_origin_start); + } + } + + /* + If we get to this point and we still haven't found a decoder, and the caller has requested a + specific encoding format, there's no hope for it. Abort. + */ + if (pConfig->encodingFormat != ma_encoding_format_unknown) { + return 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_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 + #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 + } + + if (result != MA_SUCCESS) { + return result; + } + + return ma_decoder__postinit(pConfig, pDecoder); +} + +MA_API 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_result result; + + config = ma_decoder_config_init_copy(pConfig); + + result = ma_decoder__preinit(onRead, onSeek, NULL, pUserData, &config, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + + return ma_decoder_init__internal(onRead, onSeek, pUserData, &config, pDecoder); +} + + +static ma_result ma_decoder__on_read_memory(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead) +{ + size_t bytesRemaining; + + MA_ASSERT(pDecoder->data.memory.dataSize >= pDecoder->data.memory.currentReadPos); + + if (pBytesRead != NULL) { + *pBytesRead = 0; + } + + bytesRemaining = pDecoder->data.memory.dataSize - pDecoder->data.memory.currentReadPos; + if (bytesToRead > bytesRemaining) { + bytesToRead = bytesRemaining; + } + + if (bytesRemaining == 0) { + return MA_AT_END; + } + + if (bytesToRead > 0) { + MA_COPY_MEMORY(pBufferOut, pDecoder->data.memory.pData + pDecoder->data.memory.currentReadPos, bytesToRead); + pDecoder->data.memory.currentReadPos += bytesToRead; + } + + if (pBytesRead != NULL) { + *pBytesRead = bytesToRead; + } + + return MA_SUCCESS; +} + +static ma_result ma_decoder__on_seek_memory(ma_decoder* pDecoder, ma_int64 byteOffset, ma_seek_origin origin) +{ + if (byteOffset > 0 && (ma_uint64)byteOffset > MA_SIZE_MAX) { + return MA_BAD_SEEK; + } + + if (origin == ma_seek_origin_current) { + if (byteOffset > 0) { + if (pDecoder->data.memory.currentReadPos + byteOffset > pDecoder->data.memory.dataSize) { + byteOffset = (ma_int64)(pDecoder->data.memory.dataSize - pDecoder->data.memory.currentReadPos); /* Trying to seek too far forward. */ + } + + pDecoder->data.memory.currentReadPos += (size_t)byteOffset; + } else { + if (pDecoder->data.memory.currentReadPos < (size_t)-byteOffset) { + byteOffset = -(ma_int64)pDecoder->data.memory.currentReadPos; /* Trying to seek too far backwards. */ + } + + pDecoder->data.memory.currentReadPos -= (size_t)-byteOffset; + } + } else { + if (origin == ma_seek_origin_end) { + if (byteOffset < 0) { + byteOffset = -byteOffset; + } + + if (byteOffset > (ma_int64)pDecoder->data.memory.dataSize) { + pDecoder->data.memory.currentReadPos = 0; /* Trying to seek too far back. */ + } else { + pDecoder->data.memory.currentReadPos = pDecoder->data.memory.dataSize - (size_t)byteOffset; + } + } else { + if ((size_t)byteOffset <= pDecoder->data.memory.dataSize) { + pDecoder->data.memory.currentReadPos = (size_t)byteOffset; + } else { + pDecoder->data.memory.currentReadPos = pDecoder->data.memory.dataSize; /* Trying to seek too far forward. */ + } + } + } + + return MA_SUCCESS; +} + +static ma_result ma_decoder__on_tell_memory(ma_decoder* pDecoder, ma_int64* pCursor) +{ + MA_ASSERT(pDecoder != NULL); + MA_ASSERT(pCursor != NULL); + + *pCursor = (ma_int64)pDecoder->data.memory.currentReadPos; + + return MA_SUCCESS; +} + +static ma_result ma_decoder__preinit_memory_wrapper(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, ma_decoder__on_tell_memory, NULL, pConfig, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + + if (pData == NULL || dataSize == 0) { + return MA_INVALID_ARGS; + } + + pDecoder->data.memory.pData = (const ma_uint8*)pData; + pDecoder->data.memory.dataSize = dataSize; + pDecoder->data.memory.currentReadPos = 0; + + (void)pConfig; + return MA_SUCCESS; +} + +MA_API ma_result ma_decoder_init_memory(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result; + ma_decoder_config config; + + config = ma_decoder_config_init_copy(pConfig); + + result = ma_decoder__preinit(NULL, NULL, NULL, NULL, &config, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + + if (pData == NULL || dataSize == 0) { + return MA_INVALID_ARGS; + } + + /* If the backend has support for loading from a file path we'll want to use that. If that all fails we'll fall back to the VFS path. */ + result = MA_NO_BACKEND; + + if (config.encodingFormat != ma_encoding_format_unknown) { + #ifdef MA_HAS_WAV + if (config.encodingFormat == ma_encoding_format_wav) { + result = ma_decoder_init_wav_from_memory__internal(pData, dataSize, &config, pDecoder); + } + #endif + #ifdef MA_HAS_FLAC + if (config.encodingFormat == ma_encoding_format_flac) { + result = ma_decoder_init_flac_from_memory__internal(pData, dataSize, &config, pDecoder); + } + #endif + #ifdef MA_HAS_MP3 + if (config.encodingFormat == ma_encoding_format_mp3) { + result = ma_decoder_init_mp3_from_memory__internal(pData, dataSize, &config, pDecoder); + } + #endif + #ifdef MA_HAS_VORBIS + if (config.encodingFormat == ma_encoding_format_vorbis) { + result = ma_decoder_init_vorbis_from_memory__internal(pData, dataSize, &config, pDecoder); + } + #endif + } + + if (result != MA_SUCCESS) { + /* Getting here means we weren't able to initialize a decoder of a specific encoding format. */ + + /* + We use trial and error to open a decoder. We prioritize custom decoders so that if they + implement the same encoding format they take priority over the built-in decoders. + */ + result = ma_decoder_init_custom_from_memory__internal(pData, dataSize, &config, pDecoder); + + /* + If we get to this point and we still haven't found a decoder, and the caller has requested a + specific encoding format, there's no hope for it. Abort. + */ + if (result != MA_SUCCESS && config.encodingFormat != ma_encoding_format_unknown) { + return MA_NO_BACKEND; + } + + /* Use trial and error for stock decoders. */ + if (result != MA_SUCCESS) { + #ifdef MA_HAS_WAV + if (result != MA_SUCCESS) { + result = ma_decoder_init_wav_from_memory__internal(pData, dataSize, &config, pDecoder); + } + #endif + #ifdef MA_HAS_FLAC + if (result != MA_SUCCESS) { + result = ma_decoder_init_flac_from_memory__internal(pData, dataSize, &config, pDecoder); + } + #endif + #ifdef MA_HAS_MP3 + if (result != MA_SUCCESS) { + result = ma_decoder_init_mp3_from_memory__internal(pData, dataSize, &config, pDecoder); + } + #endif + #ifdef MA_HAS_VORBIS + if (result != MA_SUCCESS) { + result = ma_decoder_init_vorbis_from_memory__internal(pData, dataSize, &config, pDecoder); + } + #endif + } + } + + /* + If at this point we still haven't successfully initialized the decoder it most likely means + the backend doesn't have an implementation for loading from a file path. We'll try using + miniaudio's built-in file IO for loading file. + */ + if (result == MA_SUCCESS) { + /* Initialization was successful. Finish up. */ + result = ma_decoder__postinit(&config, pDecoder); + if (result != MA_SUCCESS) { + /* + The backend was initialized successfully, but for some reason post-initialization failed. This is most likely + due to an out of memory error. We're going to abort with an error here and not try to recover. + */ + if (pDecoder->pBackendVTable != NULL && pDecoder->pBackendVTable->onUninit != NULL) { + pDecoder->pBackendVTable->onUninit(pDecoder->pBackendUserData, &pDecoder->pBackend, &pDecoder->allocationCallbacks); + } + + return result; + } + } else { + /* Probably no implementation for loading from a block of memory. Use miniaudio's abstraction instead. */ + result = ma_decoder__preinit_memory_wrapper(pData, dataSize, &config, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_decoder_init__internal(ma_decoder__on_read_memory, ma_decoder__on_seek_memory, NULL, &config, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + } + + return MA_SUCCESS; +} + + +#if defined(MA_HAS_WAV) || \ + defined(MA_HAS_MP3) || \ + defined(MA_HAS_FLAC) || \ + defined(MA_HAS_VORBIS) || \ + defined(MA_HAS_OPUS) +#define MA_HAS_PATH_API +#endif + +#if defined(MA_HAS_PATH_API) +static const char* ma_path_file_name(const char* path) +{ + const char* fileName; + + if (path == NULL) { + return NULL; + } + + 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; +} + +static const wchar_t* ma_path_file_name_w(const wchar_t* path) +{ + const wchar_t* fileName; + + if (path == NULL) { + return NULL; + } + + 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; +} + + +static const char* ma_path_extension(const char* path) +{ + const char* extension; + const char* lastOccurance; + + if (path == NULL) { + path = ""; + } + + extension = ma_path_file_name(path); + 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; +} + +static const wchar_t* ma_path_extension_w(const wchar_t* path) +{ + const wchar_t* extension; + const wchar_t* lastOccurance; + + if (path == NULL) { + path = L""; + } + + extension = ma_path_file_name_w(path); + 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; +} + + +static 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; + } + + ext1 = extension; + ext2 = ma_path_extension(path); + +#if defined(_MSC_VER) || defined(__DMC__) + return _stricmp(ext1, ext2) == 0; +#else + return strcasecmp(ext1, ext2) == 0; +#endif +} + +static ma_bool32 ma_path_extension_equal_w(const wchar_t* path, const wchar_t* extension) +{ + const wchar_t* ext1; + const wchar_t* ext2; + + if (path == NULL || extension == NULL) { + return MA_FALSE; + } + + ext1 = extension; + ext2 = ma_path_extension_w(path); + +#if defined(_MSC_VER) || defined(__WATCOMC__) || defined(__DMC__) + return _wcsicmp(ext1, ext2) == 0; +#else + /* + I'm not aware of a wide character version of strcasecmp(). I'm therefore converting the extensions to multibyte strings and comparing those. This + isn't the most efficient way to do it, but it should work OK. + */ + { + char ext1MB[4096]; + char ext2MB[4096]; + const wchar_t* pext1 = ext1; + const wchar_t* pext2 = ext2; + mbstate_t mbs1; + mbstate_t mbs2; + + MA_ZERO_OBJECT(&mbs1); + MA_ZERO_OBJECT(&mbs2); + + if (wcsrtombs(ext1MB, &pext1, sizeof(ext1MB), &mbs1) == (size_t)-1) { + return MA_FALSE; + } + if (wcsrtombs(ext2MB, &pext2, sizeof(ext2MB), &mbs2) == (size_t)-1) { + return MA_FALSE; + } + + return strcasecmp(ext1MB, ext2MB) == 0; + } +#endif +} +#endif /* MA_HAS_PATH_API */ + + + +static ma_result ma_decoder__on_read_vfs(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead) +{ + MA_ASSERT(pDecoder != NULL); + MA_ASSERT(pBufferOut != NULL); + + return ma_vfs_or_default_read(pDecoder->data.vfs.pVFS, pDecoder->data.vfs.file, pBufferOut, bytesToRead, pBytesRead); +} + +static ma_result ma_decoder__on_seek_vfs(ma_decoder* pDecoder, ma_int64 offset, ma_seek_origin origin) +{ + MA_ASSERT(pDecoder != NULL); + + return ma_vfs_or_default_seek(pDecoder->data.vfs.pVFS, pDecoder->data.vfs.file, offset, origin); +} + +static ma_result ma_decoder__on_tell_vfs(ma_decoder* pDecoder, ma_int64* pCursor) +{ + MA_ASSERT(pDecoder != NULL); + + return ma_vfs_or_default_tell(pDecoder->data.vfs.pVFS, pDecoder->data.vfs.file, pCursor); +} + +static ma_result ma_decoder__preinit_vfs(ma_vfs* pVFS, const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result; + ma_vfs_file file; + + result = ma_decoder__preinit(ma_decoder__on_read_vfs, ma_decoder__on_seek_vfs, ma_decoder__on_tell_vfs, NULL, pConfig, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + + if (pFilePath == NULL || pFilePath[0] == '\0') { + return MA_INVALID_ARGS; + } + + result = ma_vfs_or_default_open(pVFS, pFilePath, MA_OPEN_MODE_READ, &file); + if (result != MA_SUCCESS) { + return result; + } + + pDecoder->data.vfs.pVFS = pVFS; + pDecoder->data.vfs.file = file; + + return MA_SUCCESS; +} + +MA_API ma_result ma_decoder_init_vfs(ma_vfs* pVFS, const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result; + ma_decoder_config config; + + config = ma_decoder_config_init_copy(pConfig); + result = ma_decoder__preinit_vfs(pVFS, pFilePath, &config, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + + result = MA_NO_BACKEND; + + if (config.encodingFormat != ma_encoding_format_unknown) { + #ifdef MA_HAS_WAV + if (config.encodingFormat == ma_encoding_format_wav) { + result = ma_decoder_init_wav__internal(&config, pDecoder); + } + #endif + #ifdef MA_HAS_FLAC + if (config.encodingFormat == ma_encoding_format_flac) { + result = ma_decoder_init_flac__internal(&config, pDecoder); + } + #endif + #ifdef MA_HAS_MP3 + if (config.encodingFormat == ma_encoding_format_mp3) { + result = ma_decoder_init_mp3__internal(&config, pDecoder); + } + #endif + #ifdef MA_HAS_VORBIS + if (config.encodingFormat == ma_encoding_format_vorbis) { + result = ma_decoder_init_vorbis__internal(&config, pDecoder); + } + #endif + + /* Make sure we seek back to the start if we didn't initialize a decoder successfully so the next attempts have a fresh start. */ + if (result != MA_SUCCESS) { + ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start); + } + } + + if (result != MA_SUCCESS) { + /* Getting here means we weren't able to initialize a decoder of a specific encoding format. */ + + /* + We use trial and error to open a decoder. We prioritize custom decoders so that if they + implement the same encoding format they take priority over the built-in decoders. + */ + if (result != MA_SUCCESS) { + result = ma_decoder_init_custom__internal(&config, pDecoder); + if (result != MA_SUCCESS) { + ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start); + } + } + + /* + If we get to this point and we still haven't found a decoder, and the caller has requested a + specific encoding format, there's no hope for it. Abort. + */ + if (config.encodingFormat != ma_encoding_format_unknown) { + return MA_NO_BACKEND; + } + + #ifdef MA_HAS_WAV + if (result != MA_SUCCESS && ma_path_extension_equal(pFilePath, "wav")) { + result = ma_decoder_init_wav__internal(&config, pDecoder); + if (result != MA_SUCCESS) { + ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start); + } + } + #endif + #ifdef MA_HAS_FLAC + if (result != MA_SUCCESS && ma_path_extension_equal(pFilePath, "flac")) { + result = ma_decoder_init_flac__internal(&config, pDecoder); + if (result != MA_SUCCESS) { + ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start); + } + } + #endif + #ifdef MA_HAS_MP3 + if (result != MA_SUCCESS && ma_path_extension_equal(pFilePath, "mp3")) { + result = ma_decoder_init_mp3__internal(&config, pDecoder); + if (result != MA_SUCCESS) { + ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start); + } + } + #endif + } + + /* If we still haven't got a result just use trial and error. Otherwise we can finish up. */ + if (result != MA_SUCCESS) { + result = ma_decoder_init__internal(ma_decoder__on_read_vfs, ma_decoder__on_seek_vfs, NULL, &config, pDecoder); + } else { + result = ma_decoder__postinit(&config, pDecoder); + } + + if (result != MA_SUCCESS) { + if (pDecoder->data.vfs.file != NULL) { /* <-- Will be reset to NULL if ma_decoder_uninit() is called in one of the steps above which allows us to avoid a double close of the file. */ + ma_vfs_or_default_close(pVFS, pDecoder->data.vfs.file); + } + + return result; + } + + return MA_SUCCESS; +} + + +static ma_result ma_decoder__preinit_vfs_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result; + ma_vfs_file file; + + result = ma_decoder__preinit(ma_decoder__on_read_vfs, ma_decoder__on_seek_vfs, ma_decoder__on_tell_vfs, NULL, pConfig, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + + if (pFilePath == NULL || pFilePath[0] == '\0') { + return MA_INVALID_ARGS; + } + + result = ma_vfs_or_default_open_w(pVFS, pFilePath, MA_OPEN_MODE_READ, &file); + if (result != MA_SUCCESS) { + return result; + } + + pDecoder->data.vfs.pVFS = pVFS; + pDecoder->data.vfs.file = file; + + return MA_SUCCESS; +} + +MA_API ma_result ma_decoder_init_vfs_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result; + ma_decoder_config config; + + config = ma_decoder_config_init_copy(pConfig); + result = ma_decoder__preinit_vfs_w(pVFS, pFilePath, &config, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + + result = MA_NO_BACKEND; + + if (config.encodingFormat != ma_encoding_format_unknown) { + #ifdef MA_HAS_WAV + if (config.encodingFormat == ma_encoding_format_wav) { + result = ma_decoder_init_wav__internal(&config, pDecoder); + } + #endif + #ifdef MA_HAS_FLAC + if (config.encodingFormat == ma_encoding_format_flac) { + result = ma_decoder_init_flac__internal(&config, pDecoder); + } + #endif + #ifdef MA_HAS_MP3 + if (config.encodingFormat == ma_encoding_format_mp3) { + result = ma_decoder_init_mp3__internal(&config, pDecoder); + } + #endif + #ifdef MA_HAS_VORBIS + if (config.encodingFormat == ma_encoding_format_vorbis) { + result = ma_decoder_init_vorbis__internal(&config, pDecoder); + } + #endif + + /* Make sure we seek back to the start if we didn't initialize a decoder successfully so the next attempts have a fresh start. */ + if (result != MA_SUCCESS) { + ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start); + } + } + + if (result != MA_SUCCESS) { + /* Getting here means we weren't able to initialize a decoder of a specific encoding format. */ + + /* + We use trial and error to open a decoder. We prioritize custom decoders so that if they + implement the same encoding format they take priority over the built-in decoders. + */ + if (result != MA_SUCCESS) { + result = ma_decoder_init_custom__internal(&config, pDecoder); + if (result != MA_SUCCESS) { + ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start); + } + } + + /* + If we get to this point and we still haven't found a decoder, and the caller has requested a + specific encoding format, there's no hope for it. Abort. + */ + if (config.encodingFormat != ma_encoding_format_unknown) { + return MA_NO_BACKEND; + } + + #ifdef MA_HAS_WAV + if (result != MA_SUCCESS && ma_path_extension_equal_w(pFilePath, L"wav")) { + result = ma_decoder_init_wav__internal(&config, pDecoder); + if (result != MA_SUCCESS) { + ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start); + } + } + #endif + #ifdef MA_HAS_FLAC + if (result != MA_SUCCESS && ma_path_extension_equal_w(pFilePath, L"flac")) { + result = ma_decoder_init_flac__internal(&config, pDecoder); + if (result != MA_SUCCESS) { + ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start); + } + } + #endif + #ifdef MA_HAS_MP3 + if (result != MA_SUCCESS && ma_path_extension_equal_w(pFilePath, L"mp3")) { + result = ma_decoder_init_mp3__internal(&config, pDecoder); + if (result != MA_SUCCESS) { + ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start); + } + } + #endif + } + + /* If we still haven't got a result just use trial and error. Otherwise we can finish up. */ + if (result != MA_SUCCESS) { + result = ma_decoder_init__internal(ma_decoder__on_read_vfs, ma_decoder__on_seek_vfs, NULL, &config, pDecoder); + } else { + result = ma_decoder__postinit(&config, pDecoder); + } + + if (result != MA_SUCCESS) { + ma_vfs_or_default_close(pVFS, pDecoder->data.vfs.file); + return result; + } + + return MA_SUCCESS; +} + + +static ma_result ma_decoder__preinit_file(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result; + + result = ma_decoder__preinit(NULL, NULL, NULL, NULL, pConfig, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + + if (pFilePath == NULL || pFilePath[0] == '\0') { + return MA_INVALID_ARGS; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_decoder_init_file(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result; + ma_decoder_config config; + + config = ma_decoder_config_init_copy(pConfig); + result = ma_decoder__preinit_file(pFilePath, &config, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + + /* If the backend has support for loading from a file path we'll want to use that. If that all fails we'll fall back to the VFS path. */ + result = MA_NO_BACKEND; + + if (config.encodingFormat != ma_encoding_format_unknown) { + #ifdef MA_HAS_WAV + if (config.encodingFormat == ma_encoding_format_wav) { + result = ma_decoder_init_wav_from_file__internal(pFilePath, &config, pDecoder); + } + #endif + #ifdef MA_HAS_FLAC + if (config.encodingFormat == ma_encoding_format_flac) { + result = ma_decoder_init_flac_from_file__internal(pFilePath, &config, pDecoder); + } + #endif + #ifdef MA_HAS_MP3 + if (config.encodingFormat == ma_encoding_format_mp3) { + result = ma_decoder_init_mp3_from_file__internal(pFilePath, &config, pDecoder); + } + #endif + #ifdef MA_HAS_VORBIS + if (config.encodingFormat == ma_encoding_format_vorbis) { + result = ma_decoder_init_vorbis_from_file__internal(pFilePath, &config, pDecoder); + } + #endif + } + + if (result != MA_SUCCESS) { + /* Getting here means we weren't able to initialize a decoder of a specific encoding format. */ + + /* + We use trial and error to open a decoder. We prioritize custom decoders so that if they + implement the same encoding format they take priority over the built-in decoders. + */ + result = ma_decoder_init_custom_from_file__internal(pFilePath, &config, pDecoder); + + /* + If we get to this point and we still haven't found a decoder, and the caller has requested a + specific encoding format, there's no hope for it. Abort. + */ + if (result != MA_SUCCESS && config.encodingFormat != ma_encoding_format_unknown) { + return MA_NO_BACKEND; + } + + /* First try loading based on the file extension so we don't waste time opening and closing files. */ + #ifdef MA_HAS_WAV + if (result != MA_SUCCESS && ma_path_extension_equal(pFilePath, "wav")) { + result = ma_decoder_init_wav_from_file__internal(pFilePath, &config, pDecoder); + } + #endif + #ifdef MA_HAS_FLAC + if (result != MA_SUCCESS && ma_path_extension_equal(pFilePath, "flac")) { + result = ma_decoder_init_flac_from_file__internal(pFilePath, &config, pDecoder); + } + #endif + #ifdef MA_HAS_MP3 + if (result != MA_SUCCESS && ma_path_extension_equal(pFilePath, "mp3")) { + result = ma_decoder_init_mp3_from_file__internal(pFilePath, &config, pDecoder); + } + #endif + #ifdef MA_HAS_VORBIS + if (result != MA_SUCCESS && ma_path_extension_equal(pFilePath, "ogg")) { + result = ma_decoder_init_vorbis_from_file__internal(pFilePath, &config, pDecoder); + } + #endif + + /* + If we still haven't got a result just use trial and error. Custom decoders have already been attempted, so here we + need only iterate over our stock decoders. + */ + if (result != MA_SUCCESS) { + #ifdef MA_HAS_WAV + if (result != MA_SUCCESS) { + result = ma_decoder_init_wav_from_file__internal(pFilePath, &config, pDecoder); + } + #endif + #ifdef MA_HAS_FLAC + if (result != MA_SUCCESS) { + result = ma_decoder_init_flac_from_file__internal(pFilePath, &config, pDecoder); + } + #endif + #ifdef MA_HAS_MP3 + if (result != MA_SUCCESS) { + result = ma_decoder_init_mp3_from_file__internal(pFilePath, &config, pDecoder); + } + #endif + #ifdef MA_HAS_VORBIS + if (result != MA_SUCCESS) { + result = ma_decoder_init_vorbis_from_file__internal(pFilePath, &config, pDecoder); + } + #endif + } + } + + /* + If at this point we still haven't successfully initialized the decoder it most likely means + the backend doesn't have an implementation for loading from a file path. We'll try using + miniaudio's built-in file IO for loading file. + */ + if (result == MA_SUCCESS) { + /* Initialization was successful. Finish up. */ + result = ma_decoder__postinit(&config, pDecoder); + if (result != MA_SUCCESS) { + /* + The backend was initialized successfully, but for some reason post-initialization failed. This is most likely + due to an out of memory error. We're going to abort with an error here and not try to recover. + */ + if (pDecoder->pBackendVTable != NULL && pDecoder->pBackendVTable->onUninit != NULL) { + pDecoder->pBackendVTable->onUninit(pDecoder->pBackendUserData, &pDecoder->pBackend, &pDecoder->allocationCallbacks); + } + + return result; + } + } else { + /* Probably no implementation for loading from a file path. Use miniaudio's file IO instead. */ + result = ma_decoder_init_vfs(NULL, pFilePath, pConfig, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + } + + return MA_SUCCESS; +} + +static ma_result ma_decoder__preinit_file_w(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result; + + result = ma_decoder__preinit(NULL, NULL, NULL, NULL, pConfig, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + + if (pFilePath == NULL || pFilePath[0] == '\0') { + return MA_INVALID_ARGS; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_decoder_init_file_w(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result; + ma_decoder_config config; + + config = ma_decoder_config_init_copy(pConfig); + result = ma_decoder__preinit_file_w(pFilePath, &config, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + + /* If the backend has support for loading from a file path we'll want to use that. If that all fails we'll fall back to the VFS path. */ + result = MA_NO_BACKEND; + + if (config.encodingFormat != ma_encoding_format_unknown) { + #ifdef MA_HAS_WAV + if (config.encodingFormat == ma_encoding_format_wav) { + result = ma_decoder_init_wav_from_file_w__internal(pFilePath, &config, pDecoder); + } + #endif + #ifdef MA_HAS_FLAC + if (config.encodingFormat == ma_encoding_format_flac) { + result = ma_decoder_init_flac_from_file_w__internal(pFilePath, &config, pDecoder); + } + #endif + #ifdef MA_HAS_MP3 + if (config.encodingFormat == ma_encoding_format_mp3) { + result = ma_decoder_init_mp3_from_file_w__internal(pFilePath, &config, pDecoder); + } + #endif + #ifdef MA_HAS_VORBIS + if (config.encodingFormat == ma_encoding_format_vorbis) { + result = ma_decoder_init_vorbis_from_file_w__internal(pFilePath, &config, pDecoder); + } + #endif + } + + if (result != MA_SUCCESS) { + /* Getting here means we weren't able to initialize a decoder of a specific encoding format. */ + + /* + We use trial and error to open a decoder. We prioritize custom decoders so that if they + implement the same encoding format they take priority over the built-in decoders. + */ + result = ma_decoder_init_custom_from_file_w__internal(pFilePath, &config, pDecoder); + + /* + If we get to this point and we still haven't found a decoder, and the caller has requested a + specific encoding format, there's no hope for it. Abort. + */ + if (result != MA_SUCCESS && config.encodingFormat != ma_encoding_format_unknown) { + return MA_NO_BACKEND; + } + + /* First try loading based on the file extension so we don't waste time opening and closing files. */ + #ifdef MA_HAS_WAV + if (result != MA_SUCCESS && ma_path_extension_equal_w(pFilePath, L"wav")) { + result = ma_decoder_init_wav_from_file_w__internal(pFilePath, &config, pDecoder); + } + #endif + #ifdef MA_HAS_FLAC + if (result != MA_SUCCESS && ma_path_extension_equal_w(pFilePath, L"flac")) { + result = ma_decoder_init_flac_from_file_w__internal(pFilePath, &config, pDecoder); + } + #endif + #ifdef MA_HAS_MP3 + if (result != MA_SUCCESS && ma_path_extension_equal_w(pFilePath, L"mp3")) { + result = ma_decoder_init_mp3_from_file_w__internal(pFilePath, &config, pDecoder); + } + #endif + #ifdef MA_HAS_VORBIS + if (result != MA_SUCCESS && ma_path_extension_equal_w(pFilePath, L"ogg")) { + result = ma_decoder_init_vorbis_from_file_w__internal(pFilePath, &config, pDecoder); + } + #endif + + /* + If we still haven't got a result just use trial and error. Custom decoders have already been attempted, so here we + need only iterate over our stock decoders. + */ + if (result != MA_SUCCESS) { + #ifdef MA_HAS_WAV + if (result != MA_SUCCESS) { + result = ma_decoder_init_wav_from_file_w__internal(pFilePath, &config, pDecoder); + } + #endif + #ifdef MA_HAS_FLAC + if (result != MA_SUCCESS) { + result = ma_decoder_init_flac_from_file_w__internal(pFilePath, &config, pDecoder); + } + #endif + #ifdef MA_HAS_MP3 + if (result != MA_SUCCESS) { + result = ma_decoder_init_mp3_from_file_w__internal(pFilePath, &config, pDecoder); + } + #endif + #ifdef MA_HAS_VORBIS + if (result != MA_SUCCESS) { + result = ma_decoder_init_vorbis_from_file_w__internal(pFilePath, &config, pDecoder); + } + #endif + } + } + + /* + If at this point we still haven't successfully initialized the decoder it most likely means + the backend doesn't have an implementation for loading from a file path. We'll try using + miniaudio's built-in file IO for loading file. + */ + if (result == MA_SUCCESS) { + /* Initialization was successful. Finish up. */ + result = ma_decoder__postinit(&config, pDecoder); + if (result != MA_SUCCESS) { + /* + The backend was initialized successfully, but for some reason post-initialization failed. This is most likely + due to an out of memory error. We're going to abort with an error here and not try to recover. + */ + if (pDecoder->pBackendVTable != NULL && pDecoder->pBackendVTable->onUninit != NULL) { + pDecoder->pBackendVTable->onUninit(pDecoder->pBackendUserData, &pDecoder->pBackend, &pDecoder->allocationCallbacks); + } + + return result; + } + } else { + /* Probably no implementation for loading from a file path. Use miniaudio's file IO instead. */ + result = ma_decoder_init_vfs_w(NULL, pFilePath, pConfig, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_decoder_uninit(ma_decoder* pDecoder) +{ + if (pDecoder == NULL) { + return MA_INVALID_ARGS; + } + + if (pDecoder->pBackend != NULL) { + if (pDecoder->pBackendVTable != NULL && pDecoder->pBackendVTable->onUninit != NULL) { + pDecoder->pBackendVTable->onUninit(pDecoder->pBackendUserData, pDecoder->pBackend, &pDecoder->allocationCallbacks); + } + } + + if (pDecoder->onRead == ma_decoder__on_read_vfs) { + ma_vfs_or_default_close(pDecoder->data.vfs.pVFS, pDecoder->data.vfs.file); + pDecoder->data.vfs.file = NULL; + } + + ma_data_converter_uninit(&pDecoder->converter, &pDecoder->allocationCallbacks); + ma_data_source_uninit(&pDecoder->ds); + + if (pDecoder->pInputCache != NULL) { + ma_free(pDecoder->pInputCache, &pDecoder->allocationCallbacks); + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_decoder_read_pcm_frames(ma_decoder* pDecoder, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + ma_result result = MA_SUCCESS; + ma_uint64 totalFramesReadOut; + void* pRunningFramesOut; + + if (pFramesRead != NULL) { + *pFramesRead = 0; /* Safety. */ + } + + if (frameCount == 0) { + return MA_INVALID_ARGS; + } + + if (pDecoder == NULL) { + return MA_INVALID_ARGS; + } + + if (pDecoder->pBackend == NULL) { + return MA_INVALID_OPERATION; + } + + /* Fast path. */ + if (pDecoder->converter.isPassthrough) { + result = ma_data_source_read_pcm_frames(pDecoder->pBackend, pFramesOut, frameCount, &totalFramesReadOut); + } else { + /* + Getting here means we need to do data conversion. If we're seeking forward and are _not_ doing resampling we can run this in a fast path. If we're doing resampling we + need to run through each sample because we need to ensure it's internal cache is updated. + */ + if (pFramesOut == NULL && pDecoder->converter.hasResampler == MA_FALSE) { + result = ma_data_source_read_pcm_frames(pDecoder->pBackend, NULL, frameCount, &totalFramesReadOut); + } else { + /* Slow path. Need to run everything through the data converter. */ + ma_format internalFormat; + ma_uint32 internalChannels; + + totalFramesReadOut = 0; + pRunningFramesOut = pFramesOut; + + result = ma_data_source_get_data_format(pDecoder->pBackend, &internalFormat, &internalChannels, NULL, NULL, 0); + if (result != MA_SUCCESS) { + return result; /* Failed to retrieve the internal format and channel count. */ + } + + /* + We run a different path depending on whether or not we are using a heap-allocated + intermediary buffer or not. If the data converter does not support the calculation of + the required number of input frames, we'll use the heap-allocated path. Otherwise we'll + use the stack-allocated path. + */ + if (pDecoder->pInputCache != NULL) { + /* We don't have a way of determining the required number of input frames, so need to persistently store input data in a cache. */ + while (totalFramesReadOut < frameCount) { + ma_uint64 framesToReadThisIterationIn; + ma_uint64 framesToReadThisIterationOut; + + /* If there's any data available in the cache, that needs to get processed first. */ + if (pDecoder->inputCacheRemaining > 0) { + framesToReadThisIterationOut = (frameCount - totalFramesReadOut); + framesToReadThisIterationIn = framesToReadThisIterationOut; + if (framesToReadThisIterationIn > pDecoder->inputCacheRemaining) { + framesToReadThisIterationIn = pDecoder->inputCacheRemaining; + } + + result = ma_data_converter_process_pcm_frames(&pDecoder->converter, ma_offset_pcm_frames_ptr(pDecoder->pInputCache, pDecoder->inputCacheConsumed, internalFormat, internalChannels), &framesToReadThisIterationIn, pRunningFramesOut, &framesToReadThisIterationOut); + if (result != MA_SUCCESS) { + break; + } + + pDecoder->inputCacheConsumed += framesToReadThisIterationIn; + pDecoder->inputCacheRemaining -= framesToReadThisIterationIn; + + totalFramesReadOut += framesToReadThisIterationOut; + + if (pRunningFramesOut != NULL) { + pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesToReadThisIterationOut * ma_get_bytes_per_frame(pDecoder->outputFormat, pDecoder->outputChannels)); + } + + if (framesToReadThisIterationIn == 0 && framesToReadThisIterationOut == 0) { + break; /* We're done. */ + } + } + + /* Getting here means there's no data in the cache and we need to fill it up from the data source. */ + if (pDecoder->inputCacheRemaining == 0) { + pDecoder->inputCacheConsumed = 0; + + result = ma_data_source_read_pcm_frames(pDecoder->pBackend, pDecoder->pInputCache, pDecoder->inputCacheCap, &pDecoder->inputCacheRemaining); + if (result != MA_SUCCESS) { + break; + } + } + } + } else { + /* We have a way of determining the required number of input frames so just use the stack. */ + while (totalFramesReadOut < frameCount) { + ma_uint8 pIntermediaryBuffer[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In internal format. */ + ma_uint64 intermediaryBufferCap = sizeof(pIntermediaryBuffer) / ma_get_bytes_per_frame(internalFormat, internalChannels); + ma_uint64 framesToReadThisIterationIn; + ma_uint64 framesReadThisIterationIn; + ma_uint64 framesToReadThisIterationOut; + ma_uint64 framesReadThisIterationOut; + ma_uint64 requiredInputFrameCount; + + framesToReadThisIterationOut = (frameCount - totalFramesReadOut); + framesToReadThisIterationIn = framesToReadThisIterationOut; + if (framesToReadThisIterationIn > intermediaryBufferCap) { + framesToReadThisIterationIn = intermediaryBufferCap; + } + + ma_data_converter_get_required_input_frame_count(&pDecoder->converter, framesToReadThisIterationOut, &requiredInputFrameCount); + if (framesToReadThisIterationIn > requiredInputFrameCount) { + framesToReadThisIterationIn = requiredInputFrameCount; + } + + if (requiredInputFrameCount > 0) { + result = ma_data_source_read_pcm_frames(pDecoder->pBackend, pIntermediaryBuffer, framesToReadThisIterationIn, &framesReadThisIterationIn); + } else { + framesReadThisIterationIn = 0; + } + + /* + At this point we have our decoded data in input format and now we need to convert to output format. Note that even if we didn't read any + input frames, we still want to try processing frames because there may some output frames generated from cached input data. + */ + framesReadThisIterationOut = framesToReadThisIterationOut; + result = ma_data_converter_process_pcm_frames(&pDecoder->converter, pIntermediaryBuffer, &framesReadThisIterationIn, pRunningFramesOut, &framesReadThisIterationOut); + if (result != MA_SUCCESS) { + break; + } + + totalFramesReadOut += framesReadThisIterationOut; + + if (pRunningFramesOut != NULL) { + pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesReadThisIterationOut * ma_get_bytes_per_frame(pDecoder->outputFormat, pDecoder->outputChannels)); + } + + if (framesReadThisIterationIn == 0 && framesReadThisIterationOut == 0) { + break; /* We're done. */ + } + } + } + } + } + + pDecoder->readPointerInPCMFrames += totalFramesReadOut; + + if (pFramesRead != NULL) { + *pFramesRead = totalFramesReadOut; + } + + if (result == MA_SUCCESS && totalFramesReadOut == 0) { + result = MA_AT_END; + } + + return result; +} + +MA_API ma_result ma_decoder_seek_to_pcm_frame(ma_decoder* pDecoder, ma_uint64 frameIndex) +{ + if (pDecoder == NULL) { + return MA_INVALID_ARGS; + } + + if (pDecoder->pBackend != NULL) { + ma_result result; + ma_uint64 internalFrameIndex; + ma_uint32 internalSampleRate; + ma_uint64 currentFrameIndex; + + result = ma_data_source_get_data_format(pDecoder->pBackend, NULL, NULL, &internalSampleRate, NULL, 0); + if (result != MA_SUCCESS) { + return result; /* Failed to retrieve the internal sample rate. */ + } + + if (internalSampleRate == pDecoder->outputSampleRate) { + internalFrameIndex = frameIndex; + } else { + internalFrameIndex = ma_calculate_frame_count_after_resampling(internalSampleRate, pDecoder->outputSampleRate, frameIndex); + } + + /* Only seek if we're requesting a different frame to what we're currently sitting on. */ + ma_data_source_get_cursor_in_pcm_frames(pDecoder->pBackend, ¤tFrameIndex); + if (currentFrameIndex != internalFrameIndex) { + result = ma_data_source_seek_to_pcm_frame(pDecoder->pBackend, internalFrameIndex); + if (result == MA_SUCCESS) { + pDecoder->readPointerInPCMFrames = frameIndex; + } + + /* Reset the data converter so that any cached data in the resampler is cleared. */ + ma_data_converter_reset(&pDecoder->converter); + } + + return result; + } + + /* Should never get here, but if we do it means onSeekToPCMFrame was not set by the backend. */ + return MA_INVALID_ARGS; +} + +MA_API ma_result ma_decoder_get_data_format(ma_decoder* pDecoder, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + if (pDecoder == NULL) { + return MA_INVALID_ARGS; + } + + if (pFormat != NULL) { + *pFormat = pDecoder->outputFormat; + } + + if (pChannels != NULL) { + *pChannels = pDecoder->outputChannels; + } + + if (pSampleRate != NULL) { + *pSampleRate = pDecoder->outputSampleRate; + } + + if (pChannelMap != NULL) { + ma_data_converter_get_output_channel_map(&pDecoder->converter, pChannelMap, channelMapCap); + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_decoder_get_cursor_in_pcm_frames(ma_decoder* pDecoder, ma_uint64* pCursor) +{ + if (pCursor == NULL) { + return MA_INVALID_ARGS; + } + + *pCursor = 0; + + if (pDecoder == NULL) { + return MA_INVALID_ARGS; + } + + *pCursor = pDecoder->readPointerInPCMFrames; + + return MA_SUCCESS; +} + +MA_API ma_result ma_decoder_get_length_in_pcm_frames(ma_decoder* pDecoder, ma_uint64* pLength) +{ + if (pLength == NULL) { + return MA_INVALID_ARGS; + } + + *pLength = 0; + + if (pDecoder == NULL) { + return MA_INVALID_ARGS; + } + + if (pDecoder->pBackend != NULL) { + ma_result result; + ma_uint64 internalLengthInPCMFrames; + ma_uint32 internalSampleRate; + + result = ma_data_source_get_length_in_pcm_frames(pDecoder->pBackend, &internalLengthInPCMFrames); + if (result != MA_SUCCESS) { + return result; /* Failed to retrieve the internal length. */ + } + + result = ma_data_source_get_data_format(pDecoder->pBackend, NULL, NULL, &internalSampleRate, NULL, 0); + if (result != MA_SUCCESS) { + return result; /* Failed to retrieve the internal sample rate. */ + } + + if (internalSampleRate == pDecoder->outputSampleRate) { + *pLength = internalLengthInPCMFrames; + } else { + *pLength = ma_calculate_frame_count_after_resampling(pDecoder->outputSampleRate, internalSampleRate, internalLengthInPCMFrames); + } + + return MA_SUCCESS; + } else { + return MA_NO_BACKEND; + } +} + +MA_API ma_result ma_decoder_get_available_frames(ma_decoder* pDecoder, ma_uint64* pAvailableFrames) +{ + ma_result result; + ma_uint64 totalFrameCount; + + if (pAvailableFrames == NULL) { + return MA_INVALID_ARGS; + } + + *pAvailableFrames = 0; + + if (pDecoder == NULL) { + return MA_INVALID_ARGS; + } + + result = ma_decoder_get_length_in_pcm_frames(pDecoder, &totalFrameCount); + if (result != MA_SUCCESS) { + return result; + } + + if (totalFrameCount <= pDecoder->readPointerInPCMFrames) { + *pAvailableFrames = 0; + } else { + *pAvailableFrames = totalFrameCount - pDecoder->readPointerInPCMFrames; + } + + return MA_SUCCESS; +} + + +static ma_result ma_decoder__full_decode_and_uninit(ma_decoder* pDecoder, ma_decoder_config* pConfigOut, ma_uint64* pFrameCountOut, void** ppPCMFramesOut) +{ + ma_result result; + ma_uint64 totalFrameCount; + ma_uint64 bpf; + ma_uint64 dataCapInFrames; + void* pPCMFramesOut; + + MA_ASSERT(pDecoder != NULL); + + 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. */ + dataCapInFrames = 0; + pPCMFramesOut = NULL; + for (;;) { + 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; + } + + if ((newDataCapInFrames * bpf) > MA_SIZE_MAX) { + ma_free(pPCMFramesOut, &pDecoder->allocationCallbacks); + return MA_TOO_BIG; + } + + pNewPCMFramesOut = (void*)ma_realloc(pPCMFramesOut, (size_t)(newDataCapInFrames * bpf), &pDecoder->allocationCallbacks); + if (pNewPCMFramesOut == NULL) { + ma_free(pPCMFramesOut, &pDecoder->allocationCallbacks); + return MA_OUT_OF_MEMORY; + } + + dataCapInFrames = newDataCapInFrames; + pPCMFramesOut = pNewPCMFramesOut; + } + + frameCountToTryReading = dataCapInFrames - totalFrameCount; + MA_ASSERT(frameCountToTryReading > 0); + + result = ma_decoder_read_pcm_frames(pDecoder, (ma_uint8*)pPCMFramesOut + (totalFrameCount * bpf), frameCountToTryReading, &framesJustRead); + totalFrameCount += framesJustRead; + + if (result != MA_SUCCESS) { + break; + } + + if (framesJustRead < frameCountToTryReading) { + break; + } + } + + + if (pConfigOut != NULL) { + pConfigOut->format = pDecoder->outputFormat; + pConfigOut->channels = pDecoder->outputChannels; + pConfigOut->sampleRate = pDecoder->outputSampleRate; + } + + if (ppPCMFramesOut != NULL) { + *ppPCMFramesOut = pPCMFramesOut; + } else { + ma_free(pPCMFramesOut, &pDecoder->allocationCallbacks); + } + + if (pFrameCountOut != NULL) { + *pFrameCountOut = totalFrameCount; + } + + ma_decoder_uninit(pDecoder); + return MA_SUCCESS; +} + +MA_API ma_result ma_decode_from_vfs(ma_vfs* pVFS, const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut) +{ + ma_result result; + ma_decoder_config config; + ma_decoder decoder; + + if (pFrameCountOut != NULL) { + *pFrameCountOut = 0; + } + if (ppPCMFramesOut != NULL) { + *ppPCMFramesOut = NULL; + } + + config = ma_decoder_config_init_copy(pConfig); + + result = ma_decoder_init_vfs(pVFS, pFilePath, &config, &decoder); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_decoder__full_decode_and_uninit(&decoder, pConfig, pFrameCountOut, ppPCMFramesOut); + + return result; +} + +MA_API ma_result ma_decode_file(const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut) +{ + return ma_decode_from_vfs(NULL, pFilePath, pConfig, pFrameCountOut, ppPCMFramesOut); +} + +MA_API 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; + } + if (ppPCMFramesOut != NULL) { + *ppPCMFramesOut = NULL; + } + + if (pData == NULL || dataSize == 0) { + return MA_INVALID_ARGS; + } + + config = ma_decoder_config_init_copy(pConfig); + + 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 */ + + +#ifndef MA_NO_ENCODING + +#if defined(MA_HAS_WAV) +static size_t ma_encoder__internal_on_write_wav(void* pUserData, const void* pData, size_t bytesToWrite) +{ + ma_encoder* pEncoder = (ma_encoder*)pUserData; + size_t bytesWritten = 0; + + MA_ASSERT(pEncoder != NULL); + + pEncoder->onWrite(pEncoder, pData, bytesToWrite, &bytesWritten); + return bytesWritten; +} + +static ma_bool32 ma_encoder__internal_on_seek_wav(void* pUserData, int offset, ma_dr_wav_seek_origin origin) +{ + ma_encoder* pEncoder = (ma_encoder*)pUserData; + ma_result result; + + MA_ASSERT(pEncoder != NULL); + + result = pEncoder->onSeek(pEncoder, offset, (origin == ma_dr_wav_seek_origin_start) ? ma_seek_origin_start : ma_seek_origin_current); + if (result != MA_SUCCESS) { + return MA_FALSE; + } else { + return MA_TRUE; + } +} + +static ma_result ma_encoder__on_init_wav(ma_encoder* pEncoder) +{ + ma_dr_wav_data_format wavFormat; + ma_allocation_callbacks allocationCallbacks; + ma_dr_wav* pWav; + + MA_ASSERT(pEncoder != NULL); + + pWav = (ma_dr_wav*)ma_malloc(sizeof(*pWav), &pEncoder->config.allocationCallbacks); + if (pWav == NULL) { + return MA_OUT_OF_MEMORY; + } + + wavFormat.container = ma_dr_wav_container_riff; + wavFormat.channels = pEncoder->config.channels; + wavFormat.sampleRate = pEncoder->config.sampleRate; + wavFormat.bitsPerSample = ma_get_bytes_per_sample(pEncoder->config.format) * 8; + if (pEncoder->config.format == ma_format_f32) { + wavFormat.format = MA_DR_WAVE_FORMAT_IEEE_FLOAT; + } else { + wavFormat.format = MA_DR_WAVE_FORMAT_PCM; + } + + allocationCallbacks.pUserData = pEncoder->config.allocationCallbacks.pUserData; + allocationCallbacks.onMalloc = pEncoder->config.allocationCallbacks.onMalloc; + allocationCallbacks.onRealloc = pEncoder->config.allocationCallbacks.onRealloc; + allocationCallbacks.onFree = pEncoder->config.allocationCallbacks.onFree; + + if (!ma_dr_wav_init_write(pWav, &wavFormat, ma_encoder__internal_on_write_wav, ma_encoder__internal_on_seek_wav, pEncoder, &allocationCallbacks)) { + return MA_ERROR; + } + + pEncoder->pInternalEncoder = pWav; + + return MA_SUCCESS; +} + +static void ma_encoder__on_uninit_wav(ma_encoder* pEncoder) +{ + ma_dr_wav* pWav; + + MA_ASSERT(pEncoder != NULL); + + pWav = (ma_dr_wav*)pEncoder->pInternalEncoder; + MA_ASSERT(pWav != NULL); + + ma_dr_wav_uninit(pWav); + ma_free(pWav, &pEncoder->config.allocationCallbacks); +} + +static ma_result ma_encoder__on_write_pcm_frames_wav(ma_encoder* pEncoder, const void* pFramesIn, ma_uint64 frameCount, ma_uint64* pFramesWritten) +{ + ma_dr_wav* pWav; + ma_uint64 framesWritten; + + MA_ASSERT(pEncoder != NULL); + + pWav = (ma_dr_wav*)pEncoder->pInternalEncoder; + MA_ASSERT(pWav != NULL); + + framesWritten = ma_dr_wav_write_pcm_frames(pWav, frameCount, pFramesIn); + + if (pFramesWritten != NULL) { + *pFramesWritten = framesWritten; + } + + return MA_SUCCESS; +} +#endif + +MA_API ma_encoder_config ma_encoder_config_init(ma_encoding_format encodingFormat, ma_format format, ma_uint32 channels, ma_uint32 sampleRate) +{ + ma_encoder_config config; + + MA_ZERO_OBJECT(&config); + config.encodingFormat = encodingFormat; + config.format = format; + config.channels = channels; + config.sampleRate = sampleRate; + + return config; +} + +MA_API ma_result ma_encoder_preinit(const ma_encoder_config* pConfig, ma_encoder* pEncoder) +{ + ma_result result; + + if (pEncoder == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pEncoder); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->format == ma_format_unknown || pConfig->channels == 0 || pConfig->sampleRate == 0) { + return MA_INVALID_ARGS; + } + + pEncoder->config = *pConfig; + + result = ma_allocation_callbacks_init_copy(&pEncoder->config.allocationCallbacks, &pConfig->allocationCallbacks); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_encoder_init__internal(ma_encoder_write_proc onWrite, ma_encoder_seek_proc onSeek, void* pUserData, ma_encoder* pEncoder) +{ + ma_result result = MA_SUCCESS; + + /* This assumes ma_encoder_preinit() has been called prior. */ + MA_ASSERT(pEncoder != NULL); + + if (onWrite == NULL || onSeek == NULL) { + return MA_INVALID_ARGS; + } + + pEncoder->onWrite = onWrite; + pEncoder->onSeek = onSeek; + pEncoder->pUserData = pUserData; + + switch (pEncoder->config.encodingFormat) + { + case ma_encoding_format_wav: + { + #if defined(MA_HAS_WAV) + pEncoder->onInit = ma_encoder__on_init_wav; + pEncoder->onUninit = ma_encoder__on_uninit_wav; + pEncoder->onWritePCMFrames = ma_encoder__on_write_pcm_frames_wav; + #else + result = MA_NO_BACKEND; + #endif + } break; + + default: + { + result = MA_INVALID_ARGS; + } break; + } + + /* Getting here means we should have our backend callbacks set up. */ + if (result == MA_SUCCESS) { + result = pEncoder->onInit(pEncoder); + } + + return result; +} + +static ma_result ma_encoder__on_write_vfs(ma_encoder* pEncoder, const void* pBufferIn, size_t bytesToWrite, size_t* pBytesWritten) +{ + return ma_vfs_or_default_write(pEncoder->data.vfs.pVFS, pEncoder->data.vfs.file, pBufferIn, bytesToWrite, pBytesWritten); +} + +static ma_result ma_encoder__on_seek_vfs(ma_encoder* pEncoder, ma_int64 offset, ma_seek_origin origin) +{ + return ma_vfs_or_default_seek(pEncoder->data.vfs.pVFS, pEncoder->data.vfs.file, offset, origin); +} + +MA_API ma_result ma_encoder_init_vfs(ma_vfs* pVFS, const char* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder) +{ + ma_result result; + ma_vfs_file file; + + result = ma_encoder_preinit(pConfig, pEncoder); + if (result != MA_SUCCESS) { + return result; + } + + /* Now open the file. If this fails we don't need to uninitialize the encoder. */ + result = ma_vfs_or_default_open(pVFS, pFilePath, MA_OPEN_MODE_WRITE, &file); + if (result != MA_SUCCESS) { + return result; + } + + pEncoder->data.vfs.pVFS = pVFS; + pEncoder->data.vfs.file = file; + + result = ma_encoder_init__internal(ma_encoder__on_write_vfs, ma_encoder__on_seek_vfs, NULL, pEncoder); + if (result != MA_SUCCESS) { + ma_vfs_or_default_close(pVFS, file); + return result; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_encoder_init_vfs_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder) +{ + ma_result result; + ma_vfs_file file; + + result = ma_encoder_preinit(pConfig, pEncoder); + if (result != MA_SUCCESS) { + return result; + } + + /* Now open the file. If this fails we don't need to uninitialize the encoder. */ + result = ma_vfs_or_default_open_w(pVFS, pFilePath, MA_OPEN_MODE_WRITE, &file); + if (result != MA_SUCCESS) { + return result; + } + + pEncoder->data.vfs.pVFS = pVFS; + pEncoder->data.vfs.file = file; + + result = ma_encoder_init__internal(ma_encoder__on_write_vfs, ma_encoder__on_seek_vfs, NULL, pEncoder); + if (result != MA_SUCCESS) { + ma_vfs_or_default_close(pVFS, file); + return result; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_encoder_init_file(const char* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder) +{ + return ma_encoder_init_vfs(NULL, pFilePath, pConfig, pEncoder); +} + +MA_API ma_result ma_encoder_init_file_w(const wchar_t* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder) +{ + return ma_encoder_init_vfs_w(NULL, pFilePath, pConfig, pEncoder); +} + +MA_API ma_result ma_encoder_init(ma_encoder_write_proc onWrite, ma_encoder_seek_proc onSeek, void* pUserData, const ma_encoder_config* pConfig, ma_encoder* pEncoder) +{ + ma_result result; + + result = ma_encoder_preinit(pConfig, pEncoder); + if (result != MA_SUCCESS) { + return result; + } + + return ma_encoder_init__internal(onWrite, onSeek, pUserData, pEncoder); +} + + +MA_API void ma_encoder_uninit(ma_encoder* pEncoder) +{ + if (pEncoder == NULL) { + return; + } + + if (pEncoder->onUninit) { + pEncoder->onUninit(pEncoder); + } + + /* If we have a file handle, close it. */ + if (pEncoder->onWrite == ma_encoder__on_write_vfs) { + ma_vfs_or_default_close(pEncoder->data.vfs.pVFS, pEncoder->data.vfs.file); + pEncoder->data.vfs.file = NULL; + } +} + + +MA_API ma_result ma_encoder_write_pcm_frames(ma_encoder* pEncoder, const void* pFramesIn, ma_uint64 frameCount, ma_uint64* pFramesWritten) +{ + if (pFramesWritten != NULL) { + *pFramesWritten = 0; + } + + if (pEncoder == NULL || pFramesIn == NULL) { + return MA_INVALID_ARGS; + } + + return pEncoder->onWritePCMFrames(pEncoder, pFramesIn, frameCount, pFramesWritten); +} +#endif /* MA_NO_ENCODING */ + + + +/************************************************************************************************************************************************************** + +Generation + +**************************************************************************************************************************************************************/ +#ifndef MA_NO_GENERATION +MA_API ma_waveform_config ma_waveform_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_waveform_type type, double amplitude, double frequency) +{ + ma_waveform_config config; + + MA_ZERO_OBJECT(&config); + config.format = format; + config.channels = channels; + config.sampleRate = sampleRate; + config.type = type; + config.amplitude = amplitude; + config.frequency = frequency; + + return config; +} + +static ma_result ma_waveform__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + return ma_waveform_read_pcm_frames((ma_waveform*)pDataSource, pFramesOut, frameCount, pFramesRead); +} + +static ma_result ma_waveform__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex) +{ + return ma_waveform_seek_to_pcm_frame((ma_waveform*)pDataSource, frameIndex); +} + +static ma_result ma_waveform__data_source_on_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + ma_waveform* pWaveform = (ma_waveform*)pDataSource; + + *pFormat = pWaveform->config.format; + *pChannels = pWaveform->config.channels; + *pSampleRate = pWaveform->config.sampleRate; + ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pWaveform->config.channels); + + return MA_SUCCESS; +} + +static ma_result ma_waveform__data_source_on_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor) +{ + ma_waveform* pWaveform = (ma_waveform*)pDataSource; + + *pCursor = (ma_uint64)(pWaveform->time / pWaveform->advance); + + return MA_SUCCESS; +} + +static double ma_waveform__calculate_advance(ma_uint32 sampleRate, double frequency) +{ + return (1.0 / (sampleRate / frequency)); +} + +static void ma_waveform__update_advance(ma_waveform* pWaveform) +{ + pWaveform->advance = ma_waveform__calculate_advance(pWaveform->config.sampleRate, pWaveform->config.frequency); +} + +static ma_data_source_vtable g_ma_waveform_data_source_vtable = +{ + ma_waveform__data_source_on_read, + ma_waveform__data_source_on_seek, + ma_waveform__data_source_on_get_data_format, + ma_waveform__data_source_on_get_cursor, + NULL, /* onGetLength. There's no notion of a length in waveforms. */ + NULL, /* onSetLooping */ + 0 +}; + +MA_API ma_result ma_waveform_init(const ma_waveform_config* pConfig, ma_waveform* pWaveform) +{ + ma_result result; + ma_data_source_config dataSourceConfig; + + if (pWaveform == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pWaveform); + + dataSourceConfig = ma_data_source_config_init(); + dataSourceConfig.vtable = &g_ma_waveform_data_source_vtable; + + result = ma_data_source_init(&dataSourceConfig, &pWaveform->ds); + if (result != MA_SUCCESS) { + return result; + } + + pWaveform->config = *pConfig; + pWaveform->advance = ma_waveform__calculate_advance(pWaveform->config.sampleRate, pWaveform->config.frequency); + pWaveform->time = 0; + + return MA_SUCCESS; +} + +MA_API void ma_waveform_uninit(ma_waveform* pWaveform) +{ + if (pWaveform == NULL) { + return; + } + + ma_data_source_uninit(&pWaveform->ds); +} + +MA_API ma_result ma_waveform_set_amplitude(ma_waveform* pWaveform, double amplitude) +{ + if (pWaveform == NULL) { + return MA_INVALID_ARGS; + } + + pWaveform->config.amplitude = amplitude; + return MA_SUCCESS; +} + +MA_API ma_result ma_waveform_set_frequency(ma_waveform* pWaveform, double frequency) +{ + if (pWaveform == NULL) { + return MA_INVALID_ARGS; + } + + pWaveform->config.frequency = frequency; + ma_waveform__update_advance(pWaveform); + + return MA_SUCCESS; +} + +MA_API ma_result ma_waveform_set_type(ma_waveform* pWaveform, ma_waveform_type type) +{ + if (pWaveform == NULL) { + return MA_INVALID_ARGS; + } + + pWaveform->config.type = type; + return MA_SUCCESS; +} + +MA_API ma_result ma_waveform_set_sample_rate(ma_waveform* pWaveform, ma_uint32 sampleRate) +{ + if (pWaveform == NULL) { + return MA_INVALID_ARGS; + } + + pWaveform->config.sampleRate = sampleRate; + ma_waveform__update_advance(pWaveform); + + return MA_SUCCESS; +} + +static float ma_waveform_sine_f32(double time, double amplitude) +{ + return (float)(ma_sind(MA_TAU_D * time) * amplitude); +} + +static ma_int16 ma_waveform_sine_s16(double time, double amplitude) +{ + return ma_pcm_sample_f32_to_s16(ma_waveform_sine_f32(time, amplitude)); +} + +static float ma_waveform_square_f32(double time, double dutyCycle, double amplitude) +{ + double f = time - (ma_int64)time; + double r; + + if (f < dutyCycle) { + r = amplitude; + } else { + r = -amplitude; + } + + return (float)r; +} + +static ma_int16 ma_waveform_square_s16(double time, double dutyCycle, double amplitude) +{ + return ma_pcm_sample_f32_to_s16(ma_waveform_square_f32(time, dutyCycle, amplitude)); +} + +static float ma_waveform_triangle_f32(double time, double amplitude) +{ + double f = time - (ma_int64)time; + double r; + + r = 2 * ma_abs(2 * (f - 0.5)) - 1; + + return (float)(r * amplitude); +} + +static ma_int16 ma_waveform_triangle_s16(double time, double amplitude) +{ + return ma_pcm_sample_f32_to_s16(ma_waveform_triangle_f32(time, amplitude)); +} + +static float ma_waveform_sawtooth_f32(double time, double amplitude) +{ + double f = time - (ma_int64)time; + double r; + + r = 2 * (f - 0.5); + + return (float)(r * amplitude); +} + +static ma_int16 ma_waveform_sawtooth_s16(double time, double amplitude) +{ + return ma_pcm_sample_f32_to_s16(ma_waveform_sawtooth_f32(time, amplitude)); +} + +static void ma_waveform_read_pcm_frames__sine(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount) +{ + ma_uint64 iFrame; + ma_uint64 iChannel; + ma_uint32 bps = ma_get_bytes_per_sample(pWaveform->config.format); + ma_uint32 bpf = bps * pWaveform->config.channels; + + MA_ASSERT(pWaveform != NULL); + MA_ASSERT(pFramesOut != NULL); + + if (pWaveform->config.format == ma_format_f32) { + float* pFramesOutF32 = (float*)pFramesOut; + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + float s = ma_waveform_sine_f32(pWaveform->time, pWaveform->config.amplitude); + pWaveform->time += pWaveform->advance; + + for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) { + pFramesOutF32[iFrame*pWaveform->config.channels + iChannel] = s; + } + } + } else if (pWaveform->config.format == ma_format_s16) { + ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut; + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_int16 s = ma_waveform_sine_s16(pWaveform->time, pWaveform->config.amplitude); + pWaveform->time += pWaveform->advance; + + for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) { + pFramesOutS16[iFrame*pWaveform->config.channels + iChannel] = s; + } + } + } else { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + float s = ma_waveform_sine_f32(pWaveform->time, pWaveform->config.amplitude); + pWaveform->time += pWaveform->advance; + + for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) { + ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pWaveform->config.format, &s, ma_format_f32, 1, ma_dither_mode_none); + } + } + } +} + +static void ma_waveform_read_pcm_frames__square(ma_waveform* pWaveform, double dutyCycle, void* pFramesOut, ma_uint64 frameCount) +{ + ma_uint64 iFrame; + ma_uint64 iChannel; + ma_uint32 bps = ma_get_bytes_per_sample(pWaveform->config.format); + ma_uint32 bpf = bps * pWaveform->config.channels; + + MA_ASSERT(pWaveform != NULL); + MA_ASSERT(pFramesOut != NULL); + + if (pWaveform->config.format == ma_format_f32) { + float* pFramesOutF32 = (float*)pFramesOut; + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + float s = ma_waveform_square_f32(pWaveform->time, dutyCycle, pWaveform->config.amplitude); + pWaveform->time += pWaveform->advance; + + for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) { + pFramesOutF32[iFrame*pWaveform->config.channels + iChannel] = s; + } + } + } else if (pWaveform->config.format == ma_format_s16) { + ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut; + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_int16 s = ma_waveform_square_s16(pWaveform->time, dutyCycle, pWaveform->config.amplitude); + pWaveform->time += pWaveform->advance; + + for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) { + pFramesOutS16[iFrame*pWaveform->config.channels + iChannel] = s; + } + } + } else { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + float s = ma_waveform_square_f32(pWaveform->time, dutyCycle, pWaveform->config.amplitude); + pWaveform->time += pWaveform->advance; + + for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) { + ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pWaveform->config.format, &s, ma_format_f32, 1, ma_dither_mode_none); + } + } + } +} + +static void ma_waveform_read_pcm_frames__triangle(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount) +{ + ma_uint64 iFrame; + ma_uint64 iChannel; + ma_uint32 bps = ma_get_bytes_per_sample(pWaveform->config.format); + ma_uint32 bpf = bps * pWaveform->config.channels; + + MA_ASSERT(pWaveform != NULL); + MA_ASSERT(pFramesOut != NULL); + + if (pWaveform->config.format == ma_format_f32) { + float* pFramesOutF32 = (float*)pFramesOut; + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + float s = ma_waveform_triangle_f32(pWaveform->time, pWaveform->config.amplitude); + pWaveform->time += pWaveform->advance; + + for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) { + pFramesOutF32[iFrame*pWaveform->config.channels + iChannel] = s; + } + } + } else if (pWaveform->config.format == ma_format_s16) { + ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut; + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_int16 s = ma_waveform_triangle_s16(pWaveform->time, pWaveform->config.amplitude); + pWaveform->time += pWaveform->advance; + + for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) { + pFramesOutS16[iFrame*pWaveform->config.channels + iChannel] = s; + } + } + } else { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + float s = ma_waveform_triangle_f32(pWaveform->time, pWaveform->config.amplitude); + pWaveform->time += pWaveform->advance; + + for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) { + ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pWaveform->config.format, &s, ma_format_f32, 1, ma_dither_mode_none); + } + } + } +} + +static void ma_waveform_read_pcm_frames__sawtooth(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount) +{ + ma_uint64 iFrame; + ma_uint64 iChannel; + ma_uint32 bps = ma_get_bytes_per_sample(pWaveform->config.format); + ma_uint32 bpf = bps * pWaveform->config.channels; + + MA_ASSERT(pWaveform != NULL); + MA_ASSERT(pFramesOut != NULL); + + if (pWaveform->config.format == ma_format_f32) { + float* pFramesOutF32 = (float*)pFramesOut; + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + float s = ma_waveform_sawtooth_f32(pWaveform->time, pWaveform->config.amplitude); + pWaveform->time += pWaveform->advance; + + for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) { + pFramesOutF32[iFrame*pWaveform->config.channels + iChannel] = s; + } + } + } else if (pWaveform->config.format == ma_format_s16) { + ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut; + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_int16 s = ma_waveform_sawtooth_s16(pWaveform->time, pWaveform->config.amplitude); + pWaveform->time += pWaveform->advance; + + for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) { + pFramesOutS16[iFrame*pWaveform->config.channels + iChannel] = s; + } + } + } else { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + float s = ma_waveform_sawtooth_f32(pWaveform->time, pWaveform->config.amplitude); + pWaveform->time += pWaveform->advance; + + for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) { + ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pWaveform->config.format, &s, ma_format_f32, 1, ma_dither_mode_none); + } + } + } +} + +MA_API ma_result ma_waveform_read_pcm_frames(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + if (pFramesRead != NULL) { + *pFramesRead = 0; + } + + if (frameCount == 0) { + return MA_INVALID_ARGS; + } + + if (pWaveform == NULL) { + return MA_INVALID_ARGS; + } + + if (pFramesOut != NULL) { + switch (pWaveform->config.type) + { + case ma_waveform_type_sine: + { + ma_waveform_read_pcm_frames__sine(pWaveform, pFramesOut, frameCount); + } break; + + case ma_waveform_type_square: + { + ma_waveform_read_pcm_frames__square(pWaveform, 0.5, pFramesOut, frameCount); + } break; + + case ma_waveform_type_triangle: + { + ma_waveform_read_pcm_frames__triangle(pWaveform, pFramesOut, frameCount); + } break; + + case ma_waveform_type_sawtooth: + { + ma_waveform_read_pcm_frames__sawtooth(pWaveform, pFramesOut, frameCount); + } break; + + default: return MA_INVALID_OPERATION; /* Unknown waveform type. */ + } + } else { + pWaveform->time += pWaveform->advance * (ma_int64)frameCount; /* Cast to int64 required for VC6. Won't affect anything in practice. */ + } + + if (pFramesRead != NULL) { + *pFramesRead = frameCount; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_waveform_seek_to_pcm_frame(ma_waveform* pWaveform, ma_uint64 frameIndex) +{ + if (pWaveform == NULL) { + return MA_INVALID_ARGS; + } + + pWaveform->time = pWaveform->advance * (ma_int64)frameIndex; /* Casting for VC6. Won't be an issue in practice. */ + + return MA_SUCCESS; +} + +MA_API ma_pulsewave_config ma_pulsewave_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double dutyCycle, double amplitude, double frequency) +{ + ma_pulsewave_config config; + + MA_ZERO_OBJECT(&config); + config.format = format; + config.channels = channels; + config.sampleRate = sampleRate; + config.dutyCycle = dutyCycle; + config.amplitude = amplitude; + config.frequency = frequency; + + return config; +} + +MA_API ma_result ma_pulsewave_init(const ma_pulsewave_config* pConfig, ma_pulsewave* pWaveform) +{ + ma_result result; + ma_waveform_config config; + + if (pWaveform == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pWaveform); + + config = ma_waveform_config_init( + pConfig->format, + pConfig->channels, + pConfig->sampleRate, + ma_waveform_type_square, + pConfig->amplitude, + pConfig->frequency + ); + + result = ma_waveform_init(&config, &pWaveform->waveform); + ma_pulsewave_set_duty_cycle(pWaveform, pConfig->dutyCycle); + + return result; +} + +MA_API void ma_pulsewave_uninit(ma_pulsewave* pWaveform) +{ + if (pWaveform == NULL) { + return; + } + + ma_waveform_uninit(&pWaveform->waveform); +} + +MA_API ma_result ma_pulsewave_read_pcm_frames(ma_pulsewave* pWaveform, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + if (pFramesRead != NULL) { + *pFramesRead = 0; + } + + if (frameCount == 0) { + return MA_INVALID_ARGS; + } + + if (pWaveform == NULL) { + return MA_INVALID_ARGS; + } + + if (pFramesOut != NULL) { + ma_waveform_read_pcm_frames__square(&pWaveform->waveform, pWaveform->config.dutyCycle, pFramesOut, frameCount); + } else { + pWaveform->waveform.time += pWaveform->waveform.advance * (ma_int64)frameCount; /* Cast to int64 required for VC6. Won't affect anything in practice. */ + } + + if (pFramesRead != NULL) { + *pFramesRead = frameCount; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_pulsewave_seek_to_pcm_frame(ma_pulsewave* pWaveform, ma_uint64 frameIndex) +{ + if (pWaveform == NULL) { + return MA_INVALID_ARGS; + } + + ma_waveform_seek_to_pcm_frame(&pWaveform->waveform, frameIndex); + + return MA_SUCCESS; +} + +MA_API ma_result ma_pulsewave_set_amplitude(ma_pulsewave* pWaveform, double amplitude) +{ + if (pWaveform == NULL) { + return MA_INVALID_ARGS; + } + + pWaveform->config.amplitude = amplitude; + ma_waveform_set_amplitude(&pWaveform->waveform, amplitude); + + return MA_SUCCESS; +} + +MA_API ma_result ma_pulsewave_set_frequency(ma_pulsewave* pWaveform, double frequency) +{ + if (pWaveform == NULL) { + return MA_INVALID_ARGS; + } + + pWaveform->config.frequency = frequency; + ma_waveform_set_frequency(&pWaveform->waveform, frequency); + + return MA_SUCCESS; +} + +MA_API ma_result ma_pulsewave_set_sample_rate(ma_pulsewave* pWaveform, ma_uint32 sampleRate) +{ + if (pWaveform == NULL) { + return MA_INVALID_ARGS; + } + + pWaveform->config.sampleRate = sampleRate; + ma_waveform_set_sample_rate(&pWaveform->waveform, sampleRate); + + return MA_SUCCESS; +} + +MA_API ma_result ma_pulsewave_set_duty_cycle(ma_pulsewave* pWaveform, double dutyCycle) +{ + if (pWaveform == NULL) { + return MA_INVALID_ARGS; + } + + pWaveform->config.dutyCycle = dutyCycle; + + return MA_SUCCESS; +} + + + +MA_API ma_noise_config ma_noise_config_init(ma_format format, ma_uint32 channels, ma_noise_type type, ma_int32 seed, double amplitude) +{ + ma_noise_config config; + MA_ZERO_OBJECT(&config); + + config.format = format; + config.channels = channels; + config.type = type; + config.seed = seed; + config.amplitude = amplitude; + + if (config.seed == 0) { + config.seed = MA_DEFAULT_LCG_SEED; + } + + return config; +} + + +static ma_result ma_noise__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + return ma_noise_read_pcm_frames((ma_noise*)pDataSource, pFramesOut, frameCount, pFramesRead); +} + +static ma_result ma_noise__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex) +{ + /* No-op. Just pretend to be successful. */ + (void)pDataSource; + (void)frameIndex; + return MA_SUCCESS; +} + +static ma_result ma_noise__data_source_on_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + ma_noise* pNoise = (ma_noise*)pDataSource; + + *pFormat = pNoise->config.format; + *pChannels = pNoise->config.channels; + *pSampleRate = 0; /* There is no notion of sample rate with noise generation. */ + ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pNoise->config.channels); + + return MA_SUCCESS; +} + +static ma_data_source_vtable g_ma_noise_data_source_vtable = +{ + ma_noise__data_source_on_read, + ma_noise__data_source_on_seek, /* No-op for noise. */ + ma_noise__data_source_on_get_data_format, + NULL, /* onGetCursor. No notion of a cursor for noise. */ + NULL, /* onGetLength. No notion of a length for noise. */ + NULL, /* onSetLooping */ + 0 +}; + + +#ifndef MA_PINK_NOISE_BIN_SIZE +#define MA_PINK_NOISE_BIN_SIZE 16 +#endif + +typedef struct +{ + size_t sizeInBytes; + struct + { + size_t binOffset; + size_t accumulationOffset; + size_t counterOffset; + } pink; + struct + { + size_t accumulationOffset; + } brownian; +} ma_noise_heap_layout; + +static ma_result ma_noise_get_heap_layout(const ma_noise_config* pConfig, ma_noise_heap_layout* pHeapLayout) +{ + MA_ASSERT(pHeapLayout != NULL); + + MA_ZERO_OBJECT(pHeapLayout); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->channels == 0) { + return MA_INVALID_ARGS; + } + + pHeapLayout->sizeInBytes = 0; + + /* Pink. */ + if (pConfig->type == ma_noise_type_pink) { + /* bin */ + pHeapLayout->pink.binOffset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += sizeof(double*) * pConfig->channels; + pHeapLayout->sizeInBytes += sizeof(double ) * pConfig->channels * MA_PINK_NOISE_BIN_SIZE; + + /* accumulation */ + pHeapLayout->pink.accumulationOffset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += sizeof(double) * pConfig->channels; + + /* counter */ + pHeapLayout->pink.counterOffset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += sizeof(ma_uint32) * pConfig->channels; + } + + /* Brownian. */ + if (pConfig->type == ma_noise_type_brownian) { + /* accumulation */ + pHeapLayout->brownian.accumulationOffset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += sizeof(double) * pConfig->channels; + } + + /* Make sure allocation size is aligned. */ + pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes); + + return MA_SUCCESS; +} + +MA_API ma_result ma_noise_get_heap_size(const ma_noise_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_result result; + ma_noise_heap_layout heapLayout; + + if (pHeapSizeInBytes == NULL) { + return MA_INVALID_ARGS; + } + + *pHeapSizeInBytes = 0; + + result = ma_noise_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + *pHeapSizeInBytes = heapLayout.sizeInBytes; + + return MA_SUCCESS; +} + +MA_API ma_result ma_noise_init_preallocated(const ma_noise_config* pConfig, void* pHeap, ma_noise* pNoise) +{ + ma_result result; + ma_noise_heap_layout heapLayout; + ma_data_source_config dataSourceConfig; + ma_uint32 iChannel; + + if (pNoise == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pNoise); + + result = ma_noise_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + pNoise->_pHeap = pHeap; + MA_ZERO_MEMORY(pNoise->_pHeap, heapLayout.sizeInBytes); + + dataSourceConfig = ma_data_source_config_init(); + dataSourceConfig.vtable = &g_ma_noise_data_source_vtable; + + result = ma_data_source_init(&dataSourceConfig, &pNoise->ds); + if (result != MA_SUCCESS) { + return result; + } + + pNoise->config = *pConfig; + ma_lcg_seed(&pNoise->lcg, pConfig->seed); + + if (pNoise->config.type == ma_noise_type_pink) { + pNoise->state.pink.bin = (double** )ma_offset_ptr(pHeap, heapLayout.pink.binOffset); + pNoise->state.pink.accumulation = (double* )ma_offset_ptr(pHeap, heapLayout.pink.accumulationOffset); + pNoise->state.pink.counter = (ma_uint32*)ma_offset_ptr(pHeap, heapLayout.pink.counterOffset); + + for (iChannel = 0; iChannel < pConfig->channels; iChannel += 1) { + pNoise->state.pink.bin[iChannel] = (double*)ma_offset_ptr(pHeap, heapLayout.pink.binOffset + (sizeof(double*) * pConfig->channels) + (sizeof(double) * MA_PINK_NOISE_BIN_SIZE * iChannel)); + pNoise->state.pink.accumulation[iChannel] = 0; + pNoise->state.pink.counter[iChannel] = 1; + } + } + + if (pNoise->config.type == ma_noise_type_brownian) { + pNoise->state.brownian.accumulation = (double*)ma_offset_ptr(pHeap, heapLayout.brownian.accumulationOffset); + + for (iChannel = 0; iChannel < pConfig->channels; iChannel += 1) { + pNoise->state.brownian.accumulation[iChannel] = 0; + } + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_noise_init(const ma_noise_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_noise* pNoise) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_noise_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_noise_init_preallocated(pConfig, pHeap, pNoise); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pNoise->_ownsHeap = MA_TRUE; + return MA_SUCCESS; +} + +MA_API void ma_noise_uninit(ma_noise* pNoise, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pNoise == NULL) { + return; + } + + ma_data_source_uninit(&pNoise->ds); + + if (pNoise->_ownsHeap) { + ma_free(pNoise->_pHeap, pAllocationCallbacks); + } +} + +MA_API ma_result ma_noise_set_amplitude(ma_noise* pNoise, double amplitude) +{ + if (pNoise == NULL) { + return MA_INVALID_ARGS; + } + + pNoise->config.amplitude = amplitude; + return MA_SUCCESS; +} + +MA_API ma_result ma_noise_set_seed(ma_noise* pNoise, ma_int32 seed) +{ + if (pNoise == NULL) { + return MA_INVALID_ARGS; + } + + pNoise->lcg.state = seed; + return MA_SUCCESS; +} + + +MA_API ma_result ma_noise_set_type(ma_noise* pNoise, ma_noise_type type) +{ + if (pNoise == NULL) { + return MA_INVALID_ARGS; + } + + /* + This function should never have been implemented in the first place. Changing the type dynamically is not + supported. Instead you need to uninitialize and reinitiailize a fresh `ma_noise` object. This function + will be removed in version 0.12. + */ + MA_ASSERT(MA_FALSE); + (void)type; + + return MA_INVALID_OPERATION; +} + +static MA_INLINE float ma_noise_f32_white(ma_noise* pNoise) +{ + return (float)(ma_lcg_rand_f64(&pNoise->lcg) * pNoise->config.amplitude); +} + +static MA_INLINE ma_int16 ma_noise_s16_white(ma_noise* pNoise) +{ + return ma_pcm_sample_f32_to_s16(ma_noise_f32_white(pNoise)); +} + +static MA_INLINE ma_uint64 ma_noise_read_pcm_frames__white(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount) +{ + ma_uint64 iFrame; + ma_uint32 iChannel; + const ma_uint32 channels = pNoise->config.channels; + MA_ASSUME(channels > 0); + + if (pNoise->config.format == ma_format_f32) { + float* pFramesOutF32 = (float*)pFramesOut; + if (pNoise->config.duplicateChannels) { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + float s = ma_noise_f32_white(pNoise); + for (iChannel = 0; iChannel < channels; iChannel += 1) { + pFramesOutF32[iFrame*channels + iChannel] = s; + } + } + } else { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannel = 0; iChannel < channels; iChannel += 1) { + pFramesOutF32[iFrame*channels + iChannel] = ma_noise_f32_white(pNoise); + } + } + } + } else if (pNoise->config.format == ma_format_s16) { + ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut; + if (pNoise->config.duplicateChannels) { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_int16 s = ma_noise_s16_white(pNoise); + for (iChannel = 0; iChannel < channels; iChannel += 1) { + pFramesOutS16[iFrame*channels + iChannel] = s; + } + } + } else { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannel = 0; iChannel < channels; iChannel += 1) { + pFramesOutS16[iFrame*channels + iChannel] = ma_noise_s16_white(pNoise); + } + } + } + } else { + const ma_uint32 bps = ma_get_bytes_per_sample(pNoise->config.format); + const ma_uint32 bpf = bps * channels; + + if (pNoise->config.duplicateChannels) { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + float s = ma_noise_f32_white(pNoise); + for (iChannel = 0; iChannel < channels; iChannel += 1) { + ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none); + } + } + } else { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannel = 0; iChannel < channels; iChannel += 1) { + float s = ma_noise_f32_white(pNoise); + ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none); + } + } + } + } + + return frameCount; +} + + +static MA_INLINE unsigned int ma_tzcnt32(unsigned int x) +{ + unsigned int n; + + /* Special case for odd numbers since they should happen about half the time. */ + if (x & 0x1) { + return 0; + } + + if (x == 0) { + return sizeof(x) << 3; + } + + n = 1; + if ((x & 0x0000FFFF) == 0) { x >>= 16; n += 16; } + if ((x & 0x000000FF) == 0) { x >>= 8; n += 8; } + if ((x & 0x0000000F) == 0) { x >>= 4; n += 4; } + if ((x & 0x00000003) == 0) { x >>= 2; n += 2; } + n -= x & 0x00000001; + + return n; +} + +/* +Pink noise generation based on Tonic (public domain) with modifications. https://github.com/TonicAudio/Tonic/blob/master/src/Tonic/Noise.h + +This is basically _the_ reference for pink noise from what I've found: http://www.firstpr.com.au/dsp/pink-noise/ +*/ +static MA_INLINE float ma_noise_f32_pink(ma_noise* pNoise, ma_uint32 iChannel) +{ + double result; + double binPrev; + double binNext; + unsigned int ibin; + + ibin = ma_tzcnt32(pNoise->state.pink.counter[iChannel]) & (MA_PINK_NOISE_BIN_SIZE - 1); + + binPrev = pNoise->state.pink.bin[iChannel][ibin]; + binNext = ma_lcg_rand_f64(&pNoise->lcg); + pNoise->state.pink.bin[iChannel][ibin] = binNext; + + pNoise->state.pink.accumulation[iChannel] += (binNext - binPrev); + pNoise->state.pink.counter[iChannel] += 1; + + result = (ma_lcg_rand_f64(&pNoise->lcg) + pNoise->state.pink.accumulation[iChannel]); + result /= 10; + + return (float)(result * pNoise->config.amplitude); +} + +static MA_INLINE ma_int16 ma_noise_s16_pink(ma_noise* pNoise, ma_uint32 iChannel) +{ + return ma_pcm_sample_f32_to_s16(ma_noise_f32_pink(pNoise, iChannel)); +} + +static MA_INLINE ma_uint64 ma_noise_read_pcm_frames__pink(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount) +{ + ma_uint64 iFrame; + ma_uint32 iChannel; + const ma_uint32 channels = pNoise->config.channels; + MA_ASSUME(channels > 0); + + if (pNoise->config.format == ma_format_f32) { + float* pFramesOutF32 = (float*)pFramesOut; + if (pNoise->config.duplicateChannels) { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + float s = ma_noise_f32_pink(pNoise, 0); + for (iChannel = 0; iChannel < channels; iChannel += 1) { + pFramesOutF32[iFrame*channels + iChannel] = s; + } + } + } else { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannel = 0; iChannel < channels; iChannel += 1) { + pFramesOutF32[iFrame*channels + iChannel] = ma_noise_f32_pink(pNoise, iChannel); + } + } + } + } else if (pNoise->config.format == ma_format_s16) { + ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut; + if (pNoise->config.duplicateChannels) { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_int16 s = ma_noise_s16_pink(pNoise, 0); + for (iChannel = 0; iChannel < channels; iChannel += 1) { + pFramesOutS16[iFrame*channels + iChannel] = s; + } + } + } else { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannel = 0; iChannel < channels; iChannel += 1) { + pFramesOutS16[iFrame*channels + iChannel] = ma_noise_s16_pink(pNoise, iChannel); + } + } + } + } else { + const ma_uint32 bps = ma_get_bytes_per_sample(pNoise->config.format); + const ma_uint32 bpf = bps * channels; + + if (pNoise->config.duplicateChannels) { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + float s = ma_noise_f32_pink(pNoise, 0); + for (iChannel = 0; iChannel < channels; iChannel += 1) { + ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none); + } + } + } else { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannel = 0; iChannel < channels; iChannel += 1) { + float s = ma_noise_f32_pink(pNoise, iChannel); + ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none); + } + } + } + } + + return frameCount; +} + + +static MA_INLINE float ma_noise_f32_brownian(ma_noise* pNoise, ma_uint32 iChannel) +{ + double result; + + result = (ma_lcg_rand_f64(&pNoise->lcg) + pNoise->state.brownian.accumulation[iChannel]); + result /= 1.005; /* Don't escape the -1..1 range on average. */ + + pNoise->state.brownian.accumulation[iChannel] = result; + result /= 20; + + return (float)(result * pNoise->config.amplitude); +} + +static MA_INLINE ma_int16 ma_noise_s16_brownian(ma_noise* pNoise, ma_uint32 iChannel) +{ + return ma_pcm_sample_f32_to_s16(ma_noise_f32_brownian(pNoise, iChannel)); +} + +static MA_INLINE ma_uint64 ma_noise_read_pcm_frames__brownian(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount) +{ + ma_uint64 iFrame; + ma_uint32 iChannel; + const ma_uint32 channels = pNoise->config.channels; + MA_ASSUME(channels > 0); + + if (pNoise->config.format == ma_format_f32) { + float* pFramesOutF32 = (float*)pFramesOut; + if (pNoise->config.duplicateChannels) { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + float s = ma_noise_f32_brownian(pNoise, 0); + for (iChannel = 0; iChannel < channels; iChannel += 1) { + pFramesOutF32[iFrame*channels + iChannel] = s; + } + } + } else { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannel = 0; iChannel < channels; iChannel += 1) { + pFramesOutF32[iFrame*channels + iChannel] = ma_noise_f32_brownian(pNoise, iChannel); + } + } + } + } else if (pNoise->config.format == ma_format_s16) { + ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut; + if (pNoise->config.duplicateChannels) { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_int16 s = ma_noise_s16_brownian(pNoise, 0); + for (iChannel = 0; iChannel < channels; iChannel += 1) { + pFramesOutS16[iFrame*channels + iChannel] = s; + } + } + } else { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannel = 0; iChannel < channels; iChannel += 1) { + pFramesOutS16[iFrame*channels + iChannel] = ma_noise_s16_brownian(pNoise, iChannel); + } + } + } + } else { + const ma_uint32 bps = ma_get_bytes_per_sample(pNoise->config.format); + const ma_uint32 bpf = bps * channels; + + if (pNoise->config.duplicateChannels) { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + float s = ma_noise_f32_brownian(pNoise, 0); + for (iChannel = 0; iChannel < channels; iChannel += 1) { + ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none); + } + } + } else { + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + for (iChannel = 0; iChannel < channels; iChannel += 1) { + float s = ma_noise_f32_brownian(pNoise, iChannel); + ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none); + } + } + } + } + + return frameCount; +} + +MA_API ma_result ma_noise_read_pcm_frames(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + ma_uint64 framesRead = 0; + + if (pFramesRead != NULL) { + *pFramesRead = 0; + } + + if (frameCount == 0) { + return MA_INVALID_ARGS; + } + + if (pNoise == NULL) { + return MA_INVALID_ARGS; + } + + /* The output buffer is allowed to be NULL. Since we aren't tracking cursors or anything we can just do nothing and pretend to be successful. */ + if (pFramesOut == NULL) { + framesRead = frameCount; + } else { + switch (pNoise->config.type) { + case ma_noise_type_white: framesRead = ma_noise_read_pcm_frames__white (pNoise, pFramesOut, frameCount); break; + case ma_noise_type_pink: framesRead = ma_noise_read_pcm_frames__pink (pNoise, pFramesOut, frameCount); break; + case ma_noise_type_brownian: framesRead = ma_noise_read_pcm_frames__brownian(pNoise, pFramesOut, frameCount); break; + default: return MA_INVALID_OPERATION; /* Unknown noise type. */ + } + } + + if (pFramesRead != NULL) { + *pFramesRead = framesRead; + } + + return MA_SUCCESS; +} +#endif /* MA_NO_GENERATION */ + + + +#ifndef MA_NO_RESOURCE_MANAGER +#ifndef MA_RESOURCE_MANAGER_PAGE_SIZE_IN_MILLISECONDS +#define MA_RESOURCE_MANAGER_PAGE_SIZE_IN_MILLISECONDS 1000 +#endif + +#ifndef MA_JOB_TYPE_RESOURCE_MANAGER_QUEUE_CAPACITY +#define MA_JOB_TYPE_RESOURCE_MANAGER_QUEUE_CAPACITY 1024 +#endif + +MA_API ma_resource_manager_pipeline_notifications ma_resource_manager_pipeline_notifications_init(void) +{ + ma_resource_manager_pipeline_notifications notifications; + + MA_ZERO_OBJECT(¬ifications); + + return notifications; +} + +static void ma_resource_manager_pipeline_notifications_signal_all_notifications(const ma_resource_manager_pipeline_notifications* pPipelineNotifications) +{ + if (pPipelineNotifications == NULL) { + return; + } + + if (pPipelineNotifications->init.pNotification) { ma_async_notification_signal(pPipelineNotifications->init.pNotification); } + if (pPipelineNotifications->done.pNotification) { ma_async_notification_signal(pPipelineNotifications->done.pNotification); } +} + +static void ma_resource_manager_pipeline_notifications_acquire_all_fences(const ma_resource_manager_pipeline_notifications* pPipelineNotifications) +{ + if (pPipelineNotifications == NULL) { + return; + } + + if (pPipelineNotifications->init.pFence != NULL) { ma_fence_acquire(pPipelineNotifications->init.pFence); } + if (pPipelineNotifications->done.pFence != NULL) { ma_fence_acquire(pPipelineNotifications->done.pFence); } +} + +static void ma_resource_manager_pipeline_notifications_release_all_fences(const ma_resource_manager_pipeline_notifications* pPipelineNotifications) +{ + if (pPipelineNotifications == NULL) { + return; + } + + if (pPipelineNotifications->init.pFence != NULL) { ma_fence_release(pPipelineNotifications->init.pFence); } + if (pPipelineNotifications->done.pFence != NULL) { ma_fence_release(pPipelineNotifications->done.pFence); } +} + + + +#ifndef MA_DEFAULT_HASH_SEED +#define MA_DEFAULT_HASH_SEED 42 +#endif + +/* MurmurHash3. Based on code from https://github.com/PeterScott/murmur3/blob/master/murmur3.c (public domain). */ +#if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))) + #pragma GCC diagnostic push + #if __GNUC__ >= 7 + #pragma GCC diagnostic ignored "-Wimplicit-fallthrough" + #endif +#endif + +static MA_INLINE ma_uint32 ma_rotl32(ma_uint32 x, ma_int8 r) +{ + return (x << r) | (x >> (32 - r)); +} + +static MA_INLINE ma_uint32 ma_hash_getblock(const ma_uint32* blocks, int i) +{ + ma_uint32 block; + + /* Try silencing a sanitization warning about unaligned access by doing a memcpy() instead of assignment. */ + MA_COPY_MEMORY(&block, ma_offset_ptr(blocks, i * sizeof(block)), sizeof(block)); + + if (ma_is_little_endian()) { + return block; + } else { + return ma_swap_endian_uint32(block); + } +} + +static MA_INLINE ma_uint32 ma_hash_fmix32(ma_uint32 h) +{ + h ^= h >> 16; + h *= 0x85ebca6b; + h ^= h >> 13; + h *= 0xc2b2ae35; + h ^= h >> 16; + + return h; +} + +static ma_uint32 ma_hash_32(const void* key, int len, ma_uint32 seed) +{ + const ma_uint8* data = (const ma_uint8*)key; + const ma_uint32* blocks; + const ma_uint8* tail; + const int nblocks = len / 4; + ma_uint32 h1 = seed; + ma_uint32 c1 = 0xcc9e2d51; + ma_uint32 c2 = 0x1b873593; + ma_uint32 k1; + int i; + + blocks = (const ma_uint32 *)(data + nblocks*4); + + for(i = -nblocks; i; i++) { + k1 = ma_hash_getblock(blocks,i); + + k1 *= c1; + k1 = ma_rotl32(k1, 15); + k1 *= c2; + + h1 ^= k1; + h1 = ma_rotl32(h1, 13); + h1 = h1*5 + 0xe6546b64; + } + + + tail = (const ma_uint8*)(data + nblocks*4); + + k1 = 0; + switch(len & 3) { + case 3: k1 ^= tail[2] << 16; + case 2: k1 ^= tail[1] << 8; + case 1: k1 ^= tail[0]; + k1 *= c1; k1 = ma_rotl32(k1, 15); k1 *= c2; h1 ^= k1; + }; + + + h1 ^= len; + h1 = ma_hash_fmix32(h1); + + return h1; +} + +#if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))) + #pragma GCC diagnostic push +#endif +/* End MurmurHash3 */ + +static ma_uint32 ma_hash_string_32(const char* str) +{ + return ma_hash_32(str, (int)strlen(str), MA_DEFAULT_HASH_SEED); +} + +static ma_uint32 ma_hash_string_w_32(const wchar_t* str) +{ + return ma_hash_32(str, (int)wcslen(str) * sizeof(*str), MA_DEFAULT_HASH_SEED); +} + + + + +/* +Basic BST Functions +*/ +static ma_result ma_resource_manager_data_buffer_node_search(ma_resource_manager* pResourceManager, ma_uint32 hashedName32, ma_resource_manager_data_buffer_node** ppDataBufferNode) +{ + ma_resource_manager_data_buffer_node* pCurrentNode; + + MA_ASSERT(pResourceManager != NULL); + MA_ASSERT(ppDataBufferNode != NULL); + + pCurrentNode = pResourceManager->pRootDataBufferNode; + while (pCurrentNode != NULL) { + if (hashedName32 == pCurrentNode->hashedName32) { + break; /* Found. */ + } else if (hashedName32 < pCurrentNode->hashedName32) { + pCurrentNode = pCurrentNode->pChildLo; + } else { + pCurrentNode = pCurrentNode->pChildHi; + } + } + + *ppDataBufferNode = pCurrentNode; + + if (pCurrentNode == NULL) { + return MA_DOES_NOT_EXIST; + } else { + return MA_SUCCESS; + } +} + +static ma_result ma_resource_manager_data_buffer_node_insert_point(ma_resource_manager* pResourceManager, ma_uint32 hashedName32, ma_resource_manager_data_buffer_node** ppInsertPoint) +{ + ma_result result = MA_SUCCESS; + ma_resource_manager_data_buffer_node* pCurrentNode; + + MA_ASSERT(pResourceManager != NULL); + MA_ASSERT(ppInsertPoint != NULL); + + *ppInsertPoint = NULL; + + if (pResourceManager->pRootDataBufferNode == NULL) { + return MA_SUCCESS; /* No items. */ + } + + /* We need to find the node that will become the parent of the new node. If a node is found that already has the same hashed name we need to return MA_ALREADY_EXISTS. */ + pCurrentNode = pResourceManager->pRootDataBufferNode; + while (pCurrentNode != NULL) { + if (hashedName32 == pCurrentNode->hashedName32) { + result = MA_ALREADY_EXISTS; + break; + } else { + if (hashedName32 < pCurrentNode->hashedName32) { + if (pCurrentNode->pChildLo == NULL) { + result = MA_SUCCESS; + break; + } else { + pCurrentNode = pCurrentNode->pChildLo; + } + } else { + if (pCurrentNode->pChildHi == NULL) { + result = MA_SUCCESS; + break; + } else { + pCurrentNode = pCurrentNode->pChildHi; + } + } + } + } + + *ppInsertPoint = pCurrentNode; + return result; +} + +static ma_result ma_resource_manager_data_buffer_node_insert_at(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode, ma_resource_manager_data_buffer_node* pInsertPoint) +{ + MA_ASSERT(pResourceManager != NULL); + MA_ASSERT(pDataBufferNode != NULL); + + /* The key must have been set before calling this function. */ + MA_ASSERT(pDataBufferNode->hashedName32 != 0); + + if (pInsertPoint == NULL) { + /* It's the first node. */ + pResourceManager->pRootDataBufferNode = pDataBufferNode; + } else { + /* It's not the first node. It needs to be inserted. */ + if (pDataBufferNode->hashedName32 < pInsertPoint->hashedName32) { + MA_ASSERT(pInsertPoint->pChildLo == NULL); + pInsertPoint->pChildLo = pDataBufferNode; + } else { + MA_ASSERT(pInsertPoint->pChildHi == NULL); + pInsertPoint->pChildHi = pDataBufferNode; + } + } + + pDataBufferNode->pParent = pInsertPoint; + + return MA_SUCCESS; +} + +#if 0 /* Unused for now. */ +static ma_result ma_resource_manager_data_buffer_node_insert(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode) +{ + ma_result result; + ma_resource_manager_data_buffer_node* pInsertPoint; + + MA_ASSERT(pResourceManager != NULL); + MA_ASSERT(pDataBufferNode != NULL); + + result = ma_resource_manager_data_buffer_node_insert_point(pResourceManager, pDataBufferNode->hashedName32, &pInsertPoint); + if (result != MA_SUCCESS) { + return MA_INVALID_ARGS; + } + + return ma_resource_manager_data_buffer_node_insert_at(pResourceManager, pDataBufferNode, pInsertPoint); +} +#endif + +static MA_INLINE ma_resource_manager_data_buffer_node* ma_resource_manager_data_buffer_node_find_min(ma_resource_manager_data_buffer_node* pDataBufferNode) +{ + ma_resource_manager_data_buffer_node* pCurrentNode; + + MA_ASSERT(pDataBufferNode != NULL); + + pCurrentNode = pDataBufferNode; + while (pCurrentNode->pChildLo != NULL) { + pCurrentNode = pCurrentNode->pChildLo; + } + + return pCurrentNode; +} + +static MA_INLINE ma_resource_manager_data_buffer_node* ma_resource_manager_data_buffer_node_find_max(ma_resource_manager_data_buffer_node* pDataBufferNode) +{ + ma_resource_manager_data_buffer_node* pCurrentNode; + + MA_ASSERT(pDataBufferNode != NULL); + + pCurrentNode = pDataBufferNode; + while (pCurrentNode->pChildHi != NULL) { + pCurrentNode = pCurrentNode->pChildHi; + } + + return pCurrentNode; +} + +static MA_INLINE ma_resource_manager_data_buffer_node* ma_resource_manager_data_buffer_node_find_inorder_successor(ma_resource_manager_data_buffer_node* pDataBufferNode) +{ + MA_ASSERT(pDataBufferNode != NULL); + MA_ASSERT(pDataBufferNode->pChildHi != NULL); + + return ma_resource_manager_data_buffer_node_find_min(pDataBufferNode->pChildHi); +} + +static MA_INLINE ma_resource_manager_data_buffer_node* ma_resource_manager_data_buffer_node_find_inorder_predecessor(ma_resource_manager_data_buffer_node* pDataBufferNode) +{ + MA_ASSERT(pDataBufferNode != NULL); + MA_ASSERT(pDataBufferNode->pChildLo != NULL); + + return ma_resource_manager_data_buffer_node_find_max(pDataBufferNode->pChildLo); +} + +static ma_result ma_resource_manager_data_buffer_node_remove(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode) +{ + MA_ASSERT(pResourceManager != NULL); + MA_ASSERT(pDataBufferNode != NULL); + + if (pDataBufferNode->pChildLo == NULL) { + if (pDataBufferNode->pChildHi == NULL) { + /* Simple case - deleting a buffer with no children. */ + if (pDataBufferNode->pParent == NULL) { + MA_ASSERT(pResourceManager->pRootDataBufferNode == pDataBufferNode); /* There is only a single buffer in the tree which should be equal to the root node. */ + pResourceManager->pRootDataBufferNode = NULL; + } else { + if (pDataBufferNode->pParent->pChildLo == pDataBufferNode) { + pDataBufferNode->pParent->pChildLo = NULL; + } else { + pDataBufferNode->pParent->pChildHi = NULL; + } + } + } else { + /* Node has one child - pChildHi != NULL. */ + pDataBufferNode->pChildHi->pParent = pDataBufferNode->pParent; + + if (pDataBufferNode->pParent == NULL) { + MA_ASSERT(pResourceManager->pRootDataBufferNode == pDataBufferNode); + pResourceManager->pRootDataBufferNode = pDataBufferNode->pChildHi; + } else { + if (pDataBufferNode->pParent->pChildLo == pDataBufferNode) { + pDataBufferNode->pParent->pChildLo = pDataBufferNode->pChildHi; + } else { + pDataBufferNode->pParent->pChildHi = pDataBufferNode->pChildHi; + } + } + } + } else { + if (pDataBufferNode->pChildHi == NULL) { + /* Node has one child - pChildLo != NULL. */ + pDataBufferNode->pChildLo->pParent = pDataBufferNode->pParent; + + if (pDataBufferNode->pParent == NULL) { + MA_ASSERT(pResourceManager->pRootDataBufferNode == pDataBufferNode); + pResourceManager->pRootDataBufferNode = pDataBufferNode->pChildLo; + } else { + if (pDataBufferNode->pParent->pChildLo == pDataBufferNode) { + pDataBufferNode->pParent->pChildLo = pDataBufferNode->pChildLo; + } else { + pDataBufferNode->pParent->pChildHi = pDataBufferNode->pChildLo; + } + } + } else { + /* Complex case - deleting a node with two children. */ + ma_resource_manager_data_buffer_node* pReplacementDataBufferNode; + + /* For now we are just going to use the in-order successor as the replacement, but we may want to try to keep this balanced by switching between the two. */ + pReplacementDataBufferNode = ma_resource_manager_data_buffer_node_find_inorder_successor(pDataBufferNode); + MA_ASSERT(pReplacementDataBufferNode != NULL); + + /* + Now that we have our replacement node we can make the change. The simple way to do this would be to just exchange the values, and then remove the replacement + node, however we track specific nodes via pointers which means we can't just swap out the values. We need to instead just change the pointers around. The + replacement node should have at most 1 child. Therefore, we can detach it in terms of our simpler cases above. What we're essentially doing is detaching the + replacement node and reinserting it into the same position as the deleted node. + */ + MA_ASSERT(pReplacementDataBufferNode->pParent != NULL); /* The replacement node should never be the root which means it should always have a parent. */ + MA_ASSERT(pReplacementDataBufferNode->pChildLo == NULL); /* Because we used in-order successor. This would be pChildHi == NULL if we used in-order predecessor. */ + + if (pReplacementDataBufferNode->pChildHi == NULL) { + if (pReplacementDataBufferNode->pParent->pChildLo == pReplacementDataBufferNode) { + pReplacementDataBufferNode->pParent->pChildLo = NULL; + } else { + pReplacementDataBufferNode->pParent->pChildHi = NULL; + } + } else { + pReplacementDataBufferNode->pChildHi->pParent = pReplacementDataBufferNode->pParent; + if (pReplacementDataBufferNode->pParent->pChildLo == pReplacementDataBufferNode) { + pReplacementDataBufferNode->pParent->pChildLo = pReplacementDataBufferNode->pChildHi; + } else { + pReplacementDataBufferNode->pParent->pChildHi = pReplacementDataBufferNode->pChildHi; + } + } + + + /* The replacement node has essentially been detached from the binary tree, so now we need to replace the old data buffer with it. The first thing to update is the parent */ + if (pDataBufferNode->pParent != NULL) { + if (pDataBufferNode->pParent->pChildLo == pDataBufferNode) { + pDataBufferNode->pParent->pChildLo = pReplacementDataBufferNode; + } else { + pDataBufferNode->pParent->pChildHi = pReplacementDataBufferNode; + } + } + + /* Now need to update the replacement node's pointers. */ + pReplacementDataBufferNode->pParent = pDataBufferNode->pParent; + pReplacementDataBufferNode->pChildLo = pDataBufferNode->pChildLo; + pReplacementDataBufferNode->pChildHi = pDataBufferNode->pChildHi; + + /* Now the children of the replacement node need to have their parent pointers updated. */ + if (pReplacementDataBufferNode->pChildLo != NULL) { + pReplacementDataBufferNode->pChildLo->pParent = pReplacementDataBufferNode; + } + if (pReplacementDataBufferNode->pChildHi != NULL) { + pReplacementDataBufferNode->pChildHi->pParent = pReplacementDataBufferNode; + } + + /* Now the root node needs to be updated. */ + if (pResourceManager->pRootDataBufferNode == pDataBufferNode) { + pResourceManager->pRootDataBufferNode = pReplacementDataBufferNode; + } + } + } + + return MA_SUCCESS; +} + +#if 0 /* Unused for now. */ +static ma_result ma_resource_manager_data_buffer_node_remove_by_key(ma_resource_manager* pResourceManager, ma_uint32 hashedName32) +{ + ma_result result; + ma_resource_manager_data_buffer_node* pDataBufferNode; + + result = ma_resource_manager_data_buffer_search(pResourceManager, hashedName32, &pDataBufferNode); + if (result != MA_SUCCESS) { + return result; /* Could not find the data buffer. */ + } + + return ma_resource_manager_data_buffer_remove(pResourceManager, pDataBufferNode); +} +#endif + +static ma_resource_manager_data_supply_type ma_resource_manager_data_buffer_node_get_data_supply_type(ma_resource_manager_data_buffer_node* pDataBufferNode) +{ + return (ma_resource_manager_data_supply_type)ma_atomic_load_i32(&pDataBufferNode->data.type); +} + +static void ma_resource_manager_data_buffer_node_set_data_supply_type(ma_resource_manager_data_buffer_node* pDataBufferNode, ma_resource_manager_data_supply_type supplyType) +{ + ma_atomic_exchange_i32(&pDataBufferNode->data.type, supplyType); +} + +static ma_result ma_resource_manager_data_buffer_node_increment_ref(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode, ma_uint32* pNewRefCount) +{ + ma_uint32 refCount; + + MA_ASSERT(pResourceManager != NULL); + MA_ASSERT(pDataBufferNode != NULL); + + (void)pResourceManager; + + refCount = ma_atomic_fetch_add_32(&pDataBufferNode->refCount, 1) + 1; + + if (pNewRefCount != NULL) { + *pNewRefCount = refCount; + } + + return MA_SUCCESS; +} + +static ma_result ma_resource_manager_data_buffer_node_decrement_ref(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode, ma_uint32* pNewRefCount) +{ + ma_uint32 refCount; + + MA_ASSERT(pResourceManager != NULL); + MA_ASSERT(pDataBufferNode != NULL); + + (void)pResourceManager; + + refCount = ma_atomic_fetch_sub_32(&pDataBufferNode->refCount, 1) - 1; + + if (pNewRefCount != NULL) { + *pNewRefCount = refCount; + } + + return MA_SUCCESS; +} + +static void ma_resource_manager_data_buffer_node_free(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode) +{ + MA_ASSERT(pResourceManager != NULL); + MA_ASSERT(pDataBufferNode != NULL); + + if (pDataBufferNode->isDataOwnedByResourceManager) { + if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBufferNode) == ma_resource_manager_data_supply_type_encoded) { + ma_free((void*)pDataBufferNode->data.backend.encoded.pData, &pResourceManager->config.allocationCallbacks); + pDataBufferNode->data.backend.encoded.pData = NULL; + pDataBufferNode->data.backend.encoded.sizeInBytes = 0; + } else if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBufferNode) == ma_resource_manager_data_supply_type_decoded) { + ma_free((void*)pDataBufferNode->data.backend.decoded.pData, &pResourceManager->config.allocationCallbacks); + pDataBufferNode->data.backend.decoded.pData = NULL; + pDataBufferNode->data.backend.decoded.totalFrameCount = 0; + } else if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBufferNode) == ma_resource_manager_data_supply_type_decoded_paged) { + ma_paged_audio_buffer_data_uninit(&pDataBufferNode->data.backend.decodedPaged.data, &pResourceManager->config.allocationCallbacks); + } else { + /* Should never hit this if the node was successfully initialized. */ + MA_ASSERT(pDataBufferNode->result != MA_SUCCESS); + } + } + + /* The data buffer itself needs to be freed. */ + ma_free(pDataBufferNode, &pResourceManager->config.allocationCallbacks); +} + +static ma_result ma_resource_manager_data_buffer_node_result(const ma_resource_manager_data_buffer_node* pDataBufferNode) +{ + MA_ASSERT(pDataBufferNode != NULL); + + return (ma_result)ma_atomic_load_i32((ma_result*)&pDataBufferNode->result); /* Need a naughty const-cast here. */ +} + + +static ma_bool32 ma_resource_manager_is_threading_enabled(const ma_resource_manager* pResourceManager) +{ + MA_ASSERT(pResourceManager != NULL); + + return (pResourceManager->config.flags & MA_RESOURCE_MANAGER_FLAG_NO_THREADING) == 0; +} + + +typedef struct +{ + union + { + ma_async_notification_event e; + ma_async_notification_poll p; + } backend; /* Must be the first member. */ + ma_resource_manager* pResourceManager; +} ma_resource_manager_inline_notification; + +static ma_result ma_resource_manager_inline_notification_init(ma_resource_manager* pResourceManager, ma_resource_manager_inline_notification* pNotification) +{ + MA_ASSERT(pResourceManager != NULL); + MA_ASSERT(pNotification != NULL); + + pNotification->pResourceManager = pResourceManager; + + if (ma_resource_manager_is_threading_enabled(pResourceManager)) { + return ma_async_notification_event_init(&pNotification->backend.e); + } else { + return ma_async_notification_poll_init(&pNotification->backend.p); + } +} + +static void ma_resource_manager_inline_notification_uninit(ma_resource_manager_inline_notification* pNotification) +{ + MA_ASSERT(pNotification != NULL); + + if (ma_resource_manager_is_threading_enabled(pNotification->pResourceManager)) { + ma_async_notification_event_uninit(&pNotification->backend.e); + } else { + /* No need to uninitialize a polling notification. */ + } +} + +static void ma_resource_manager_inline_notification_wait(ma_resource_manager_inline_notification* pNotification) +{ + MA_ASSERT(pNotification != NULL); + + if (ma_resource_manager_is_threading_enabled(pNotification->pResourceManager)) { + ma_async_notification_event_wait(&pNotification->backend.e); + } else { + while (ma_async_notification_poll_is_signalled(&pNotification->backend.p) == MA_FALSE) { + ma_result result = ma_resource_manager_process_next_job(pNotification->pResourceManager); + if (result == MA_NO_DATA_AVAILABLE || result == MA_CANCELLED) { + break; + } + } + } +} + +static void ma_resource_manager_inline_notification_wait_and_uninit(ma_resource_manager_inline_notification* pNotification) +{ + ma_resource_manager_inline_notification_wait(pNotification); + ma_resource_manager_inline_notification_uninit(pNotification); +} + + +static void ma_resource_manager_data_buffer_bst_lock(ma_resource_manager* pResourceManager) +{ + MA_ASSERT(pResourceManager != NULL); + + if (ma_resource_manager_is_threading_enabled(pResourceManager)) { + #ifndef MA_NO_THREADING + { + ma_mutex_lock(&pResourceManager->dataBufferBSTLock); + } + #else + { + MA_ASSERT(MA_FALSE); /* Should never hit this. */ + } + #endif + } else { + /* Threading not enabled. Do nothing. */ + } +} + +static void ma_resource_manager_data_buffer_bst_unlock(ma_resource_manager* pResourceManager) +{ + MA_ASSERT(pResourceManager != NULL); + + if (ma_resource_manager_is_threading_enabled(pResourceManager)) { + #ifndef MA_NO_THREADING + { + ma_mutex_unlock(&pResourceManager->dataBufferBSTLock); + } + #else + { + MA_ASSERT(MA_FALSE); /* Should never hit this. */ + } + #endif + } else { + /* Threading not enabled. Do nothing. */ + } +} + +#ifndef MA_NO_THREADING +static ma_thread_result MA_THREADCALL ma_resource_manager_job_thread(void* pUserData) +{ + ma_resource_manager* pResourceManager = (ma_resource_manager*)pUserData; + MA_ASSERT(pResourceManager != NULL); + + for (;;) { + ma_result result; + ma_job job; + + result = ma_resource_manager_next_job(pResourceManager, &job); + if (result != MA_SUCCESS) { + break; + } + + /* Terminate if we got a quit message. */ + if (job.toc.breakup.code == MA_JOB_TYPE_QUIT) { + break; + } + + ma_job_process(&job); + } + + return (ma_thread_result)0; +} +#endif + +MA_API ma_resource_manager_config ma_resource_manager_config_init(void) +{ + ma_resource_manager_config config; + + MA_ZERO_OBJECT(&config); + config.decodedFormat = ma_format_unknown; + config.decodedChannels = 0; + config.decodedSampleRate = 0; + config.jobThreadCount = 1; /* A single miniaudio-managed job thread by default. */ + config.jobQueueCapacity = MA_JOB_TYPE_RESOURCE_MANAGER_QUEUE_CAPACITY; + + /* Flags. */ + config.flags = 0; + #ifdef MA_NO_THREADING + { + /* Threading is disabled at compile time so disable threading at runtime as well by default. */ + config.flags |= MA_RESOURCE_MANAGER_FLAG_NO_THREADING; + config.jobThreadCount = 0; + } + #endif + + return config; +} + + +MA_API ma_result ma_resource_manager_init(const ma_resource_manager_config* pConfig, ma_resource_manager* pResourceManager) +{ + ma_result result; + ma_job_queue_config jobQueueConfig; + + if (pResourceManager == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pResourceManager); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + #ifndef MA_NO_THREADING + { + if (pConfig->jobThreadCount > ma_countof(pResourceManager->jobThreads)) { + return MA_INVALID_ARGS; /* Requesting too many job threads. */ + } + } + #endif + + pResourceManager->config = *pConfig; + ma_allocation_callbacks_init_copy(&pResourceManager->config.allocationCallbacks, &pConfig->allocationCallbacks); + + /* Get the log set up early so we can start using it as soon as possible. */ + if (pResourceManager->config.pLog == NULL) { + result = ma_log_init(&pResourceManager->config.allocationCallbacks, &pResourceManager->log); + if (result == MA_SUCCESS) { + pResourceManager->config.pLog = &pResourceManager->log; + } else { + pResourceManager->config.pLog = NULL; /* Logging is unavailable. */ + } + } + + if (pResourceManager->config.pVFS == NULL) { + result = ma_default_vfs_init(&pResourceManager->defaultVFS, &pResourceManager->config.allocationCallbacks); + if (result != MA_SUCCESS) { + return result; /* Failed to initialize the default file system. */ + } + + pResourceManager->config.pVFS = &pResourceManager->defaultVFS; + } + + /* If threading has been disabled at compile time, enfore it at run time as well. */ + #ifdef MA_NO_THREADING + { + pResourceManager->config.flags |= MA_RESOURCE_MANAGER_FLAG_NO_THREADING; + } + #endif + + /* We need to force MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING if MA_RESOURCE_MANAGER_FLAG_NO_THREADING is set. */ + if ((pResourceManager->config.flags & MA_RESOURCE_MANAGER_FLAG_NO_THREADING) != 0) { + pResourceManager->config.flags |= MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING; + + /* We cannot allow job threads when MA_RESOURCE_MANAGER_FLAG_NO_THREADING has been set. This is an invalid use case. */ + if (pResourceManager->config.jobThreadCount > 0) { + return MA_INVALID_ARGS; + } + } + + /* Job queue. */ + jobQueueConfig.capacity = pResourceManager->config.jobQueueCapacity; + jobQueueConfig.flags = 0; + if ((pResourceManager->config.flags & MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING) != 0) { + if (pResourceManager->config.jobThreadCount > 0) { + return MA_INVALID_ARGS; /* Non-blocking mode is only valid for self-managed job threads. */ + } + + jobQueueConfig.flags |= MA_JOB_QUEUE_FLAG_NON_BLOCKING; + } + + result = ma_job_queue_init(&jobQueueConfig, &pResourceManager->config.allocationCallbacks, &pResourceManager->jobQueue); + if (result != MA_SUCCESS) { + return result; + } + + + /* Custom decoding backends. */ + if (pConfig->ppCustomDecodingBackendVTables != NULL && pConfig->customDecodingBackendCount > 0) { + size_t sizeInBytes = sizeof(*pResourceManager->config.ppCustomDecodingBackendVTables) * pConfig->customDecodingBackendCount; + + pResourceManager->config.ppCustomDecodingBackendVTables = (ma_decoding_backend_vtable**)ma_malloc(sizeInBytes, &pResourceManager->config.allocationCallbacks); + if (pResourceManager->config.ppCustomDecodingBackendVTables == NULL) { + ma_job_queue_uninit(&pResourceManager->jobQueue, &pResourceManager->config.allocationCallbacks); + return MA_OUT_OF_MEMORY; + } + + MA_COPY_MEMORY(pResourceManager->config.ppCustomDecodingBackendVTables, pConfig->ppCustomDecodingBackendVTables, sizeInBytes); + + pResourceManager->config.customDecodingBackendCount = pConfig->customDecodingBackendCount; + pResourceManager->config.pCustomDecodingBackendUserData = pConfig->pCustomDecodingBackendUserData; + } + + + + /* Here is where we initialize our threading stuff. We don't do this if we don't support threading. */ + if (ma_resource_manager_is_threading_enabled(pResourceManager)) { + #ifndef MA_NO_THREADING + { + ma_uint32 iJobThread; + + /* Data buffer lock. */ + result = ma_mutex_init(&pResourceManager->dataBufferBSTLock); + if (result != MA_SUCCESS) { + ma_job_queue_uninit(&pResourceManager->jobQueue, &pResourceManager->config.allocationCallbacks); + return result; + } + + /* Create the job threads last to ensure the threads has access to valid data. */ + for (iJobThread = 0; iJobThread < pResourceManager->config.jobThreadCount; iJobThread += 1) { + result = ma_thread_create(&pResourceManager->jobThreads[iJobThread], ma_thread_priority_normal, pResourceManager->config.jobThreadStackSize, ma_resource_manager_job_thread, pResourceManager, &pResourceManager->config.allocationCallbacks); + if (result != MA_SUCCESS) { + ma_mutex_uninit(&pResourceManager->dataBufferBSTLock); + ma_job_queue_uninit(&pResourceManager->jobQueue, &pResourceManager->config.allocationCallbacks); + return result; + } + } + } + #else + { + /* Threading is disabled at compile time. We should never get here because validation checks should have already been performed. */ + MA_ASSERT(MA_FALSE); + } + #endif + } + + return MA_SUCCESS; +} + + +static void ma_resource_manager_delete_all_data_buffer_nodes(ma_resource_manager* pResourceManager) +{ + MA_ASSERT(pResourceManager); + + /* If everything was done properly, there shouldn't be any active data buffers. */ + while (pResourceManager->pRootDataBufferNode != NULL) { + ma_resource_manager_data_buffer_node* pDataBufferNode = pResourceManager->pRootDataBufferNode; + ma_resource_manager_data_buffer_node_remove(pResourceManager, pDataBufferNode); + + /* The data buffer has been removed from the BST, so now we need to free it's data. */ + ma_resource_manager_data_buffer_node_free(pResourceManager, pDataBufferNode); + } +} + +MA_API void ma_resource_manager_uninit(ma_resource_manager* pResourceManager) +{ + if (pResourceManager == NULL) { + return; + } + + /* + Job threads need to be killed first. To do this we need to post a quit message to the message queue and then wait for the thread. The quit message will never be removed from the + queue which means it will never not be returned after being encounted for the first time which means all threads will eventually receive it. + */ + ma_resource_manager_post_job_quit(pResourceManager); + + /* Wait for every job to finish before continuing to ensure nothing is sill trying to access any of our objects below. */ + if (ma_resource_manager_is_threading_enabled(pResourceManager)) { + #ifndef MA_NO_THREADING + { + ma_uint32 iJobThread; + + for (iJobThread = 0; iJobThread < pResourceManager->config.jobThreadCount; iJobThread += 1) { + ma_thread_wait(&pResourceManager->jobThreads[iJobThread]); + } + } + #else + { + MA_ASSERT(MA_FALSE); /* Should never hit this. */ + } + #endif + } + + /* At this point the thread should have returned and no other thread should be accessing our data. We can now delete all data buffers. */ + ma_resource_manager_delete_all_data_buffer_nodes(pResourceManager); + + /* The job queue is no longer needed. */ + ma_job_queue_uninit(&pResourceManager->jobQueue, &pResourceManager->config.allocationCallbacks); + + /* We're no longer doing anything with data buffers so the lock can now be uninitialized. */ + if (ma_resource_manager_is_threading_enabled(pResourceManager)) { + #ifndef MA_NO_THREADING + { + ma_mutex_uninit(&pResourceManager->dataBufferBSTLock); + } + #else + { + MA_ASSERT(MA_FALSE); /* Should never hit this. */ + } + #endif + } + + ma_free(pResourceManager->config.ppCustomDecodingBackendVTables, &pResourceManager->config.allocationCallbacks); + + if (pResourceManager->config.pLog == &pResourceManager->log) { + ma_log_uninit(&pResourceManager->log); + } +} + +MA_API ma_log* ma_resource_manager_get_log(ma_resource_manager* pResourceManager) +{ + if (pResourceManager == NULL) { + return NULL; + } + + return pResourceManager->config.pLog; +} + + + +MA_API ma_resource_manager_data_source_config ma_resource_manager_data_source_config_init(void) +{ + ma_resource_manager_data_source_config config; + + MA_ZERO_OBJECT(&config); + config.rangeBegInPCMFrames = MA_DATA_SOURCE_DEFAULT_RANGE_BEG; + config.rangeEndInPCMFrames = MA_DATA_SOURCE_DEFAULT_RANGE_END; + config.loopPointBegInPCMFrames = MA_DATA_SOURCE_DEFAULT_LOOP_POINT_BEG; + config.loopPointEndInPCMFrames = MA_DATA_SOURCE_DEFAULT_LOOP_POINT_END; + config.isLooping = MA_FALSE; + + return config; +} + + +static ma_decoder_config ma_resource_manager__init_decoder_config(ma_resource_manager* pResourceManager) +{ + ma_decoder_config config; + + config = ma_decoder_config_init(pResourceManager->config.decodedFormat, pResourceManager->config.decodedChannels, pResourceManager->config.decodedSampleRate); + config.allocationCallbacks = pResourceManager->config.allocationCallbacks; + config.ppCustomBackendVTables = pResourceManager->config.ppCustomDecodingBackendVTables; + config.customBackendCount = pResourceManager->config.customDecodingBackendCount; + config.pCustomBackendUserData = pResourceManager->config.pCustomDecodingBackendUserData; + + return config; +} + +static ma_result ma_resource_manager__init_decoder(ma_resource_manager* pResourceManager, const char* pFilePath, const wchar_t* pFilePathW, ma_decoder* pDecoder) +{ + ma_result result; + ma_decoder_config config; + + MA_ASSERT(pResourceManager != NULL); + MA_ASSERT(pFilePath != NULL || pFilePathW != NULL); + MA_ASSERT(pDecoder != NULL); + + config = ma_resource_manager__init_decoder_config(pResourceManager); + + if (pFilePath != NULL) { + result = ma_decoder_init_vfs(pResourceManager->config.pVFS, pFilePath, &config, pDecoder); + if (result != MA_SUCCESS) { + ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_WARNING, "Failed to load file \"%s\". %s.\n", pFilePath, ma_result_description(result)); + return result; + } + } else { + result = ma_decoder_init_vfs_w(pResourceManager->config.pVFS, pFilePathW, &config, pDecoder); + if (result != MA_SUCCESS) { + #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(_MSC_VER) + ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_WARNING, "Failed to load file \"%ls\". %s.\n", pFilePathW, ma_result_description(result)); + #endif + return result; + } + } + + return MA_SUCCESS; +} + +static ma_bool32 ma_resource_manager_data_buffer_has_connector(ma_resource_manager_data_buffer* pDataBuffer) +{ + return ma_atomic_bool32_get(&pDataBuffer->isConnectorInitialized); +} + +static ma_data_source* ma_resource_manager_data_buffer_get_connector(ma_resource_manager_data_buffer* pDataBuffer) +{ + if (ma_resource_manager_data_buffer_has_connector(pDataBuffer) == MA_FALSE) { + return NULL; /* Connector not yet initialized. */ + } + + switch (pDataBuffer->pNode->data.type) + { + case ma_resource_manager_data_supply_type_encoded: return &pDataBuffer->connector.decoder; + case ma_resource_manager_data_supply_type_decoded: return &pDataBuffer->connector.buffer; + case ma_resource_manager_data_supply_type_decoded_paged: return &pDataBuffer->connector.pagedBuffer; + + case ma_resource_manager_data_supply_type_unknown: + default: + { + ma_log_postf(ma_resource_manager_get_log(pDataBuffer->pResourceManager), MA_LOG_LEVEL_ERROR, "Failed to retrieve data buffer connector. Unknown data supply type.\n"); + return NULL; + }; + }; +} + +static ma_result ma_resource_manager_data_buffer_init_connector(ma_resource_manager_data_buffer* pDataBuffer, const ma_resource_manager_data_source_config* pConfig, ma_async_notification* pInitNotification, ma_fence* pInitFence) +{ + ma_result result; + + MA_ASSERT(pDataBuffer != NULL); + MA_ASSERT(pConfig != NULL); + MA_ASSERT(ma_resource_manager_data_buffer_has_connector(pDataBuffer) == MA_FALSE); + + /* The underlying data buffer must be initialized before we'll be able to know how to initialize the backend. */ + result = ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode); + if (result != MA_SUCCESS && result != MA_BUSY) { + return result; /* The data buffer is in an erroneous state. */ + } + + /* + We need to initialize either a ma_decoder or an ma_audio_buffer depending on whether or not the backing data is encoded or decoded. These act as the + "instance" to the data and are used to form the connection between underlying data buffer and the data source. If the data buffer is decoded, we can use + an ma_audio_buffer. This enables us to use memory mapping when mixing which saves us a bit of data movement overhead. + */ + switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode)) + { + case ma_resource_manager_data_supply_type_encoded: /* Connector is a decoder. */ + { + ma_decoder_config config; + config = ma_resource_manager__init_decoder_config(pDataBuffer->pResourceManager); + result = ma_decoder_init_memory(pDataBuffer->pNode->data.backend.encoded.pData, pDataBuffer->pNode->data.backend.encoded.sizeInBytes, &config, &pDataBuffer->connector.decoder); + } break; + + case ma_resource_manager_data_supply_type_decoded: /* Connector is an audio buffer. */ + { + ma_audio_buffer_config config; + config = ma_audio_buffer_config_init(pDataBuffer->pNode->data.backend.decoded.format, pDataBuffer->pNode->data.backend.decoded.channels, pDataBuffer->pNode->data.backend.decoded.totalFrameCount, pDataBuffer->pNode->data.backend.decoded.pData, NULL); + result = ma_audio_buffer_init(&config, &pDataBuffer->connector.buffer); + } break; + + case ma_resource_manager_data_supply_type_decoded_paged: /* Connector is a paged audio buffer. */ + { + ma_paged_audio_buffer_config config; + config = ma_paged_audio_buffer_config_init(&pDataBuffer->pNode->data.backend.decodedPaged.data); + result = ma_paged_audio_buffer_init(&config, &pDataBuffer->connector.pagedBuffer); + } break; + + case ma_resource_manager_data_supply_type_unknown: + default: + { + /* Unknown data supply type. Should never happen. Need to post an error here. */ + return MA_INVALID_ARGS; + }; + } + + /* + Initialization of the connector is when we can fire the init notification. This will give the application access to + the format/channels/rate of the data source. + */ + if (result == MA_SUCCESS) { + /* + The resource manager supports the ability to set the range and loop settings via a config at + initialization time. This results in an case where the ranges could be set explicitly via + ma_data_source_set_*() before we get to this point here. If this happens, we'll end up + hitting a case where we just override those settings which results in what feels like a bug. + + To address this we only change the relevant properties if they're not equal to defaults. If + they're equal to defaults there's no need to change them anyway. If they're *not* set to the + default values, we can assume the user has set the range and loop settings via the config. If + they're doing their own calls to ma_data_source_set_*() in addition to setting them via the + config, that's entirely on the caller and any synchronization issue becomes their problem. + */ + if (pConfig->rangeBegInPCMFrames != MA_DATA_SOURCE_DEFAULT_RANGE_BEG || pConfig->rangeEndInPCMFrames != MA_DATA_SOURCE_DEFAULT_RANGE_END) { + ma_data_source_set_range_in_pcm_frames(pDataBuffer, pConfig->rangeBegInPCMFrames, pConfig->rangeEndInPCMFrames); + } + + if (pConfig->loopPointBegInPCMFrames != MA_DATA_SOURCE_DEFAULT_LOOP_POINT_BEG || pConfig->loopPointEndInPCMFrames != MA_DATA_SOURCE_DEFAULT_LOOP_POINT_END) { + ma_data_source_set_loop_point_in_pcm_frames(pDataBuffer, pConfig->loopPointBegInPCMFrames, pConfig->loopPointEndInPCMFrames); + } + + if (pConfig->isLooping != MA_FALSE) { + ma_data_source_set_looping(pDataBuffer, pConfig->isLooping); + } + + ma_atomic_bool32_set(&pDataBuffer->isConnectorInitialized, MA_TRUE); + + if (pInitNotification != NULL) { + ma_async_notification_signal(pInitNotification); + } + + if (pInitFence != NULL) { + ma_fence_release(pInitFence); + } + } + + /* At this point the backend should be initialized. We do *not* want to set pDataSource->result here - that needs to be done at a higher level to ensure it's done as the last step. */ + return result; +} + +static ma_result ma_resource_manager_data_buffer_uninit_connector(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer* pDataBuffer) +{ + MA_ASSERT(pResourceManager != NULL); + MA_ASSERT(pDataBuffer != NULL); + + (void)pResourceManager; + + switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode)) + { + case ma_resource_manager_data_supply_type_encoded: /* Connector is a decoder. */ + { + ma_decoder_uninit(&pDataBuffer->connector.decoder); + } break; + + case ma_resource_manager_data_supply_type_decoded: /* Connector is an audio buffer. */ + { + ma_audio_buffer_uninit(&pDataBuffer->connector.buffer); + } break; + + case ma_resource_manager_data_supply_type_decoded_paged: /* Connector is a paged audio buffer. */ + { + ma_paged_audio_buffer_uninit(&pDataBuffer->connector.pagedBuffer); + } break; + + case ma_resource_manager_data_supply_type_unknown: + default: + { + /* Unknown data supply type. Should never happen. Need to post an error here. */ + return MA_INVALID_ARGS; + }; + } + + return MA_SUCCESS; +} + +static ma_uint32 ma_resource_manager_data_buffer_node_next_execution_order(ma_resource_manager_data_buffer_node* pDataBufferNode) +{ + MA_ASSERT(pDataBufferNode != NULL); + return ma_atomic_fetch_add_32(&pDataBufferNode->executionCounter, 1); +} + +static ma_result ma_resource_manager_data_buffer_node_init_supply_encoded(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode, const char* pFilePath, const wchar_t* pFilePathW) +{ + ma_result result; + size_t dataSizeInBytes; + void* pData; + + MA_ASSERT(pResourceManager != NULL); + MA_ASSERT(pDataBufferNode != NULL); + MA_ASSERT(pFilePath != NULL || pFilePathW != NULL); + + result = ma_vfs_open_and_read_file_ex(pResourceManager->config.pVFS, pFilePath, pFilePathW, &pData, &dataSizeInBytes, &pResourceManager->config.allocationCallbacks); + if (result != MA_SUCCESS) { + if (pFilePath != NULL) { + ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_WARNING, "Failed to load file \"%s\". %s.\n", pFilePath, ma_result_description(result)); + } else { + #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(_MSC_VER) + ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_WARNING, "Failed to load file \"%ls\". %s.\n", pFilePathW, ma_result_description(result)); + #endif + } + + return result; + } + + pDataBufferNode->data.backend.encoded.pData = pData; + pDataBufferNode->data.backend.encoded.sizeInBytes = dataSizeInBytes; + ma_resource_manager_data_buffer_node_set_data_supply_type(pDataBufferNode, ma_resource_manager_data_supply_type_encoded); /* <-- Must be set last. */ + + return MA_SUCCESS; +} + +static ma_result ma_resource_manager_data_buffer_node_init_supply_decoded(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode, const char* pFilePath, const wchar_t* pFilePathW, ma_uint32 flags, ma_decoder** ppDecoder) +{ + ma_result result = MA_SUCCESS; + ma_decoder* pDecoder; + ma_uint64 totalFrameCount; + + MA_ASSERT(pResourceManager != NULL); + MA_ASSERT(pDataBufferNode != NULL); + MA_ASSERT(ppDecoder != NULL); + MA_ASSERT(pFilePath != NULL || pFilePathW != NULL); + + *ppDecoder = NULL; /* For safety. */ + + pDecoder = (ma_decoder*)ma_malloc(sizeof(*pDecoder), &pResourceManager->config.allocationCallbacks); + if (pDecoder == NULL) { + return MA_OUT_OF_MEMORY; + } + + result = ma_resource_manager__init_decoder(pResourceManager, pFilePath, pFilePathW, pDecoder); + if (result != MA_SUCCESS) { + ma_free(pDecoder, &pResourceManager->config.allocationCallbacks); + return result; + } + + /* + At this point we have the decoder and we now need to initialize the data supply. This will + be either a decoded buffer, or a decoded paged buffer. A regular buffer is just one big heap + allocated buffer, whereas a paged buffer is a linked list of paged-sized buffers. The latter + is used when the length of a sound is unknown until a full decode has been performed. + */ + if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_UNKNOWN_LENGTH) == 0) { + result = ma_decoder_get_length_in_pcm_frames(pDecoder, &totalFrameCount); + if (result != MA_SUCCESS) { + return result; + } + } else { + totalFrameCount = 0; + } + + if (totalFrameCount > 0) { + /* It's a known length. The data supply is a regular decoded buffer. */ + ma_uint64 dataSizeInBytes; + void* pData; + + dataSizeInBytes = totalFrameCount * ma_get_bytes_per_frame(pDecoder->outputFormat, pDecoder->outputChannels); + if (dataSizeInBytes > MA_SIZE_MAX) { + ma_decoder_uninit(pDecoder); + ma_free(pDecoder, &pResourceManager->config.allocationCallbacks); + return MA_TOO_BIG; + } + + pData = ma_malloc((size_t)dataSizeInBytes, &pResourceManager->config.allocationCallbacks); + if (pData == NULL) { + ma_decoder_uninit(pDecoder); + ma_free(pDecoder, &pResourceManager->config.allocationCallbacks); + return MA_OUT_OF_MEMORY; + } + + /* The buffer needs to be initialized to silence in case the caller reads from it. */ + ma_silence_pcm_frames(pData, totalFrameCount, pDecoder->outputFormat, pDecoder->outputChannels); + + /* Data has been allocated and the data supply can now be initialized. */ + pDataBufferNode->data.backend.decoded.pData = pData; + pDataBufferNode->data.backend.decoded.totalFrameCount = totalFrameCount; + pDataBufferNode->data.backend.decoded.format = pDecoder->outputFormat; + pDataBufferNode->data.backend.decoded.channels = pDecoder->outputChannels; + pDataBufferNode->data.backend.decoded.sampleRate = pDecoder->outputSampleRate; + pDataBufferNode->data.backend.decoded.decodedFrameCount = 0; + ma_resource_manager_data_buffer_node_set_data_supply_type(pDataBufferNode, ma_resource_manager_data_supply_type_decoded); /* <-- Must be set last. */ + } else { + /* + It's an unknown length. The data supply is a paged decoded buffer. Setting this up is + actually easier than the non-paged decoded buffer because we just need to initialize + a ma_paged_audio_buffer object. + */ + result = ma_paged_audio_buffer_data_init(pDecoder->outputFormat, pDecoder->outputChannels, &pDataBufferNode->data.backend.decodedPaged.data); + if (result != MA_SUCCESS) { + ma_decoder_uninit(pDecoder); + ma_free(pDecoder, &pResourceManager->config.allocationCallbacks); + return result; + } + + pDataBufferNode->data.backend.decodedPaged.sampleRate = pDecoder->outputSampleRate; + pDataBufferNode->data.backend.decodedPaged.decodedFrameCount = 0; + ma_resource_manager_data_buffer_node_set_data_supply_type(pDataBufferNode, ma_resource_manager_data_supply_type_decoded_paged); /* <-- Must be set last. */ + } + + *ppDecoder = pDecoder; + + return MA_SUCCESS; +} + +static ma_result ma_resource_manager_data_buffer_node_decode_next_page(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode, ma_decoder* pDecoder) +{ + ma_result result = MA_SUCCESS; + ma_uint64 pageSizeInFrames; + ma_uint64 framesToTryReading; + ma_uint64 framesRead; + + MA_ASSERT(pResourceManager != NULL); + MA_ASSERT(pDataBufferNode != NULL); + MA_ASSERT(pDecoder != NULL); + + /* We need to know the size of a page in frames to know how many frames to decode. */ + pageSizeInFrames = MA_RESOURCE_MANAGER_PAGE_SIZE_IN_MILLISECONDS * (pDecoder->outputSampleRate/1000); + framesToTryReading = pageSizeInFrames; + + /* + Here is where we do the decoding of the next page. We'll run a slightly different path depending + on whether or not we're using a flat or paged buffer because the allocation of the page differs + between the two. For a flat buffer it's an offset to an already-allocated buffer. For a paged + buffer, we need to allocate a new page and attach it to the linked list. + */ + switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBufferNode)) + { + case ma_resource_manager_data_supply_type_decoded: + { + /* The destination buffer is an offset to the existing buffer. Don't read more than we originally retrieved when we first initialized the decoder. */ + void* pDst; + ma_uint64 framesRemaining = pDataBufferNode->data.backend.decoded.totalFrameCount - pDataBufferNode->data.backend.decoded.decodedFrameCount; + if (framesToTryReading > framesRemaining) { + framesToTryReading = framesRemaining; + } + + if (framesToTryReading > 0) { + pDst = ma_offset_ptr( + pDataBufferNode->data.backend.decoded.pData, + pDataBufferNode->data.backend.decoded.decodedFrameCount * ma_get_bytes_per_frame(pDataBufferNode->data.backend.decoded.format, pDataBufferNode->data.backend.decoded.channels) + ); + MA_ASSERT(pDst != NULL); + + result = ma_decoder_read_pcm_frames(pDecoder, pDst, framesToTryReading, &framesRead); + if (framesRead > 0) { + pDataBufferNode->data.backend.decoded.decodedFrameCount += framesRead; + } + } else { + framesRead = 0; + } + } break; + + case ma_resource_manager_data_supply_type_decoded_paged: + { + /* The destination buffer is a freshly allocated page. */ + ma_paged_audio_buffer_page* pPage; + + result = ma_paged_audio_buffer_data_allocate_page(&pDataBufferNode->data.backend.decodedPaged.data, framesToTryReading, NULL, &pResourceManager->config.allocationCallbacks, &pPage); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_decoder_read_pcm_frames(pDecoder, pPage->pAudioData, framesToTryReading, &framesRead); + if (framesRead > 0) { + pPage->sizeInFrames = framesRead; + + result = ma_paged_audio_buffer_data_append_page(&pDataBufferNode->data.backend.decodedPaged.data, pPage); + if (result == MA_SUCCESS) { + pDataBufferNode->data.backend.decodedPaged.decodedFrameCount += framesRead; + } else { + /* Failed to append the page. Just abort and set the status to MA_AT_END. */ + ma_paged_audio_buffer_data_free_page(&pDataBufferNode->data.backend.decodedPaged.data, pPage, &pResourceManager->config.allocationCallbacks); + result = MA_AT_END; + } + } else { + /* No frames were read. Free the page and just set the status to MA_AT_END. */ + ma_paged_audio_buffer_data_free_page(&pDataBufferNode->data.backend.decodedPaged.data, pPage, &pResourceManager->config.allocationCallbacks); + result = MA_AT_END; + } + } break; + + case ma_resource_manager_data_supply_type_encoded: + case ma_resource_manager_data_supply_type_unknown: + default: + { + /* Unexpected data supply type. */ + ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_ERROR, "Unexpected data supply type (%d) when decoding page.", ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBufferNode)); + return MA_ERROR; + }; + } + + if (result == MA_SUCCESS && framesRead == 0) { + result = MA_AT_END; + } + + return result; +} + +static ma_result ma_resource_manager_data_buffer_node_acquire_critical_section(ma_resource_manager* pResourceManager, const char* pFilePath, const wchar_t* pFilePathW, ma_uint32 hashedName32, ma_uint32 flags, const ma_resource_manager_data_supply* pExistingData, ma_fence* pInitFence, ma_fence* pDoneFence, ma_resource_manager_inline_notification* pInitNotification, ma_resource_manager_data_buffer_node** ppDataBufferNode) +{ + ma_result result = MA_SUCCESS; + ma_resource_manager_data_buffer_node* pDataBufferNode = NULL; + ma_resource_manager_data_buffer_node* pInsertPoint; + + if (ppDataBufferNode != NULL) { + *ppDataBufferNode = NULL; + } + + result = ma_resource_manager_data_buffer_node_insert_point(pResourceManager, hashedName32, &pInsertPoint); + if (result == MA_ALREADY_EXISTS) { + /* The node already exists. We just need to increment the reference count. */ + pDataBufferNode = pInsertPoint; + + result = ma_resource_manager_data_buffer_node_increment_ref(pResourceManager, pDataBufferNode, NULL); + if (result != MA_SUCCESS) { + return result; /* Should never happen. Failed to increment the reference count. */ + } + + result = MA_ALREADY_EXISTS; + goto done; + } else { + /* + The node does not already exist. We need to post a LOAD_DATA_BUFFER_NODE job here. This + needs to be done inside the critical section to ensure an uninitialization of the node + does not occur before initialization on another thread. + */ + pDataBufferNode = (ma_resource_manager_data_buffer_node*)ma_malloc(sizeof(*pDataBufferNode), &pResourceManager->config.allocationCallbacks); + if (pDataBufferNode == NULL) { + return MA_OUT_OF_MEMORY; + } + + MA_ZERO_OBJECT(pDataBufferNode); + pDataBufferNode->hashedName32 = hashedName32; + pDataBufferNode->refCount = 1; /* Always set to 1 by default (this is our first reference). */ + + if (pExistingData == NULL) { + pDataBufferNode->data.type = ma_resource_manager_data_supply_type_unknown; /* <-- We won't know this until we start decoding. */ + pDataBufferNode->result = MA_BUSY; /* Must be set to MA_BUSY before we leave the critical section, so might as well do it now. */ + pDataBufferNode->isDataOwnedByResourceManager = MA_TRUE; + } else { + pDataBufferNode->data = *pExistingData; + pDataBufferNode->result = MA_SUCCESS; /* Not loading asynchronously, so just set the status */ + pDataBufferNode->isDataOwnedByResourceManager = MA_FALSE; + } + + result = ma_resource_manager_data_buffer_node_insert_at(pResourceManager, pDataBufferNode, pInsertPoint); + if (result != MA_SUCCESS) { + ma_free(pDataBufferNode, &pResourceManager->config.allocationCallbacks); + return result; /* Should never happen. Failed to insert the data buffer into the BST. */ + } + + /* + Here is where we'll post the job, but only if we're loading asynchronously. If we're + loading synchronously we'll defer loading to a later stage, outside of the critical + section. + */ + if (pDataBufferNode->isDataOwnedByResourceManager && (flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC) != 0) { + /* Loading asynchronously. Post the job. */ + ma_job job; + char* pFilePathCopy = NULL; + wchar_t* pFilePathWCopy = NULL; + + /* We need a copy of the file path. We should probably make this more efficient, but for now we'll do a transient memory allocation. */ + if (pFilePath != NULL) { + pFilePathCopy = ma_copy_string(pFilePath, &pResourceManager->config.allocationCallbacks); + } else { + pFilePathWCopy = ma_copy_string_w(pFilePathW, &pResourceManager->config.allocationCallbacks); + } + + if (pFilePathCopy == NULL && pFilePathWCopy == NULL) { + ma_resource_manager_data_buffer_node_remove(pResourceManager, pDataBufferNode); + ma_free(pDataBufferNode, &pResourceManager->config.allocationCallbacks); + return MA_OUT_OF_MEMORY; + } + + if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) { + ma_resource_manager_inline_notification_init(pResourceManager, pInitNotification); + } + + /* Acquire init and done fences before posting the job. These will be unacquired by the job thread. */ + if (pInitFence != NULL) { ma_fence_acquire(pInitFence); } + if (pDoneFence != NULL) { ma_fence_acquire(pDoneFence); } + + /* We now have everything we need to post the job to the job thread. */ + job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER_NODE); + job.order = ma_resource_manager_data_buffer_node_next_execution_order(pDataBufferNode); + job.data.resourceManager.loadDataBufferNode.pResourceManager = pResourceManager; + job.data.resourceManager.loadDataBufferNode.pDataBufferNode = pDataBufferNode; + job.data.resourceManager.loadDataBufferNode.pFilePath = pFilePathCopy; + job.data.resourceManager.loadDataBufferNode.pFilePathW = pFilePathWCopy; + job.data.resourceManager.loadDataBufferNode.flags = flags; + job.data.resourceManager.loadDataBufferNode.pInitNotification = ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) ? pInitNotification : NULL; + job.data.resourceManager.loadDataBufferNode.pDoneNotification = NULL; + job.data.resourceManager.loadDataBufferNode.pInitFence = pInitFence; + job.data.resourceManager.loadDataBufferNode.pDoneFence = pDoneFence; + + if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) { + result = ma_job_process(&job); + } else { + result = ma_resource_manager_post_job(pResourceManager, &job); + } + + if (result != MA_SUCCESS) { + /* Failed to post job. Probably ran out of memory. */ + ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_ERROR, "Failed to post MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER_NODE job. %s.\n", ma_result_description(result)); + + /* + Fences were acquired before posting the job, but since the job was not able to + be posted, we need to make sure we release them so nothing gets stuck waiting. + */ + if (pInitFence != NULL) { ma_fence_release(pInitFence); } + if (pDoneFence != NULL) { ma_fence_release(pDoneFence); } + + if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) { + ma_resource_manager_inline_notification_uninit(pInitNotification); + } else { + /* These will have been freed by the job thread, but with WAIT_INIT they will already have happend sinced the job has already been handled. */ + ma_free(pFilePathCopy, &pResourceManager->config.allocationCallbacks); + ma_free(pFilePathWCopy, &pResourceManager->config.allocationCallbacks); + } + + ma_resource_manager_data_buffer_node_remove(pResourceManager, pDataBufferNode); + ma_free(pDataBufferNode, &pResourceManager->config.allocationCallbacks); + + return result; + } + } + } + +done: + if (ppDataBufferNode != NULL) { + *ppDataBufferNode = pDataBufferNode; + } + + return result; +} + +static ma_result ma_resource_manager_data_buffer_node_acquire(ma_resource_manager* pResourceManager, const char* pFilePath, const wchar_t* pFilePathW, ma_uint32 hashedName32, ma_uint32 flags, const ma_resource_manager_data_supply* pExistingData, ma_fence* pInitFence, ma_fence* pDoneFence, ma_resource_manager_data_buffer_node** ppDataBufferNode) +{ + ma_result result = MA_SUCCESS; + ma_bool32 nodeAlreadyExists = MA_FALSE; + ma_resource_manager_data_buffer_node* pDataBufferNode = NULL; + ma_resource_manager_inline_notification initNotification; /* Used when the WAIT_INIT flag is set. */ + + if (ppDataBufferNode != NULL) { + *ppDataBufferNode = NULL; /* Safety. */ + } + + if (pResourceManager == NULL || (pFilePath == NULL && pFilePathW == NULL && hashedName32 == 0)) { + return MA_INVALID_ARGS; + } + + /* If we're specifying existing data, it must be valid. */ + if (pExistingData != NULL && pExistingData->type == ma_resource_manager_data_supply_type_unknown) { + return MA_INVALID_ARGS; + } + + /* If we don't support threading, remove the ASYNC flag to make the rest of this a bit simpler. */ + if (ma_resource_manager_is_threading_enabled(pResourceManager) == MA_FALSE) { + flags &= ~MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC; + } + + if (hashedName32 == 0) { + if (pFilePath != NULL) { + hashedName32 = ma_hash_string_32(pFilePath); + } else { + hashedName32 = ma_hash_string_w_32(pFilePathW); + } + } + + /* + Here is where we either increment the node's reference count or allocate a new one and add it + to the BST. When allocating a new node, we need to make sure the LOAD_DATA_BUFFER_NODE job is + posted inside the critical section just in case the caller immediately uninitializes the node + as this will ensure the FREE_DATA_BUFFER_NODE job is given an execution order such that the + node is not uninitialized before initialization. + */ + ma_resource_manager_data_buffer_bst_lock(pResourceManager); + { + result = ma_resource_manager_data_buffer_node_acquire_critical_section(pResourceManager, pFilePath, pFilePathW, hashedName32, flags, pExistingData, pInitFence, pDoneFence, &initNotification, &pDataBufferNode); + } + ma_resource_manager_data_buffer_bst_unlock(pResourceManager); + + if (result == MA_ALREADY_EXISTS) { + nodeAlreadyExists = MA_TRUE; + result = MA_SUCCESS; + } else { + if (result != MA_SUCCESS) { + return result; + } + } + + /* + If we're loading synchronously, we'll need to load everything now. When loading asynchronously, + a job will have been posted inside the BST critical section so that an uninitialization can be + allocated an appropriate execution order thereby preventing it from being uninitialized before + the node is initialized by the decoding thread(s). + */ + if (nodeAlreadyExists == MA_FALSE) { /* Don't need to try loading anything if the node already exists. */ + if (pFilePath == NULL && pFilePathW == NULL) { + /* + If this path is hit, it means a buffer is being copied (i.e. initialized from only the + hashed name), but that node has been freed in the meantime, probably from some other + thread. This is an invalid operation. + */ + ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_WARNING, "Cloning data buffer node failed because the source node was released. The source node must remain valid until the cloning has completed.\n"); + result = MA_INVALID_OPERATION; + goto done; + } + + if (pDataBufferNode->isDataOwnedByResourceManager) { + if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC) == 0) { + /* Loading synchronously. Load the sound in it's entirety here. */ + if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE) == 0) { + /* No decoding. This is the simple case - just store the file contents in memory. */ + result = ma_resource_manager_data_buffer_node_init_supply_encoded(pResourceManager, pDataBufferNode, pFilePath, pFilePathW); + if (result != MA_SUCCESS) { + goto done; + } + } else { + /* Decoding. We do this the same way as we do when loading asynchronously. */ + ma_decoder* pDecoder; + result = ma_resource_manager_data_buffer_node_init_supply_decoded(pResourceManager, pDataBufferNode, pFilePath, pFilePathW, flags, &pDecoder); + if (result != MA_SUCCESS) { + goto done; + } + + /* We have the decoder, now decode page by page just like we do when loading asynchronously. */ + for (;;) { + /* Decode next page. */ + result = ma_resource_manager_data_buffer_node_decode_next_page(pResourceManager, pDataBufferNode, pDecoder); + if (result != MA_SUCCESS) { + break; /* Will return MA_AT_END when the last page has been decoded. */ + } + } + + /* Reaching the end needs to be considered successful. */ + if (result == MA_AT_END) { + result = MA_SUCCESS; + } + + /* + At this point the data buffer is either fully decoded or some error occurred. Either + way, the decoder is no longer necessary. + */ + ma_decoder_uninit(pDecoder); + ma_free(pDecoder, &pResourceManager->config.allocationCallbacks); + } + + /* Getting here means we were successful. Make sure the status of the node is updated accordingly. */ + ma_atomic_exchange_i32(&pDataBufferNode->result, result); + } else { + /* Loading asynchronously. We may need to wait for initialization. */ + if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) { + ma_resource_manager_inline_notification_wait(&initNotification); + } + } + } else { + /* The data is not managed by the resource manager so there's nothing else to do. */ + MA_ASSERT(pExistingData != NULL); + } + } + +done: + /* If we failed to initialize the data buffer we need to free it. */ + if (result != MA_SUCCESS) { + if (nodeAlreadyExists == MA_FALSE) { + ma_resource_manager_data_buffer_node_remove(pResourceManager, pDataBufferNode); + ma_free(pDataBufferNode, &pResourceManager->config.allocationCallbacks); + } + } + + /* + The init notification needs to be uninitialized. This will be used if the node does not already + exist, and we've specified ASYNC | WAIT_INIT. + */ + if (nodeAlreadyExists == MA_FALSE && pDataBufferNode->isDataOwnedByResourceManager && (flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC) != 0) { + if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) { + ma_resource_manager_inline_notification_uninit(&initNotification); + } + } + + if (ppDataBufferNode != NULL) { + *ppDataBufferNode = pDataBufferNode; + } + + return result; +} + +static ma_result ma_resource_manager_data_buffer_node_unacquire(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode, const char* pName, const wchar_t* pNameW) +{ + ma_result result = MA_SUCCESS; + ma_uint32 refCount = 0xFFFFFFFF; /* The new reference count of the node after decrementing. Initialize to non-0 to be safe we don't fall into the freeing path. */ + ma_uint32 hashedName32 = 0; + + if (pResourceManager == NULL) { + return MA_INVALID_ARGS; + } + + if (pDataBufferNode == NULL) { + if (pName == NULL && pNameW == NULL) { + return MA_INVALID_ARGS; + } + + if (pName != NULL) { + hashedName32 = ma_hash_string_32(pName); + } else { + hashedName32 = ma_hash_string_w_32(pNameW); + } + } + + /* + The first thing to do is decrement the reference counter of the node. Then, if the reference + count is zero, we need to free the node. If the node is still in the process of loading, we'll + need to post a job to the job queue to free the node. Otherwise we'll just do it here. + */ + ma_resource_manager_data_buffer_bst_lock(pResourceManager); + { + /* Might need to find the node. Must be done inside the critical section. */ + if (pDataBufferNode == NULL) { + result = ma_resource_manager_data_buffer_node_search(pResourceManager, hashedName32, &pDataBufferNode); + if (result != MA_SUCCESS) { + goto stage2; /* Couldn't find the node. */ + } + } + + result = ma_resource_manager_data_buffer_node_decrement_ref(pResourceManager, pDataBufferNode, &refCount); + if (result != MA_SUCCESS) { + goto stage2; /* Should never happen. */ + } + + if (refCount == 0) { + result = ma_resource_manager_data_buffer_node_remove(pResourceManager, pDataBufferNode); + if (result != MA_SUCCESS) { + goto stage2; /* An error occurred when trying to remove the data buffer. This should never happen. */ + } + } + } + ma_resource_manager_data_buffer_bst_unlock(pResourceManager); + +stage2: + if (result != MA_SUCCESS) { + return result; + } + + /* + Here is where we need to free the node. We don't want to do this inside the critical section + above because we want to keep that as small as possible for multi-threaded efficiency. + */ + if (refCount == 0) { + if (ma_resource_manager_data_buffer_node_result(pDataBufferNode) == MA_BUSY) { + /* The sound is still loading. We need to delay the freeing of the node to a safe time. */ + ma_job job; + + /* We need to mark the node as unavailable for the sake of the resource manager worker threads. */ + ma_atomic_exchange_i32(&pDataBufferNode->result, MA_UNAVAILABLE); + + job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER_NODE); + job.order = ma_resource_manager_data_buffer_node_next_execution_order(pDataBufferNode); + job.data.resourceManager.freeDataBufferNode.pResourceManager = pResourceManager; + job.data.resourceManager.freeDataBufferNode.pDataBufferNode = pDataBufferNode; + + result = ma_resource_manager_post_job(pResourceManager, &job); + if (result != MA_SUCCESS) { + ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_ERROR, "Failed to post MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER_NODE job. %s.\n", ma_result_description(result)); + return result; + } + + /* If we don't support threading, process the job queue here. */ + if (ma_resource_manager_is_threading_enabled(pResourceManager) == MA_FALSE) { + while (ma_resource_manager_data_buffer_node_result(pDataBufferNode) == MA_BUSY) { + result = ma_resource_manager_process_next_job(pResourceManager); + if (result == MA_NO_DATA_AVAILABLE || result == MA_CANCELLED) { + result = MA_SUCCESS; + break; + } + } + } else { + /* Threading is enabled. The job queue will deal with the rest of the cleanup from here. */ + } + } else { + /* The sound isn't loading so we can just free the node here. */ + ma_resource_manager_data_buffer_node_free(pResourceManager, pDataBufferNode); + } + } + + return result; +} + + + +static ma_uint32 ma_resource_manager_data_buffer_next_execution_order(ma_resource_manager_data_buffer* pDataBuffer) +{ + MA_ASSERT(pDataBuffer != NULL); + return ma_atomic_fetch_add_32(&pDataBuffer->executionCounter, 1); +} + +static ma_result ma_resource_manager_data_buffer_cb__read_pcm_frames(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + return ma_resource_manager_data_buffer_read_pcm_frames((ma_resource_manager_data_buffer*)pDataSource, pFramesOut, frameCount, pFramesRead); +} + +static ma_result ma_resource_manager_data_buffer_cb__seek_to_pcm_frame(ma_data_source* pDataSource, ma_uint64 frameIndex) +{ + return ma_resource_manager_data_buffer_seek_to_pcm_frame((ma_resource_manager_data_buffer*)pDataSource, frameIndex); +} + +static ma_result ma_resource_manager_data_buffer_cb__get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + return ma_resource_manager_data_buffer_get_data_format((ma_resource_manager_data_buffer*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap); +} + +static ma_result ma_resource_manager_data_buffer_cb__get_cursor_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pCursor) +{ + return ma_resource_manager_data_buffer_get_cursor_in_pcm_frames((ma_resource_manager_data_buffer*)pDataSource, pCursor); +} + +static ma_result ma_resource_manager_data_buffer_cb__get_length_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pLength) +{ + return ma_resource_manager_data_buffer_get_length_in_pcm_frames((ma_resource_manager_data_buffer*)pDataSource, pLength); +} + +static ma_result ma_resource_manager_data_buffer_cb__set_looping(ma_data_source* pDataSource, ma_bool32 isLooping) +{ + ma_resource_manager_data_buffer* pDataBuffer = (ma_resource_manager_data_buffer*)pDataSource; + MA_ASSERT(pDataBuffer != NULL); + + ma_atomic_exchange_32(&pDataBuffer->isLooping, isLooping); + + /* The looping state needs to be set on the connector as well or else looping won't work when we read audio data. */ + ma_data_source_set_looping(ma_resource_manager_data_buffer_get_connector(pDataBuffer), isLooping); + + return MA_SUCCESS; +} + +static ma_data_source_vtable g_ma_resource_manager_data_buffer_vtable = +{ + ma_resource_manager_data_buffer_cb__read_pcm_frames, + ma_resource_manager_data_buffer_cb__seek_to_pcm_frame, + ma_resource_manager_data_buffer_cb__get_data_format, + ma_resource_manager_data_buffer_cb__get_cursor_in_pcm_frames, + ma_resource_manager_data_buffer_cb__get_length_in_pcm_frames, + ma_resource_manager_data_buffer_cb__set_looping, + 0 +}; + +static ma_result ma_resource_manager_data_buffer_init_ex_internal(ma_resource_manager* pResourceManager, const ma_resource_manager_data_source_config* pConfig, ma_uint32 hashedName32, ma_resource_manager_data_buffer* pDataBuffer) +{ + ma_result result = MA_SUCCESS; + ma_resource_manager_data_buffer_node* pDataBufferNode; + ma_data_source_config dataSourceConfig; + ma_bool32 async; + ma_uint32 flags; + ma_resource_manager_pipeline_notifications notifications; + + if (pDataBuffer == NULL) { + if (pConfig != NULL && pConfig->pNotifications != NULL) { + ma_resource_manager_pipeline_notifications_signal_all_notifications(pConfig->pNotifications); + } + + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pDataBuffer); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->pNotifications != NULL) { + notifications = *pConfig->pNotifications; /* From here on out we should be referencing `notifications` instead of `pNotifications`. Set this to NULL to catch errors at testing time. */ + } else { + MA_ZERO_OBJECT(¬ifications); + } + + /* For safety, always remove the ASYNC flag if threading is disabled on the resource manager. */ + flags = pConfig->flags; + if (ma_resource_manager_is_threading_enabled(pResourceManager) == MA_FALSE) { + flags &= ~MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC; + } + + async = (flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC) != 0; + + /* + Fences need to be acquired before doing anything. These must be acquired and released outside of + the node to ensure there's no holes where ma_fence_wait() could prematurely return before the + data buffer has completed initialization. + + When loading asynchronously, the node acquisition routine below will acquire the fences on this + thread and then release them on the async thread when the operation is complete. + + These fences are always released at the "done" tag at the end of this function. They'll be + acquired a second if loading asynchronously. This double acquisition system is just done to + simplify code maintanence. + */ + ma_resource_manager_pipeline_notifications_acquire_all_fences(¬ifications); + { + /* We first need to acquire a node. If ASYNC is not set, this will not return until the entire sound has been loaded. */ + result = ma_resource_manager_data_buffer_node_acquire(pResourceManager, pConfig->pFilePath, pConfig->pFilePathW, hashedName32, flags, NULL, notifications.init.pFence, notifications.done.pFence, &pDataBufferNode); + if (result != MA_SUCCESS) { + ma_resource_manager_pipeline_notifications_signal_all_notifications(¬ifications); + goto done; + } + + dataSourceConfig = ma_data_source_config_init(); + dataSourceConfig.vtable = &g_ma_resource_manager_data_buffer_vtable; + + result = ma_data_source_init(&dataSourceConfig, &pDataBuffer->ds); + if (result != MA_SUCCESS) { + ma_resource_manager_data_buffer_node_unacquire(pResourceManager, pDataBufferNode, NULL, NULL); + ma_resource_manager_pipeline_notifications_signal_all_notifications(¬ifications); + goto done; + } + + pDataBuffer->pResourceManager = pResourceManager; + pDataBuffer->pNode = pDataBufferNode; + pDataBuffer->flags = flags; + pDataBuffer->result = MA_BUSY; /* Always default to MA_BUSY for safety. It'll be overwritten when loading completes or an error occurs. */ + + /* If we're loading asynchronously we need to post a job to the job queue to initialize the connector. */ + if (async == MA_FALSE || ma_resource_manager_data_buffer_node_result(pDataBufferNode) == MA_SUCCESS) { + /* Loading synchronously or the data has already been fully loaded. We can just initialize the connector from here without a job. */ + result = ma_resource_manager_data_buffer_init_connector(pDataBuffer, pConfig, NULL, NULL); + ma_atomic_exchange_i32(&pDataBuffer->result, result); + + ma_resource_manager_pipeline_notifications_signal_all_notifications(¬ifications); + goto done; + } else { + /* The node's data supply isn't initialized yet. The caller has requested that we load asynchronously so we need to post a job to do this. */ + ma_job job; + ma_resource_manager_inline_notification initNotification; /* Used when the WAIT_INIT flag is set. */ + + if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) { + ma_resource_manager_inline_notification_init(pResourceManager, &initNotification); + } + + /* + The status of the data buffer needs to be set to MA_BUSY before posting the job so that the + worker thread is aware of it's busy state. If the LOAD_DATA_BUFFER job sees a status other + than MA_BUSY, it'll assume an error and fall through to an early exit. + */ + ma_atomic_exchange_i32(&pDataBuffer->result, MA_BUSY); + + /* Acquire fences a second time. These will be released by the async thread. */ + ma_resource_manager_pipeline_notifications_acquire_all_fences(¬ifications); + + job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER); + job.order = ma_resource_manager_data_buffer_next_execution_order(pDataBuffer); + job.data.resourceManager.loadDataBuffer.pDataBuffer = pDataBuffer; + job.data.resourceManager.loadDataBuffer.pInitNotification = ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) ? &initNotification : notifications.init.pNotification; + job.data.resourceManager.loadDataBuffer.pDoneNotification = notifications.done.pNotification; + job.data.resourceManager.loadDataBuffer.pInitFence = notifications.init.pFence; + job.data.resourceManager.loadDataBuffer.pDoneFence = notifications.done.pFence; + job.data.resourceManager.loadDataBuffer.rangeBegInPCMFrames = pConfig->rangeBegInPCMFrames; + job.data.resourceManager.loadDataBuffer.rangeEndInPCMFrames = pConfig->rangeEndInPCMFrames; + job.data.resourceManager.loadDataBuffer.loopPointBegInPCMFrames = pConfig->loopPointBegInPCMFrames; + job.data.resourceManager.loadDataBuffer.loopPointEndInPCMFrames = pConfig->loopPointEndInPCMFrames; + job.data.resourceManager.loadDataBuffer.isLooping = pConfig->isLooping; + + /* If we need to wait for initialization to complete we can just process the job in place. */ + if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) { + result = ma_job_process(&job); + } else { + result = ma_resource_manager_post_job(pResourceManager, &job); + } + + if (result != MA_SUCCESS) { + /* We failed to post the job. Most likely there isn't enough room in the queue's buffer. */ + ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_ERROR, "Failed to post MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER job. %s.\n", ma_result_description(result)); + ma_atomic_exchange_i32(&pDataBuffer->result, result); + + /* Release the fences after the result has been set on the data buffer. */ + ma_resource_manager_pipeline_notifications_release_all_fences(¬ifications); + } else { + if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) { + ma_resource_manager_inline_notification_wait(&initNotification); + + if (notifications.init.pNotification != NULL) { + ma_async_notification_signal(notifications.init.pNotification); + } + + /* NOTE: Do not release the init fence here. It will have been done by the job. */ + + /* Make sure we return an error if initialization failed on the async thread. */ + result = ma_resource_manager_data_buffer_result(pDataBuffer); + if (result == MA_BUSY) { + result = MA_SUCCESS; + } + } + } + + if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) { + ma_resource_manager_inline_notification_uninit(&initNotification); + } + } + + if (result != MA_SUCCESS) { + ma_resource_manager_data_buffer_node_unacquire(pResourceManager, pDataBufferNode, NULL, NULL); + goto done; + } + } +done: + if (result == MA_SUCCESS) { + if (pConfig->initialSeekPointInPCMFrames > 0) { + ma_resource_manager_data_buffer_seek_to_pcm_frame(pDataBuffer, pConfig->initialSeekPointInPCMFrames); + } + } + + ma_resource_manager_pipeline_notifications_release_all_fences(¬ifications); + + return result; +} + +MA_API ma_result ma_resource_manager_data_buffer_init_ex(ma_resource_manager* pResourceManager, const ma_resource_manager_data_source_config* pConfig, ma_resource_manager_data_buffer* pDataBuffer) +{ + return ma_resource_manager_data_buffer_init_ex_internal(pResourceManager, pConfig, 0, pDataBuffer); +} + +MA_API ma_result ma_resource_manager_data_buffer_init(ma_resource_manager* pResourceManager, const char* pFilePath, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_buffer* pDataBuffer) +{ + ma_resource_manager_data_source_config config; + + config = ma_resource_manager_data_source_config_init(); + config.pFilePath = pFilePath; + config.flags = flags; + config.pNotifications = pNotifications; + + return ma_resource_manager_data_buffer_init_ex(pResourceManager, &config, pDataBuffer); +} + +MA_API ma_result ma_resource_manager_data_buffer_init_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_buffer* pDataBuffer) +{ + ma_resource_manager_data_source_config config; + + config = ma_resource_manager_data_source_config_init(); + config.pFilePathW = pFilePath; + config.flags = flags; + config.pNotifications = pNotifications; + + return ma_resource_manager_data_buffer_init_ex(pResourceManager, &config, pDataBuffer); +} + +MA_API ma_result ma_resource_manager_data_buffer_init_copy(ma_resource_manager* pResourceManager, const ma_resource_manager_data_buffer* pExistingDataBuffer, ma_resource_manager_data_buffer* pDataBuffer) +{ + ma_resource_manager_data_source_config config; + + if (pExistingDataBuffer == NULL) { + return MA_INVALID_ARGS; + } + + MA_ASSERT(pExistingDataBuffer->pNode != NULL); /* <-- If you've triggered this, you've passed in an invalid existing data buffer. */ + + config = ma_resource_manager_data_source_config_init(); + config.flags = pExistingDataBuffer->flags; + + return ma_resource_manager_data_buffer_init_ex_internal(pResourceManager, &config, pExistingDataBuffer->pNode->hashedName32, pDataBuffer); +} + +static ma_result ma_resource_manager_data_buffer_uninit_internal(ma_resource_manager_data_buffer* pDataBuffer) +{ + MA_ASSERT(pDataBuffer != NULL); + + /* The connector should be uninitialized first. */ + ma_resource_manager_data_buffer_uninit_connector(pDataBuffer->pResourceManager, pDataBuffer); + + /* With the connector uninitialized we can unacquire the node. */ + ma_resource_manager_data_buffer_node_unacquire(pDataBuffer->pResourceManager, pDataBuffer->pNode, NULL, NULL); + + /* The base data source needs to be uninitialized as well. */ + ma_data_source_uninit(&pDataBuffer->ds); + + return MA_SUCCESS; +} + +MA_API ma_result ma_resource_manager_data_buffer_uninit(ma_resource_manager_data_buffer* pDataBuffer) +{ + ma_result result; + + if (pDataBuffer == NULL) { + return MA_INVALID_ARGS; + } + + if (ma_resource_manager_data_buffer_result(pDataBuffer) == MA_SUCCESS) { + /* The data buffer can be deleted synchronously. */ + return ma_resource_manager_data_buffer_uninit_internal(pDataBuffer); + } else { + /* + The data buffer needs to be deleted asynchronously because it's still loading. With the status set to MA_UNAVAILABLE, no more pages will + be loaded and the uninitialization should happen fairly quickly. Since the caller owns the data buffer, we need to wait for this event + to get processed before returning. + */ + ma_resource_manager_inline_notification notification; + ma_job job; + + /* + We need to mark the node as unavailable so we don't try reading from it anymore, but also to + let the loading thread know that it needs to abort it's loading procedure. + */ + ma_atomic_exchange_i32(&pDataBuffer->result, MA_UNAVAILABLE); + + result = ma_resource_manager_inline_notification_init(pDataBuffer->pResourceManager, ¬ification); + if (result != MA_SUCCESS) { + return result; /* Failed to create the notification. This should rarely, if ever, happen. */ + } + + job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER); + job.order = ma_resource_manager_data_buffer_next_execution_order(pDataBuffer); + job.data.resourceManager.freeDataBuffer.pDataBuffer = pDataBuffer; + job.data.resourceManager.freeDataBuffer.pDoneNotification = ¬ification; + job.data.resourceManager.freeDataBuffer.pDoneFence = NULL; + + result = ma_resource_manager_post_job(pDataBuffer->pResourceManager, &job); + if (result != MA_SUCCESS) { + ma_resource_manager_inline_notification_uninit(¬ification); + return result; + } + + ma_resource_manager_inline_notification_wait_and_uninit(¬ification); + } + + return result; +} + +MA_API ma_result ma_resource_manager_data_buffer_read_pcm_frames(ma_resource_manager_data_buffer* pDataBuffer, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + ma_result result = MA_SUCCESS; + ma_uint64 framesRead = 0; + ma_bool32 isDecodedBufferBusy = MA_FALSE; + + /* Safety. */ + if (pFramesRead != NULL) { + *pFramesRead = 0; + } + + if (frameCount == 0) { + return MA_INVALID_ARGS; + } + + /* + We cannot be using the data buffer after it's been uninitialized. If you trigger this assert it means you're trying to read from the data buffer after + it's been uninitialized or is in the process of uninitializing. + */ + MA_ASSERT(ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) != MA_UNAVAILABLE); + + /* If the node is not initialized we need to abort with a busy code. */ + if (ma_resource_manager_data_buffer_has_connector(pDataBuffer) == MA_FALSE) { + return MA_BUSY; /* Still loading. */ + } + + /* + If we've got a seek scheduled we'll want to do that before reading. However, for paged buffers, there's + a chance that the sound hasn't yet been decoded up to the seek point will result in the seek failing. If + this happens, we need to keep the seek scheduled and return MA_BUSY. + */ + if (pDataBuffer->seekToCursorOnNextRead) { + pDataBuffer->seekToCursorOnNextRead = MA_FALSE; + + result = ma_data_source_seek_to_pcm_frame(ma_resource_manager_data_buffer_get_connector(pDataBuffer), pDataBuffer->seekTargetInPCMFrames); + if (result != MA_SUCCESS) { + if (result == MA_BAD_SEEK && ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode) == ma_resource_manager_data_supply_type_decoded_paged) { + pDataBuffer->seekToCursorOnNextRead = MA_TRUE; /* Keep the seek scheduled. We just haven't loaded enough data yet to do the seek properly. */ + return MA_BUSY; + } + + return result; + } + } + + /* + For decoded buffers (not paged) we need to check beforehand how many frames we have available. We cannot + exceed this amount. We'll read as much as we can, and then return MA_BUSY. + */ + if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode) == ma_resource_manager_data_supply_type_decoded) { + ma_uint64 availableFrames; + + isDecodedBufferBusy = (ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) == MA_BUSY); + + if (ma_resource_manager_data_buffer_get_available_frames(pDataBuffer, &availableFrames) == MA_SUCCESS) { + /* Don't try reading more than the available frame count. */ + if (frameCount > availableFrames) { + frameCount = availableFrames; + + /* + If there's no frames available we want to set the status to MA_AT_END. The logic below + will check if the node is busy, and if so, change it to MA_BUSY. The reason we do this + is because we don't want to call `ma_data_source_read_pcm_frames()` if the frame count + is 0 because that'll result in a situation where it's possible MA_AT_END won't get + returned. + */ + if (frameCount == 0) { + result = MA_AT_END; + } + } else { + isDecodedBufferBusy = MA_FALSE; /* We have enough frames available in the buffer to avoid a MA_BUSY status. */ + } + } + } + + /* Don't attempt to read anything if we've got no frames available. */ + if (frameCount > 0) { + result = ma_data_source_read_pcm_frames(ma_resource_manager_data_buffer_get_connector(pDataBuffer), pFramesOut, frameCount, &framesRead); + } + + /* + If we returned MA_AT_END, but the node is still loading, we don't want to return that code or else the caller will interpret the sound + as at the end and terminate decoding. + */ + if (result == MA_AT_END) { + if (ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) == MA_BUSY) { + result = MA_BUSY; + } + } + + if (isDecodedBufferBusy) { + result = MA_BUSY; + } + + if (pFramesRead != NULL) { + *pFramesRead = framesRead; + } + + if (result == MA_SUCCESS && framesRead == 0) { + result = MA_AT_END; + } + + return result; +} + +MA_API ma_result ma_resource_manager_data_buffer_seek_to_pcm_frame(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64 frameIndex) +{ + ma_result result; + + /* We cannot be using the data source after it's been uninitialized. */ + MA_ASSERT(ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) != MA_UNAVAILABLE); + + /* If we haven't yet got a connector we need to abort. */ + if (ma_resource_manager_data_buffer_has_connector(pDataBuffer) == MA_FALSE) { + pDataBuffer->seekTargetInPCMFrames = frameIndex; + pDataBuffer->seekToCursorOnNextRead = MA_TRUE; + return MA_BUSY; /* Still loading. */ + } + + result = ma_data_source_seek_to_pcm_frame(ma_resource_manager_data_buffer_get_connector(pDataBuffer), frameIndex); + if (result != MA_SUCCESS) { + return result; + } + + pDataBuffer->seekTargetInPCMFrames = ~(ma_uint64)0; /* <-- For identification purposes. */ + pDataBuffer->seekToCursorOnNextRead = MA_FALSE; + + return MA_SUCCESS; +} + +MA_API ma_result ma_resource_manager_data_buffer_get_data_format(ma_resource_manager_data_buffer* pDataBuffer, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + /* We cannot be using the data source after it's been uninitialized. */ + MA_ASSERT(ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) != MA_UNAVAILABLE); + + switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode)) + { + case ma_resource_manager_data_supply_type_encoded: + { + return ma_data_source_get_data_format(&pDataBuffer->connector.decoder, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap); + }; + + case ma_resource_manager_data_supply_type_decoded: + { + *pFormat = pDataBuffer->pNode->data.backend.decoded.format; + *pChannels = pDataBuffer->pNode->data.backend.decoded.channels; + *pSampleRate = pDataBuffer->pNode->data.backend.decoded.sampleRate; + ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pDataBuffer->pNode->data.backend.decoded.channels); + return MA_SUCCESS; + }; + + case ma_resource_manager_data_supply_type_decoded_paged: + { + *pFormat = pDataBuffer->pNode->data.backend.decodedPaged.data.format; + *pChannels = pDataBuffer->pNode->data.backend.decodedPaged.data.channels; + *pSampleRate = pDataBuffer->pNode->data.backend.decodedPaged.sampleRate; + ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pDataBuffer->pNode->data.backend.decoded.channels); + return MA_SUCCESS; + }; + + case ma_resource_manager_data_supply_type_unknown: + { + return MA_BUSY; /* Still loading. */ + }; + + default: + { + /* Unknown supply type. Should never hit this. */ + return MA_INVALID_ARGS; + } + } +} + +MA_API ma_result ma_resource_manager_data_buffer_get_cursor_in_pcm_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pCursor) +{ + /* We cannot be using the data source after it's been uninitialized. */ + MA_ASSERT(ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) != MA_UNAVAILABLE); + + if (pDataBuffer == NULL || pCursor == NULL) { + return MA_INVALID_ARGS; + } + + *pCursor = 0; + + switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode)) + { + case ma_resource_manager_data_supply_type_encoded: + { + return ma_decoder_get_cursor_in_pcm_frames(&pDataBuffer->connector.decoder, pCursor); + }; + + case ma_resource_manager_data_supply_type_decoded: + { + return ma_audio_buffer_get_cursor_in_pcm_frames(&pDataBuffer->connector.buffer, pCursor); + }; + + case ma_resource_manager_data_supply_type_decoded_paged: + { + return ma_paged_audio_buffer_get_cursor_in_pcm_frames(&pDataBuffer->connector.pagedBuffer, pCursor); + }; + + case ma_resource_manager_data_supply_type_unknown: + { + return MA_BUSY; + }; + + default: + { + return MA_INVALID_ARGS; + } + } +} + +MA_API ma_result ma_resource_manager_data_buffer_get_length_in_pcm_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pLength) +{ + /* We cannot be using the data source after it's been uninitialized. */ + MA_ASSERT(ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) != MA_UNAVAILABLE); + + if (pDataBuffer == NULL || pLength == NULL) { + return MA_INVALID_ARGS; + } + + if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode) == ma_resource_manager_data_supply_type_unknown) { + return MA_BUSY; /* Still loading. */ + } + + return ma_data_source_get_length_in_pcm_frames(ma_resource_manager_data_buffer_get_connector(pDataBuffer), pLength); +} + +MA_API ma_result ma_resource_manager_data_buffer_result(const ma_resource_manager_data_buffer* pDataBuffer) +{ + if (pDataBuffer == NULL) { + return MA_INVALID_ARGS; + } + + return (ma_result)ma_atomic_load_i32((ma_result*)&pDataBuffer->result); /* Need a naughty const-cast here. */ +} + +MA_API ma_result ma_resource_manager_data_buffer_set_looping(ma_resource_manager_data_buffer* pDataBuffer, ma_bool32 isLooping) +{ + return ma_data_source_set_looping(pDataBuffer, isLooping); +} + +MA_API ma_bool32 ma_resource_manager_data_buffer_is_looping(const ma_resource_manager_data_buffer* pDataBuffer) +{ + return ma_data_source_is_looping(pDataBuffer); +} + +MA_API ma_result ma_resource_manager_data_buffer_get_available_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pAvailableFrames) +{ + if (pAvailableFrames == NULL) { + return MA_INVALID_ARGS; + } + + *pAvailableFrames = 0; + + if (pDataBuffer == NULL) { + return MA_INVALID_ARGS; + } + + if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode) == ma_resource_manager_data_supply_type_unknown) { + if (ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) == MA_BUSY) { + return MA_BUSY; + } else { + return MA_INVALID_OPERATION; /* No connector. */ + } + } + + switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode)) + { + case ma_resource_manager_data_supply_type_encoded: + { + return ma_decoder_get_available_frames(&pDataBuffer->connector.decoder, pAvailableFrames); + }; + + case ma_resource_manager_data_supply_type_decoded: + { + return ma_audio_buffer_get_available_frames(&pDataBuffer->connector.buffer, pAvailableFrames); + }; + + case ma_resource_manager_data_supply_type_decoded_paged: + { + ma_uint64 cursor; + ma_paged_audio_buffer_get_cursor_in_pcm_frames(&pDataBuffer->connector.pagedBuffer, &cursor); + + if (pDataBuffer->pNode->data.backend.decodedPaged.decodedFrameCount > cursor) { + *pAvailableFrames = pDataBuffer->pNode->data.backend.decodedPaged.decodedFrameCount - cursor; + } else { + *pAvailableFrames = 0; + } + + return MA_SUCCESS; + }; + + case ma_resource_manager_data_supply_type_unknown: + default: + { + /* Unknown supply type. Should never hit this. */ + return MA_INVALID_ARGS; + } + } +} + +MA_API ma_result ma_resource_manager_register_file(ma_resource_manager* pResourceManager, const char* pFilePath, ma_uint32 flags) +{ + return ma_resource_manager_data_buffer_node_acquire(pResourceManager, pFilePath, NULL, 0, flags, NULL, NULL, NULL, NULL); +} + +MA_API ma_result ma_resource_manager_register_file_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath, ma_uint32 flags) +{ + return ma_resource_manager_data_buffer_node_acquire(pResourceManager, NULL, pFilePath, 0, flags, NULL, NULL, NULL, NULL); +} + + +static ma_result ma_resource_manager_register_data(ma_resource_manager* pResourceManager, const char* pName, const wchar_t* pNameW, ma_resource_manager_data_supply* pExistingData) +{ + return ma_resource_manager_data_buffer_node_acquire(pResourceManager, pName, pNameW, 0, 0, pExistingData, NULL, NULL, NULL); +} + +static ma_result ma_resource_manager_register_decoded_data_internal(ma_resource_manager* pResourceManager, const char* pName, const wchar_t* pNameW, const void* pData, ma_uint64 frameCount, ma_format format, ma_uint32 channels, ma_uint32 sampleRate) +{ + ma_resource_manager_data_supply data; + data.type = ma_resource_manager_data_supply_type_decoded; + data.backend.decoded.pData = pData; + data.backend.decoded.totalFrameCount = frameCount; + data.backend.decoded.format = format; + data.backend.decoded.channels = channels; + data.backend.decoded.sampleRate = sampleRate; + + return ma_resource_manager_register_data(pResourceManager, pName, pNameW, &data); +} + +MA_API ma_result ma_resource_manager_register_decoded_data(ma_resource_manager* pResourceManager, const char* pName, const void* pData, ma_uint64 frameCount, ma_format format, ma_uint32 channels, ma_uint32 sampleRate) +{ + return ma_resource_manager_register_decoded_data_internal(pResourceManager, pName, NULL, pData, frameCount, format, channels, sampleRate); +} + +MA_API ma_result ma_resource_manager_register_decoded_data_w(ma_resource_manager* pResourceManager, const wchar_t* pName, const void* pData, ma_uint64 frameCount, ma_format format, ma_uint32 channels, ma_uint32 sampleRate) +{ + return ma_resource_manager_register_decoded_data_internal(pResourceManager, NULL, pName, pData, frameCount, format, channels, sampleRate); +} + + +static ma_result ma_resource_manager_register_encoded_data_internal(ma_resource_manager* pResourceManager, const char* pName, const wchar_t* pNameW, const void* pData, size_t sizeInBytes) +{ + ma_resource_manager_data_supply data; + data.type = ma_resource_manager_data_supply_type_encoded; + data.backend.encoded.pData = pData; + data.backend.encoded.sizeInBytes = sizeInBytes; + + return ma_resource_manager_register_data(pResourceManager, pName, pNameW, &data); +} + +MA_API ma_result ma_resource_manager_register_encoded_data(ma_resource_manager* pResourceManager, const char* pName, const void* pData, size_t sizeInBytes) +{ + return ma_resource_manager_register_encoded_data_internal(pResourceManager, pName, NULL, pData, sizeInBytes); +} + +MA_API ma_result ma_resource_manager_register_encoded_data_w(ma_resource_manager* pResourceManager, const wchar_t* pName, const void* pData, size_t sizeInBytes) +{ + return ma_resource_manager_register_encoded_data_internal(pResourceManager, NULL, pName, pData, sizeInBytes); +} + + +MA_API ma_result ma_resource_manager_unregister_file(ma_resource_manager* pResourceManager, const char* pFilePath) +{ + return ma_resource_manager_unregister_data(pResourceManager, pFilePath); +} + +MA_API ma_result ma_resource_manager_unregister_file_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath) +{ + return ma_resource_manager_unregister_data_w(pResourceManager, pFilePath); +} + +MA_API ma_result ma_resource_manager_unregister_data(ma_resource_manager* pResourceManager, const char* pName) +{ + return ma_resource_manager_data_buffer_node_unacquire(pResourceManager, NULL, pName, NULL); +} + +MA_API ma_result ma_resource_manager_unregister_data_w(ma_resource_manager* pResourceManager, const wchar_t* pName) +{ + return ma_resource_manager_data_buffer_node_unacquire(pResourceManager, NULL, NULL, pName); +} + + +static ma_uint32 ma_resource_manager_data_stream_next_execution_order(ma_resource_manager_data_stream* pDataStream) +{ + MA_ASSERT(pDataStream != NULL); + return ma_atomic_fetch_add_32(&pDataStream->executionCounter, 1); +} + +static ma_bool32 ma_resource_manager_data_stream_is_decoder_at_end(const ma_resource_manager_data_stream* pDataStream) +{ + MA_ASSERT(pDataStream != NULL); + return ma_atomic_load_32((ma_bool32*)&pDataStream->isDecoderAtEnd); +} + +static ma_uint32 ma_resource_manager_data_stream_seek_counter(const ma_resource_manager_data_stream* pDataStream) +{ + MA_ASSERT(pDataStream != NULL); + return ma_atomic_load_32((ma_uint32*)&pDataStream->seekCounter); +} + + +static ma_result ma_resource_manager_data_stream_cb__read_pcm_frames(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + return ma_resource_manager_data_stream_read_pcm_frames((ma_resource_manager_data_stream*)pDataSource, pFramesOut, frameCount, pFramesRead); +} + +static ma_result ma_resource_manager_data_stream_cb__seek_to_pcm_frame(ma_data_source* pDataSource, ma_uint64 frameIndex) +{ + return ma_resource_manager_data_stream_seek_to_pcm_frame((ma_resource_manager_data_stream*)pDataSource, frameIndex); +} + +static ma_result ma_resource_manager_data_stream_cb__get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + return ma_resource_manager_data_stream_get_data_format((ma_resource_manager_data_stream*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap); +} + +static ma_result ma_resource_manager_data_stream_cb__get_cursor_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pCursor) +{ + return ma_resource_manager_data_stream_get_cursor_in_pcm_frames((ma_resource_manager_data_stream*)pDataSource, pCursor); +} + +static ma_result ma_resource_manager_data_stream_cb__get_length_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pLength) +{ + return ma_resource_manager_data_stream_get_length_in_pcm_frames((ma_resource_manager_data_stream*)pDataSource, pLength); +} + +static ma_result ma_resource_manager_data_stream_cb__set_looping(ma_data_source* pDataSource, ma_bool32 isLooping) +{ + ma_resource_manager_data_stream* pDataStream = (ma_resource_manager_data_stream*)pDataSource; + MA_ASSERT(pDataStream != NULL); + + ma_atomic_exchange_32(&pDataStream->isLooping, isLooping); + + return MA_SUCCESS; +} + +static ma_data_source_vtable g_ma_resource_manager_data_stream_vtable = +{ + ma_resource_manager_data_stream_cb__read_pcm_frames, + ma_resource_manager_data_stream_cb__seek_to_pcm_frame, + ma_resource_manager_data_stream_cb__get_data_format, + ma_resource_manager_data_stream_cb__get_cursor_in_pcm_frames, + ma_resource_manager_data_stream_cb__get_length_in_pcm_frames, + ma_resource_manager_data_stream_cb__set_looping, + 0 /*MA_DATA_SOURCE_SELF_MANAGED_RANGE_AND_LOOP_POINT*/ +}; + +static void ma_resource_manager_data_stream_set_absolute_cursor(ma_resource_manager_data_stream* pDataStream, ma_uint64 absoluteCursor) +{ + /* Loop if possible. */ + if (absoluteCursor > pDataStream->totalLengthInPCMFrames && pDataStream->totalLengthInPCMFrames > 0) { + absoluteCursor = absoluteCursor % pDataStream->totalLengthInPCMFrames; + } + + ma_atomic_exchange_64(&pDataStream->absoluteCursor, absoluteCursor); +} + +MA_API ma_result ma_resource_manager_data_stream_init_ex(ma_resource_manager* pResourceManager, const ma_resource_manager_data_source_config* pConfig, ma_resource_manager_data_stream* pDataStream) +{ + ma_result result; + ma_data_source_config dataSourceConfig; + char* pFilePathCopy = NULL; + wchar_t* pFilePathWCopy = NULL; + ma_job job; + ma_bool32 waitBeforeReturning = MA_FALSE; + ma_resource_manager_inline_notification waitNotification; + ma_resource_manager_pipeline_notifications notifications; + + if (pDataStream == NULL) { + if (pConfig != NULL && pConfig->pNotifications != NULL) { + ma_resource_manager_pipeline_notifications_signal_all_notifications(pConfig->pNotifications); + } + + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pDataStream); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->pNotifications != NULL) { + notifications = *pConfig->pNotifications; /* From here on out, `notifications` should be used instead of `pNotifications`. Setting this to NULL to catch any errors at testing time. */ + } else { + MA_ZERO_OBJECT(¬ifications); + } + + dataSourceConfig = ma_data_source_config_init(); + dataSourceConfig.vtable = &g_ma_resource_manager_data_stream_vtable; + + result = ma_data_source_init(&dataSourceConfig, &pDataStream->ds); + if (result != MA_SUCCESS) { + ma_resource_manager_pipeline_notifications_signal_all_notifications(¬ifications); + return result; + } + + pDataStream->pResourceManager = pResourceManager; + pDataStream->flags = pConfig->flags; + pDataStream->result = MA_BUSY; + + ma_data_source_set_range_in_pcm_frames(pDataStream, pConfig->rangeBegInPCMFrames, pConfig->rangeEndInPCMFrames); + ma_data_source_set_loop_point_in_pcm_frames(pDataStream, pConfig->loopPointBegInPCMFrames, pConfig->loopPointEndInPCMFrames); + ma_data_source_set_looping(pDataStream, pConfig->isLooping); + + if (pResourceManager == NULL || (pConfig->pFilePath == NULL && pConfig->pFilePathW == NULL)) { + ma_resource_manager_pipeline_notifications_signal_all_notifications(¬ifications); + return MA_INVALID_ARGS; + } + + /* We want all access to the VFS and the internal decoder to happen on the job thread just to keep things easier to manage for the VFS. */ + + /* We need a copy of the file path. We should probably make this more efficient, but for now we'll do a transient memory allocation. */ + if (pConfig->pFilePath != NULL) { + pFilePathCopy = ma_copy_string(pConfig->pFilePath, &pResourceManager->config.allocationCallbacks); + } else { + pFilePathWCopy = ma_copy_string_w(pConfig->pFilePathW, &pResourceManager->config.allocationCallbacks); + } + + if (pFilePathCopy == NULL && pFilePathWCopy == NULL) { + ma_resource_manager_pipeline_notifications_signal_all_notifications(¬ifications); + return MA_OUT_OF_MEMORY; + } + + /* + We need to check for the presence of MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC. If it's not set, we need to wait before returning. Otherwise we + can return immediately. Likewise, we'll also check for MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT and do the same. + */ + if ((pConfig->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC) == 0 || (pConfig->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) { + waitBeforeReturning = MA_TRUE; + ma_resource_manager_inline_notification_init(pResourceManager, &waitNotification); + } + + ma_resource_manager_pipeline_notifications_acquire_all_fences(¬ifications); + + /* Set the absolute cursor to our initial seek position so retrieval of the cursor returns a good value. */ + ma_resource_manager_data_stream_set_absolute_cursor(pDataStream, pConfig->initialSeekPointInPCMFrames); + + /* We now have everything we need to post the job. This is the last thing we need to do from here. The rest will be done by the job thread. */ + job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_STREAM); + job.order = ma_resource_manager_data_stream_next_execution_order(pDataStream); + job.data.resourceManager.loadDataStream.pDataStream = pDataStream; + job.data.resourceManager.loadDataStream.pFilePath = pFilePathCopy; + job.data.resourceManager.loadDataStream.pFilePathW = pFilePathWCopy; + job.data.resourceManager.loadDataStream.initialSeekPoint = pConfig->initialSeekPointInPCMFrames; + job.data.resourceManager.loadDataStream.pInitNotification = (waitBeforeReturning == MA_TRUE) ? &waitNotification : notifications.init.pNotification; + job.data.resourceManager.loadDataStream.pInitFence = notifications.init.pFence; + result = ma_resource_manager_post_job(pResourceManager, &job); + if (result != MA_SUCCESS) { + ma_resource_manager_pipeline_notifications_signal_all_notifications(¬ifications); + ma_resource_manager_pipeline_notifications_release_all_fences(¬ifications); + + if (waitBeforeReturning) { + ma_resource_manager_inline_notification_uninit(&waitNotification); + } + + ma_free(pFilePathCopy, &pResourceManager->config.allocationCallbacks); + ma_free(pFilePathWCopy, &pResourceManager->config.allocationCallbacks); + return result; + } + + /* Wait if needed. */ + if (waitBeforeReturning) { + ma_resource_manager_inline_notification_wait_and_uninit(&waitNotification); + + if (notifications.init.pNotification != NULL) { + ma_async_notification_signal(notifications.init.pNotification); + } + + /* + If there was an error during initialization make sure we return that result here. We don't want to do this + if we're not waiting because it will most likely be in a busy state. + */ + if (pDataStream->result != MA_SUCCESS) { + return pDataStream->result; + } + + /* NOTE: Do not release pInitFence here. That will be done by the job. */ + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_resource_manager_data_stream_init(ma_resource_manager* pResourceManager, const char* pFilePath, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_stream* pDataStream) +{ + ma_resource_manager_data_source_config config; + + config = ma_resource_manager_data_source_config_init(); + config.pFilePath = pFilePath; + config.flags = flags; + config.pNotifications = pNotifications; + + return ma_resource_manager_data_stream_init_ex(pResourceManager, &config, pDataStream); +} + +MA_API ma_result ma_resource_manager_data_stream_init_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_stream* pDataStream) +{ + ma_resource_manager_data_source_config config; + + config = ma_resource_manager_data_source_config_init(); + config.pFilePathW = pFilePath; + config.flags = flags; + config.pNotifications = pNotifications; + + return ma_resource_manager_data_stream_init_ex(pResourceManager, &config, pDataStream); +} + +MA_API ma_result ma_resource_manager_data_stream_uninit(ma_resource_manager_data_stream* pDataStream) +{ + ma_resource_manager_inline_notification freeEvent; + ma_job job; + + if (pDataStream == NULL) { + return MA_INVALID_ARGS; + } + + /* The first thing to do is set the result to unavailable. This will prevent future page decoding. */ + ma_atomic_exchange_i32(&pDataStream->result, MA_UNAVAILABLE); + + /* + We need to post a job to ensure we're not in the middle or decoding or anything. Because the object is owned by the caller, we'll need + to wait for it to complete before returning which means we need an event. + */ + ma_resource_manager_inline_notification_init(pDataStream->pResourceManager, &freeEvent); + + job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_STREAM); + job.order = ma_resource_manager_data_stream_next_execution_order(pDataStream); + job.data.resourceManager.freeDataStream.pDataStream = pDataStream; + job.data.resourceManager.freeDataStream.pDoneNotification = &freeEvent; + job.data.resourceManager.freeDataStream.pDoneFence = NULL; + ma_resource_manager_post_job(pDataStream->pResourceManager, &job); + + /* We need to wait for the job to finish processing before we return. */ + ma_resource_manager_inline_notification_wait_and_uninit(&freeEvent); + + return MA_SUCCESS; +} + + +static ma_uint32 ma_resource_manager_data_stream_get_page_size_in_frames(ma_resource_manager_data_stream* pDataStream) +{ + MA_ASSERT(pDataStream != NULL); + MA_ASSERT(pDataStream->isDecoderInitialized == MA_TRUE); + + return MA_RESOURCE_MANAGER_PAGE_SIZE_IN_MILLISECONDS * (pDataStream->decoder.outputSampleRate/1000); +} + +static void* ma_resource_manager_data_stream_get_page_data_pointer(ma_resource_manager_data_stream* pDataStream, ma_uint32 pageIndex, ma_uint32 relativeCursor) +{ + MA_ASSERT(pDataStream != NULL); + MA_ASSERT(pDataStream->isDecoderInitialized == MA_TRUE); + MA_ASSERT(pageIndex == 0 || pageIndex == 1); + + return ma_offset_ptr(pDataStream->pPageData, ((ma_resource_manager_data_stream_get_page_size_in_frames(pDataStream) * pageIndex) + relativeCursor) * ma_get_bytes_per_frame(pDataStream->decoder.outputFormat, pDataStream->decoder.outputChannels)); +} + +static void ma_resource_manager_data_stream_fill_page(ma_resource_manager_data_stream* pDataStream, ma_uint32 pageIndex) +{ + ma_result result = MA_SUCCESS; + ma_uint64 pageSizeInFrames; + ma_uint64 totalFramesReadForThisPage = 0; + void* pPageData = ma_resource_manager_data_stream_get_page_data_pointer(pDataStream, pageIndex, 0); + + pageSizeInFrames = ma_resource_manager_data_stream_get_page_size_in_frames(pDataStream); + + /* The decoder needs to inherit the stream's looping and range state. */ + { + ma_uint64 rangeBeg; + ma_uint64 rangeEnd; + ma_uint64 loopPointBeg; + ma_uint64 loopPointEnd; + + ma_data_source_set_looping(&pDataStream->decoder, ma_resource_manager_data_stream_is_looping(pDataStream)); + + ma_data_source_get_range_in_pcm_frames(pDataStream, &rangeBeg, &rangeEnd); + ma_data_source_set_range_in_pcm_frames(&pDataStream->decoder, rangeBeg, rangeEnd); + + ma_data_source_get_loop_point_in_pcm_frames(pDataStream, &loopPointBeg, &loopPointEnd); + ma_data_source_set_loop_point_in_pcm_frames(&pDataStream->decoder, loopPointBeg, loopPointEnd); + } + + /* Just read straight from the decoder. It will deal with ranges and looping for us. */ + result = ma_data_source_read_pcm_frames(&pDataStream->decoder, pPageData, pageSizeInFrames, &totalFramesReadForThisPage); + if (result == MA_AT_END || totalFramesReadForThisPage < pageSizeInFrames) { + ma_atomic_exchange_32(&pDataStream->isDecoderAtEnd, MA_TRUE); + } + + ma_atomic_exchange_32(&pDataStream->pageFrameCount[pageIndex], (ma_uint32)totalFramesReadForThisPage); + ma_atomic_exchange_32(&pDataStream->isPageValid[pageIndex], MA_TRUE); +} + +static void ma_resource_manager_data_stream_fill_pages(ma_resource_manager_data_stream* pDataStream) +{ + ma_uint32 iPage; + + MA_ASSERT(pDataStream != NULL); + + for (iPage = 0; iPage < 2; iPage += 1) { + ma_resource_manager_data_stream_fill_page(pDataStream, iPage); + } +} + + +static ma_result ma_resource_manager_data_stream_map(ma_resource_manager_data_stream* pDataStream, void** ppFramesOut, ma_uint64* pFrameCount) +{ + ma_uint64 framesAvailable; + ma_uint64 frameCount = 0; + + /* We cannot be using the data source after it's been uninitialized. */ + MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) != MA_UNAVAILABLE); + + if (pFrameCount != NULL) { + frameCount = *pFrameCount; + *pFrameCount = 0; + } + if (ppFramesOut != NULL) { + *ppFramesOut = NULL; + } + + if (pDataStream == NULL || ppFramesOut == NULL || pFrameCount == NULL) { + return MA_INVALID_ARGS; + } + + if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS) { + return MA_INVALID_OPERATION; + } + + /* Don't attempt to read while we're in the middle of seeking. Tell the caller that we're busy. */ + if (ma_resource_manager_data_stream_seek_counter(pDataStream) > 0) { + return MA_BUSY; + } + + /* If the page we're on is invalid it means we've caught up to the job thread. */ + if (ma_atomic_load_32(&pDataStream->isPageValid[pDataStream->currentPageIndex]) == MA_FALSE) { + framesAvailable = 0; + } else { + /* + The page we're on is valid so we must have some frames available. We need to make sure that we don't overflow into the next page, even if it's valid. The reason is + that the unmap process will only post an update for one page at a time. Keeping mapping tied to page boundaries makes this simpler. + */ + ma_uint32 currentPageFrameCount = ma_atomic_load_32(&pDataStream->pageFrameCount[pDataStream->currentPageIndex]); + MA_ASSERT(currentPageFrameCount >= pDataStream->relativeCursor); + + framesAvailable = currentPageFrameCount - pDataStream->relativeCursor; + } + + /* If there's no frames available and the result is set to MA_AT_END we need to return MA_AT_END. */ + if (framesAvailable == 0) { + if (ma_resource_manager_data_stream_is_decoder_at_end(pDataStream)) { + return MA_AT_END; + } else { + return MA_BUSY; /* There are no frames available, but we're not marked as EOF so we might have caught up to the job thread. Need to return MA_BUSY and wait for more data. */ + } + } + + MA_ASSERT(framesAvailable > 0); + + if (frameCount > framesAvailable) { + frameCount = framesAvailable; + } + + *ppFramesOut = ma_resource_manager_data_stream_get_page_data_pointer(pDataStream, pDataStream->currentPageIndex, pDataStream->relativeCursor); + *pFrameCount = frameCount; + + return MA_SUCCESS; +} + +static ma_result ma_resource_manager_data_stream_unmap(ma_resource_manager_data_stream* pDataStream, ma_uint64 frameCount) +{ + ma_uint32 newRelativeCursor; + ma_uint32 pageSizeInFrames; + ma_job job; + + /* We cannot be using the data source after it's been uninitialized. */ + MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) != MA_UNAVAILABLE); + + if (pDataStream == NULL) { + return MA_INVALID_ARGS; + } + + if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS) { + return MA_INVALID_OPERATION; + } + + /* The frame count should always fit inside a 32-bit integer. */ + if (frameCount > 0xFFFFFFFF) { + return MA_INVALID_ARGS; + } + + pageSizeInFrames = ma_resource_manager_data_stream_get_page_size_in_frames(pDataStream); + + /* The absolute cursor needs to be updated for ma_resource_manager_data_stream_get_cursor_in_pcm_frames(). */ + ma_resource_manager_data_stream_set_absolute_cursor(pDataStream, ma_atomic_load_64(&pDataStream->absoluteCursor) + frameCount); + + /* Here is where we need to check if we need to load a new page, and if so, post a job to load it. */ + newRelativeCursor = pDataStream->relativeCursor + (ma_uint32)frameCount; + + /* If the new cursor has flowed over to the next page we need to mark the old one as invalid and post an event for it. */ + if (newRelativeCursor >= pageSizeInFrames) { + newRelativeCursor -= pageSizeInFrames; + + /* Here is where we post the job start decoding. */ + job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_STREAM); + job.order = ma_resource_manager_data_stream_next_execution_order(pDataStream); + job.data.resourceManager.pageDataStream.pDataStream = pDataStream; + job.data.resourceManager.pageDataStream.pageIndex = pDataStream->currentPageIndex; + + /* The page needs to be marked as invalid so that the public API doesn't try reading from it. */ + ma_atomic_exchange_32(&pDataStream->isPageValid[pDataStream->currentPageIndex], MA_FALSE); + + /* Before posting the job we need to make sure we set some state. */ + pDataStream->relativeCursor = newRelativeCursor; + pDataStream->currentPageIndex = (pDataStream->currentPageIndex + 1) & 0x01; + return ma_resource_manager_post_job(pDataStream->pResourceManager, &job); + } else { + /* We haven't moved into a new page so we can just move the cursor forward. */ + pDataStream->relativeCursor = newRelativeCursor; + return MA_SUCCESS; + } +} + + +MA_API ma_result ma_resource_manager_data_stream_read_pcm_frames(ma_resource_manager_data_stream* pDataStream, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + ma_result result = MA_SUCCESS; + ma_uint64 totalFramesProcessed; + ma_format format; + ma_uint32 channels; + + /* Safety. */ + if (pFramesRead != NULL) { + *pFramesRead = 0; + } + + if (frameCount == 0) { + return MA_INVALID_ARGS; + } + + /* We cannot be using the data source after it's been uninitialized. */ + MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) != MA_UNAVAILABLE); + + if (pDataStream == NULL) { + return MA_INVALID_ARGS; + } + + if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS) { + return MA_INVALID_OPERATION; + } + + /* Don't attempt to read while we're in the middle of seeking. Tell the caller that we're busy. */ + if (ma_resource_manager_data_stream_seek_counter(pDataStream) > 0) { + return MA_BUSY; + } + + ma_resource_manager_data_stream_get_data_format(pDataStream, &format, &channels, NULL, NULL, 0); + + /* Reading is implemented in terms of map/unmap. We need to run this in a loop because mapping is clamped against page boundaries. */ + totalFramesProcessed = 0; + while (totalFramesProcessed < frameCount) { + void* pMappedFrames; + ma_uint64 mappedFrameCount; + + mappedFrameCount = frameCount - totalFramesProcessed; + result = ma_resource_manager_data_stream_map(pDataStream, &pMappedFrames, &mappedFrameCount); + if (result != MA_SUCCESS) { + break; + } + + /* Copy the mapped data to the output buffer if we have one. It's allowed for pFramesOut to be NULL in which case a relative forward seek is performed. */ + if (pFramesOut != NULL) { + ma_copy_pcm_frames(ma_offset_pcm_frames_ptr(pFramesOut, totalFramesProcessed, format, channels), pMappedFrames, mappedFrameCount, format, channels); + } + + totalFramesProcessed += mappedFrameCount; + + result = ma_resource_manager_data_stream_unmap(pDataStream, mappedFrameCount); + if (result != MA_SUCCESS) { + break; /* This is really bad - will only get an error here if we failed to post a job to the queue for loading the next page. */ + } + } + + if (pFramesRead != NULL) { + *pFramesRead = totalFramesProcessed; + } + + if (result == MA_SUCCESS && totalFramesProcessed == 0) { + result = MA_AT_END; + } + + return result; +} + +MA_API ma_result ma_resource_manager_data_stream_seek_to_pcm_frame(ma_resource_manager_data_stream* pDataStream, ma_uint64 frameIndex) +{ + ma_job job; + ma_result streamResult; + + streamResult = ma_resource_manager_data_stream_result(pDataStream); + + /* We cannot be using the data source after it's been uninitialized. */ + MA_ASSERT(streamResult != MA_UNAVAILABLE); + + if (pDataStream == NULL) { + return MA_INVALID_ARGS; + } + + if (streamResult != MA_SUCCESS && streamResult != MA_BUSY) { + return MA_INVALID_OPERATION; + } + + /* If we're not already seeking and we're sitting on the same frame, just make this a no-op. */ + if (ma_atomic_load_32(&pDataStream->seekCounter) == 0) { + if (ma_atomic_load_64(&pDataStream->absoluteCursor) == frameIndex) { + return MA_SUCCESS; + } + } + + + /* Increment the seek counter first to indicate to read_paged_pcm_frames() and map_paged_pcm_frames() that we are in the middle of a seek and MA_BUSY should be returned. */ + ma_atomic_fetch_add_32(&pDataStream->seekCounter, 1); + + /* Update the absolute cursor so that ma_resource_manager_data_stream_get_cursor_in_pcm_frames() returns the new position. */ + ma_resource_manager_data_stream_set_absolute_cursor(pDataStream, frameIndex); + + /* + We need to clear our currently loaded pages so that the stream starts playback from the new seek point as soon as possible. These are for the purpose of the public + API and will be ignored by the seek job. The seek job will operate on the assumption that both pages have been marked as invalid and the cursor is at the start of + the first page. + */ + pDataStream->relativeCursor = 0; + pDataStream->currentPageIndex = 0; + ma_atomic_exchange_32(&pDataStream->isPageValid[0], MA_FALSE); + ma_atomic_exchange_32(&pDataStream->isPageValid[1], MA_FALSE); + + /* Make sure the data stream is not marked as at the end or else if we seek in response to hitting the end, we won't be able to read any more data. */ + ma_atomic_exchange_32(&pDataStream->isDecoderAtEnd, MA_FALSE); + + /* + The public API is not allowed to touch the internal decoder so we need to use a job to perform the seek. When seeking, the job thread will assume both pages + are invalid and any content contained within them will be discarded and replaced with newly decoded data. + */ + job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_SEEK_DATA_STREAM); + job.order = ma_resource_manager_data_stream_next_execution_order(pDataStream); + job.data.resourceManager.seekDataStream.pDataStream = pDataStream; + job.data.resourceManager.seekDataStream.frameIndex = frameIndex; + return ma_resource_manager_post_job(pDataStream->pResourceManager, &job); +} + +MA_API ma_result ma_resource_manager_data_stream_get_data_format(ma_resource_manager_data_stream* pDataStream, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + /* We cannot be using the data source after it's been uninitialized. */ + MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) != MA_UNAVAILABLE); + + if (pFormat != NULL) { + *pFormat = ma_format_unknown; + } + + if (pChannels != NULL) { + *pChannels = 0; + } + + if (pSampleRate != NULL) { + *pSampleRate = 0; + } + + if (pChannelMap != NULL) { + MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap); + } + + if (pDataStream == NULL) { + return MA_INVALID_ARGS; + } + + if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS) { + return MA_INVALID_OPERATION; + } + + /* + We're being a little bit naughty here and accessing the internal decoder from the public API. The output data format is constant, and we've defined this function + such that the application is responsible for ensuring it's not called while uninitializing so it should be safe. + */ + return ma_data_source_get_data_format(&pDataStream->decoder, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap); +} + +MA_API ma_result ma_resource_manager_data_stream_get_cursor_in_pcm_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pCursor) +{ + ma_result result; + + if (pCursor == NULL) { + return MA_INVALID_ARGS; + } + + *pCursor = 0; + + /* We cannot be using the data source after it's been uninitialized. */ + MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) != MA_UNAVAILABLE); + + if (pDataStream == NULL) { + return MA_INVALID_ARGS; + } + + /* + If the stream is in an erroneous state we need to return an invalid operation. We can allow + this to be called when the data stream is in a busy state because the caller may have asked + for an initial seek position and it's convenient to return that as the cursor position. + */ + result = ma_resource_manager_data_stream_result(pDataStream); + if (result != MA_SUCCESS && result != MA_BUSY) { + return MA_INVALID_OPERATION; + } + + *pCursor = ma_atomic_load_64(&pDataStream->absoluteCursor); + + return MA_SUCCESS; +} + +MA_API ma_result ma_resource_manager_data_stream_get_length_in_pcm_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pLength) +{ + ma_result streamResult; + + if (pLength == NULL) { + return MA_INVALID_ARGS; + } + + *pLength = 0; + + streamResult = ma_resource_manager_data_stream_result(pDataStream); + + /* We cannot be using the data source after it's been uninitialized. */ + MA_ASSERT(streamResult != MA_UNAVAILABLE); + + if (pDataStream == NULL) { + return MA_INVALID_ARGS; + } + + if (streamResult != MA_SUCCESS) { + return streamResult; + } + + /* + We most definitely do not want to be calling ma_decoder_get_length_in_pcm_frames() directly. Instead we want to use a cached value that we + calculated when we initialized it on the job thread. + */ + *pLength = pDataStream->totalLengthInPCMFrames; + if (*pLength == 0) { + return MA_NOT_IMPLEMENTED; /* Some decoders may not have a known length. */ + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_resource_manager_data_stream_result(const ma_resource_manager_data_stream* pDataStream) +{ + if (pDataStream == NULL) { + return MA_INVALID_ARGS; + } + + return (ma_result)ma_atomic_load_i32(&pDataStream->result); +} + +MA_API ma_result ma_resource_manager_data_stream_set_looping(ma_resource_manager_data_stream* pDataStream, ma_bool32 isLooping) +{ + return ma_data_source_set_looping(pDataStream, isLooping); +} + +MA_API ma_bool32 ma_resource_manager_data_stream_is_looping(const ma_resource_manager_data_stream* pDataStream) +{ + if (pDataStream == NULL) { + return MA_FALSE; + } + + return ma_atomic_load_32((ma_bool32*)&pDataStream->isLooping); /* Naughty const-cast. Value won't change from here in practice (maybe from another thread). */ +} + +MA_API ma_result ma_resource_manager_data_stream_get_available_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pAvailableFrames) +{ + ma_uint32 pageIndex0; + ma_uint32 pageIndex1; + ma_uint32 relativeCursor; + ma_uint64 availableFrames; + + if (pAvailableFrames == NULL) { + return MA_INVALID_ARGS; + } + + *pAvailableFrames = 0; + + if (pDataStream == NULL) { + return MA_INVALID_ARGS; + } + + pageIndex0 = pDataStream->currentPageIndex; + pageIndex1 = (pDataStream->currentPageIndex + 1) & 0x01; + relativeCursor = pDataStream->relativeCursor; + + availableFrames = 0; + if (ma_atomic_load_32(&pDataStream->isPageValid[pageIndex0])) { + availableFrames += ma_atomic_load_32(&pDataStream->pageFrameCount[pageIndex0]) - relativeCursor; + if (ma_atomic_load_32(&pDataStream->isPageValid[pageIndex1])) { + availableFrames += ma_atomic_load_32(&pDataStream->pageFrameCount[pageIndex1]); + } + } + + *pAvailableFrames = availableFrames; + return MA_SUCCESS; +} + + +static ma_result ma_resource_manager_data_source_preinit(ma_resource_manager* pResourceManager, const ma_resource_manager_data_source_config* pConfig, ma_resource_manager_data_source* pDataSource) +{ + if (pDataSource == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pDataSource); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pResourceManager == NULL) { + return MA_INVALID_ARGS; + } + + pDataSource->flags = pConfig->flags; + + return MA_SUCCESS; +} + +MA_API ma_result ma_resource_manager_data_source_init_ex(ma_resource_manager* pResourceManager, const ma_resource_manager_data_source_config* pConfig, ma_resource_manager_data_source* pDataSource) +{ + ma_result result; + + result = ma_resource_manager_data_source_preinit(pResourceManager, pConfig, pDataSource); + if (result != MA_SUCCESS) { + return result; + } + + /* The data source itself is just a data stream or a data buffer. */ + if ((pConfig->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) { + return ma_resource_manager_data_stream_init_ex(pResourceManager, pConfig, &pDataSource->backend.stream); + } else { + return ma_resource_manager_data_buffer_init_ex(pResourceManager, pConfig, &pDataSource->backend.buffer); + } +} + +MA_API ma_result ma_resource_manager_data_source_init(ma_resource_manager* pResourceManager, const char* pName, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_source* pDataSource) +{ + ma_resource_manager_data_source_config config; + + config = ma_resource_manager_data_source_config_init(); + config.pFilePath = pName; + config.flags = flags; + config.pNotifications = pNotifications; + + return ma_resource_manager_data_source_init_ex(pResourceManager, &config, pDataSource); +} + +MA_API ma_result ma_resource_manager_data_source_init_w(ma_resource_manager* pResourceManager, const wchar_t* pName, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_source* pDataSource) +{ + ma_resource_manager_data_source_config config; + + config = ma_resource_manager_data_source_config_init(); + config.pFilePathW = pName; + config.flags = flags; + config.pNotifications = pNotifications; + + return ma_resource_manager_data_source_init_ex(pResourceManager, &config, pDataSource); +} + +MA_API ma_result ma_resource_manager_data_source_init_copy(ma_resource_manager* pResourceManager, const ma_resource_manager_data_source* pExistingDataSource, ma_resource_manager_data_source* pDataSource) +{ + ma_result result; + ma_resource_manager_data_source_config config; + + if (pExistingDataSource == NULL) { + return MA_INVALID_ARGS; + } + + config = ma_resource_manager_data_source_config_init(); + config.flags = pExistingDataSource->flags; + + result = ma_resource_manager_data_source_preinit(pResourceManager, &config, pDataSource); + if (result != MA_SUCCESS) { + return result; + } + + /* Copying can only be done from data buffers. Streams cannot be copied. */ + if ((pExistingDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) { + return MA_INVALID_OPERATION; + } + + return ma_resource_manager_data_buffer_init_copy(pResourceManager, &pExistingDataSource->backend.buffer, &pDataSource->backend.buffer); +} + +MA_API ma_result ma_resource_manager_data_source_uninit(ma_resource_manager_data_source* pDataSource) +{ + if (pDataSource == NULL) { + return MA_INVALID_ARGS; + } + + /* All we need to is uninitialize the underlying data buffer or data stream. */ + if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) { + return ma_resource_manager_data_stream_uninit(&pDataSource->backend.stream); + } else { + return ma_resource_manager_data_buffer_uninit(&pDataSource->backend.buffer); + } +} + +MA_API ma_result ma_resource_manager_data_source_read_pcm_frames(ma_resource_manager_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + /* Safety. */ + if (pFramesRead != NULL) { + *pFramesRead = 0; + } + + if (pDataSource == NULL) { + return MA_INVALID_ARGS; + } + + if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) { + return ma_resource_manager_data_stream_read_pcm_frames(&pDataSource->backend.stream, pFramesOut, frameCount, pFramesRead); + } else { + return ma_resource_manager_data_buffer_read_pcm_frames(&pDataSource->backend.buffer, pFramesOut, frameCount, pFramesRead); + } +} + +MA_API ma_result ma_resource_manager_data_source_seek_to_pcm_frame(ma_resource_manager_data_source* pDataSource, ma_uint64 frameIndex) +{ + if (pDataSource == NULL) { + return MA_INVALID_ARGS; + } + + if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) { + return ma_resource_manager_data_stream_seek_to_pcm_frame(&pDataSource->backend.stream, frameIndex); + } else { + return ma_resource_manager_data_buffer_seek_to_pcm_frame(&pDataSource->backend.buffer, frameIndex); + } +} + +MA_API ma_result ma_resource_manager_data_source_map(ma_resource_manager_data_source* pDataSource, void** ppFramesOut, ma_uint64* pFrameCount) +{ + if (pDataSource == NULL) { + return MA_INVALID_ARGS; + } + + if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) { + return ma_resource_manager_data_stream_map(&pDataSource->backend.stream, ppFramesOut, pFrameCount); + } else { + return MA_NOT_IMPLEMENTED; /* Mapping not supported with data buffers. */ + } +} + +MA_API ma_result ma_resource_manager_data_source_unmap(ma_resource_manager_data_source* pDataSource, ma_uint64 frameCount) +{ + if (pDataSource == NULL) { + return MA_INVALID_ARGS; + } + + if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) { + return ma_resource_manager_data_stream_unmap(&pDataSource->backend.stream, frameCount); + } else { + return MA_NOT_IMPLEMENTED; /* Mapping not supported with data buffers. */ + } +} + +MA_API ma_result ma_resource_manager_data_source_get_data_format(ma_resource_manager_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + if (pDataSource == NULL) { + return MA_INVALID_ARGS; + } + + if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) { + return ma_resource_manager_data_stream_get_data_format(&pDataSource->backend.stream, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap); + } else { + return ma_resource_manager_data_buffer_get_data_format(&pDataSource->backend.buffer, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap); + } +} + +MA_API ma_result ma_resource_manager_data_source_get_cursor_in_pcm_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pCursor) +{ + if (pDataSource == NULL) { + return MA_INVALID_ARGS; + } + + if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) { + return ma_resource_manager_data_stream_get_cursor_in_pcm_frames(&pDataSource->backend.stream, pCursor); + } else { + return ma_resource_manager_data_buffer_get_cursor_in_pcm_frames(&pDataSource->backend.buffer, pCursor); + } +} + +MA_API ma_result ma_resource_manager_data_source_get_length_in_pcm_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pLength) +{ + if (pDataSource == NULL) { + return MA_INVALID_ARGS; + } + + if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) { + return ma_resource_manager_data_stream_get_length_in_pcm_frames(&pDataSource->backend.stream, pLength); + } else { + return ma_resource_manager_data_buffer_get_length_in_pcm_frames(&pDataSource->backend.buffer, pLength); + } +} + +MA_API ma_result ma_resource_manager_data_source_result(const ma_resource_manager_data_source* pDataSource) +{ + if (pDataSource == NULL) { + return MA_INVALID_ARGS; + } + + if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) { + return ma_resource_manager_data_stream_result(&pDataSource->backend.stream); + } else { + return ma_resource_manager_data_buffer_result(&pDataSource->backend.buffer); + } +} + +MA_API ma_result ma_resource_manager_data_source_set_looping(ma_resource_manager_data_source* pDataSource, ma_bool32 isLooping) +{ + if (pDataSource == NULL) { + return MA_INVALID_ARGS; + } + + if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) { + return ma_resource_manager_data_stream_set_looping(&pDataSource->backend.stream, isLooping); + } else { + return ma_resource_manager_data_buffer_set_looping(&pDataSource->backend.buffer, isLooping); + } +} + +MA_API ma_bool32 ma_resource_manager_data_source_is_looping(const ma_resource_manager_data_source* pDataSource) +{ + if (pDataSource == NULL) { + return MA_FALSE; + } + + if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) { + return ma_resource_manager_data_stream_is_looping(&pDataSource->backend.stream); + } else { + return ma_resource_manager_data_buffer_is_looping(&pDataSource->backend.buffer); + } +} + +MA_API ma_result ma_resource_manager_data_source_get_available_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pAvailableFrames) +{ + if (pAvailableFrames == NULL) { + return MA_INVALID_ARGS; + } + + *pAvailableFrames = 0; + + if (pDataSource == NULL) { + return MA_INVALID_ARGS; + } + + if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) { + return ma_resource_manager_data_stream_get_available_frames(&pDataSource->backend.stream, pAvailableFrames); + } else { + return ma_resource_manager_data_buffer_get_available_frames(&pDataSource->backend.buffer, pAvailableFrames); + } +} + + +MA_API ma_result ma_resource_manager_post_job(ma_resource_manager* pResourceManager, const ma_job* pJob) +{ + if (pResourceManager == NULL) { + return MA_INVALID_ARGS; + } + + return ma_job_queue_post(&pResourceManager->jobQueue, pJob); +} + +MA_API ma_result ma_resource_manager_post_job_quit(ma_resource_manager* pResourceManager) +{ + ma_job job = ma_job_init(MA_JOB_TYPE_QUIT); + return ma_resource_manager_post_job(pResourceManager, &job); +} + +MA_API ma_result ma_resource_manager_next_job(ma_resource_manager* pResourceManager, ma_job* pJob) +{ + if (pResourceManager == NULL) { + return MA_INVALID_ARGS; + } + + return ma_job_queue_next(&pResourceManager->jobQueue, pJob); +} + + +static ma_result ma_job_process__resource_manager__load_data_buffer_node(ma_job* pJob) +{ + ma_result result = MA_SUCCESS; + ma_resource_manager* pResourceManager; + ma_resource_manager_data_buffer_node* pDataBufferNode; + + MA_ASSERT(pJob != NULL); + + pResourceManager = (ma_resource_manager*)pJob->data.resourceManager.loadDataBufferNode.pResourceManager; + MA_ASSERT(pResourceManager != NULL); + + pDataBufferNode = (ma_resource_manager_data_buffer_node*)pJob->data.resourceManager.loadDataBufferNode.pDataBufferNode; + MA_ASSERT(pDataBufferNode != NULL); + MA_ASSERT(pDataBufferNode->isDataOwnedByResourceManager == MA_TRUE); /* The data should always be owned by the resource manager. */ + + /* The data buffer is not getting deleted, but we may be getting executed out of order. If so, we need to push the job back onto the queue and return. */ + if (pJob->order != ma_atomic_load_32(&pDataBufferNode->executionPointer)) { + return ma_resource_manager_post_job(pResourceManager, pJob); /* Attempting to execute out of order. Probably interleaved with a MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER job. */ + } + + /* First thing we need to do is check whether or not the data buffer is getting deleted. If so we just abort. */ + if (ma_resource_manager_data_buffer_node_result(pDataBufferNode) != MA_BUSY) { + result = ma_resource_manager_data_buffer_node_result(pDataBufferNode); /* The data buffer may be getting deleted before it's even been loaded. */ + goto done; + } + + /* + We're ready to start loading. Essentially what we're doing here is initializing the data supply + of the node. Once this is complete, data buffers can have their connectors initialized which + will allow then to have audio data read from them. + + Note that when the data supply type has been moved away from "unknown", that is when other threads + will determine that the node is available for data delivery and the data buffer connectors can be + initialized. Therefore, it's important that it is set after the data supply has been initialized. + */ + if ((pJob->data.resourceManager.loadDataBufferNode.flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE) != 0) { + /* + Decoding. This is the complex case because we're not going to be doing the entire decoding + process here. Instead it's going to be split of multiple jobs and loaded in pages. The + reason for this is to evenly distribute decoding time across multiple sounds, rather than + having one huge sound hog all the available processing resources. + + The first thing we do is initialize a decoder. This is allocated on the heap and is passed + around to the paging jobs. When the last paging job has completed it's processing, it'll + free the decoder for us. + + This job does not do any actual decoding. It instead just posts a PAGE_DATA_BUFFER_NODE job + which is where the actual decoding work will be done. However, once this job is complete, + the node will be in a state where data buffer connectors can be initialized. + */ + ma_decoder* pDecoder; /* <-- Free'd on the last page decode. */ + ma_job pageDataBufferNodeJob; + + /* Allocate the decoder by initializing a decoded data supply. */ + result = ma_resource_manager_data_buffer_node_init_supply_decoded(pResourceManager, pDataBufferNode, pJob->data.resourceManager.loadDataBufferNode.pFilePath, pJob->data.resourceManager.loadDataBufferNode.pFilePathW, pJob->data.resourceManager.loadDataBufferNode.flags, &pDecoder); + + /* + Don't ever propagate an MA_BUSY result code or else the resource manager will think the + node is just busy decoding rather than in an error state. This should never happen, but + including this logic for safety just in case. + */ + if (result == MA_BUSY) { + result = MA_ERROR; + } + + if (result != MA_SUCCESS) { + if (pJob->data.resourceManager.loadDataBufferNode.pFilePath != NULL) { + ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_WARNING, "Failed to initialize data supply for \"%s\". %s.\n", pJob->data.resourceManager.loadDataBufferNode.pFilePath, ma_result_description(result)); + } else { + #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(_MSC_VER) + ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_WARNING, "Failed to initialize data supply for \"%ls\", %s.\n", pJob->data.resourceManager.loadDataBufferNode.pFilePathW, ma_result_description(result)); + #endif + } + + goto done; + } + + /* + At this point the node's data supply is initialized and other threads can start initializing + their data buffer connectors. However, no data will actually be available until we start to + actually decode it. To do this, we need to post a paging job which is where the decoding + work is done. + + Note that if an error occurred at an earlier point, this section will have been skipped. + */ + pageDataBufferNodeJob = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE); + pageDataBufferNodeJob.order = ma_resource_manager_data_buffer_node_next_execution_order(pDataBufferNode); + pageDataBufferNodeJob.data.resourceManager.pageDataBufferNode.pResourceManager = pResourceManager; + pageDataBufferNodeJob.data.resourceManager.pageDataBufferNode.pDataBufferNode = pDataBufferNode; + pageDataBufferNodeJob.data.resourceManager.pageDataBufferNode.pDecoder = pDecoder; + pageDataBufferNodeJob.data.resourceManager.pageDataBufferNode.pDoneNotification = pJob->data.resourceManager.loadDataBufferNode.pDoneNotification; + pageDataBufferNodeJob.data.resourceManager.pageDataBufferNode.pDoneFence = pJob->data.resourceManager.loadDataBufferNode.pDoneFence; + + /* The job has been set up so it can now be posted. */ + result = ma_resource_manager_post_job(pResourceManager, &pageDataBufferNodeJob); + + /* + When we get here, we want to make sure the result code is set to MA_BUSY. The reason for + this is that the result will be copied over to the node's internal result variable. In + this case, since the decoding is still in-progress, we need to make sure the result code + is set to MA_BUSY. + */ + if (result != MA_SUCCESS) { + ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_ERROR, "Failed to post MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE job. %s\n", ma_result_description(result)); + ma_decoder_uninit(pDecoder); + ma_free(pDecoder, &pResourceManager->config.allocationCallbacks); + } else { + result = MA_BUSY; + } + } else { + /* No decoding. This is the simple case. We need only read the file content into memory and we're done. */ + result = ma_resource_manager_data_buffer_node_init_supply_encoded(pResourceManager, pDataBufferNode, pJob->data.resourceManager.loadDataBufferNode.pFilePath, pJob->data.resourceManager.loadDataBufferNode.pFilePathW); + } + + +done: + /* File paths are no longer needed. */ + ma_free(pJob->data.resourceManager.loadDataBufferNode.pFilePath, &pResourceManager->config.allocationCallbacks); + ma_free(pJob->data.resourceManager.loadDataBufferNode.pFilePathW, &pResourceManager->config.allocationCallbacks); + + /* + We need to set the result to at the very end to ensure no other threads try reading the data before we've fully initialized the object. Other threads + are going to be inspecting this variable to determine whether or not they're ready to read data. We can only change the result if it's set to MA_BUSY + because otherwise we may be changing away from an error code which would be bad. An example is if the application creates a data buffer, but then + immediately deletes it before we've got to this point. In this case, pDataBuffer->result will be MA_UNAVAILABLE, and setting it to MA_SUCCESS or any + other error code would cause the buffer to look like it's in a state that it's not. + */ + ma_atomic_compare_and_swap_i32(&pDataBufferNode->result, MA_BUSY, result); + + /* At this point initialization is complete and we can signal the notification if any. */ + if (pJob->data.resourceManager.loadDataBufferNode.pInitNotification != NULL) { + ma_async_notification_signal(pJob->data.resourceManager.loadDataBufferNode.pInitNotification); + } + if (pJob->data.resourceManager.loadDataBufferNode.pInitFence != NULL) { + ma_fence_release(pJob->data.resourceManager.loadDataBufferNode.pInitFence); + } + + /* If we have a success result it means we've fully loaded the buffer. This will happen in the non-decoding case. */ + if (result != MA_BUSY) { + if (pJob->data.resourceManager.loadDataBufferNode.pDoneNotification != NULL) { + ma_async_notification_signal(pJob->data.resourceManager.loadDataBufferNode.pDoneNotification); + } + if (pJob->data.resourceManager.loadDataBufferNode.pDoneFence != NULL) { + ma_fence_release(pJob->data.resourceManager.loadDataBufferNode.pDoneFence); + } + } + + /* Increment the node's execution pointer so that the next jobs can be processed. This is how we keep decoding of pages in-order. */ + ma_atomic_fetch_add_32(&pDataBufferNode->executionPointer, 1); + + /* A busy result should be considered successful from the point of view of the job system. */ + if (result == MA_BUSY) { + result = MA_SUCCESS; + } + + return result; +} + +static ma_result ma_job_process__resource_manager__free_data_buffer_node(ma_job* pJob) +{ + ma_resource_manager* pResourceManager; + ma_resource_manager_data_buffer_node* pDataBufferNode; + + MA_ASSERT(pJob != NULL); + + pResourceManager = (ma_resource_manager*)pJob->data.resourceManager.freeDataBufferNode.pResourceManager; + MA_ASSERT(pResourceManager != NULL); + + pDataBufferNode = (ma_resource_manager_data_buffer_node*)pJob->data.resourceManager.freeDataBufferNode.pDataBufferNode; + MA_ASSERT(pDataBufferNode != NULL); + + if (pJob->order != ma_atomic_load_32(&pDataBufferNode->executionPointer)) { + return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */ + } + + ma_resource_manager_data_buffer_node_free(pResourceManager, pDataBufferNode); + + /* The event needs to be signalled last. */ + if (pJob->data.resourceManager.freeDataBufferNode.pDoneNotification != NULL) { + ma_async_notification_signal(pJob->data.resourceManager.freeDataBufferNode.pDoneNotification); + } + + if (pJob->data.resourceManager.freeDataBufferNode.pDoneFence != NULL) { + ma_fence_release(pJob->data.resourceManager.freeDataBufferNode.pDoneFence); + } + + ma_atomic_fetch_add_32(&pDataBufferNode->executionPointer, 1); + return MA_SUCCESS; +} + +static ma_result ma_job_process__resource_manager__page_data_buffer_node(ma_job* pJob) +{ + ma_result result = MA_SUCCESS; + ma_resource_manager* pResourceManager; + ma_resource_manager_data_buffer_node* pDataBufferNode; + + MA_ASSERT(pJob != NULL); + + pResourceManager = (ma_resource_manager*)pJob->data.resourceManager.pageDataBufferNode.pResourceManager; + MA_ASSERT(pResourceManager != NULL); + + pDataBufferNode = (ma_resource_manager_data_buffer_node*)pJob->data.resourceManager.pageDataBufferNode.pDataBufferNode; + MA_ASSERT(pDataBufferNode != NULL); + + if (pJob->order != ma_atomic_load_32(&pDataBufferNode->executionPointer)) { + return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */ + } + + /* Don't do any more decoding if the data buffer has started the uninitialization process. */ + result = ma_resource_manager_data_buffer_node_result(pDataBufferNode); + if (result != MA_BUSY) { + goto done; + } + + /* We're ready to decode the next page. */ + result = ma_resource_manager_data_buffer_node_decode_next_page(pResourceManager, pDataBufferNode, (ma_decoder*)pJob->data.resourceManager.pageDataBufferNode.pDecoder); + + /* + If we have a success code by this point, we want to post another job. We're going to set the + result back to MA_BUSY to make it clear that there's still more to load. + */ + if (result == MA_SUCCESS) { + ma_job newJob; + newJob = *pJob; /* Everything is the same as the input job, except the execution order. */ + newJob.order = ma_resource_manager_data_buffer_node_next_execution_order(pDataBufferNode); /* We need a fresh execution order. */ + + result = ma_resource_manager_post_job(pResourceManager, &newJob); + + /* Since the sound isn't yet fully decoded we want the status to be set to busy. */ + if (result == MA_SUCCESS) { + result = MA_BUSY; + } + } + +done: + /* If there's still more to decode the result will be set to MA_BUSY. Otherwise we can free the decoder. */ + if (result != MA_BUSY) { + ma_decoder_uninit((ma_decoder*)pJob->data.resourceManager.pageDataBufferNode.pDecoder); + ma_free(pJob->data.resourceManager.pageDataBufferNode.pDecoder, &pResourceManager->config.allocationCallbacks); + } + + /* If we reached the end we need to treat it as successful. */ + if (result == MA_AT_END) { + result = MA_SUCCESS; + } + + /* Make sure we set the result of node in case some error occurred. */ + ma_atomic_compare_and_swap_i32(&pDataBufferNode->result, MA_BUSY, result); + + /* Signal the notification after setting the result in case the notification callback wants to inspect the result code. */ + if (result != MA_BUSY) { + if (pJob->data.resourceManager.pageDataBufferNode.pDoneNotification != NULL) { + ma_async_notification_signal(pJob->data.resourceManager.pageDataBufferNode.pDoneNotification); + } + + if (pJob->data.resourceManager.pageDataBufferNode.pDoneFence != NULL) { + ma_fence_release(pJob->data.resourceManager.pageDataBufferNode.pDoneFence); + } + } + + ma_atomic_fetch_add_32(&pDataBufferNode->executionPointer, 1); + return result; +} + + +static ma_result ma_job_process__resource_manager__load_data_buffer(ma_job* pJob) +{ + ma_result result = MA_SUCCESS; + ma_resource_manager* pResourceManager; + ma_resource_manager_data_buffer* pDataBuffer; + ma_resource_manager_data_supply_type dataSupplyType = ma_resource_manager_data_supply_type_unknown; + ma_bool32 isConnectorInitialized = MA_FALSE; + + /* + All we're doing here is checking if the node has finished loading. If not, we just re-post the job + and keep waiting. Otherwise we increment the execution counter and set the buffer's result code. + */ + MA_ASSERT(pJob != NULL); + + pDataBuffer = (ma_resource_manager_data_buffer*)pJob->data.resourceManager.loadDataBuffer.pDataBuffer; + MA_ASSERT(pDataBuffer != NULL); + + pResourceManager = pDataBuffer->pResourceManager; + + if (pJob->order != ma_atomic_load_32(&pDataBuffer->executionPointer)) { + return ma_resource_manager_post_job(pResourceManager, pJob); /* Attempting to execute out of order. Probably interleaved with a MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER job. */ + } + + /* + First thing we need to do is check whether or not the data buffer is getting deleted. If so we + just abort, but making sure we increment the execution pointer. + */ + result = ma_resource_manager_data_buffer_result(pDataBuffer); + if (result != MA_BUSY) { + goto done; /* <-- This will ensure the exucution pointer is incremented. */ + } else { + result = MA_SUCCESS; /* <-- Make sure this is reset. */ + } + + /* Try initializing the connector if we haven't already. */ + isConnectorInitialized = ma_resource_manager_data_buffer_has_connector(pDataBuffer); + if (isConnectorInitialized == MA_FALSE) { + dataSupplyType = ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode); + + if (dataSupplyType != ma_resource_manager_data_supply_type_unknown) { + /* We can now initialize the connector. If this fails, we need to abort. It's very rare for this to fail. */ + ma_resource_manager_data_source_config dataSourceConfig; /* For setting initial looping state and range. */ + dataSourceConfig = ma_resource_manager_data_source_config_init(); + dataSourceConfig.rangeBegInPCMFrames = pJob->data.resourceManager.loadDataBuffer.rangeBegInPCMFrames; + dataSourceConfig.rangeEndInPCMFrames = pJob->data.resourceManager.loadDataBuffer.rangeEndInPCMFrames; + dataSourceConfig.loopPointBegInPCMFrames = pJob->data.resourceManager.loadDataBuffer.loopPointBegInPCMFrames; + dataSourceConfig.loopPointEndInPCMFrames = pJob->data.resourceManager.loadDataBuffer.loopPointEndInPCMFrames; + dataSourceConfig.isLooping = pJob->data.resourceManager.loadDataBuffer.isLooping; + + result = ma_resource_manager_data_buffer_init_connector(pDataBuffer, &dataSourceConfig, pJob->data.resourceManager.loadDataBuffer.pInitNotification, pJob->data.resourceManager.loadDataBuffer.pInitFence); + if (result != MA_SUCCESS) { + ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_ERROR, "Failed to initialize connector for data buffer. %s.\n", ma_result_description(result)); + goto done; + } + } else { + /* Don't have a known data supply type. Most likely the data buffer node is still loading, but it could be that an error occurred. */ + } + } else { + /* The connector is already initialized. Nothing to do here. */ + } + + /* + If the data node is still loading, we need to repost the job and *not* increment the execution + pointer (i.e. we need to not fall through to the "done" label). + + There is a hole between here and the where the data connector is initialized where the data + buffer node may have finished initializing. We need to check for this by checking the result of + the data buffer node and whether or not we had an unknown data supply type at the time of + trying to initialize the data connector. + */ + result = ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode); + if (result == MA_BUSY || (result == MA_SUCCESS && isConnectorInitialized == MA_FALSE && dataSupplyType == ma_resource_manager_data_supply_type_unknown)) { + return ma_resource_manager_post_job(pResourceManager, pJob); + } + +done: + /* Only move away from a busy code so that we don't trash any existing error codes. */ + ma_atomic_compare_and_swap_i32(&pDataBuffer->result, MA_BUSY, result); + + /* Only signal the other threads after the result has been set just for cleanliness sake. */ + if (pJob->data.resourceManager.loadDataBuffer.pDoneNotification != NULL) { + ma_async_notification_signal(pJob->data.resourceManager.loadDataBuffer.pDoneNotification); + } + if (pJob->data.resourceManager.loadDataBuffer.pDoneFence != NULL) { + ma_fence_release(pJob->data.resourceManager.loadDataBuffer.pDoneFence); + } + + /* + If at this point the data buffer has not had it's connector initialized, it means the + notification event was never signalled which means we need to signal it here. + */ + if (ma_resource_manager_data_buffer_has_connector(pDataBuffer) == MA_FALSE && result != MA_SUCCESS) { + if (pJob->data.resourceManager.loadDataBuffer.pInitNotification != NULL) { + ma_async_notification_signal(pJob->data.resourceManager.loadDataBuffer.pInitNotification); + } + if (pJob->data.resourceManager.loadDataBuffer.pInitFence != NULL) { + ma_fence_release(pJob->data.resourceManager.loadDataBuffer.pInitFence); + } + } + + ma_atomic_fetch_add_32(&pDataBuffer->executionPointer, 1); + return result; +} + +static ma_result ma_job_process__resource_manager__free_data_buffer(ma_job* pJob) +{ + ma_resource_manager* pResourceManager; + ma_resource_manager_data_buffer* pDataBuffer; + + MA_ASSERT(pJob != NULL); + + pDataBuffer = (ma_resource_manager_data_buffer*)pJob->data.resourceManager.freeDataBuffer.pDataBuffer; + MA_ASSERT(pDataBuffer != NULL); + + pResourceManager = pDataBuffer->pResourceManager; + + if (pJob->order != ma_atomic_load_32(&pDataBuffer->executionPointer)) { + return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */ + } + + ma_resource_manager_data_buffer_uninit_internal(pDataBuffer); + + /* The event needs to be signalled last. */ + if (pJob->data.resourceManager.freeDataBuffer.pDoneNotification != NULL) { + ma_async_notification_signal(pJob->data.resourceManager.freeDataBuffer.pDoneNotification); + } + + if (pJob->data.resourceManager.freeDataBuffer.pDoneFence != NULL) { + ma_fence_release(pJob->data.resourceManager.freeDataBuffer.pDoneFence); + } + + ma_atomic_fetch_add_32(&pDataBuffer->executionPointer, 1); + return MA_SUCCESS; +} + +static ma_result ma_job_process__resource_manager__load_data_stream(ma_job* pJob) +{ + ma_result result = MA_SUCCESS; + ma_decoder_config decoderConfig; + ma_uint32 pageBufferSizeInBytes; + ma_resource_manager* pResourceManager; + ma_resource_manager_data_stream* pDataStream; + + MA_ASSERT(pJob != NULL); + + pDataStream = (ma_resource_manager_data_stream*)pJob->data.resourceManager.loadDataStream.pDataStream; + MA_ASSERT(pDataStream != NULL); + + pResourceManager = pDataStream->pResourceManager; + + if (pJob->order != ma_atomic_load_32(&pDataStream->executionPointer)) { + return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */ + } + + if (ma_resource_manager_data_stream_result(pDataStream) != MA_BUSY) { + result = MA_INVALID_OPERATION; /* Most likely the data stream is being uninitialized. */ + goto done; + } + + /* We need to initialize the decoder first so we can determine the size of the pages. */ + decoderConfig = ma_resource_manager__init_decoder_config(pResourceManager); + + if (pJob->data.resourceManager.loadDataStream.pFilePath != NULL) { + result = ma_decoder_init_vfs(pResourceManager->config.pVFS, pJob->data.resourceManager.loadDataStream.pFilePath, &decoderConfig, &pDataStream->decoder); + } else { + result = ma_decoder_init_vfs_w(pResourceManager->config.pVFS, pJob->data.resourceManager.loadDataStream.pFilePathW, &decoderConfig, &pDataStream->decoder); + } + if (result != MA_SUCCESS) { + goto done; + } + + /* Retrieve the total length of the file before marking the decoder as loaded. */ + if ((pDataStream->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_UNKNOWN_LENGTH) == 0) { + result = ma_decoder_get_length_in_pcm_frames(&pDataStream->decoder, &pDataStream->totalLengthInPCMFrames); + if (result != MA_SUCCESS) { + goto done; /* Failed to retrieve the length. */ + } + } else { + pDataStream->totalLengthInPCMFrames = 0; + } + + /* + Only mark the decoder as initialized when the length of the decoder has been retrieved because that can possibly require a scan over the whole file + and we don't want to have another thread trying to access the decoder while it's scanning. + */ + pDataStream->isDecoderInitialized = MA_TRUE; + + /* We have the decoder so we can now initialize our page buffer. */ + pageBufferSizeInBytes = ma_resource_manager_data_stream_get_page_size_in_frames(pDataStream) * 2 * ma_get_bytes_per_frame(pDataStream->decoder.outputFormat, pDataStream->decoder.outputChannels); + + pDataStream->pPageData = ma_malloc(pageBufferSizeInBytes, &pResourceManager->config.allocationCallbacks); + if (pDataStream->pPageData == NULL) { + ma_decoder_uninit(&pDataStream->decoder); + result = MA_OUT_OF_MEMORY; + goto done; + } + + /* Seek to our initial seek point before filling the initial pages. */ + ma_decoder_seek_to_pcm_frame(&pDataStream->decoder, pJob->data.resourceManager.loadDataStream.initialSeekPoint); + + /* We have our decoder and our page buffer, so now we need to fill our pages. */ + ma_resource_manager_data_stream_fill_pages(pDataStream); + + /* And now we're done. We want to make sure the result is MA_SUCCESS. */ + result = MA_SUCCESS; + +done: + ma_free(pJob->data.resourceManager.loadDataStream.pFilePath, &pResourceManager->config.allocationCallbacks); + ma_free(pJob->data.resourceManager.loadDataStream.pFilePathW, &pResourceManager->config.allocationCallbacks); + + /* We can only change the status away from MA_BUSY. If it's set to anything else it means an error has occurred somewhere or the uninitialization process has started (most likely). */ + ma_atomic_compare_and_swap_i32(&pDataStream->result, MA_BUSY, result); + + /* Only signal the other threads after the result has been set just for cleanliness sake. */ + if (pJob->data.resourceManager.loadDataStream.pInitNotification != NULL) { + ma_async_notification_signal(pJob->data.resourceManager.loadDataStream.pInitNotification); + } + if (pJob->data.resourceManager.loadDataStream.pInitFence != NULL) { + ma_fence_release(pJob->data.resourceManager.loadDataStream.pInitFence); + } + + ma_atomic_fetch_add_32(&pDataStream->executionPointer, 1); + return result; +} + +static ma_result ma_job_process__resource_manager__free_data_stream(ma_job* pJob) +{ + ma_resource_manager* pResourceManager; + ma_resource_manager_data_stream* pDataStream; + + MA_ASSERT(pJob != NULL); + + pDataStream = (ma_resource_manager_data_stream*)pJob->data.resourceManager.freeDataStream.pDataStream; + MA_ASSERT(pDataStream != NULL); + + pResourceManager = pDataStream->pResourceManager; + + if (pJob->order != ma_atomic_load_32(&pDataStream->executionPointer)) { + return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */ + } + + /* If our status is not MA_UNAVAILABLE we have a bug somewhere. */ + MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) == MA_UNAVAILABLE); + + if (pDataStream->isDecoderInitialized) { + ma_decoder_uninit(&pDataStream->decoder); + } + + if (pDataStream->pPageData != NULL) { + ma_free(pDataStream->pPageData, &pResourceManager->config.allocationCallbacks); + pDataStream->pPageData = NULL; /* Just in case... */ + } + + ma_data_source_uninit(&pDataStream->ds); + + /* The event needs to be signalled last. */ + if (pJob->data.resourceManager.freeDataStream.pDoneNotification != NULL) { + ma_async_notification_signal(pJob->data.resourceManager.freeDataStream.pDoneNotification); + } + if (pJob->data.resourceManager.freeDataStream.pDoneFence != NULL) { + ma_fence_release(pJob->data.resourceManager.freeDataStream.pDoneFence); + } + + /*ma_atomic_fetch_add_32(&pDataStream->executionPointer, 1);*/ + return MA_SUCCESS; +} + +static ma_result ma_job_process__resource_manager__page_data_stream(ma_job* pJob) +{ + ma_result result = MA_SUCCESS; + ma_resource_manager* pResourceManager; + ma_resource_manager_data_stream* pDataStream; + + MA_ASSERT(pJob != NULL); + + pDataStream = (ma_resource_manager_data_stream*)pJob->data.resourceManager.pageDataStream.pDataStream; + MA_ASSERT(pDataStream != NULL); + + pResourceManager = pDataStream->pResourceManager; + + if (pJob->order != ma_atomic_load_32(&pDataStream->executionPointer)) { + return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */ + } + + /* For streams, the status should be MA_SUCCESS. */ + if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS) { + result = MA_INVALID_OPERATION; + goto done; + } + + ma_resource_manager_data_stream_fill_page(pDataStream, pJob->data.resourceManager.pageDataStream.pageIndex); + +done: + ma_atomic_fetch_add_32(&pDataStream->executionPointer, 1); + return result; +} + +static ma_result ma_job_process__resource_manager__seek_data_stream(ma_job* pJob) +{ + ma_result result = MA_SUCCESS; + ma_resource_manager* pResourceManager; + ma_resource_manager_data_stream* pDataStream; + + MA_ASSERT(pJob != NULL); + + pDataStream = (ma_resource_manager_data_stream*)pJob->data.resourceManager.seekDataStream.pDataStream; + MA_ASSERT(pDataStream != NULL); + + pResourceManager = pDataStream->pResourceManager; + + if (pJob->order != ma_atomic_load_32(&pDataStream->executionPointer)) { + return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */ + } + + /* For streams the status should be MA_SUCCESS for this to do anything. */ + if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS || pDataStream->isDecoderInitialized == MA_FALSE) { + result = MA_INVALID_OPERATION; + goto done; + } + + /* + With seeking we just assume both pages are invalid and the relative frame cursor at position 0. This is basically exactly the same as loading, except + instead of initializing the decoder, we seek to a frame. + */ + ma_decoder_seek_to_pcm_frame(&pDataStream->decoder, pJob->data.resourceManager.seekDataStream.frameIndex); + + /* After seeking we'll need to reload the pages. */ + ma_resource_manager_data_stream_fill_pages(pDataStream); + + /* We need to let the public API know that we're done seeking. */ + ma_atomic_fetch_sub_32(&pDataStream->seekCounter, 1); + +done: + ma_atomic_fetch_add_32(&pDataStream->executionPointer, 1); + return result; +} + +MA_API ma_result ma_resource_manager_process_job(ma_resource_manager* pResourceManager, ma_job* pJob) +{ + if (pResourceManager == NULL || pJob == NULL) { + return MA_INVALID_ARGS; + } + + return ma_job_process(pJob); +} + +MA_API ma_result ma_resource_manager_process_next_job(ma_resource_manager* pResourceManager) +{ + ma_result result; + ma_job job; + + if (pResourceManager == NULL) { + return MA_INVALID_ARGS; + } + + /* This will return MA_CANCELLED if the next job is a quit job. */ + result = ma_resource_manager_next_job(pResourceManager, &job); + if (result != MA_SUCCESS) { + return result; + } + + return ma_job_process(&job); +} +#else +/* We'll get here if the resource manager is being excluded from the build. We need to define the job processing callbacks as no-ops. */ +static ma_result ma_job_process__resource_manager__load_data_buffer_node(ma_job* pJob) { return ma_job_process__noop(pJob); } +static ma_result ma_job_process__resource_manager__free_data_buffer_node(ma_job* pJob) { return ma_job_process__noop(pJob); } +static ma_result ma_job_process__resource_manager__page_data_buffer_node(ma_job* pJob) { return ma_job_process__noop(pJob); } +static ma_result ma_job_process__resource_manager__load_data_buffer(ma_job* pJob) { return ma_job_process__noop(pJob); } +static ma_result ma_job_process__resource_manager__free_data_buffer(ma_job* pJob) { return ma_job_process__noop(pJob); } +static ma_result ma_job_process__resource_manager__load_data_stream(ma_job* pJob) { return ma_job_process__noop(pJob); } +static ma_result ma_job_process__resource_manager__free_data_stream(ma_job* pJob) { return ma_job_process__noop(pJob); } +static ma_result ma_job_process__resource_manager__page_data_stream(ma_job* pJob) { return ma_job_process__noop(pJob); } +static ma_result ma_job_process__resource_manager__seek_data_stream(ma_job* pJob) { return ma_job_process__noop(pJob); } +#endif /* MA_NO_RESOURCE_MANAGER */ + + +#ifndef MA_NO_NODE_GRAPH +/* 10ms @ 48K = 480. Must never exceed 65535. */ +#ifndef MA_DEFAULT_NODE_CACHE_CAP_IN_FRAMES_PER_BUS +#define MA_DEFAULT_NODE_CACHE_CAP_IN_FRAMES_PER_BUS 480 +#endif + + +static ma_result ma_node_read_pcm_frames(ma_node* pNode, ma_uint32 outputBusIndex, float* pFramesOut, ma_uint32 frameCount, ma_uint32* pFramesRead, ma_uint64 globalTime); + +MA_API void ma_debug_fill_pcm_frames_with_sine_wave(float* pFramesOut, ma_uint32 frameCount, ma_format format, ma_uint32 channels, ma_uint32 sampleRate) +{ + #ifndef MA_NO_GENERATION + { + ma_waveform_config waveformConfig; + ma_waveform waveform; + + waveformConfig = ma_waveform_config_init(format, channels, sampleRate, ma_waveform_type_sine, 1.0, 400); + ma_waveform_init(&waveformConfig, &waveform); + ma_waveform_read_pcm_frames(&waveform, pFramesOut, frameCount, NULL); + } + #else + { + (void)pFramesOut; + (void)frameCount; + (void)format; + (void)channels; + (void)sampleRate; + #if defined(MA_DEBUG_OUTPUT) + { + #if _MSC_VER + #pragma message ("ma_debug_fill_pcm_frames_with_sine_wave() will do nothing because MA_NO_GENERATION is enabled.") + #endif + } + #endif + } + #endif +} + + + +MA_API ma_node_graph_config ma_node_graph_config_init(ma_uint32 channels) +{ + ma_node_graph_config config; + + MA_ZERO_OBJECT(&config); + config.channels = channels; + config.nodeCacheCapInFrames = MA_DEFAULT_NODE_CACHE_CAP_IN_FRAMES_PER_BUS; + + return config; +} + + +static void ma_node_graph_set_is_reading(ma_node_graph* pNodeGraph, ma_bool32 isReading) +{ + MA_ASSERT(pNodeGraph != NULL); + ma_atomic_exchange_32(&pNodeGraph->isReading, isReading); +} + +#if 0 +static ma_bool32 ma_node_graph_is_reading(ma_node_graph* pNodeGraph) +{ + MA_ASSERT(pNodeGraph != NULL); + return ma_atomic_load_32(&pNodeGraph->isReading); +} +#endif + + +static void ma_node_graph_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut) +{ + ma_node_graph* pNodeGraph = (ma_node_graph*)pNode; + ma_uint64 framesRead; + + ma_node_graph_read_pcm_frames(pNodeGraph, ppFramesOut[0], *pFrameCountOut, &framesRead); + + *pFrameCountOut = (ma_uint32)framesRead; /* Safe cast. */ + + (void)ppFramesIn; + (void)pFrameCountIn; +} + +static ma_node_vtable g_node_graph_node_vtable = +{ + ma_node_graph_node_process_pcm_frames, + NULL, /* onGetRequiredInputFrameCount */ + 0, /* 0 input buses. */ + 1, /* 1 output bus. */ + 0 /* Flags. */ +}; + +static void ma_node_graph_endpoint_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut) +{ + MA_ASSERT(pNode != NULL); + MA_ASSERT(ma_node_get_input_bus_count(pNode) == 1); + MA_ASSERT(ma_node_get_output_bus_count(pNode) == 1); + + /* Input channel count needs to be the same as the output channel count. */ + MA_ASSERT(ma_node_get_input_channels(pNode, 0) == ma_node_get_output_channels(pNode, 0)); + + /* We don't need to do anything here because it's a passthrough. */ + (void)pNode; + (void)ppFramesIn; + (void)pFrameCountIn; + (void)ppFramesOut; + (void)pFrameCountOut; + +#if 0 + /* The data has already been mixed. We just need to move it to the output buffer. */ + if (ppFramesIn != NULL) { + ma_copy_pcm_frames(ppFramesOut[0], ppFramesIn[0], *pFrameCountOut, ma_format_f32, ma_node_get_output_channels(pNode, 0)); + } +#endif +} + +static ma_node_vtable g_node_graph_endpoint_vtable = +{ + ma_node_graph_endpoint_process_pcm_frames, + NULL, /* onGetRequiredInputFrameCount */ + 1, /* 1 input bus. */ + 1, /* 1 output bus. */ + MA_NODE_FLAG_PASSTHROUGH /* Flags. The endpoint is a passthrough. */ +}; + +MA_API ma_result ma_node_graph_init(const ma_node_graph_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_node_graph* pNodeGraph) +{ + ma_result result; + ma_node_config baseConfig; + ma_node_config endpointConfig; + + if (pNodeGraph == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pNodeGraph); + pNodeGraph->nodeCacheCapInFrames = pConfig->nodeCacheCapInFrames; + if (pNodeGraph->nodeCacheCapInFrames == 0) { + pNodeGraph->nodeCacheCapInFrames = MA_DEFAULT_NODE_CACHE_CAP_IN_FRAMES_PER_BUS; + } + + + /* Base node so we can use the node graph as a node into another graph. */ + baseConfig = ma_node_config_init(); + baseConfig.vtable = &g_node_graph_node_vtable; + baseConfig.pOutputChannels = &pConfig->channels; + + result = ma_node_init(pNodeGraph, &baseConfig, pAllocationCallbacks, &pNodeGraph->base); + if (result != MA_SUCCESS) { + return result; + } + + + /* Endpoint. */ + endpointConfig = ma_node_config_init(); + endpointConfig.vtable = &g_node_graph_endpoint_vtable; + endpointConfig.pInputChannels = &pConfig->channels; + endpointConfig.pOutputChannels = &pConfig->channels; + + result = ma_node_init(pNodeGraph, &endpointConfig, pAllocationCallbacks, &pNodeGraph->endpoint); + if (result != MA_SUCCESS) { + ma_node_uninit(&pNodeGraph->base, pAllocationCallbacks); + return result; + } + + return MA_SUCCESS; +} + +MA_API void ma_node_graph_uninit(ma_node_graph* pNodeGraph, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pNodeGraph == NULL) { + return; + } + + ma_node_uninit(&pNodeGraph->endpoint, pAllocationCallbacks); +} + +MA_API ma_node* ma_node_graph_get_endpoint(ma_node_graph* pNodeGraph) +{ + if (pNodeGraph == NULL) { + return NULL; + } + + return &pNodeGraph->endpoint; +} + +MA_API ma_result ma_node_graph_read_pcm_frames(ma_node_graph* pNodeGraph, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + ma_result result = MA_SUCCESS; + ma_uint64 totalFramesRead; + ma_uint32 channels; + + if (pFramesRead != NULL) { + *pFramesRead = 0; /* Safety. */ + } + + if (pNodeGraph == NULL) { + return MA_INVALID_ARGS; + } + + channels = ma_node_get_output_channels(&pNodeGraph->endpoint, 0); + + + /* We'll be nice and try to do a full read of all frameCount frames. */ + totalFramesRead = 0; + while (totalFramesRead < frameCount) { + ma_uint32 framesJustRead; + ma_uint64 framesToRead = frameCount - totalFramesRead; + + if (framesToRead > 0xFFFFFFFF) { + framesToRead = 0xFFFFFFFF; + } + + ma_node_graph_set_is_reading(pNodeGraph, MA_TRUE); + { + result = ma_node_read_pcm_frames(&pNodeGraph->endpoint, 0, (float*)ma_offset_pcm_frames_ptr(pFramesOut, totalFramesRead, ma_format_f32, channels), (ma_uint32)framesToRead, &framesJustRead, ma_node_get_time(&pNodeGraph->endpoint)); + } + ma_node_graph_set_is_reading(pNodeGraph, MA_FALSE); + + totalFramesRead += framesJustRead; + + if (result != MA_SUCCESS) { + break; + } + + /* Abort if we weren't able to read any frames or else we risk getting stuck in a loop. */ + if (framesJustRead == 0) { + break; + } + } + + /* Let's go ahead and silence any leftover frames just for some added safety to ensure the caller doesn't try emitting garbage out of the speakers. */ + if (totalFramesRead < frameCount) { + ma_silence_pcm_frames(ma_offset_pcm_frames_ptr(pFramesOut, totalFramesRead, ma_format_f32, channels), (frameCount - totalFramesRead), ma_format_f32, channels); + } + + if (pFramesRead != NULL) { + *pFramesRead = totalFramesRead; + } + + return result; +} + +MA_API ma_uint32 ma_node_graph_get_channels(const ma_node_graph* pNodeGraph) +{ + if (pNodeGraph == NULL) { + return 0; + } + + return ma_node_get_output_channels(&pNodeGraph->endpoint, 0); +} + +MA_API ma_uint64 ma_node_graph_get_time(const ma_node_graph* pNodeGraph) +{ + if (pNodeGraph == NULL) { + return 0; + } + + return ma_node_get_time(&pNodeGraph->endpoint); /* Global time is just the local time of the endpoint. */ +} + +MA_API ma_result ma_node_graph_set_time(ma_node_graph* pNodeGraph, ma_uint64 globalTime) +{ + if (pNodeGraph == NULL) { + return MA_INVALID_ARGS; + } + + return ma_node_set_time(&pNodeGraph->endpoint, globalTime); /* Global time is just the local time of the endpoint. */ +} + + +#define MA_NODE_OUTPUT_BUS_FLAG_HAS_READ 0x01 /* Whether or not this bus ready to read more data. Only used on nodes with multiple output buses. */ + +static ma_result ma_node_output_bus_init(ma_node* pNode, ma_uint32 outputBusIndex, ma_uint32 channels, ma_node_output_bus* pOutputBus) +{ + MA_ASSERT(pOutputBus != NULL); + MA_ASSERT(outputBusIndex < MA_MAX_NODE_BUS_COUNT); + MA_ASSERT(outputBusIndex < ma_node_get_output_bus_count(pNode)); + MA_ASSERT(channels < 256); + + MA_ZERO_OBJECT(pOutputBus); + + if (channels == 0) { + return MA_INVALID_ARGS; + } + + pOutputBus->pNode = pNode; + pOutputBus->outputBusIndex = (ma_uint8)outputBusIndex; + pOutputBus->channels = (ma_uint8)channels; + pOutputBus->flags = MA_NODE_OUTPUT_BUS_FLAG_HAS_READ; /* <-- Important that this flag is set by default. */ + pOutputBus->volume = 1; + + return MA_SUCCESS; +} + +static void ma_node_output_bus_lock(ma_node_output_bus* pOutputBus) +{ + ma_spinlock_lock(&pOutputBus->lock); +} + +static void ma_node_output_bus_unlock(ma_node_output_bus* pOutputBus) +{ + ma_spinlock_unlock(&pOutputBus->lock); +} + + +static ma_uint32 ma_node_output_bus_get_channels(const ma_node_output_bus* pOutputBus) +{ + return pOutputBus->channels; +} + + +static void ma_node_output_bus_set_has_read(ma_node_output_bus* pOutputBus, ma_bool32 hasRead) +{ + if (hasRead) { + ma_atomic_fetch_or_32(&pOutputBus->flags, MA_NODE_OUTPUT_BUS_FLAG_HAS_READ); + } else { + ma_atomic_fetch_and_32(&pOutputBus->flags, (ma_uint32)~MA_NODE_OUTPUT_BUS_FLAG_HAS_READ); + } +} + +static ma_bool32 ma_node_output_bus_has_read(ma_node_output_bus* pOutputBus) +{ + return (ma_atomic_load_32(&pOutputBus->flags) & MA_NODE_OUTPUT_BUS_FLAG_HAS_READ) != 0; +} + + +static void ma_node_output_bus_set_is_attached(ma_node_output_bus* pOutputBus, ma_bool32 isAttached) +{ + ma_atomic_exchange_32(&pOutputBus->isAttached, isAttached); +} + +static ma_bool32 ma_node_output_bus_is_attached(ma_node_output_bus* pOutputBus) +{ + return ma_atomic_load_32(&pOutputBus->isAttached); +} + + +static ma_result ma_node_output_bus_set_volume(ma_node_output_bus* pOutputBus, float volume) +{ + MA_ASSERT(pOutputBus != NULL); + + if (volume < 0.0f) { + volume = 0.0f; + } + + ma_atomic_exchange_f32(&pOutputBus->volume, volume); + + return MA_SUCCESS; +} + +static float ma_node_output_bus_get_volume(const ma_node_output_bus* pOutputBus) +{ + return ma_atomic_load_f32((float*)&pOutputBus->volume); +} + + +static ma_result ma_node_input_bus_init(ma_uint32 channels, ma_node_input_bus* pInputBus) +{ + MA_ASSERT(pInputBus != NULL); + MA_ASSERT(channels < 256); + + MA_ZERO_OBJECT(pInputBus); + + if (channels == 0) { + return MA_INVALID_ARGS; + } + + pInputBus->channels = (ma_uint8)channels; + + return MA_SUCCESS; +} + +static void ma_node_input_bus_lock(ma_node_input_bus* pInputBus) +{ + MA_ASSERT(pInputBus != NULL); + + ma_spinlock_lock(&pInputBus->lock); +} + +static void ma_node_input_bus_unlock(ma_node_input_bus* pInputBus) +{ + MA_ASSERT(pInputBus != NULL); + + ma_spinlock_unlock(&pInputBus->lock); +} + + +static void ma_node_input_bus_next_begin(ma_node_input_bus* pInputBus) +{ + ma_atomic_fetch_add_32(&pInputBus->nextCounter, 1); +} + +static void ma_node_input_bus_next_end(ma_node_input_bus* pInputBus) +{ + ma_atomic_fetch_sub_32(&pInputBus->nextCounter, 1); +} + +static ma_uint32 ma_node_input_bus_get_next_counter(ma_node_input_bus* pInputBus) +{ + return ma_atomic_load_32(&pInputBus->nextCounter); +} + + +static ma_uint32 ma_node_input_bus_get_channels(const ma_node_input_bus* pInputBus) +{ + return pInputBus->channels; +} + + +static void ma_node_input_bus_detach__no_output_bus_lock(ma_node_input_bus* pInputBus, ma_node_output_bus* pOutputBus) +{ + MA_ASSERT(pInputBus != NULL); + MA_ASSERT(pOutputBus != NULL); + + /* + Mark the output bus as detached first. This will prevent future iterations on the audio thread + from iterating this output bus. + */ + ma_node_output_bus_set_is_attached(pOutputBus, MA_FALSE); + + /* + We cannot use the output bus lock here since it'll be getting used at a higher level, but we do + still need to use the input bus lock since we'll be updating pointers on two different output + buses. The same rules apply here as the attaching case. Although we're using a lock here, we're + *not* using a lock when iterating over the list in the audio thread. We therefore need to craft + this in a way such that the iteration on the audio thread doesn't break. + + The the first thing to do is swap out the "next" pointer of the previous output bus with the + new "next" output bus. This is the operation that matters for iteration on the audio thread. + After that, the previous pointer on the new "next" pointer needs to be updated, after which + point the linked list will be in a good state. + */ + ma_node_input_bus_lock(pInputBus); + { + ma_node_output_bus* pOldPrev = (ma_node_output_bus*)ma_atomic_load_ptr(&pOutputBus->pPrev); + ma_node_output_bus* pOldNext = (ma_node_output_bus*)ma_atomic_load_ptr(&pOutputBus->pNext); + + if (pOldPrev != NULL) { + ma_atomic_exchange_ptr(&pOldPrev->pNext, pOldNext); /* <-- This is where the output bus is detached from the list. */ + } + if (pOldNext != NULL) { + ma_atomic_exchange_ptr(&pOldNext->pPrev, pOldPrev); /* <-- This is required for detachment. */ + } + } + ma_node_input_bus_unlock(pInputBus); + + /* At this point the output bus is detached and the linked list is completely unaware of it. Reset some data for safety. */ + ma_atomic_exchange_ptr(&pOutputBus->pNext, NULL); /* Using atomic exchanges here, mainly for the benefit of analysis tools which don't always recognize spinlocks. */ + ma_atomic_exchange_ptr(&pOutputBus->pPrev, NULL); /* As above. */ + pOutputBus->pInputNode = NULL; + pOutputBus->inputNodeInputBusIndex = 0; + + + /* + For thread-safety reasons, we don't want to be returning from this straight away. We need to + wait for the audio thread to finish with the output bus. There's two things we need to wait + for. The first is the part that selects the next output bus in the list, and the other is the + part that reads from the output bus. Basically all we're doing is waiting for the input bus + to stop referencing the output bus. + + We're doing this part last because we want the section above to run while the audio thread + is finishing up with the output bus, just for efficiency reasons. We marked the output bus as + detached right at the top of this function which is going to prevent the audio thread from + iterating the output bus again. + */ + + /* Part 1: Wait for the current iteration to complete. */ + while (ma_node_input_bus_get_next_counter(pInputBus) > 0) { + ma_yield(); + } + + /* Part 2: Wait for any reads to complete. */ + while (ma_atomic_load_32(&pOutputBus->refCount) > 0) { + ma_yield(); + } + + /* + At this point we're done detaching and we can be guaranteed that the audio thread is not going + to attempt to reference this output bus again (until attached again). + */ +} + +#if 0 /* Not used at the moment, but leaving here in case I need it later. */ +static void ma_node_input_bus_detach(ma_node_input_bus* pInputBus, ma_node_output_bus* pOutputBus) +{ + MA_ASSERT(pInputBus != NULL); + MA_ASSERT(pOutputBus != NULL); + + ma_node_output_bus_lock(pOutputBus); + { + ma_node_input_bus_detach__no_output_bus_lock(pInputBus, pOutputBus); + } + ma_node_output_bus_unlock(pOutputBus); +} +#endif + +static void ma_node_input_bus_attach(ma_node_input_bus* pInputBus, ma_node_output_bus* pOutputBus, ma_node* pNewInputNode, ma_uint32 inputNodeInputBusIndex) +{ + MA_ASSERT(pInputBus != NULL); + MA_ASSERT(pOutputBus != NULL); + + ma_node_output_bus_lock(pOutputBus); + { + ma_node_output_bus* pOldInputNode = (ma_node_output_bus*)ma_atomic_load_ptr(&pOutputBus->pInputNode); + + /* Detach from any existing attachment first if necessary. */ + if (pOldInputNode != NULL) { + ma_node_input_bus_detach__no_output_bus_lock(pInputBus, pOutputBus); + } + + /* + At this point we can be sure the output bus is not attached to anything. The linked list in the + old input bus has been updated so that pOutputBus will not get iterated again. + */ + pOutputBus->pInputNode = pNewInputNode; /* No need for an atomic assignment here because modification of this variable always happens within a lock. */ + pOutputBus->inputNodeInputBusIndex = (ma_uint8)inputNodeInputBusIndex; + + /* + Now we need to attach the output bus to the linked list. This involves updating two pointers on + two different output buses so I'm going to go ahead and keep this simple and just use a lock. + There are ways to do this without a lock, but it's just too hard to maintain for it's value. + + Although we're locking here, it's important to remember that we're *not* locking when iterating + and reading audio data since that'll be running on the audio thread. As a result we need to be + careful how we craft this so that we don't break iteration. What we're going to do is always + attach the new item so that it becomes the first item in the list. That way, as we're iterating + we won't break any links in the list and iteration will continue safely. The detaching case will + also be crafted in a way as to not break list iteration. It's important to remember to use + atomic exchanges here since no locking is happening on the audio thread during iteration. + */ + ma_node_input_bus_lock(pInputBus); + { + ma_node_output_bus* pNewPrev = &pInputBus->head; + ma_node_output_bus* pNewNext = (ma_node_output_bus*)ma_atomic_load_ptr(&pInputBus->head.pNext); + + /* Update the local output bus. */ + ma_atomic_exchange_ptr(&pOutputBus->pPrev, pNewPrev); + ma_atomic_exchange_ptr(&pOutputBus->pNext, pNewNext); + + /* Update the other output buses to point back to the local output bus. */ + ma_atomic_exchange_ptr(&pInputBus->head.pNext, pOutputBus); /* <-- This is where the output bus is actually attached to the input bus. */ + + /* Do the previous pointer last. This is only used for detachment. */ + if (pNewNext != NULL) { + ma_atomic_exchange_ptr(&pNewNext->pPrev, pOutputBus); + } + } + ma_node_input_bus_unlock(pInputBus); + + /* + Mark the node as attached last. This is used to controlling whether or the output bus will be + iterated on the audio thread. Mainly required for detachment purposes. + */ + ma_node_output_bus_set_is_attached(pOutputBus, MA_TRUE); + } + ma_node_output_bus_unlock(pOutputBus); +} + +static ma_node_output_bus* ma_node_input_bus_next(ma_node_input_bus* pInputBus, ma_node_output_bus* pOutputBus) +{ + ma_node_output_bus* pNext; + + MA_ASSERT(pInputBus != NULL); + + if (pOutputBus == NULL) { + return NULL; + } + + ma_node_input_bus_next_begin(pInputBus); + { + pNext = pOutputBus; + for (;;) { + pNext = (ma_node_output_bus*)ma_atomic_load_ptr(&pNext->pNext); + if (pNext == NULL) { + break; /* Reached the end. */ + } + + if (ma_node_output_bus_is_attached(pNext) == MA_FALSE) { + continue; /* The node is not attached. Keep checking. */ + } + + /* The next node has been selected. */ + break; + } + + /* We need to increment the reference count of the selected node. */ + if (pNext != NULL) { + ma_atomic_fetch_add_32(&pNext->refCount, 1); + } + + /* The previous node is no longer being referenced. */ + ma_atomic_fetch_sub_32(&pOutputBus->refCount, 1); + } + ma_node_input_bus_next_end(pInputBus); + + return pNext; +} + +static ma_node_output_bus* ma_node_input_bus_first(ma_node_input_bus* pInputBus) +{ + return ma_node_input_bus_next(pInputBus, &pInputBus->head); +} + + + +static ma_result ma_node_input_bus_read_pcm_frames(ma_node* pInputNode, ma_node_input_bus* pInputBus, float* pFramesOut, ma_uint32 frameCount, ma_uint32* pFramesRead, ma_uint64 globalTime) +{ + ma_result result = MA_SUCCESS; + ma_node_output_bus* pOutputBus; + ma_node_output_bus* pFirst; + ma_uint32 inputChannels; + ma_bool32 doesOutputBufferHaveContent = MA_FALSE; + + (void)pInputNode; /* Not currently used. */ + + /* + This will be called from the audio thread which means we can't be doing any locking. Basically, + this function will not perfom any locking, whereas attaching and detaching will, but crafted in + such a way that we don't need to perform any locking here. The important thing to remember is + to always iterate in a forward direction. + + In order to process any data we need to first read from all input buses. That's where this + function comes in. This iterates over each of the attachments and accumulates/mixes them. We + also convert the channels to the nodes output channel count before mixing. We want to do this + channel conversion so that the caller of this function can invoke the processing callback + without having to do it themselves. + + When we iterate over each of the attachments on the input bus, we need to read as much data as + we can from each of them so that we don't end up with holes between each of the attachments. To + do this, we need to read from each attachment in a loop and read as many frames as we can, up + to `frameCount`. + */ + MA_ASSERT(pInputNode != NULL); + MA_ASSERT(pFramesRead != NULL); /* pFramesRead is critical and must always be specified. On input it's undefined and on output it'll be set to the number of frames actually read. */ + + *pFramesRead = 0; /* Safety. */ + + inputChannels = ma_node_input_bus_get_channels(pInputBus); + + /* + We need to be careful with how we call ma_node_input_bus_first() and ma_node_input_bus_next(). They + are both critical to our lock-free thread-safety system. We can only call ma_node_input_bus_first() + once per iteration, however we have an optimization to checks whether or not it's the first item in + the list. We therefore need to store a pointer to the first item rather than repeatedly calling + ma_node_input_bus_first(). It's safe to keep hold of this pointer, so long as we don't dereference it + after calling ma_node_input_bus_next(), which we won't be. + */ + pFirst = ma_node_input_bus_first(pInputBus); + if (pFirst == NULL) { + return MA_SUCCESS; /* No attachments. Read nothing. */ + } + + for (pOutputBus = pFirst; pOutputBus != NULL; pOutputBus = ma_node_input_bus_next(pInputBus, pOutputBus)) { + ma_uint32 framesProcessed = 0; + ma_bool32 isSilentOutput = MA_FALSE; + + MA_ASSERT(pOutputBus->pNode != NULL); + MA_ASSERT(((ma_node_base*)pOutputBus->pNode)->vtable != NULL); + + isSilentOutput = (((ma_node_base*)pOutputBus->pNode)->vtable->flags & MA_NODE_FLAG_SILENT_OUTPUT) != 0; + + if (pFramesOut != NULL) { + /* Read. */ + float temp[MA_DATA_CONVERTER_STACK_BUFFER_SIZE / sizeof(float)]; + ma_uint32 tempCapInFrames = ma_countof(temp) / inputChannels; + + while (framesProcessed < frameCount) { + float* pRunningFramesOut; + ma_uint32 framesToRead; + ma_uint32 framesJustRead; + + framesToRead = frameCount - framesProcessed; + if (framesToRead > tempCapInFrames) { + framesToRead = tempCapInFrames; + } + + pRunningFramesOut = ma_offset_pcm_frames_ptr_f32(pFramesOut, framesProcessed, inputChannels); + + if (doesOutputBufferHaveContent == MA_FALSE) { + /* Fast path. First attachment. We just read straight into the output buffer (no mixing required). */ + result = ma_node_read_pcm_frames(pOutputBus->pNode, pOutputBus->outputBusIndex, pRunningFramesOut, framesToRead, &framesJustRead, globalTime + framesProcessed); + } else { + /* Slow path. Not the first attachment. Mixing required. */ + result = ma_node_read_pcm_frames(pOutputBus->pNode, pOutputBus->outputBusIndex, temp, framesToRead, &framesJustRead, globalTime + framesProcessed); + if (result == MA_SUCCESS || result == MA_AT_END) { + if (isSilentOutput == MA_FALSE) { /* Don't mix if the node outputs silence. */ + ma_mix_pcm_frames_f32(pRunningFramesOut, temp, framesJustRead, inputChannels, /*volume*/1); + } + } + } + + framesProcessed += framesJustRead; + + /* If we reached the end or otherwise failed to read any data we need to finish up with this output node. */ + if (result != MA_SUCCESS) { + break; + } + + /* If we didn't read anything, abort so we don't get stuck in a loop. */ + if (framesJustRead == 0) { + break; + } + } + + /* If it's the first attachment we didn't do any mixing. Any leftover samples need to be silenced. */ + if (pOutputBus == pFirst && framesProcessed < frameCount) { + ma_silence_pcm_frames(ma_offset_pcm_frames_ptr(pFramesOut, framesProcessed, ma_format_f32, inputChannels), (frameCount - framesProcessed), ma_format_f32, inputChannels); + } + + if (isSilentOutput == MA_FALSE) { + doesOutputBufferHaveContent = MA_TRUE; + } + } else { + /* Seek. */ + ma_node_read_pcm_frames(pOutputBus->pNode, pOutputBus->outputBusIndex, NULL, frameCount, &framesProcessed, globalTime); + } + } + + /* If we didn't output anything, output silence. */ + if (doesOutputBufferHaveContent == MA_FALSE && pFramesOut != NULL) { + ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, inputChannels); + } + + /* In this path we always "process" the entire amount. */ + *pFramesRead = frameCount; + + return result; +} + + +MA_API ma_node_config ma_node_config_init(void) +{ + ma_node_config config; + + MA_ZERO_OBJECT(&config); + config.initialState = ma_node_state_started; /* Nodes are started by default. */ + config.inputBusCount = MA_NODE_BUS_COUNT_UNKNOWN; + config.outputBusCount = MA_NODE_BUS_COUNT_UNKNOWN; + + return config; +} + + + +static ma_result ma_node_detach_full(ma_node* pNode); + +static float* ma_node_get_cached_input_ptr(ma_node* pNode, ma_uint32 inputBusIndex) +{ + ma_node_base* pNodeBase = (ma_node_base*)pNode; + ma_uint32 iInputBus; + float* pBasePtr; + + MA_ASSERT(pNodeBase != NULL); + + /* Input data is stored at the front of the buffer. */ + pBasePtr = pNodeBase->pCachedData; + for (iInputBus = 0; iInputBus < inputBusIndex; iInputBus += 1) { + pBasePtr += pNodeBase->cachedDataCapInFramesPerBus * ma_node_input_bus_get_channels(&pNodeBase->pInputBuses[iInputBus]); + } + + return pBasePtr; +} + +static float* ma_node_get_cached_output_ptr(ma_node* pNode, ma_uint32 outputBusIndex) +{ + ma_node_base* pNodeBase = (ma_node_base*)pNode; + ma_uint32 iInputBus; + ma_uint32 iOutputBus; + float* pBasePtr; + + MA_ASSERT(pNodeBase != NULL); + + /* Cached output data starts after the input data. */ + pBasePtr = pNodeBase->pCachedData; + for (iInputBus = 0; iInputBus < ma_node_get_input_bus_count(pNodeBase); iInputBus += 1) { + pBasePtr += pNodeBase->cachedDataCapInFramesPerBus * ma_node_input_bus_get_channels(&pNodeBase->pInputBuses[iInputBus]); + } + + for (iOutputBus = 0; iOutputBus < outputBusIndex; iOutputBus += 1) { + pBasePtr += pNodeBase->cachedDataCapInFramesPerBus * ma_node_output_bus_get_channels(&pNodeBase->pOutputBuses[iOutputBus]); + } + + return pBasePtr; +} + + +typedef struct +{ + size_t sizeInBytes; + size_t inputBusOffset; + size_t outputBusOffset; + size_t cachedDataOffset; + ma_uint32 inputBusCount; /* So it doesn't have to be calculated twice. */ + ma_uint32 outputBusCount; /* So it doesn't have to be calculated twice. */ +} ma_node_heap_layout; + +static ma_result ma_node_translate_bus_counts(const ma_node_config* pConfig, ma_uint32* pInputBusCount, ma_uint32* pOutputBusCount) +{ + ma_uint32 inputBusCount; + ma_uint32 outputBusCount; + + MA_ASSERT(pConfig != NULL); + MA_ASSERT(pInputBusCount != NULL); + MA_ASSERT(pOutputBusCount != NULL); + + /* Bus counts are determined by the vtable, unless they're set to `MA_NODE_BUS_COUNT_UNKNWON`, in which case they're taken from the config. */ + if (pConfig->vtable->inputBusCount == MA_NODE_BUS_COUNT_UNKNOWN) { + inputBusCount = pConfig->inputBusCount; + } else { + inputBusCount = pConfig->vtable->inputBusCount; + + if (pConfig->inputBusCount != MA_NODE_BUS_COUNT_UNKNOWN && pConfig->inputBusCount != pConfig->vtable->inputBusCount) { + return MA_INVALID_ARGS; /* Invalid configuration. You must not specify a conflicting bus count between the node's config and the vtable. */ + } + } + + if (pConfig->vtable->outputBusCount == MA_NODE_BUS_COUNT_UNKNOWN) { + outputBusCount = pConfig->outputBusCount; + } else { + outputBusCount = pConfig->vtable->outputBusCount; + + if (pConfig->outputBusCount != MA_NODE_BUS_COUNT_UNKNOWN && pConfig->outputBusCount != pConfig->vtable->outputBusCount) { + return MA_INVALID_ARGS; /* Invalid configuration. You must not specify a conflicting bus count between the node's config and the vtable. */ + } + } + + /* Bus counts must be within limits. */ + if (inputBusCount > MA_MAX_NODE_BUS_COUNT || outputBusCount > MA_MAX_NODE_BUS_COUNT) { + return MA_INVALID_ARGS; + } + + + /* We must have channel counts for each bus. */ + if ((inputBusCount > 0 && pConfig->pInputChannels == NULL) || (outputBusCount > 0 && pConfig->pOutputChannels == NULL)) { + return MA_INVALID_ARGS; /* You must specify channel counts for each input and output bus. */ + } + + + /* Some special rules for passthrough nodes. */ + if ((pConfig->vtable->flags & MA_NODE_FLAG_PASSTHROUGH) != 0) { + if ((pConfig->vtable->inputBusCount != 0 && pConfig->vtable->inputBusCount != 1) || pConfig->vtable->outputBusCount != 1) { + return MA_INVALID_ARGS; /* Passthrough nodes must have exactly 1 output bus and either 0 or 1 input bus. */ + } + + if (pConfig->pInputChannels[0] != pConfig->pOutputChannels[0]) { + return MA_INVALID_ARGS; /* Passthrough nodes must have the same number of channels between input and output nodes. */ + } + } + + + *pInputBusCount = inputBusCount; + *pOutputBusCount = outputBusCount; + + return MA_SUCCESS; +} + +static ma_result ma_node_get_heap_layout(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, ma_node_heap_layout* pHeapLayout) +{ + ma_result result; + ma_uint32 inputBusCount; + ma_uint32 outputBusCount; + + MA_ASSERT(pHeapLayout != NULL); + + MA_ZERO_OBJECT(pHeapLayout); + + if (pConfig == NULL || pConfig->vtable == NULL || pConfig->vtable->onProcess == NULL) { + return MA_INVALID_ARGS; + } + + result = ma_node_translate_bus_counts(pConfig, &inputBusCount, &outputBusCount); + if (result != MA_SUCCESS) { + return result; + } + + pHeapLayout->sizeInBytes = 0; + + /* Input buses. */ + if (inputBusCount > MA_MAX_NODE_LOCAL_BUS_COUNT) { + pHeapLayout->inputBusOffset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += ma_align_64(sizeof(ma_node_input_bus) * inputBusCount); + } else { + pHeapLayout->inputBusOffset = MA_SIZE_MAX; /* MA_SIZE_MAX indicates that no heap allocation is required for the input bus. */ + } + + /* Output buses. */ + if (outputBusCount > MA_MAX_NODE_LOCAL_BUS_COUNT) { + pHeapLayout->outputBusOffset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += ma_align_64(sizeof(ma_node_output_bus) * outputBusCount); + } else { + pHeapLayout->outputBusOffset = MA_SIZE_MAX; + } + + /* + Cached audio data. + + We need to allocate memory for a caching both input and output data. We have an optimization + where no caching is necessary for specific conditions: + + - The node has 0 inputs and 1 output. + + When a node meets the above conditions, no cache is allocated. + + The size choice for this buffer is a little bit finicky. We don't want to be too wasteful by + allocating too much, but at the same time we want it be large enough so that enough frames can + be processed for each call to ma_node_read_pcm_frames() so that it keeps things efficient. For + now I'm going with 10ms @ 48K which is 480 frames per bus. This is configurable at compile + time. It might also be worth investigating whether or not this can be configured at run time. + */ + if (inputBusCount == 0 && outputBusCount == 1) { + /* Fast path. No cache needed. */ + pHeapLayout->cachedDataOffset = MA_SIZE_MAX; + } else { + /* Slow path. Cache needed. */ + size_t cachedDataSizeInBytes = 0; + ma_uint32 iBus; + + for (iBus = 0; iBus < inputBusCount; iBus += 1) { + cachedDataSizeInBytes += pNodeGraph->nodeCacheCapInFrames * ma_get_bytes_per_frame(ma_format_f32, pConfig->pInputChannels[iBus]); + } + + for (iBus = 0; iBus < outputBusCount; iBus += 1) { + cachedDataSizeInBytes += pNodeGraph->nodeCacheCapInFrames * ma_get_bytes_per_frame(ma_format_f32, pConfig->pOutputChannels[iBus]); + } + + pHeapLayout->cachedDataOffset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += ma_align_64(cachedDataSizeInBytes); + } + + + /* + Not technically part of the heap, but we can output the input and output bus counts so we can + avoid a redundant call to ma_node_translate_bus_counts(). + */ + pHeapLayout->inputBusCount = inputBusCount; + pHeapLayout->outputBusCount = outputBusCount; + + /* Make sure allocation size is aligned. */ + pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes); + + return MA_SUCCESS; +} + +MA_API ma_result ma_node_get_heap_size(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_result result; + ma_node_heap_layout heapLayout; + + if (pHeapSizeInBytes == NULL) { + return MA_INVALID_ARGS; + } + + *pHeapSizeInBytes = 0; + + result = ma_node_get_heap_layout(pNodeGraph, pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + *pHeapSizeInBytes = heapLayout.sizeInBytes; + + return MA_SUCCESS; +} + +MA_API ma_result ma_node_init_preallocated(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, void* pHeap, ma_node* pNode) +{ + ma_node_base* pNodeBase = (ma_node_base*)pNode; + ma_result result; + ma_node_heap_layout heapLayout; + ma_uint32 iInputBus; + ma_uint32 iOutputBus; + + if (pNodeBase == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pNodeBase); + + result = ma_node_get_heap_layout(pNodeGraph, pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + pNodeBase->_pHeap = pHeap; + MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes); + + pNodeBase->pNodeGraph = pNodeGraph; + pNodeBase->vtable = pConfig->vtable; + pNodeBase->state = pConfig->initialState; + pNodeBase->stateTimes[ma_node_state_started] = 0; + pNodeBase->stateTimes[ma_node_state_stopped] = (ma_uint64)(ma_int64)-1; /* Weird casting for VC6 compatibility. */ + pNodeBase->inputBusCount = heapLayout.inputBusCount; + pNodeBase->outputBusCount = heapLayout.outputBusCount; + + if (heapLayout.inputBusOffset != MA_SIZE_MAX) { + pNodeBase->pInputBuses = (ma_node_input_bus*)ma_offset_ptr(pHeap, heapLayout.inputBusOffset); + } else { + pNodeBase->pInputBuses = pNodeBase->_inputBuses; + } + + if (heapLayout.outputBusOffset != MA_SIZE_MAX) { + pNodeBase->pOutputBuses = (ma_node_output_bus*)ma_offset_ptr(pHeap, heapLayout.outputBusOffset); + } else { + pNodeBase->pOutputBuses = pNodeBase->_outputBuses; + } + + if (heapLayout.cachedDataOffset != MA_SIZE_MAX) { + pNodeBase->pCachedData = (float*)ma_offset_ptr(pHeap, heapLayout.cachedDataOffset); + pNodeBase->cachedDataCapInFramesPerBus = pNodeGraph->nodeCacheCapInFrames; + } else { + pNodeBase->pCachedData = NULL; + } + + + + /* We need to run an initialization step for each input and output bus. */ + for (iInputBus = 0; iInputBus < ma_node_get_input_bus_count(pNodeBase); iInputBus += 1) { + result = ma_node_input_bus_init(pConfig->pInputChannels[iInputBus], &pNodeBase->pInputBuses[iInputBus]); + if (result != MA_SUCCESS) { + return result; + } + } + + for (iOutputBus = 0; iOutputBus < ma_node_get_output_bus_count(pNodeBase); iOutputBus += 1) { + result = ma_node_output_bus_init(pNodeBase, iOutputBus, pConfig->pOutputChannels[iOutputBus], &pNodeBase->pOutputBuses[iOutputBus]); + if (result != MA_SUCCESS) { + return result; + } + } + + + /* The cached data needs to be initialized to silence (or a sine wave tone if we're debugging). */ + if (pNodeBase->pCachedData != NULL) { + ma_uint32 iBus; + + #if 1 /* Toggle this between 0 and 1 to turn debugging on or off. 1 = fill with a sine wave for debugging; 0 = fill with silence. */ + /* For safety we'll go ahead and default the buffer to silence. */ + for (iBus = 0; iBus < ma_node_get_input_bus_count(pNodeBase); iBus += 1) { + ma_silence_pcm_frames(ma_node_get_cached_input_ptr(pNode, iBus), pNodeBase->cachedDataCapInFramesPerBus, ma_format_f32, ma_node_input_bus_get_channels(&pNodeBase->pInputBuses[iBus])); + } + for (iBus = 0; iBus < ma_node_get_output_bus_count(pNodeBase); iBus += 1) { + ma_silence_pcm_frames(ma_node_get_cached_output_ptr(pNode, iBus), pNodeBase->cachedDataCapInFramesPerBus, ma_format_f32, ma_node_output_bus_get_channels(&pNodeBase->pOutputBuses[iBus])); + } + #else + /* For debugging. Default to a sine wave. */ + for (iBus = 0; iBus < ma_node_get_input_bus_count(pNodeBase); iBus += 1) { + ma_debug_fill_pcm_frames_with_sine_wave(ma_node_get_cached_input_ptr(pNode, iBus), pNodeBase->cachedDataCapInFramesPerBus, ma_format_f32, ma_node_input_bus_get_channels(&pNodeBase->pInputBuses[iBus]), 48000); + } + for (iBus = 0; iBus < ma_node_get_output_bus_count(pNodeBase); iBus += 1) { + ma_debug_fill_pcm_frames_with_sine_wave(ma_node_get_cached_output_ptr(pNode, iBus), pNodeBase->cachedDataCapInFramesPerBus, ma_format_f32, ma_node_output_bus_get_channels(&pNodeBase->pOutputBuses[iBus]), 48000); + } + #endif + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_node_init(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_node* pNode) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_node_get_heap_size(pNodeGraph, pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_node_init_preallocated(pNodeGraph, pConfig, pHeap, pNode); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + ((ma_node_base*)pNode)->_ownsHeap = MA_TRUE; + return MA_SUCCESS; +} + +MA_API void ma_node_uninit(ma_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_node_base* pNodeBase = (ma_node_base*)pNode; + + if (pNodeBase == NULL) { + return; + } + + /* + The first thing we need to do is fully detach the node. This will detach all inputs and + outputs. We need to do this first because it will sever the connection with the node graph and + allow us to complete uninitialization without needing to worry about thread-safety with the + audio thread. The detachment process will wait for any local processing of the node to finish. + */ + ma_node_detach_full(pNode); + + /* + At this point the node should be completely unreferenced by the node graph and we can finish up + the uninitialization process without needing to worry about thread-safety. + */ + if (pNodeBase->_ownsHeap) { + ma_free(pNodeBase->_pHeap, pAllocationCallbacks); + } +} + +MA_API ma_node_graph* ma_node_get_node_graph(const ma_node* pNode) +{ + if (pNode == NULL) { + return NULL; + } + + return ((const ma_node_base*)pNode)->pNodeGraph; +} + +MA_API ma_uint32 ma_node_get_input_bus_count(const ma_node* pNode) +{ + if (pNode == NULL) { + return 0; + } + + return ((ma_node_base*)pNode)->inputBusCount; +} + +MA_API ma_uint32 ma_node_get_output_bus_count(const ma_node* pNode) +{ + if (pNode == NULL) { + return 0; + } + + return ((ma_node_base*)pNode)->outputBusCount; +} + + +MA_API ma_uint32 ma_node_get_input_channels(const ma_node* pNode, ma_uint32 inputBusIndex) +{ + const ma_node_base* pNodeBase = (const ma_node_base*)pNode; + + if (pNode == NULL) { + return 0; + } + + if (inputBusIndex >= ma_node_get_input_bus_count(pNode)) { + return 0; /* Invalid bus index. */ + } + + return ma_node_input_bus_get_channels(&pNodeBase->pInputBuses[inputBusIndex]); +} + +MA_API ma_uint32 ma_node_get_output_channels(const ma_node* pNode, ma_uint32 outputBusIndex) +{ + const ma_node_base* pNodeBase = (const ma_node_base*)pNode; + + if (pNode == NULL) { + return 0; + } + + if (outputBusIndex >= ma_node_get_output_bus_count(pNode)) { + return 0; /* Invalid bus index. */ + } + + return ma_node_output_bus_get_channels(&pNodeBase->pOutputBuses[outputBusIndex]); +} + + +static ma_result ma_node_detach_full(ma_node* pNode) +{ + ma_node_base* pNodeBase = (ma_node_base*)pNode; + ma_uint32 iInputBus; + + if (pNodeBase == NULL) { + return MA_INVALID_ARGS; + } + + /* + Make sure the node is completely detached first. This will not return until the output bus is + guaranteed to no longer be referenced by the audio thread. + */ + ma_node_detach_all_output_buses(pNode); + + /* + At this point all output buses will have been detached from the graph and we can be guaranteed + that none of it's input nodes will be getting processed by the graph. We can detach these + without needing to worry about the audio thread touching them. + */ + for (iInputBus = 0; iInputBus < ma_node_get_input_bus_count(pNode); iInputBus += 1) { + ma_node_input_bus* pInputBus; + ma_node_output_bus* pOutputBus; + + pInputBus = &pNodeBase->pInputBuses[iInputBus]; + + /* + This is important. We cannot be using ma_node_input_bus_first() or ma_node_input_bus_next(). Those + functions are specifically for the audio thread. We'll instead just manually iterate using standard + linked list logic. We don't need to worry about the audio thread referencing these because the step + above severed the connection to the graph. + */ + for (pOutputBus = (ma_node_output_bus*)ma_atomic_load_ptr(&pInputBus->head.pNext); pOutputBus != NULL; pOutputBus = (ma_node_output_bus*)ma_atomic_load_ptr(&pOutputBus->pNext)) { + ma_node_detach_output_bus(pOutputBus->pNode, pOutputBus->outputBusIndex); /* This won't do any waiting in practice and should be efficient. */ + } + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_node_detach_output_bus(ma_node* pNode, ma_uint32 outputBusIndex) +{ + ma_result result = MA_SUCCESS; + ma_node_base* pNodeBase = (ma_node_base*)pNode; + ma_node_base* pInputNodeBase; + + if (pNode == NULL) { + return MA_INVALID_ARGS; + } + + if (outputBusIndex >= ma_node_get_output_bus_count(pNode)) { + return MA_INVALID_ARGS; /* Invalid output bus index. */ + } + + /* We need to lock the output bus because we need to inspect the input node and grab it's input bus. */ + ma_node_output_bus_lock(&pNodeBase->pOutputBuses[outputBusIndex]); + { + pInputNodeBase = (ma_node_base*)pNodeBase->pOutputBuses[outputBusIndex].pInputNode; + if (pInputNodeBase != NULL) { + ma_node_input_bus_detach__no_output_bus_lock(&pInputNodeBase->pInputBuses[pNodeBase->pOutputBuses[outputBusIndex].inputNodeInputBusIndex], &pNodeBase->pOutputBuses[outputBusIndex]); + } + } + ma_node_output_bus_unlock(&pNodeBase->pOutputBuses[outputBusIndex]); + + return result; +} + +MA_API ma_result ma_node_detach_all_output_buses(ma_node* pNode) +{ + ma_uint32 iOutputBus; + + if (pNode == NULL) { + return MA_INVALID_ARGS; + } + + for (iOutputBus = 0; iOutputBus < ma_node_get_output_bus_count(pNode); iOutputBus += 1) { + ma_node_detach_output_bus(pNode, iOutputBus); + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_node_attach_output_bus(ma_node* pNode, ma_uint32 outputBusIndex, ma_node* pOtherNode, ma_uint32 otherNodeInputBusIndex) +{ + ma_node_base* pNodeBase = (ma_node_base*)pNode; + ma_node_base* pOtherNodeBase = (ma_node_base*)pOtherNode; + + if (pNodeBase == NULL || pOtherNodeBase == NULL) { + return MA_INVALID_ARGS; + } + + if (pNodeBase == pOtherNodeBase) { + return MA_INVALID_OPERATION; /* Cannot attach a node to itself. */ + } + + if (outputBusIndex >= ma_node_get_output_bus_count(pNode) || otherNodeInputBusIndex >= ma_node_get_input_bus_count(pOtherNode)) { + return MA_INVALID_OPERATION; /* Invalid bus index. */ + } + + /* The output channel count of the output node must be the same as the input channel count of the input node. */ + if (ma_node_get_output_channels(pNode, outputBusIndex) != ma_node_get_input_channels(pOtherNode, otherNodeInputBusIndex)) { + return MA_INVALID_OPERATION; /* Channel count is incompatible. */ + } + + /* This will deal with detaching if the output bus is already attached to something. */ + ma_node_input_bus_attach(&pOtherNodeBase->pInputBuses[otherNodeInputBusIndex], &pNodeBase->pOutputBuses[outputBusIndex], pOtherNode, otherNodeInputBusIndex); + + return MA_SUCCESS; +} + +MA_API ma_result ma_node_set_output_bus_volume(ma_node* pNode, ma_uint32 outputBusIndex, float volume) +{ + ma_node_base* pNodeBase = (ma_node_base*)pNode; + + if (pNodeBase == NULL) { + return MA_INVALID_ARGS; + } + + if (outputBusIndex >= ma_node_get_output_bus_count(pNode)) { + return MA_INVALID_ARGS; /* Invalid bus index. */ + } + + return ma_node_output_bus_set_volume(&pNodeBase->pOutputBuses[outputBusIndex], volume); +} + +MA_API float ma_node_get_output_bus_volume(const ma_node* pNode, ma_uint32 outputBusIndex) +{ + const ma_node_base* pNodeBase = (const ma_node_base*)pNode; + + if (pNodeBase == NULL) { + return 0; + } + + if (outputBusIndex >= ma_node_get_output_bus_count(pNode)) { + return 0; /* Invalid bus index. */ + } + + return ma_node_output_bus_get_volume(&pNodeBase->pOutputBuses[outputBusIndex]); +} + +MA_API ma_result ma_node_set_state(ma_node* pNode, ma_node_state state) +{ + ma_node_base* pNodeBase = (ma_node_base*)pNode; + + if (pNodeBase == NULL) { + return MA_INVALID_ARGS; + } + + ma_atomic_exchange_i32(&pNodeBase->state, state); + + return MA_SUCCESS; +} + +MA_API ma_node_state ma_node_get_state(const ma_node* pNode) +{ + const ma_node_base* pNodeBase = (const ma_node_base*)pNode; + + if (pNodeBase == NULL) { + return ma_node_state_stopped; + } + + return (ma_node_state)ma_atomic_load_i32(&pNodeBase->state); +} + +MA_API ma_result ma_node_set_state_time(ma_node* pNode, ma_node_state state, ma_uint64 globalTime) +{ + if (pNode == NULL) { + return MA_INVALID_ARGS; + } + + /* Validation check for safety since we'll be using this as an index into stateTimes[]. */ + if (state != ma_node_state_started && state != ma_node_state_stopped) { + return MA_INVALID_ARGS; + } + + ma_atomic_exchange_64(&((ma_node_base*)pNode)->stateTimes[state], globalTime); + + return MA_SUCCESS; +} + +MA_API ma_uint64 ma_node_get_state_time(const ma_node* pNode, ma_node_state state) +{ + if (pNode == NULL) { + return 0; + } + + /* Validation check for safety since we'll be using this as an index into stateTimes[]. */ + if (state != ma_node_state_started && state != ma_node_state_stopped) { + return 0; + } + + return ma_atomic_load_64(&((ma_node_base*)pNode)->stateTimes[state]); +} + +MA_API ma_node_state ma_node_get_state_by_time(const ma_node* pNode, ma_uint64 globalTime) +{ + if (pNode == NULL) { + return ma_node_state_stopped; + } + + return ma_node_get_state_by_time_range(pNode, globalTime, globalTime); +} + +MA_API ma_node_state ma_node_get_state_by_time_range(const ma_node* pNode, ma_uint64 globalTimeBeg, ma_uint64 globalTimeEnd) +{ + ma_node_state state; + + if (pNode == NULL) { + return ma_node_state_stopped; + } + + state = ma_node_get_state(pNode); + + /* An explicitly stopped node is always stopped. */ + if (state == ma_node_state_stopped) { + return ma_node_state_stopped; + } + + /* + Getting here means the node is marked as started, but it may still not be truly started due to + it's start time not having been reached yet. Also, the stop time may have also been reached in + which case it'll be considered stopped. + */ + if (ma_node_get_state_time(pNode, ma_node_state_started) > globalTimeBeg) { + return ma_node_state_stopped; /* Start time has not yet been reached. */ + } + + if (ma_node_get_state_time(pNode, ma_node_state_stopped) <= globalTimeEnd) { + return ma_node_state_stopped; /* Stop time has been reached. */ + } + + /* Getting here means the node is marked as started and is within it's start/stop times. */ + return ma_node_state_started; +} + +MA_API ma_uint64 ma_node_get_time(const ma_node* pNode) +{ + if (pNode == NULL) { + return 0; + } + + return ma_atomic_load_64(&((ma_node_base*)pNode)->localTime); +} + +MA_API ma_result ma_node_set_time(ma_node* pNode, ma_uint64 localTime) +{ + if (pNode == NULL) { + return MA_INVALID_ARGS; + } + + ma_atomic_exchange_64(&((ma_node_base*)pNode)->localTime, localTime); + + return MA_SUCCESS; +} + + + +static void ma_node_process_pcm_frames_internal(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut) +{ + ma_node_base* pNodeBase = (ma_node_base*)pNode; + + MA_ASSERT(pNode != NULL); + + if (pNodeBase->vtable->onProcess) { + pNodeBase->vtable->onProcess(pNode, ppFramesIn, pFrameCountIn, ppFramesOut, pFrameCountOut); + } +} + +static ma_result ma_node_read_pcm_frames(ma_node* pNode, ma_uint32 outputBusIndex, float* pFramesOut, ma_uint32 frameCount, ma_uint32* pFramesRead, ma_uint64 globalTime) +{ + ma_node_base* pNodeBase = (ma_node_base*)pNode; + ma_result result = MA_SUCCESS; + ma_uint32 iInputBus; + ma_uint32 iOutputBus; + ma_uint32 inputBusCount; + ma_uint32 outputBusCount; + ma_uint32 totalFramesRead = 0; + float* ppFramesIn[MA_MAX_NODE_BUS_COUNT]; + float* ppFramesOut[MA_MAX_NODE_BUS_COUNT]; + ma_uint64 globalTimeBeg; + ma_uint64 globalTimeEnd; + ma_uint64 startTime; + ma_uint64 stopTime; + ma_uint32 timeOffsetBeg; + ma_uint32 timeOffsetEnd; + ma_uint32 frameCountIn; + ma_uint32 frameCountOut; + + /* + pFramesRead is mandatory. It must be used to determine how many frames were read. It's normal and + expected that the number of frames read may be different to that requested. Therefore, the caller + must look at this value to correctly determine how many frames were read. + */ + MA_ASSERT(pFramesRead != NULL); /* <-- If you've triggered this assert, you're using this function wrong. You *must* use this variable and inspect it after the call returns. */ + if (pFramesRead == NULL) { + return MA_INVALID_ARGS; + } + + *pFramesRead = 0; /* Safety. */ + + if (pNodeBase == NULL) { + return MA_INVALID_ARGS; + } + + if (outputBusIndex >= ma_node_get_output_bus_count(pNodeBase)) { + return MA_INVALID_ARGS; /* Invalid output bus index. */ + } + + /* Don't do anything if we're in a stopped state. */ + if (ma_node_get_state_by_time_range(pNode, globalTime, globalTime + frameCount) != ma_node_state_started) { + return MA_SUCCESS; /* We're in a stopped state. This is not an error - we just need to not read anything. */ + } + + + globalTimeBeg = globalTime; + globalTimeEnd = globalTime + frameCount; + startTime = ma_node_get_state_time(pNode, ma_node_state_started); + stopTime = ma_node_get_state_time(pNode, ma_node_state_stopped); + + /* + At this point we know that we are inside our start/stop times. However, we may need to adjust + our frame count and output pointer to accommodate since we could be straddling the time period + that this function is getting called for. + + It's possible (and likely) that the start time does not line up with the output buffer. We + therefore need to offset it by a number of frames to accommodate. The same thing applies for + the stop time. + */ + timeOffsetBeg = (globalTimeBeg < startTime) ? (ma_uint32)(globalTimeEnd - startTime) : 0; + timeOffsetEnd = (globalTimeEnd > stopTime) ? (ma_uint32)(globalTimeEnd - stopTime) : 0; + + /* Trim based on the start offset. We need to silence the start of the buffer. */ + if (timeOffsetBeg > 0) { + ma_silence_pcm_frames(pFramesOut, timeOffsetBeg, ma_format_f32, ma_node_get_output_channels(pNode, outputBusIndex)); + pFramesOut += timeOffsetBeg * ma_node_get_output_channels(pNode, outputBusIndex); + frameCount -= timeOffsetBeg; + } + + /* Trim based on the end offset. We don't need to silence the tail section because we'll just have a reduced value written to pFramesRead. */ + if (timeOffsetEnd > 0) { + frameCount -= timeOffsetEnd; + } + + + /* We run on different paths depending on the bus counts. */ + inputBusCount = ma_node_get_input_bus_count(pNode); + outputBusCount = ma_node_get_output_bus_count(pNode); + + /* + Run a simplified path when there are no inputs and one output. In this case there's nothing to + actually read and we can go straight to output. This is a very common scenario because the vast + majority of data source nodes will use this setup so this optimization I think is worthwhile. + */ + if (inputBusCount == 0 && outputBusCount == 1) { + /* Fast path. No need to read from input and no need for any caching. */ + frameCountIn = 0; + frameCountOut = frameCount; /* Just read as much as we can. The callback will return what was actually read. */ + + ppFramesOut[0] = pFramesOut; + + /* + If it's a passthrough we won't be expecting the callback to output anything, so we'll + need to pre-silence the output buffer. + */ + if ((pNodeBase->vtable->flags & MA_NODE_FLAG_PASSTHROUGH) != 0) { + ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, ma_node_get_output_channels(pNode, outputBusIndex)); + } + + ma_node_process_pcm_frames_internal(pNode, NULL, &frameCountIn, ppFramesOut, &frameCountOut); + totalFramesRead = frameCountOut; + } else { + /* Slow path. Need to read input data. */ + if ((pNodeBase->vtable->flags & MA_NODE_FLAG_PASSTHROUGH) != 0) { + /* + Fast path. We're running a passthrough. We need to read directly into the output buffer, but + still fire the callback so that event handling and trigger nodes can do their thing. Since + it's a passthrough there's no need for any kind of caching logic. + */ + MA_ASSERT(outputBusCount == inputBusCount); + MA_ASSERT(outputBusCount == 1); + MA_ASSERT(outputBusIndex == 0); + + /* We just read directly from input bus to output buffer, and then afterwards fire the callback. */ + ppFramesOut[0] = pFramesOut; + ppFramesIn[0] = ppFramesOut[0]; + + result = ma_node_input_bus_read_pcm_frames(pNodeBase, &pNodeBase->pInputBuses[0], ppFramesIn[0], frameCount, &totalFramesRead, globalTime); + if (result == MA_SUCCESS) { + /* Even though it's a passthrough, we still need to fire the callback. */ + frameCountIn = totalFramesRead; + frameCountOut = totalFramesRead; + + if (totalFramesRead > 0) { + ma_node_process_pcm_frames_internal(pNode, (const float**)ppFramesIn, &frameCountIn, ppFramesOut, &frameCountOut); /* From GCC: expected 'const float **' but argument is of type 'float **'. Shouldn't this be implicit? Excplicit cast to silence the warning. */ + } + + /* + A passthrough should never have modified the input and output frame counts. If you're + triggering these assers you need to fix your processing callback. + */ + MA_ASSERT(frameCountIn == totalFramesRead); + MA_ASSERT(frameCountOut == totalFramesRead); + } + } else { + /* Slow path. Need to do caching. */ + ma_uint32 framesToProcessIn; + ma_uint32 framesToProcessOut; + ma_bool32 consumeNullInput = MA_FALSE; + + /* + We use frameCount as a basis for the number of frames to read since that's what's being + requested, however we still need to clamp it to whatever can fit in the cache. + + This will also be used as the basis for determining how many input frames to read. This is + not ideal because it can result in too many input frames being read which introduces latency. + To solve this, nodes can implement an optional callback called onGetRequiredInputFrameCount + which is used as hint to miniaudio as to how many input frames it needs to read at a time. This + callback is completely optional, and if it's not set, miniaudio will assume `frameCount`. + + This function will be called multiple times for each period of time, once for each output node. + We cannot read from each input node each time this function is called. Instead we need to check + whether or not this is first output bus to be read from for this time period, and if so, read + from our input data. + + To determine whether or not we're ready to read data, we check a flag. There will be one flag + for each output. When the flag is set, it means data has been read previously and that we're + ready to advance time forward for our input nodes by reading fresh data. + */ + framesToProcessOut = frameCount; + if (framesToProcessOut > pNodeBase->cachedDataCapInFramesPerBus) { + framesToProcessOut = pNodeBase->cachedDataCapInFramesPerBus; + } + + framesToProcessIn = frameCount; + if (pNodeBase->vtable->onGetRequiredInputFrameCount) { + pNodeBase->vtable->onGetRequiredInputFrameCount(pNode, framesToProcessOut, &framesToProcessIn); /* <-- It does not matter if this fails. */ + } + if (framesToProcessIn > pNodeBase->cachedDataCapInFramesPerBus) { + framesToProcessIn = pNodeBase->cachedDataCapInFramesPerBus; + } + + + MA_ASSERT(framesToProcessIn <= 0xFFFF); + MA_ASSERT(framesToProcessOut <= 0xFFFF); + + if (ma_node_output_bus_has_read(&pNodeBase->pOutputBuses[outputBusIndex])) { + /* Getting here means we need to do another round of processing. */ + pNodeBase->cachedFrameCountOut = 0; + + for (;;) { + frameCountOut = 0; + + /* + We need to prepare our output frame pointers for processing. In the same iteration we need + to mark every output bus as unread so that future calls to this function for different buses + for the current time period don't pull in data when they should instead be reading from cache. + */ + for (iOutputBus = 0; iOutputBus < outputBusCount; iOutputBus += 1) { + ma_node_output_bus_set_has_read(&pNodeBase->pOutputBuses[iOutputBus], MA_FALSE); /* <-- This is what tells the next calls to this function for other output buses for this time period to read from cache instead of pulling in more data. */ + ppFramesOut[iOutputBus] = ma_node_get_cached_output_ptr(pNode, iOutputBus); + } + + /* We only need to read from input buses if there isn't already some data in the cache. */ + if (pNodeBase->cachedFrameCountIn == 0) { + ma_uint32 maxFramesReadIn = 0; + + /* Here is where we pull in data from the input buses. This is what will trigger an advance in time. */ + for (iInputBus = 0; iInputBus < inputBusCount; iInputBus += 1) { + ma_uint32 framesRead; + + /* The first thing to do is get the offset within our bulk allocation to store this input data. */ + ppFramesIn[iInputBus] = ma_node_get_cached_input_ptr(pNode, iInputBus); + + /* Once we've determined our destination pointer we can read. Note that we must inspect the number of frames read and fill any leftovers with silence for safety. */ + result = ma_node_input_bus_read_pcm_frames(pNodeBase, &pNodeBase->pInputBuses[iInputBus], ppFramesIn[iInputBus], framesToProcessIn, &framesRead, globalTime); + if (result != MA_SUCCESS) { + /* It doesn't really matter if we fail because we'll just fill with silence. */ + framesRead = 0; /* Just for safety, but I don't think it's really needed. */ + } + + /* TODO: Minor optimization opportunity here. If no frames were read and the buffer is already filled with silence, no need to re-silence it. */ + /* Any leftover frames need to silenced for safety. */ + if (framesRead < framesToProcessIn) { + ma_silence_pcm_frames(ppFramesIn[iInputBus] + (framesRead * ma_node_get_input_channels(pNodeBase, iInputBus)), (framesToProcessIn - framesRead), ma_format_f32, ma_node_get_input_channels(pNodeBase, iInputBus)); + } + + maxFramesReadIn = ma_max(maxFramesReadIn, framesRead); + } + + /* This was a fresh load of input data so reset our consumption counter. */ + pNodeBase->consumedFrameCountIn = 0; + + /* + We don't want to keep processing if there's nothing to process, so set the number of cached + input frames to the maximum number we read from each attachment (the lesser will be padded + with silence). If we didn't read anything, this will be set to 0 and the entire buffer will + have been assigned to silence. This being equal to 0 is an important property for us because + it allows us to detect when NULL can be passed into the processing callback for the input + buffer for the purpose of continuous processing. + */ + pNodeBase->cachedFrameCountIn = (ma_uint16)maxFramesReadIn; + } else { + /* We don't need to read anything, but we do need to prepare our input frame pointers. */ + for (iInputBus = 0; iInputBus < inputBusCount; iInputBus += 1) { + ppFramesIn[iInputBus] = ma_node_get_cached_input_ptr(pNode, iInputBus) + (pNodeBase->consumedFrameCountIn * ma_node_get_input_channels(pNodeBase, iInputBus)); + } + } + + /* + At this point we have our input data so now we need to do some processing. Sneaky little + optimization here - we can set the pointer to the output buffer for this output bus so + that the final copy into the output buffer is done directly by onProcess(). + */ + if (pFramesOut != NULL) { + ppFramesOut[outputBusIndex] = ma_offset_pcm_frames_ptr_f32(pFramesOut, pNodeBase->cachedFrameCountOut, ma_node_get_output_channels(pNode, outputBusIndex)); + } + + + /* Give the processing function the entire capacity of the output buffer. */ + frameCountOut = (framesToProcessOut - pNodeBase->cachedFrameCountOut); + + /* + We need to treat nodes with continuous processing a little differently. For these ones, + we always want to fire the callback with the requested number of frames, regardless of + pNodeBase->cachedFrameCountIn, which could be 0. Also, we want to check if we can pass + in NULL for the input buffer to the callback. + */ + if ((pNodeBase->vtable->flags & MA_NODE_FLAG_CONTINUOUS_PROCESSING) != 0) { + /* We're using continuous processing. Make sure we specify the whole frame count at all times. */ + frameCountIn = framesToProcessIn; /* Give the processing function as much input data as we've got in the buffer, including any silenced padding from short reads. */ + + if ((pNodeBase->vtable->flags & MA_NODE_FLAG_ALLOW_NULL_INPUT) != 0 && pNodeBase->consumedFrameCountIn == 0 && pNodeBase->cachedFrameCountIn == 0) { + consumeNullInput = MA_TRUE; + } else { + consumeNullInput = MA_FALSE; + } + + /* + Since we're using continuous processing we're always passing in a full frame count + regardless of how much input data was read. If this is greater than what we read as + input, we'll end up with an underflow. We instead need to make sure our cached frame + count is set to the number of frames we'll be passing to the data callback. Not + doing this will result in an underflow when we "consume" the cached data later on. + + Note that this check needs to be done after the "consumeNullInput" check above because + we use the property of cachedFrameCountIn being 0 to determine whether or not we + should be passing in a null pointer to the processing callback for when the node is + configured with MA_NODE_FLAG_ALLOW_NULL_INPUT. + */ + if (pNodeBase->cachedFrameCountIn < (ma_uint16)frameCountIn) { + pNodeBase->cachedFrameCountIn = (ma_uint16)frameCountIn; + } + } else { + frameCountIn = pNodeBase->cachedFrameCountIn; /* Give the processing function as much valid input data as we've got. */ + consumeNullInput = MA_FALSE; + } + + /* + Process data slightly differently depending on whether or not we're consuming NULL + input (checked just above). + */ + if (consumeNullInput) { + ma_node_process_pcm_frames_internal(pNode, NULL, &frameCountIn, ppFramesOut, &frameCountOut); + } else { + /* + We want to skip processing if there's no input data, but we can only do that safely if + we know that there is no chance of any output frames being produced. If continuous + processing is being used, this won't be a problem because the input frame count will + always be non-0. However, if continuous processing is *not* enabled and input and output + data is processed at different rates, we still need to process that last input frame + because there could be a few excess output frames needing to be produced from cached + data. The `MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES` flag is used as the indicator for + determining whether or not we need to process the node even when there are no input + frames available right now. + */ + if (frameCountIn > 0 || (pNodeBase->vtable->flags & MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES) != 0) { + ma_node_process_pcm_frames_internal(pNode, (const float**)ppFramesIn, &frameCountIn, ppFramesOut, &frameCountOut); /* From GCC: expected 'const float **' but argument is of type 'float **'. Shouldn't this be implicit? Excplicit cast to silence the warning. */ + } else { + frameCountOut = 0; /* No data was processed. */ + } + } + + /* + Thanks to our sneaky optimization above we don't need to do any data copying directly into + the output buffer - the onProcess() callback just did that for us. We do, however, need to + apply the number of input and output frames that were processed. Note that due to continuous + processing above, we need to do explicit checks here. If we just consumed a NULL input + buffer it means that no actual input data was processed from the internal buffers and we + don't want to be modifying any counters. + */ + if (consumeNullInput == MA_FALSE) { + pNodeBase->consumedFrameCountIn += (ma_uint16)frameCountIn; + pNodeBase->cachedFrameCountIn -= (ma_uint16)frameCountIn; + } + + /* The cached output frame count is always equal to what we just read. */ + pNodeBase->cachedFrameCountOut += (ma_uint16)frameCountOut; + + /* If we couldn't process any data, we're done. The loop needs to be terminated here or else we'll get stuck in a loop. */ + if (pNodeBase->cachedFrameCountOut == framesToProcessOut || (frameCountOut == 0 && frameCountIn == 0)) { + break; + } + } + } else { + /* + We're not needing to read anything from the input buffer so just read directly from our + already-processed data. + */ + if (pFramesOut != NULL) { + ma_copy_pcm_frames(pFramesOut, ma_node_get_cached_output_ptr(pNodeBase, outputBusIndex), pNodeBase->cachedFrameCountOut, ma_format_f32, ma_node_get_output_channels(pNodeBase, outputBusIndex)); + } + } + + /* The number of frames read is always equal to the number of cached output frames. */ + totalFramesRead = pNodeBase->cachedFrameCountOut; + + /* Now that we've read the data, make sure our read flag is set. */ + ma_node_output_bus_set_has_read(&pNodeBase->pOutputBuses[outputBusIndex], MA_TRUE); + } + } + + /* Apply volume, if necessary. */ + ma_apply_volume_factor_f32(pFramesOut, totalFramesRead * ma_node_get_output_channels(pNodeBase, outputBusIndex), ma_node_output_bus_get_volume(&pNodeBase->pOutputBuses[outputBusIndex])); + + /* Advance our local time forward. */ + ma_atomic_fetch_add_64(&pNodeBase->localTime, (ma_uint64)totalFramesRead); + + *pFramesRead = totalFramesRead + timeOffsetBeg; /* Must include the silenced section at the start of the buffer. */ + return result; +} + + + + +/* Data source node. */ +MA_API ma_data_source_node_config ma_data_source_node_config_init(ma_data_source* pDataSource) +{ + ma_data_source_node_config config; + + MA_ZERO_OBJECT(&config); + config.nodeConfig = ma_node_config_init(); + config.pDataSource = pDataSource; + + return config; +} + + +static void ma_data_source_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut) +{ + ma_data_source_node* pDataSourceNode = (ma_data_source_node*)pNode; + ma_format format; + ma_uint32 channels; + ma_uint32 frameCount; + ma_uint64 framesRead = 0; + + MA_ASSERT(pDataSourceNode != NULL); + MA_ASSERT(pDataSourceNode->pDataSource != NULL); + MA_ASSERT(ma_node_get_input_bus_count(pDataSourceNode) == 0); + MA_ASSERT(ma_node_get_output_bus_count(pDataSourceNode) == 1); + + /* We don't want to read from ppFramesIn at all. Instead we read from the data source. */ + (void)ppFramesIn; + (void)pFrameCountIn; + + frameCount = *pFrameCountOut; + + /* miniaudio should never be calling this with a frame count of zero. */ + MA_ASSERT(frameCount > 0); + + if (ma_data_source_get_data_format(pDataSourceNode->pDataSource, &format, &channels, NULL, NULL, 0) == MA_SUCCESS) { /* <-- Don't care about sample rate here. */ + /* The node graph system requires samples be in floating point format. This is checked in ma_data_source_node_init(). */ + MA_ASSERT(format == ma_format_f32); + (void)format; /* Just to silence some static analysis tools. */ + + ma_data_source_read_pcm_frames(pDataSourceNode->pDataSource, ppFramesOut[0], frameCount, &framesRead); + } + + *pFrameCountOut = (ma_uint32)framesRead; +} + +static ma_node_vtable g_ma_data_source_node_vtable = +{ + ma_data_source_node_process_pcm_frames, + NULL, /* onGetRequiredInputFrameCount */ + 0, /* 0 input buses. */ + 1, /* 1 output bus. */ + 0 +}; + +MA_API ma_result ma_data_source_node_init(ma_node_graph* pNodeGraph, const ma_data_source_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source_node* pDataSourceNode) +{ + ma_result result; + ma_format format; /* For validating the format, which must be ma_format_f32. */ + ma_uint32 channels; /* For specifying the channel count of the output bus. */ + ma_node_config baseConfig; + + if (pDataSourceNode == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pDataSourceNode); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + result = ma_data_source_get_data_format(pConfig->pDataSource, &format, &channels, NULL, NULL, 0); /* Don't care about sample rate. This will check pDataSource for NULL. */ + if (result != MA_SUCCESS) { + return result; + } + + MA_ASSERT(format == ma_format_f32); /* <-- If you've triggered this it means your data source is not outputting floating-point samples. You must configure your data source to use ma_format_f32. */ + if (format != ma_format_f32) { + return MA_INVALID_ARGS; /* Invalid format. */ + } + + /* The channel count is defined by the data source. If the caller has manually changed the channels we just ignore it. */ + baseConfig = pConfig->nodeConfig; + baseConfig.vtable = &g_ma_data_source_node_vtable; /* Explicitly set the vtable here to prevent callers from setting it incorrectly. */ + + /* + The channel count is defined by the data source. It is invalid for the caller to manually set + the channel counts in the config. `ma_data_source_node_config_init()` will have defaulted the + channel count pointer to NULL which is how it must remain. If you trigger any of these asserts + it means you're explicitly setting the channel count. Instead, configure the output channel + count of your data source to be the necessary channel count. + */ + if (baseConfig.pOutputChannels != NULL) { + return MA_INVALID_ARGS; + } + + baseConfig.pOutputChannels = &channels; + + result = ma_node_init(pNodeGraph, &baseConfig, pAllocationCallbacks, &pDataSourceNode->base); + if (result != MA_SUCCESS) { + return result; + } + + pDataSourceNode->pDataSource = pConfig->pDataSource; + + return MA_SUCCESS; +} + +MA_API void ma_data_source_node_uninit(ma_data_source_node* pDataSourceNode, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_node_uninit(&pDataSourceNode->base, pAllocationCallbacks); +} + +MA_API ma_result ma_data_source_node_set_looping(ma_data_source_node* pDataSourceNode, ma_bool32 isLooping) +{ + if (pDataSourceNode == NULL) { + return MA_INVALID_ARGS; + } + + return ma_data_source_set_looping(pDataSourceNode->pDataSource, isLooping); +} + +MA_API ma_bool32 ma_data_source_node_is_looping(ma_data_source_node* pDataSourceNode) +{ + if (pDataSourceNode == NULL) { + return MA_FALSE; + } + + return ma_data_source_is_looping(pDataSourceNode->pDataSource); +} + + + +/* Splitter Node. */ +MA_API ma_splitter_node_config ma_splitter_node_config_init(ma_uint32 channels) +{ + ma_splitter_node_config config; + + MA_ZERO_OBJECT(&config); + config.nodeConfig = ma_node_config_init(); + config.channels = channels; + config.outputBusCount = 2; + + return config; +} + + +static void ma_splitter_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut) +{ + ma_node_base* pNodeBase = (ma_node_base*)pNode; + ma_uint32 iOutputBus; + ma_uint32 channels; + + MA_ASSERT(pNodeBase != NULL); + MA_ASSERT(ma_node_get_input_bus_count(pNodeBase) == 1); + + /* We don't need to consider the input frame count - it'll be the same as the output frame count and we process everything. */ + (void)pFrameCountIn; + + /* NOTE: This assumes the same number of channels for all inputs and outputs. This was checked in ma_splitter_node_init(). */ + channels = ma_node_get_input_channels(pNodeBase, 0); + + /* Splitting is just copying the first input bus and copying it over to each output bus. */ + for (iOutputBus = 0; iOutputBus < ma_node_get_output_bus_count(pNodeBase); iOutputBus += 1) { + ma_copy_pcm_frames(ppFramesOut[iOutputBus], ppFramesIn[0], *pFrameCountOut, ma_format_f32, channels); + } +} + +static ma_node_vtable g_ma_splitter_node_vtable = +{ + ma_splitter_node_process_pcm_frames, + NULL, /* onGetRequiredInputFrameCount */ + 1, /* 1 input bus. */ + MA_NODE_BUS_COUNT_UNKNOWN, /* The output bus count is specified on a per-node basis. */ + 0 +}; + +MA_API ma_result ma_splitter_node_init(ma_node_graph* pNodeGraph, const ma_splitter_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_splitter_node* pSplitterNode) +{ + ma_result result; + ma_node_config baseConfig; + ma_uint32 pInputChannels[1]; + ma_uint32 pOutputChannels[MA_MAX_NODE_BUS_COUNT]; + ma_uint32 iOutputBus; + + if (pSplitterNode == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pSplitterNode); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->outputBusCount > MA_MAX_NODE_BUS_COUNT) { + return MA_INVALID_ARGS; /* Too many output buses. */ + } + + /* Splitters require the same number of channels between inputs and outputs. */ + pInputChannels[0] = pConfig->channels; + for (iOutputBus = 0; iOutputBus < pConfig->outputBusCount; iOutputBus += 1) { + pOutputChannels[iOutputBus] = pConfig->channels; + } + + baseConfig = pConfig->nodeConfig; + baseConfig.vtable = &g_ma_splitter_node_vtable; + baseConfig.pInputChannels = pInputChannels; + baseConfig.pOutputChannels = pOutputChannels; + baseConfig.outputBusCount = pConfig->outputBusCount; + + result = ma_node_init(pNodeGraph, &baseConfig, pAllocationCallbacks, &pSplitterNode->base); + if (result != MA_SUCCESS) { + return result; /* Failed to initialize the base node. */ + } + + return MA_SUCCESS; +} + +MA_API void ma_splitter_node_uninit(ma_splitter_node* pSplitterNode, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_node_uninit(pSplitterNode, pAllocationCallbacks); +} + + +/* +Biquad Node +*/ +MA_API ma_biquad_node_config ma_biquad_node_config_init(ma_uint32 channels, float b0, float b1, float b2, float a0, float a1, float a2) +{ + ma_biquad_node_config config; + + config.nodeConfig = ma_node_config_init(); + config.biquad = ma_biquad_config_init(ma_format_f32, channels, b0, b1, b2, a0, a1, a2); + + return config; +} + +static void ma_biquad_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut) +{ + ma_biquad_node* pLPFNode = (ma_biquad_node*)pNode; + + MA_ASSERT(pNode != NULL); + (void)pFrameCountIn; + + ma_biquad_process_pcm_frames(&pLPFNode->biquad, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut); +} + +static ma_node_vtable g_ma_biquad_node_vtable = +{ + ma_biquad_node_process_pcm_frames, + NULL, /* onGetRequiredInputFrameCount */ + 1, /* One input. */ + 1, /* One output. */ + 0 /* Default flags. */ +}; + +MA_API ma_result ma_biquad_node_init(ma_node_graph* pNodeGraph, const ma_biquad_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_biquad_node* pNode) +{ + ma_result result; + ma_node_config baseNodeConfig; + + if (pNode == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pNode); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->biquad.format != ma_format_f32) { + return MA_INVALID_ARGS; /* The format must be f32. */ + } + + result = ma_biquad_init(&pConfig->biquad, pAllocationCallbacks, &pNode->biquad); + if (result != MA_SUCCESS) { + return result; + } + + baseNodeConfig = ma_node_config_init(); + baseNodeConfig.vtable = &g_ma_biquad_node_vtable; + baseNodeConfig.pInputChannels = &pConfig->biquad.channels; + baseNodeConfig.pOutputChannels = &pConfig->biquad.channels; + + result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode); + if (result != MA_SUCCESS) { + return result; + } + + return result; +} + +MA_API ma_result ma_biquad_node_reinit(const ma_biquad_config* pConfig, ma_biquad_node* pNode) +{ + ma_biquad_node* pLPFNode = (ma_biquad_node*)pNode; + + MA_ASSERT(pNode != NULL); + + return ma_biquad_reinit(pConfig, &pLPFNode->biquad); +} + +MA_API void ma_biquad_node_uninit(ma_biquad_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_biquad_node* pLPFNode = (ma_biquad_node*)pNode; + + if (pNode == NULL) { + return; + } + + ma_node_uninit(pNode, pAllocationCallbacks); + ma_biquad_uninit(&pLPFNode->biquad, pAllocationCallbacks); +} + + + +/* +Low Pass Filter Node +*/ +MA_API ma_lpf_node_config ma_lpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order) +{ + ma_lpf_node_config config; + + config.nodeConfig = ma_node_config_init(); + config.lpf = ma_lpf_config_init(ma_format_f32, channels, sampleRate, cutoffFrequency, order); + + return config; +} + +static void ma_lpf_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut) +{ + ma_lpf_node* pLPFNode = (ma_lpf_node*)pNode; + + MA_ASSERT(pNode != NULL); + (void)pFrameCountIn; + + ma_lpf_process_pcm_frames(&pLPFNode->lpf, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut); +} + +static ma_node_vtable g_ma_lpf_node_vtable = +{ + ma_lpf_node_process_pcm_frames, + NULL, /* onGetRequiredInputFrameCount */ + 1, /* One input. */ + 1, /* One output. */ + 0 /* Default flags. */ +}; + +MA_API ma_result ma_lpf_node_init(ma_node_graph* pNodeGraph, const ma_lpf_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf_node* pNode) +{ + ma_result result; + ma_node_config baseNodeConfig; + + if (pNode == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pNode); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->lpf.format != ma_format_f32) { + return MA_INVALID_ARGS; /* The format must be f32. */ + } + + result = ma_lpf_init(&pConfig->lpf, pAllocationCallbacks, &pNode->lpf); + if (result != MA_SUCCESS) { + return result; + } + + baseNodeConfig = ma_node_config_init(); + baseNodeConfig.vtable = &g_ma_lpf_node_vtable; + baseNodeConfig.pInputChannels = &pConfig->lpf.channels; + baseNodeConfig.pOutputChannels = &pConfig->lpf.channels; + + result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode); + if (result != MA_SUCCESS) { + return result; + } + + return result; +} + +MA_API ma_result ma_lpf_node_reinit(const ma_lpf_config* pConfig, ma_lpf_node* pNode) +{ + ma_lpf_node* pLPFNode = (ma_lpf_node*)pNode; + + if (pNode == NULL) { + return MA_INVALID_ARGS; + } + + return ma_lpf_reinit(pConfig, &pLPFNode->lpf); +} + +MA_API void ma_lpf_node_uninit(ma_lpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_lpf_node* pLPFNode = (ma_lpf_node*)pNode; + + if (pNode == NULL) { + return; + } + + ma_node_uninit(pNode, pAllocationCallbacks); + ma_lpf_uninit(&pLPFNode->lpf, pAllocationCallbacks); +} + + + +/* +High Pass Filter Node +*/ +MA_API ma_hpf_node_config ma_hpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order) +{ + ma_hpf_node_config config; + + config.nodeConfig = ma_node_config_init(); + config.hpf = ma_hpf_config_init(ma_format_f32, channels, sampleRate, cutoffFrequency, order); + + return config; +} + +static void ma_hpf_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut) +{ + ma_hpf_node* pHPFNode = (ma_hpf_node*)pNode; + + MA_ASSERT(pNode != NULL); + (void)pFrameCountIn; + + ma_hpf_process_pcm_frames(&pHPFNode->hpf, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut); +} + +static ma_node_vtable g_ma_hpf_node_vtable = +{ + ma_hpf_node_process_pcm_frames, + NULL, /* onGetRequiredInputFrameCount */ + 1, /* One input. */ + 1, /* One output. */ + 0 /* Default flags. */ +}; + +MA_API ma_result ma_hpf_node_init(ma_node_graph* pNodeGraph, const ma_hpf_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf_node* pNode) +{ + ma_result result; + ma_node_config baseNodeConfig; + + if (pNode == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pNode); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->hpf.format != ma_format_f32) { + return MA_INVALID_ARGS; /* The format must be f32. */ + } + + result = ma_hpf_init(&pConfig->hpf, pAllocationCallbacks, &pNode->hpf); + if (result != MA_SUCCESS) { + return result; + } + + baseNodeConfig = ma_node_config_init(); + baseNodeConfig.vtable = &g_ma_hpf_node_vtable; + baseNodeConfig.pInputChannels = &pConfig->hpf.channels; + baseNodeConfig.pOutputChannels = &pConfig->hpf.channels; + + result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode); + if (result != MA_SUCCESS) { + return result; + } + + return result; +} + +MA_API ma_result ma_hpf_node_reinit(const ma_hpf_config* pConfig, ma_hpf_node* pNode) +{ + ma_hpf_node* pHPFNode = (ma_hpf_node*)pNode; + + if (pNode == NULL) { + return MA_INVALID_ARGS; + } + + return ma_hpf_reinit(pConfig, &pHPFNode->hpf); +} + +MA_API void ma_hpf_node_uninit(ma_hpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_hpf_node* pHPFNode = (ma_hpf_node*)pNode; + + if (pNode == NULL) { + return; + } + + ma_node_uninit(pNode, pAllocationCallbacks); + ma_hpf_uninit(&pHPFNode->hpf, pAllocationCallbacks); +} + + + + +/* +Band Pass Filter Node +*/ +MA_API ma_bpf_node_config ma_bpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order) +{ + ma_bpf_node_config config; + + config.nodeConfig = ma_node_config_init(); + config.bpf = ma_bpf_config_init(ma_format_f32, channels, sampleRate, cutoffFrequency, order); + + return config; +} + +static void ma_bpf_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut) +{ + ma_bpf_node* pBPFNode = (ma_bpf_node*)pNode; + + MA_ASSERT(pNode != NULL); + (void)pFrameCountIn; + + ma_bpf_process_pcm_frames(&pBPFNode->bpf, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut); +} + +static ma_node_vtable g_ma_bpf_node_vtable = +{ + ma_bpf_node_process_pcm_frames, + NULL, /* onGetRequiredInputFrameCount */ + 1, /* One input. */ + 1, /* One output. */ + 0 /* Default flags. */ +}; + +MA_API ma_result ma_bpf_node_init(ma_node_graph* pNodeGraph, const ma_bpf_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf_node* pNode) +{ + ma_result result; + ma_node_config baseNodeConfig; + + if (pNode == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pNode); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->bpf.format != ma_format_f32) { + return MA_INVALID_ARGS; /* The format must be f32. */ + } + + result = ma_bpf_init(&pConfig->bpf, pAllocationCallbacks, &pNode->bpf); + if (result != MA_SUCCESS) { + return result; + } + + baseNodeConfig = ma_node_config_init(); + baseNodeConfig.vtable = &g_ma_bpf_node_vtable; + baseNodeConfig.pInputChannels = &pConfig->bpf.channels; + baseNodeConfig.pOutputChannels = &pConfig->bpf.channels; + + result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode); + if (result != MA_SUCCESS) { + return result; + } + + return result; +} + +MA_API ma_result ma_bpf_node_reinit(const ma_bpf_config* pConfig, ma_bpf_node* pNode) +{ + ma_bpf_node* pBPFNode = (ma_bpf_node*)pNode; + + if (pNode == NULL) { + return MA_INVALID_ARGS; + } + + return ma_bpf_reinit(pConfig, &pBPFNode->bpf); +} + +MA_API void ma_bpf_node_uninit(ma_bpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_bpf_node* pBPFNode = (ma_bpf_node*)pNode; + + if (pNode == NULL) { + return; + } + + ma_node_uninit(pNode, pAllocationCallbacks); + ma_bpf_uninit(&pBPFNode->bpf, pAllocationCallbacks); +} + + + +/* +Notching Filter Node +*/ +MA_API ma_notch_node_config ma_notch_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double q, double frequency) +{ + ma_notch_node_config config; + + config.nodeConfig = ma_node_config_init(); + config.notch = ma_notch2_config_init(ma_format_f32, channels, sampleRate, q, frequency); + + return config; +} + +static void ma_notch_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut) +{ + ma_notch_node* pBPFNode = (ma_notch_node*)pNode; + + MA_ASSERT(pNode != NULL); + (void)pFrameCountIn; + + ma_notch2_process_pcm_frames(&pBPFNode->notch, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut); +} + +static ma_node_vtable g_ma_notch_node_vtable = +{ + ma_notch_node_process_pcm_frames, + NULL, /* onGetRequiredInputFrameCount */ + 1, /* One input. */ + 1, /* One output. */ + 0 /* Default flags. */ +}; + +MA_API ma_result ma_notch_node_init(ma_node_graph* pNodeGraph, const ma_notch_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_notch_node* pNode) +{ + ma_result result; + ma_node_config baseNodeConfig; + + if (pNode == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pNode); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->notch.format != ma_format_f32) { + return MA_INVALID_ARGS; /* The format must be f32. */ + } + + result = ma_notch2_init(&pConfig->notch, pAllocationCallbacks, &pNode->notch); + if (result != MA_SUCCESS) { + return result; + } + + baseNodeConfig = ma_node_config_init(); + baseNodeConfig.vtable = &g_ma_notch_node_vtable; + baseNodeConfig.pInputChannels = &pConfig->notch.channels; + baseNodeConfig.pOutputChannels = &pConfig->notch.channels; + + result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode); + if (result != MA_SUCCESS) { + return result; + } + + return result; +} + +MA_API ma_result ma_notch_node_reinit(const ma_notch_config* pConfig, ma_notch_node* pNode) +{ + ma_notch_node* pNotchNode = (ma_notch_node*)pNode; + + if (pNode == NULL) { + return MA_INVALID_ARGS; + } + + return ma_notch2_reinit(pConfig, &pNotchNode->notch); +} + +MA_API void ma_notch_node_uninit(ma_notch_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_notch_node* pNotchNode = (ma_notch_node*)pNode; + + if (pNode == NULL) { + return; + } + + ma_node_uninit(pNode, pAllocationCallbacks); + ma_notch2_uninit(&pNotchNode->notch, pAllocationCallbacks); +} + + + +/* +Peaking Filter Node +*/ +MA_API ma_peak_node_config ma_peak_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency) +{ + ma_peak_node_config config; + + config.nodeConfig = ma_node_config_init(); + config.peak = ma_peak2_config_init(ma_format_f32, channels, sampleRate, gainDB, q, frequency); + + return config; +} + +static void ma_peak_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut) +{ + ma_peak_node* pBPFNode = (ma_peak_node*)pNode; + + MA_ASSERT(pNode != NULL); + (void)pFrameCountIn; + + ma_peak2_process_pcm_frames(&pBPFNode->peak, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut); +} + +static ma_node_vtable g_ma_peak_node_vtable = +{ + ma_peak_node_process_pcm_frames, + NULL, /* onGetRequiredInputFrameCount */ + 1, /* One input. */ + 1, /* One output. */ + 0 /* Default flags. */ +}; + +MA_API ma_result ma_peak_node_init(ma_node_graph* pNodeGraph, const ma_peak_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_peak_node* pNode) +{ + ma_result result; + ma_node_config baseNodeConfig; + + if (pNode == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pNode); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->peak.format != ma_format_f32) { + return MA_INVALID_ARGS; /* The format must be f32. */ + } + + result = ma_peak2_init(&pConfig->peak, pAllocationCallbacks, &pNode->peak); + if (result != MA_SUCCESS) { + ma_node_uninit(pNode, pAllocationCallbacks); + return result; + } + + baseNodeConfig = ma_node_config_init(); + baseNodeConfig.vtable = &g_ma_peak_node_vtable; + baseNodeConfig.pInputChannels = &pConfig->peak.channels; + baseNodeConfig.pOutputChannels = &pConfig->peak.channels; + + result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode); + if (result != MA_SUCCESS) { + return result; + } + + return result; +} + +MA_API ma_result ma_peak_node_reinit(const ma_peak_config* pConfig, ma_peak_node* pNode) +{ + ma_peak_node* pPeakNode = (ma_peak_node*)pNode; + + if (pNode == NULL) { + return MA_INVALID_ARGS; + } + + return ma_peak2_reinit(pConfig, &pPeakNode->peak); +} + +MA_API void ma_peak_node_uninit(ma_peak_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_peak_node* pPeakNode = (ma_peak_node*)pNode; + + if (pNode == NULL) { + return; + } + + ma_node_uninit(pNode, pAllocationCallbacks); + ma_peak2_uninit(&pPeakNode->peak, pAllocationCallbacks); +} + + + +/* +Low Shelf Filter Node +*/ +MA_API ma_loshelf_node_config ma_loshelf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency) +{ + ma_loshelf_node_config config; + + config.nodeConfig = ma_node_config_init(); + config.loshelf = ma_loshelf2_config_init(ma_format_f32, channels, sampleRate, gainDB, q, frequency); + + return config; +} + +static void ma_loshelf_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut) +{ + ma_loshelf_node* pBPFNode = (ma_loshelf_node*)pNode; + + MA_ASSERT(pNode != NULL); + (void)pFrameCountIn; + + ma_loshelf2_process_pcm_frames(&pBPFNode->loshelf, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut); +} + +static ma_node_vtable g_ma_loshelf_node_vtable = +{ + ma_loshelf_node_process_pcm_frames, + NULL, /* onGetRequiredInputFrameCount */ + 1, /* One input. */ + 1, /* One output. */ + 0 /* Default flags. */ +}; + +MA_API ma_result ma_loshelf_node_init(ma_node_graph* pNodeGraph, const ma_loshelf_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_loshelf_node* pNode) +{ + ma_result result; + ma_node_config baseNodeConfig; + + if (pNode == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pNode); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->loshelf.format != ma_format_f32) { + return MA_INVALID_ARGS; /* The format must be f32. */ + } + + result = ma_loshelf2_init(&pConfig->loshelf, pAllocationCallbacks, &pNode->loshelf); + if (result != MA_SUCCESS) { + return result; + } + + baseNodeConfig = ma_node_config_init(); + baseNodeConfig.vtable = &g_ma_loshelf_node_vtable; + baseNodeConfig.pInputChannels = &pConfig->loshelf.channels; + baseNodeConfig.pOutputChannels = &pConfig->loshelf.channels; + + result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode); + if (result != MA_SUCCESS) { + return result; + } + + return result; +} + +MA_API ma_result ma_loshelf_node_reinit(const ma_loshelf_config* pConfig, ma_loshelf_node* pNode) +{ + ma_loshelf_node* pLoshelfNode = (ma_loshelf_node*)pNode; + + if (pNode == NULL) { + return MA_INVALID_ARGS; + } + + return ma_loshelf2_reinit(pConfig, &pLoshelfNode->loshelf); +} + +MA_API void ma_loshelf_node_uninit(ma_loshelf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_loshelf_node* pLoshelfNode = (ma_loshelf_node*)pNode; + + if (pNode == NULL) { + return; + } + + ma_node_uninit(pNode, pAllocationCallbacks); + ma_loshelf2_uninit(&pLoshelfNode->loshelf, pAllocationCallbacks); +} + + + +/* +High Shelf Filter Node +*/ +MA_API ma_hishelf_node_config ma_hishelf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency) +{ + ma_hishelf_node_config config; + + config.nodeConfig = ma_node_config_init(); + config.hishelf = ma_hishelf2_config_init(ma_format_f32, channels, sampleRate, gainDB, q, frequency); + + return config; +} + +static void ma_hishelf_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut) +{ + ma_hishelf_node* pBPFNode = (ma_hishelf_node*)pNode; + + MA_ASSERT(pNode != NULL); + (void)pFrameCountIn; + + ma_hishelf2_process_pcm_frames(&pBPFNode->hishelf, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut); +} + +static ma_node_vtable g_ma_hishelf_node_vtable = +{ + ma_hishelf_node_process_pcm_frames, + NULL, /* onGetRequiredInputFrameCount */ + 1, /* One input. */ + 1, /* One output. */ + 0 /* Default flags. */ +}; + +MA_API ma_result ma_hishelf_node_init(ma_node_graph* pNodeGraph, const ma_hishelf_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hishelf_node* pNode) +{ + ma_result result; + ma_node_config baseNodeConfig; + + if (pNode == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pNode); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->hishelf.format != ma_format_f32) { + return MA_INVALID_ARGS; /* The format must be f32. */ + } + + result = ma_hishelf2_init(&pConfig->hishelf, pAllocationCallbacks, &pNode->hishelf); + if (result != MA_SUCCESS) { + return result; + } + + baseNodeConfig = ma_node_config_init(); + baseNodeConfig.vtable = &g_ma_hishelf_node_vtable; + baseNodeConfig.pInputChannels = &pConfig->hishelf.channels; + baseNodeConfig.pOutputChannels = &pConfig->hishelf.channels; + + result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode); + if (result != MA_SUCCESS) { + return result; + } + + return result; +} + +MA_API ma_result ma_hishelf_node_reinit(const ma_hishelf_config* pConfig, ma_hishelf_node* pNode) +{ + ma_hishelf_node* pHishelfNode = (ma_hishelf_node*)pNode; + + if (pNode == NULL) { + return MA_INVALID_ARGS; + } + + return ma_hishelf2_reinit(pConfig, &pHishelfNode->hishelf); +} + +MA_API void ma_hishelf_node_uninit(ma_hishelf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_hishelf_node* pHishelfNode = (ma_hishelf_node*)pNode; + + if (pNode == NULL) { + return; + } + + ma_node_uninit(pNode, pAllocationCallbacks); + ma_hishelf2_uninit(&pHishelfNode->hishelf, pAllocationCallbacks); +} + + + + +MA_API ma_delay_node_config ma_delay_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 delayInFrames, float decay) +{ + ma_delay_node_config config; + + config.nodeConfig = ma_node_config_init(); + config.delay = ma_delay_config_init(channels, sampleRate, delayInFrames, decay); + + return config; +} + + +static void ma_delay_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut) +{ + ma_delay_node* pDelayNode = (ma_delay_node*)pNode; + + (void)pFrameCountIn; + + ma_delay_process_pcm_frames(&pDelayNode->delay, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut); +} + +static ma_node_vtable g_ma_delay_node_vtable = +{ + ma_delay_node_process_pcm_frames, + NULL, + 1, /* 1 input channels. */ + 1, /* 1 output channel. */ + MA_NODE_FLAG_CONTINUOUS_PROCESSING /* Delay requires continuous processing to ensure the tail get's processed. */ +}; + +MA_API ma_result ma_delay_node_init(ma_node_graph* pNodeGraph, const ma_delay_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_delay_node* pDelayNode) +{ + ma_result result; + ma_node_config baseConfig; + + if (pDelayNode == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pDelayNode); + + result = ma_delay_init(&pConfig->delay, pAllocationCallbacks, &pDelayNode->delay); + if (result != MA_SUCCESS) { + return result; + } + + baseConfig = pConfig->nodeConfig; + baseConfig.vtable = &g_ma_delay_node_vtable; + baseConfig.pInputChannels = &pConfig->delay.channels; + baseConfig.pOutputChannels = &pConfig->delay.channels; + + result = ma_node_init(pNodeGraph, &baseConfig, pAllocationCallbacks, &pDelayNode->baseNode); + if (result != MA_SUCCESS) { + ma_delay_uninit(&pDelayNode->delay, pAllocationCallbacks); + return result; + } + + return result; +} + +MA_API void ma_delay_node_uninit(ma_delay_node* pDelayNode, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pDelayNode == NULL) { + return; + } + + /* The base node is always uninitialized first. */ + ma_node_uninit(pDelayNode, pAllocationCallbacks); + ma_delay_uninit(&pDelayNode->delay, pAllocationCallbacks); +} + +MA_API void ma_delay_node_set_wet(ma_delay_node* pDelayNode, float value) +{ + if (pDelayNode == NULL) { + return; + } + + ma_delay_set_wet(&pDelayNode->delay, value); +} + +MA_API float ma_delay_node_get_wet(const ma_delay_node* pDelayNode) +{ + if (pDelayNode == NULL) { + return 0; + } + + return ma_delay_get_wet(&pDelayNode->delay); +} + +MA_API void ma_delay_node_set_dry(ma_delay_node* pDelayNode, float value) +{ + if (pDelayNode == NULL) { + return; + } + + ma_delay_set_dry(&pDelayNode->delay, value); +} + +MA_API float ma_delay_node_get_dry(const ma_delay_node* pDelayNode) +{ + if (pDelayNode == NULL) { + return 0; + } + + return ma_delay_get_dry(&pDelayNode->delay); +} + +MA_API void ma_delay_node_set_decay(ma_delay_node* pDelayNode, float value) +{ + if (pDelayNode == NULL) { + return; + } + + ma_delay_set_decay(&pDelayNode->delay, value); +} + +MA_API float ma_delay_node_get_decay(const ma_delay_node* pDelayNode) +{ + if (pDelayNode == NULL) { + return 0; + } + + return ma_delay_get_decay(&pDelayNode->delay); +} +#endif /* MA_NO_NODE_GRAPH */ + + +/* SECTION: miniaudio_engine.c */ +#if !defined(MA_NO_ENGINE) && !defined(MA_NO_NODE_GRAPH) +/************************************************************************************************************************************************************** + +Engine + +**************************************************************************************************************************************************************/ +#define MA_SEEK_TARGET_NONE (~(ma_uint64)0) + + +static void ma_sound_set_at_end(ma_sound* pSound, ma_bool32 atEnd) +{ + MA_ASSERT(pSound != NULL); + ma_atomic_exchange_32(&pSound->atEnd, atEnd); + + /* Fire any callbacks or events. */ + if (atEnd) { + if (pSound->endCallback != NULL) { + pSound->endCallback(pSound->pEndCallbackUserData, pSound); + } + } +} + +static ma_bool32 ma_sound_get_at_end(const ma_sound* pSound) +{ + MA_ASSERT(pSound != NULL); + return ma_atomic_load_32(&pSound->atEnd); +} + + +MA_API ma_engine_node_config ma_engine_node_config_init(ma_engine* pEngine, ma_engine_node_type type, ma_uint32 flags) +{ + ma_engine_node_config config; + + MA_ZERO_OBJECT(&config); + config.pEngine = pEngine; + config.type = type; + config.isPitchDisabled = (flags & MA_SOUND_FLAG_NO_PITCH) != 0; + config.isSpatializationDisabled = (flags & MA_SOUND_FLAG_NO_SPATIALIZATION) != 0; + config.monoExpansionMode = pEngine->monoExpansionMode; + + return config; +} + + +static void ma_engine_node_update_pitch_if_required(ma_engine_node* pEngineNode) +{ + ma_bool32 isUpdateRequired = MA_FALSE; + float newPitch; + + MA_ASSERT(pEngineNode != NULL); + + newPitch = ma_atomic_load_explicit_f32(&pEngineNode->pitch, ma_atomic_memory_order_acquire); + + if (pEngineNode->oldPitch != newPitch) { + pEngineNode->oldPitch = newPitch; + isUpdateRequired = MA_TRUE; + } + + if (pEngineNode->oldDopplerPitch != pEngineNode->spatializer.dopplerPitch) { + pEngineNode->oldDopplerPitch = pEngineNode->spatializer.dopplerPitch; + isUpdateRequired = MA_TRUE; + } + + if (isUpdateRequired) { + float basePitch = (float)pEngineNode->sampleRate / ma_engine_get_sample_rate(pEngineNode->pEngine); + ma_linear_resampler_set_rate_ratio(&pEngineNode->resampler, basePitch * pEngineNode->oldPitch * pEngineNode->oldDopplerPitch); + } +} + +static ma_bool32 ma_engine_node_is_pitching_enabled(const ma_engine_node* pEngineNode) +{ + MA_ASSERT(pEngineNode != NULL); + + /* Don't try to be clever by skiping resampling in the pitch=1 case or else you'll glitch when moving away from 1. */ + return !ma_atomic_load_explicit_32(&pEngineNode->isPitchDisabled, ma_atomic_memory_order_acquire); +} + +static ma_bool32 ma_engine_node_is_spatialization_enabled(const ma_engine_node* pEngineNode) +{ + MA_ASSERT(pEngineNode != NULL); + + return !ma_atomic_load_explicit_32(&pEngineNode->isSpatializationDisabled, ma_atomic_memory_order_acquire); +} + +static ma_uint64 ma_engine_node_get_required_input_frame_count(const ma_engine_node* pEngineNode, ma_uint64 outputFrameCount) +{ + ma_uint64 inputFrameCount = 0; + + if (ma_engine_node_is_pitching_enabled(pEngineNode)) { + ma_result result = ma_linear_resampler_get_required_input_frame_count(&pEngineNode->resampler, outputFrameCount, &inputFrameCount); + if (result != MA_SUCCESS) { + inputFrameCount = 0; + } + } else { + inputFrameCount = outputFrameCount; /* No resampling, so 1:1. */ + } + + return inputFrameCount; +} + +static ma_result ma_engine_node_set_volume(ma_engine_node* pEngineNode, float volume) +{ + if (pEngineNode == NULL) { + return MA_INVALID_ARGS; + } + + ma_atomic_float_set(&pEngineNode->volume, volume); + + /* If we're not smoothing we should bypass the volume gainer entirely. */ + if (pEngineNode->volumeSmoothTimeInPCMFrames == 0) { + /* We should always have an active spatializer because it can be enabled and disabled dynamically. We can just use that for hodling our volume. */ + ma_spatializer_set_master_volume(&pEngineNode->spatializer, volume); + } else { + /* We're using volume smoothing, so apply the master volume to the gainer. */ + ma_gainer_set_gain(&pEngineNode->volumeGainer, volume); + } + + return MA_SUCCESS; +} + +static ma_result ma_engine_node_get_volume(const ma_engine_node* pEngineNode, float* pVolume) +{ + if (pVolume == NULL) { + return MA_INVALID_ARGS; + } + + *pVolume = 0.0f; + + if (pEngineNode == NULL) { + return MA_INVALID_ARGS; + } + + *pVolume = ma_atomic_float_get((ma_atomic_float*)&pEngineNode->volume); + + return MA_SUCCESS; +} + + +static void ma_engine_node_process_pcm_frames__general(ma_engine_node* pEngineNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut) +{ + ma_uint32 frameCountIn; + ma_uint32 frameCountOut; + ma_uint32 totalFramesProcessedIn; + ma_uint32 totalFramesProcessedOut; + ma_uint32 channelsIn; + ma_uint32 channelsOut; + ma_bool32 isPitchingEnabled; + ma_bool32 isFadingEnabled; + ma_bool32 isSpatializationEnabled; + ma_bool32 isPanningEnabled; + ma_bool32 isVolumeSmoothingEnabled; + + frameCountIn = *pFrameCountIn; + frameCountOut = *pFrameCountOut; + + channelsIn = ma_spatializer_get_input_channels(&pEngineNode->spatializer); + channelsOut = ma_spatializer_get_output_channels(&pEngineNode->spatializer); + + totalFramesProcessedIn = 0; + totalFramesProcessedOut = 0; + + /* Update the fader if applicable. */ + { + ma_uint64 fadeLengthInFrames = ma_atomic_uint64_get(&pEngineNode->fadeSettings.fadeLengthInFrames); + if (fadeLengthInFrames != ~(ma_uint64)0) { + float fadeVolumeBeg = ma_atomic_float_get(&pEngineNode->fadeSettings.volumeBeg); + float fadeVolumeEnd = ma_atomic_float_get(&pEngineNode->fadeSettings.volumeEnd); + ma_int64 fadeStartOffsetInFrames = (ma_int64)ma_atomic_uint64_get(&pEngineNode->fadeSettings.absoluteGlobalTimeInFrames); + if (fadeStartOffsetInFrames == (ma_int64)(~(ma_uint64)0)) { + fadeStartOffsetInFrames = 0; + } else { + fadeStartOffsetInFrames -= ma_engine_get_time_in_pcm_frames(pEngineNode->pEngine); + } + + ma_fader_set_fade_ex(&pEngineNode->fader, fadeVolumeBeg, fadeVolumeEnd, fadeLengthInFrames, fadeStartOffsetInFrames); + + /* Reset the fade length so we don't erroneously apply it again. */ + ma_atomic_uint64_set(&pEngineNode->fadeSettings.fadeLengthInFrames, ~(ma_uint64)0); + } + } + + isPitchingEnabled = ma_engine_node_is_pitching_enabled(pEngineNode); + isFadingEnabled = pEngineNode->fader.volumeBeg != 1 || pEngineNode->fader.volumeEnd != 1; + isSpatializationEnabled = ma_engine_node_is_spatialization_enabled(pEngineNode); + isPanningEnabled = pEngineNode->panner.pan != 0 && channelsOut != 1; + isVolumeSmoothingEnabled = pEngineNode->volumeSmoothTimeInPCMFrames > 0; + + /* Keep going while we've still got data available for processing. */ + while (totalFramesProcessedOut < frameCountOut) { + /* + We need to process in a specific order. We always do resampling first because it's likely + we're going to be increasing the channel count after spatialization. Also, I want to do + fading based on the output sample rate. + + We'll first read into a buffer from the resampler. Then we'll do all processing that + operates on the on the input channel count. We'll then get the spatializer to output to + the output buffer and then do all effects from that point directly in the output buffer + in-place. + + Note that we're always running the resampler if pitching is enabled, even when the pitch + is 1. If we try to be clever and skip resampling when the pitch is 1, we'll get a glitch + when we move away from 1, back to 1, and then away from 1 again. We'll want to implement + any pitch=1 optimizations in the resampler itself. + + There's a small optimization here that we'll utilize since it might be a fairly common + case. When the input and output channel counts are the same, we'll read straight into the + output buffer from the resampler and do everything in-place. + */ + const float* pRunningFramesIn; + float* pRunningFramesOut; + float* pWorkingBuffer; /* This is the buffer that we'll be processing frames in. This is in input channels. */ + float temp[MA_DATA_CONVERTER_STACK_BUFFER_SIZE / sizeof(float)]; + ma_uint32 tempCapInFrames = ma_countof(temp) / channelsIn; + ma_uint32 framesAvailableIn; + ma_uint32 framesAvailableOut; + ma_uint32 framesJustProcessedIn; + ma_uint32 framesJustProcessedOut; + ma_bool32 isWorkingBufferValid = MA_FALSE; + + framesAvailableIn = frameCountIn - totalFramesProcessedIn; + framesAvailableOut = frameCountOut - totalFramesProcessedOut; + + pRunningFramesIn = ma_offset_pcm_frames_const_ptr_f32(ppFramesIn[0], totalFramesProcessedIn, channelsIn); + pRunningFramesOut = ma_offset_pcm_frames_ptr_f32(ppFramesOut[0], totalFramesProcessedOut, channelsOut); + + if (channelsIn == channelsOut) { + /* Fast path. Channel counts are the same. No need for an intermediary input buffer. */ + pWorkingBuffer = pRunningFramesOut; + } else { + /* Slow path. Channel counts are different. Need to use an intermediary input buffer. */ + pWorkingBuffer = temp; + if (framesAvailableOut > tempCapInFrames) { + framesAvailableOut = tempCapInFrames; + } + } + + /* First is resampler. */ + if (isPitchingEnabled) { + ma_uint64 resampleFrameCountIn = framesAvailableIn; + ma_uint64 resampleFrameCountOut = framesAvailableOut; + + ma_linear_resampler_process_pcm_frames(&pEngineNode->resampler, pRunningFramesIn, &resampleFrameCountIn, pWorkingBuffer, &resampleFrameCountOut); + isWorkingBufferValid = MA_TRUE; + + framesJustProcessedIn = (ma_uint32)resampleFrameCountIn; + framesJustProcessedOut = (ma_uint32)resampleFrameCountOut; + } else { + framesJustProcessedIn = ma_min(framesAvailableIn, framesAvailableOut); + framesJustProcessedOut = framesJustProcessedIn; /* When no resampling is being performed, the number of output frames is the same as input frames. */ + } + + /* Fading. */ + if (isFadingEnabled) { + if (isWorkingBufferValid) { + ma_fader_process_pcm_frames(&pEngineNode->fader, pWorkingBuffer, pWorkingBuffer, framesJustProcessedOut); /* In-place processing. */ + } else { + ma_fader_process_pcm_frames(&pEngineNode->fader, pWorkingBuffer, pRunningFramesIn, framesJustProcessedOut); + isWorkingBufferValid = MA_TRUE; + } + } + + /* + If we're using smoothing, we won't be applying volume via the spatializer, but instead from a ma_gainer. In this case + we'll want to apply our volume now. + */ + if (isVolumeSmoothingEnabled) { + if (isWorkingBufferValid) { + ma_gainer_process_pcm_frames(&pEngineNode->volumeGainer, pWorkingBuffer, pWorkingBuffer, framesJustProcessedOut); + } else { + ma_gainer_process_pcm_frames(&pEngineNode->volumeGainer, pWorkingBuffer, pRunningFramesIn, framesJustProcessedOut); + isWorkingBufferValid = MA_TRUE; + } + } + + /* + If at this point we still haven't actually done anything with the working buffer we need + to just read straight from the input buffer. + */ + if (isWorkingBufferValid == MA_FALSE) { + pWorkingBuffer = (float*)pRunningFramesIn; /* Naughty const cast, but it's safe at this point because we won't ever be writing to it from this point out. */ + } + + /* Spatialization. */ + if (isSpatializationEnabled) { + ma_uint32 iListener; + + /* + When determining the listener to use, we first check to see if the sound is pinned to a + specific listener. If so, we use that. Otherwise we just use the closest listener. + */ + if (pEngineNode->pinnedListenerIndex != MA_LISTENER_INDEX_CLOSEST && pEngineNode->pinnedListenerIndex < ma_engine_get_listener_count(pEngineNode->pEngine)) { + iListener = pEngineNode->pinnedListenerIndex; + } else { + ma_vec3f spatializerPosition = ma_spatializer_get_position(&pEngineNode->spatializer); + iListener = ma_engine_find_closest_listener(pEngineNode->pEngine, spatializerPosition.x, spatializerPosition.y, spatializerPosition.z); + } + + ma_spatializer_process_pcm_frames(&pEngineNode->spatializer, &pEngineNode->pEngine->listeners[iListener], pRunningFramesOut, pWorkingBuffer, framesJustProcessedOut); + } else { + /* No spatialization, but we still need to do channel conversion and master volume. */ + float volume; + ma_engine_node_get_volume(pEngineNode, &volume); /* Should never fail. */ + + if (channelsIn == channelsOut) { + /* No channel conversion required. Just copy straight to the output buffer. */ + if (isVolumeSmoothingEnabled) { + /* Volume has already been applied. Just copy straight to the output buffer. */ + ma_copy_pcm_frames(pRunningFramesOut, pWorkingBuffer, framesJustProcessedOut * channelsOut, ma_format_f32, channelsOut); + } else { + /* Volume has not been applied yet. Copy and apply volume in the same pass. */ + ma_copy_and_apply_volume_factor_f32(pRunningFramesOut, pWorkingBuffer, framesJustProcessedOut * channelsOut, volume); + } + } else { + /* Channel conversion required. TODO: Add support for channel maps here. */ + ma_channel_map_apply_f32(pRunningFramesOut, NULL, channelsOut, pWorkingBuffer, NULL, channelsIn, framesJustProcessedOut, ma_channel_mix_mode_simple, pEngineNode->monoExpansionMode); + + /* If we're using smoothing, the volume will have already been applied. */ + if (!isVolumeSmoothingEnabled) { + ma_apply_volume_factor_f32(pRunningFramesOut, framesJustProcessedOut * channelsOut, volume); + } + } + } + + /* At this point we can guarantee that the output buffer contains valid data. We can process everything in place now. */ + + /* Panning. */ + if (isPanningEnabled) { + ma_panner_process_pcm_frames(&pEngineNode->panner, pRunningFramesOut, pRunningFramesOut, framesJustProcessedOut); /* In-place processing. */ + } + + /* We're done for this chunk. */ + totalFramesProcessedIn += framesJustProcessedIn; + totalFramesProcessedOut += framesJustProcessedOut; + + /* If we didn't process any output frames this iteration it means we've either run out of input data, or run out of room in the output buffer. */ + if (framesJustProcessedOut == 0) { + break; + } + } + + /* At this point we're done processing. */ + *pFrameCountIn = totalFramesProcessedIn; + *pFrameCountOut = totalFramesProcessedOut; +} + +static void ma_engine_node_process_pcm_frames__sound(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut) +{ + /* For sounds, we need to first read from the data source. Then we need to apply the engine effects (pan, pitch, fades, etc.). */ + ma_result result = MA_SUCCESS; + ma_sound* pSound = (ma_sound*)pNode; + ma_uint32 frameCount = *pFrameCountOut; + ma_uint32 totalFramesRead = 0; + ma_format dataSourceFormat; + ma_uint32 dataSourceChannels; + ma_uint8 temp[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; + ma_uint32 tempCapInFrames; + ma_uint64 seekTarget; + + /* This is a data source node which means no input buses. */ + (void)ppFramesIn; + (void)pFrameCountIn; + + /* If we're marked at the end we need to stop the sound and do nothing. */ + if (ma_sound_at_end(pSound)) { + ma_sound_stop(pSound); + *pFrameCountOut = 0; + return; + } + + /* If we're seeking, do so now before reading. */ + seekTarget = ma_atomic_load_64(&pSound->seekTarget); + if (seekTarget != MA_SEEK_TARGET_NONE) { + ma_data_source_seek_to_pcm_frame(pSound->pDataSource, seekTarget); + + /* Any time-dependant effects need to have their times updated. */ + ma_node_set_time(pSound, seekTarget); + + ma_atomic_exchange_64(&pSound->seekTarget, MA_SEEK_TARGET_NONE); + } + + /* + We want to update the pitch once. For sounds, this can be either at the start or at the end. If + we don't force this to only ever be updating once, we could end up in a situation where + retrieving the required input frame count ends up being different to what we actually retrieve. + What could happen is that the required input frame count is calculated, the pitch is update, + and then this processing function is called resulting in a different number of input frames + being processed. Do not call this in ma_engine_node_process_pcm_frames__general() or else + you'll hit the aforementioned bug. + */ + ma_engine_node_update_pitch_if_required(&pSound->engineNode); + + /* + For the convenience of the caller, we're doing to allow data sources to use non-floating-point formats and channel counts that differ + from the main engine. + */ + result = ma_data_source_get_data_format(pSound->pDataSource, &dataSourceFormat, &dataSourceChannels, NULL, NULL, 0); + if (result == MA_SUCCESS) { + tempCapInFrames = sizeof(temp) / ma_get_bytes_per_frame(dataSourceFormat, dataSourceChannels); + + /* Keep reading until we've read as much as was requested or we reach the end of the data source. */ + while (totalFramesRead < frameCount) { + ma_uint32 framesRemaining = frameCount - totalFramesRead; + ma_uint32 framesToRead; + ma_uint64 framesJustRead; + ma_uint32 frameCountIn; + ma_uint32 frameCountOut; + const float* pRunningFramesIn; + float* pRunningFramesOut; + + /* + The first thing we need to do is read into the temporary buffer. We can calculate exactly + how many input frames we'll need after resampling. + */ + framesToRead = (ma_uint32)ma_engine_node_get_required_input_frame_count(&pSound->engineNode, framesRemaining); + if (framesToRead > tempCapInFrames) { + framesToRead = tempCapInFrames; + } + + result = ma_data_source_read_pcm_frames(pSound->pDataSource, temp, framesToRead, &framesJustRead); + + /* If we reached the end of the sound we'll want to mark it as at the end and stop it. This should never be returned for looping sounds. */ + if (result == MA_AT_END) { + ma_sound_set_at_end(pSound, MA_TRUE); /* This will be set to false in ma_sound_start(). */ + } + + pRunningFramesOut = ma_offset_pcm_frames_ptr_f32(ppFramesOut[0], totalFramesRead, ma_engine_get_channels(ma_sound_get_engine(pSound))); + + frameCountIn = (ma_uint32)framesJustRead; + frameCountOut = framesRemaining; + + /* Convert if necessary. */ + if (dataSourceFormat == ma_format_f32) { + /* Fast path. No data conversion necessary. */ + pRunningFramesIn = (float*)temp; + ma_engine_node_process_pcm_frames__general(&pSound->engineNode, &pRunningFramesIn, &frameCountIn, &pRunningFramesOut, &frameCountOut); + } else { + /* Slow path. Need to do sample format conversion to f32. If we give the f32 buffer the same count as the first temp buffer, we're guaranteed it'll be large enough. */ + float tempf32[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* Do not do `MA_DATA_CONVERTER_STACK_BUFFER_SIZE/sizeof(float)` here like we've done in other places. */ + ma_convert_pcm_frames_format(tempf32, ma_format_f32, temp, dataSourceFormat, framesJustRead, dataSourceChannels, ma_dither_mode_none); + + /* Now that we have our samples in f32 format we can process like normal. */ + pRunningFramesIn = tempf32; + ma_engine_node_process_pcm_frames__general(&pSound->engineNode, &pRunningFramesIn, &frameCountIn, &pRunningFramesOut, &frameCountOut); + } + + /* We should have processed all of our input frames since we calculated the required number of input frames at the top. */ + MA_ASSERT(frameCountIn == framesJustRead); + totalFramesRead += (ma_uint32)frameCountOut; /* Safe cast. */ + + if (result != MA_SUCCESS || ma_sound_at_end(pSound)) { + break; /* Might have reached the end. */ + } + } + } + + *pFrameCountOut = totalFramesRead; +} + +static void ma_engine_node_process_pcm_frames__group(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut) +{ + /* + Make sure the pitch is updated before trying to read anything. It's important that this is done + only once and not in ma_engine_node_process_pcm_frames__general(). The reason for this is that + ma_engine_node_process_pcm_frames__general() will call ma_engine_node_get_required_input_frame_count(), + and if another thread modifies the pitch just after that call it can result in a glitch due to + the input rate changing. + */ + ma_engine_node_update_pitch_if_required((ma_engine_node*)pNode); + + /* For groups, the input data has already been read and we just need to apply the effect. */ + ma_engine_node_process_pcm_frames__general((ma_engine_node*)pNode, ppFramesIn, pFrameCountIn, ppFramesOut, pFrameCountOut); +} + +static ma_result ma_engine_node_get_required_input_frame_count__group(ma_node* pNode, ma_uint32 outputFrameCount, ma_uint32* pInputFrameCount) +{ + ma_uint64 inputFrameCount; + + MA_ASSERT(pInputFrameCount != NULL); + + /* Our pitch will affect this calculation. We need to update it. */ + ma_engine_node_update_pitch_if_required((ma_engine_node*)pNode); + + inputFrameCount = ma_engine_node_get_required_input_frame_count((ma_engine_node*)pNode, outputFrameCount); + if (inputFrameCount > 0xFFFFFFFF) { + inputFrameCount = 0xFFFFFFFF; /* Will never happen because miniaudio will only ever process in relatively small chunks. */ + } + + *pInputFrameCount = (ma_uint32)inputFrameCount; + + return MA_SUCCESS; +} + + +static ma_node_vtable g_ma_engine_node_vtable__sound = +{ + ma_engine_node_process_pcm_frames__sound, + NULL, /* onGetRequiredInputFrameCount */ + 0, /* Sounds are data source nodes which means they have zero inputs (their input is drawn from the data source itself). */ + 1, /* Sounds have one output bus. */ + 0 /* Default flags. */ +}; + +static ma_node_vtable g_ma_engine_node_vtable__group = +{ + ma_engine_node_process_pcm_frames__group, + ma_engine_node_get_required_input_frame_count__group, + 1, /* Groups have one input bus. */ + 1, /* Groups have one output bus. */ + MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES /* The engine node does resampling so should let miniaudio know about it. */ +}; + + + +static ma_node_config ma_engine_node_base_node_config_init(const ma_engine_node_config* pConfig) +{ + ma_node_config baseNodeConfig; + + if (pConfig->type == ma_engine_node_type_sound) { + /* Sound. */ + baseNodeConfig = ma_node_config_init(); + baseNodeConfig.vtable = &g_ma_engine_node_vtable__sound; + baseNodeConfig.initialState = ma_node_state_stopped; /* Sounds are stopped by default. */ + } else { + /* Group. */ + baseNodeConfig = ma_node_config_init(); + baseNodeConfig.vtable = &g_ma_engine_node_vtable__group; + baseNodeConfig.initialState = ma_node_state_started; /* Groups are started by default. */ + } + + return baseNodeConfig; +} + +static ma_spatializer_config ma_engine_node_spatializer_config_init(const ma_node_config* pBaseNodeConfig) +{ + return ma_spatializer_config_init(pBaseNodeConfig->pInputChannels[0], pBaseNodeConfig->pOutputChannels[0]); +} + +typedef struct +{ + size_t sizeInBytes; + size_t baseNodeOffset; + size_t resamplerOffset; + size_t spatializerOffset; + size_t gainerOffset; +} ma_engine_node_heap_layout; + +static ma_result ma_engine_node_get_heap_layout(const ma_engine_node_config* pConfig, ma_engine_node_heap_layout* pHeapLayout) +{ + ma_result result; + size_t tempHeapSize; + ma_node_config baseNodeConfig; + ma_linear_resampler_config resamplerConfig; + ma_spatializer_config spatializerConfig; + ma_gainer_config gainerConfig; + ma_uint32 channelsIn; + ma_uint32 channelsOut; + ma_channel defaultStereoChannelMap[2] = {MA_CHANNEL_SIDE_LEFT, MA_CHANNEL_SIDE_RIGHT}; /* <-- Consistent with the default channel map of a stereo listener. Means channel conversion can run on a fast path. */ + + MA_ASSERT(pHeapLayout); + + MA_ZERO_OBJECT(pHeapLayout); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + if (pConfig->pEngine == NULL) { + return MA_INVALID_ARGS; /* An engine must be specified. */ + } + + pHeapLayout->sizeInBytes = 0; + + channelsIn = (pConfig->channelsIn != 0) ? pConfig->channelsIn : ma_engine_get_channels(pConfig->pEngine); + channelsOut = (pConfig->channelsOut != 0) ? pConfig->channelsOut : ma_engine_get_channels(pConfig->pEngine); + + + /* Base node. */ + baseNodeConfig = ma_engine_node_base_node_config_init(pConfig); + baseNodeConfig.pInputChannels = &channelsIn; + baseNodeConfig.pOutputChannels = &channelsOut; + + result = ma_node_get_heap_size(ma_engine_get_node_graph(pConfig->pEngine), &baseNodeConfig, &tempHeapSize); + if (result != MA_SUCCESS) { + return result; /* Failed to retrieve the size of the heap for the base node. */ + } + + pHeapLayout->baseNodeOffset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += ma_align_64(tempHeapSize); + + + /* Resmapler. */ + resamplerConfig = ma_linear_resampler_config_init(ma_format_f32, channelsIn, 1, 1); /* Input and output sample rates don't affect the calculation of the heap size. */ + resamplerConfig.lpfOrder = 0; + + result = ma_linear_resampler_get_heap_size(&resamplerConfig, &tempHeapSize); + if (result != MA_SUCCESS) { + return result; /* Failed to retrieve the size of the heap for the resampler. */ + } + + pHeapLayout->resamplerOffset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += ma_align_64(tempHeapSize); + + + /* Spatializer. */ + spatializerConfig = ma_engine_node_spatializer_config_init(&baseNodeConfig); + + if (spatializerConfig.channelsIn == 2) { + spatializerConfig.pChannelMapIn = defaultStereoChannelMap; + } + + result = ma_spatializer_get_heap_size(&spatializerConfig, &tempHeapSize); + if (result != MA_SUCCESS) { + return result; /* Failed to retrieve the size of the heap for the spatializer. */ + } + + pHeapLayout->spatializerOffset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += ma_align_64(tempHeapSize); + + + /* Gainer. Will not be used if we are not using smoothing. */ + if (pConfig->volumeSmoothTimeInPCMFrames > 0) { + gainerConfig = ma_gainer_config_init(channelsIn, pConfig->volumeSmoothTimeInPCMFrames); + + result = ma_gainer_get_heap_size(&gainerConfig, &tempHeapSize); + if (result != MA_SUCCESS) { + return result; + } + + pHeapLayout->gainerOffset = pHeapLayout->sizeInBytes; + pHeapLayout->sizeInBytes += ma_align_64(tempHeapSize); + } + + + return MA_SUCCESS; +} + +MA_API ma_result ma_engine_node_get_heap_size(const ma_engine_node_config* pConfig, size_t* pHeapSizeInBytes) +{ + ma_result result; + ma_engine_node_heap_layout heapLayout; + + if (pHeapSizeInBytes == NULL) { + return MA_INVALID_ARGS; + } + + *pHeapSizeInBytes = 0; + + result = ma_engine_node_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + *pHeapSizeInBytes = heapLayout.sizeInBytes; + + return MA_SUCCESS; +} + +MA_API ma_result ma_engine_node_init_preallocated(const ma_engine_node_config* pConfig, void* pHeap, ma_engine_node* pEngineNode) +{ + ma_result result; + ma_engine_node_heap_layout heapLayout; + ma_node_config baseNodeConfig; + ma_linear_resampler_config resamplerConfig; + ma_fader_config faderConfig; + ma_spatializer_config spatializerConfig; + ma_panner_config pannerConfig; + ma_gainer_config gainerConfig; + ma_uint32 channelsIn; + ma_uint32 channelsOut; + ma_channel defaultStereoChannelMap[2] = {MA_CHANNEL_SIDE_LEFT, MA_CHANNEL_SIDE_RIGHT}; /* <-- Consistent with the default channel map of a stereo listener. Means channel conversion can run on a fast path. */ + + if (pEngineNode == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pEngineNode); + + result = ma_engine_node_get_heap_layout(pConfig, &heapLayout); + if (result != MA_SUCCESS) { + return result; + } + + if (pConfig->pinnedListenerIndex != MA_LISTENER_INDEX_CLOSEST && pConfig->pinnedListenerIndex >= ma_engine_get_listener_count(pConfig->pEngine)) { + return MA_INVALID_ARGS; /* Invalid listener. */ + } + + pEngineNode->_pHeap = pHeap; + MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes); + + pEngineNode->pEngine = pConfig->pEngine; + pEngineNode->sampleRate = (pConfig->sampleRate > 0) ? pConfig->sampleRate : ma_engine_get_sample_rate(pEngineNode->pEngine); + pEngineNode->volumeSmoothTimeInPCMFrames = pConfig->volumeSmoothTimeInPCMFrames; + pEngineNode->monoExpansionMode = pConfig->monoExpansionMode; + ma_atomic_float_set(&pEngineNode->volume, 1); + pEngineNode->pitch = 1; + pEngineNode->oldPitch = 1; + pEngineNode->oldDopplerPitch = 1; + pEngineNode->isPitchDisabled = pConfig->isPitchDisabled; + pEngineNode->isSpatializationDisabled = pConfig->isSpatializationDisabled; + pEngineNode->pinnedListenerIndex = pConfig->pinnedListenerIndex; + ma_atomic_float_set(&pEngineNode->fadeSettings.volumeBeg, 1); + ma_atomic_float_set(&pEngineNode->fadeSettings.volumeEnd, 1); + ma_atomic_uint64_set(&pEngineNode->fadeSettings.fadeLengthInFrames, (~(ma_uint64)0)); + ma_atomic_uint64_set(&pEngineNode->fadeSettings.absoluteGlobalTimeInFrames, (~(ma_uint64)0)); /* <-- Indicates that the fade should start immediately. */ + + channelsIn = (pConfig->channelsIn != 0) ? pConfig->channelsIn : ma_engine_get_channels(pConfig->pEngine); + channelsOut = (pConfig->channelsOut != 0) ? pConfig->channelsOut : ma_engine_get_channels(pConfig->pEngine); + + /* + If the sample rate of the sound is different to the engine, make sure pitching is enabled so that the resampler + is activated. Not doing this will result in the sound not being resampled if MA_SOUND_FLAG_NO_PITCH is used. + */ + if (pEngineNode->sampleRate != ma_engine_get_sample_rate(pEngineNode->pEngine)) { + pEngineNode->isPitchDisabled = MA_FALSE; + } + + + /* Base node. */ + baseNodeConfig = ma_engine_node_base_node_config_init(pConfig); + baseNodeConfig.pInputChannels = &channelsIn; + baseNodeConfig.pOutputChannels = &channelsOut; + + result = ma_node_init_preallocated(&pConfig->pEngine->nodeGraph, &baseNodeConfig, ma_offset_ptr(pHeap, heapLayout.baseNodeOffset), &pEngineNode->baseNode); + if (result != MA_SUCCESS) { + goto error0; + } + + + /* + We can now initialize the effects we need in order to implement the engine node. There's a + defined order of operations here, mainly centered around when we convert our channels from the + data source's native channel count to the engine's channel count. As a rule, we want to do as + much computation as possible before spatialization because there's a chance that will increase + the channel count, thereby increasing the amount of work needing to be done to process. + */ + + /* We'll always do resampling first. */ + resamplerConfig = ma_linear_resampler_config_init(ma_format_f32, baseNodeConfig.pInputChannels[0], pEngineNode->sampleRate, ma_engine_get_sample_rate(pEngineNode->pEngine)); + resamplerConfig.lpfOrder = 0; /* <-- Need to disable low-pass filtering for pitch shifting for now because there's cases where the biquads are becoming unstable. Need to figure out a better fix for this. */ + + result = ma_linear_resampler_init_preallocated(&resamplerConfig, ma_offset_ptr(pHeap, heapLayout.resamplerOffset), &pEngineNode->resampler); + if (result != MA_SUCCESS) { + goto error1; + } + + + /* After resampling will come the fader. */ + faderConfig = ma_fader_config_init(ma_format_f32, baseNodeConfig.pInputChannels[0], ma_engine_get_sample_rate(pEngineNode->pEngine)); + + result = ma_fader_init(&faderConfig, &pEngineNode->fader); + if (result != MA_SUCCESS) { + goto error2; + } + + + /* + Spatialization comes next. We spatialize based ont he node's output channel count. It's up the caller to + ensure channels counts link up correctly in the node graph. + */ + spatializerConfig = ma_engine_node_spatializer_config_init(&baseNodeConfig); + spatializerConfig.gainSmoothTimeInFrames = pEngineNode->pEngine->gainSmoothTimeInFrames; + + if (spatializerConfig.channelsIn == 2) { + spatializerConfig.pChannelMapIn = defaultStereoChannelMap; + } + + result = ma_spatializer_init_preallocated(&spatializerConfig, ma_offset_ptr(pHeap, heapLayout.spatializerOffset), &pEngineNode->spatializer); + if (result != MA_SUCCESS) { + goto error2; + } + + + /* + After spatialization comes panning. We need to do this after spatialization because otherwise we wouldn't + be able to pan mono sounds. + */ + pannerConfig = ma_panner_config_init(ma_format_f32, baseNodeConfig.pOutputChannels[0]); + + result = ma_panner_init(&pannerConfig, &pEngineNode->panner); + if (result != MA_SUCCESS) { + goto error3; + } + + + /* We'll need a gainer for smoothing out volume changes if we have a non-zero smooth time. We apply this before converting to the output channel count. */ + if (pConfig->volumeSmoothTimeInPCMFrames > 0) { + gainerConfig = ma_gainer_config_init(channelsIn, pConfig->volumeSmoothTimeInPCMFrames); + + result = ma_gainer_init_preallocated(&gainerConfig, ma_offset_ptr(pHeap, heapLayout.gainerOffset), &pEngineNode->volumeGainer); + if (result != MA_SUCCESS) { + goto error3; + } + } + + + return MA_SUCCESS; + + /* No need for allocation callbacks here because we use a preallocated heap. */ +error3: ma_spatializer_uninit(&pEngineNode->spatializer, NULL); +error2: ma_linear_resampler_uninit(&pEngineNode->resampler, NULL); +error1: ma_node_uninit(&pEngineNode->baseNode, NULL); +error0: return result; +} + +MA_API ma_result ma_engine_node_init(const ma_engine_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_engine_node* pEngineNode) +{ + ma_result result; + size_t heapSizeInBytes; + void* pHeap; + + result = ma_engine_node_get_heap_size(pConfig, &heapSizeInBytes); + if (result != MA_SUCCESS) { + return result; + } + + if (heapSizeInBytes > 0) { + pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks); + if (pHeap == NULL) { + return MA_OUT_OF_MEMORY; + } + } else { + pHeap = NULL; + } + + result = ma_engine_node_init_preallocated(pConfig, pHeap, pEngineNode); + if (result != MA_SUCCESS) { + ma_free(pHeap, pAllocationCallbacks); + return result; + } + + pEngineNode->_ownsHeap = MA_TRUE; + return MA_SUCCESS; +} + +MA_API void ma_engine_node_uninit(ma_engine_node* pEngineNode, const ma_allocation_callbacks* pAllocationCallbacks) +{ + /* + The base node always needs to be uninitialized first to ensure it's detached from the graph completely before we + destroy anything that might be in the middle of being used by the processing function. + */ + ma_node_uninit(&pEngineNode->baseNode, pAllocationCallbacks); + + /* Now that the node has been uninitialized we can safely uninitialize the rest. */ + if (pEngineNode->volumeSmoothTimeInPCMFrames > 0) { + ma_gainer_uninit(&pEngineNode->volumeGainer, pAllocationCallbacks); + } + + ma_spatializer_uninit(&pEngineNode->spatializer, pAllocationCallbacks); + ma_linear_resampler_uninit(&pEngineNode->resampler, pAllocationCallbacks); + + /* Free the heap last. */ + if (pEngineNode->_ownsHeap) { + ma_free(pEngineNode->_pHeap, pAllocationCallbacks); + } +} + + +MA_API ma_sound_config ma_sound_config_init(void) +{ + return ma_sound_config_init_2(NULL); +} + +MA_API ma_sound_config ma_sound_config_init_2(ma_engine* pEngine) +{ + ma_sound_config config; + + MA_ZERO_OBJECT(&config); + + if (pEngine != NULL) { + config.monoExpansionMode = pEngine->monoExpansionMode; + } else { + config.monoExpansionMode = ma_mono_expansion_mode_default; + } + + config.rangeEndInPCMFrames = ~((ma_uint64)0); + config.loopPointEndInPCMFrames = ~((ma_uint64)0); + + return config; +} + +MA_API ma_sound_group_config ma_sound_group_config_init(void) +{ + return ma_sound_group_config_init_2(NULL); +} + +MA_API ma_sound_group_config ma_sound_group_config_init_2(ma_engine* pEngine) +{ + ma_sound_group_config config; + + MA_ZERO_OBJECT(&config); + + if (pEngine != NULL) { + config.monoExpansionMode = pEngine->monoExpansionMode; + } else { + config.monoExpansionMode = ma_mono_expansion_mode_default; + } + + return config; +} + + +MA_API ma_engine_config ma_engine_config_init(void) +{ + ma_engine_config config; + + MA_ZERO_OBJECT(&config); + config.listenerCount = 1; /* Always want at least one listener. */ + config.monoExpansionMode = ma_mono_expansion_mode_default; + + return config; +} + + +#if !defined(MA_NO_DEVICE_IO) +static void ma_engine_data_callback_internal(ma_device* pDevice, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount) +{ + ma_engine* pEngine = (ma_engine*)pDevice->pUserData; + + (void)pFramesIn; + + /* + Experiment: Try processing a resource manager job if we're on the Emscripten build. + + This serves two purposes: + + 1) It ensures jobs are actually processed at some point since we cannot guarantee that the + caller is doing the right thing and calling ma_resource_manager_process_next_job(); and + + 2) It's an attempt at working around an issue where processing jobs on the Emscripten main + loop doesn't work as well as it should. When trying to load sounds without the `DECODE` + flag or with the `ASYNC` flag, the sound data is just not able to be loaded in time + before the callback is processed. I think it's got something to do with the single- + threaded nature of Web, but I'm not entirely sure. + */ + #if !defined(MA_NO_RESOURCE_MANAGER) && defined(MA_EMSCRIPTEN) + { + if (pEngine->pResourceManager != NULL) { + if ((pEngine->pResourceManager->config.flags & MA_RESOURCE_MANAGER_FLAG_NO_THREADING) != 0) { + ma_resource_manager_process_next_job(pEngine->pResourceManager); + } + } + } + #endif + + ma_engine_read_pcm_frames(pEngine, pFramesOut, frameCount, NULL); +} +#endif + +MA_API ma_result ma_engine_init(const ma_engine_config* pConfig, ma_engine* pEngine) +{ + ma_result result; + ma_node_graph_config nodeGraphConfig; + ma_engine_config engineConfig; + ma_spatializer_listener_config listenerConfig; + ma_uint32 iListener; + + if (pEngine == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pEngine); + + /* The config is allowed to be NULL in which case we use defaults for everything. */ + if (pConfig != NULL) { + engineConfig = *pConfig; + } else { + engineConfig = ma_engine_config_init(); + } + + pEngine->monoExpansionMode = engineConfig.monoExpansionMode; + pEngine->defaultVolumeSmoothTimeInPCMFrames = engineConfig.defaultVolumeSmoothTimeInPCMFrames; + pEngine->onProcess = engineConfig.onProcess; + pEngine->pProcessUserData = engineConfig.pProcessUserData; + ma_allocation_callbacks_init_copy(&pEngine->allocationCallbacks, &engineConfig.allocationCallbacks); + + #if !defined(MA_NO_RESOURCE_MANAGER) + { + pEngine->pResourceManager = engineConfig.pResourceManager; + } + #endif + + #if !defined(MA_NO_DEVICE_IO) + { + pEngine->pDevice = engineConfig.pDevice; + + /* If we don't have a device, we need one. */ + if (pEngine->pDevice == NULL && engineConfig.noDevice == MA_FALSE) { + ma_device_config deviceConfig; + + pEngine->pDevice = (ma_device*)ma_malloc(sizeof(*pEngine->pDevice), &pEngine->allocationCallbacks); + if (pEngine->pDevice == NULL) { + return MA_OUT_OF_MEMORY; + } + + deviceConfig = ma_device_config_init(ma_device_type_playback); + deviceConfig.playback.pDeviceID = engineConfig.pPlaybackDeviceID; + deviceConfig.playback.format = ma_format_f32; + deviceConfig.playback.channels = engineConfig.channels; + deviceConfig.sampleRate = engineConfig.sampleRate; + deviceConfig.dataCallback = (engineConfig.dataCallback != NULL) ? engineConfig.dataCallback : ma_engine_data_callback_internal; + deviceConfig.pUserData = pEngine; + deviceConfig.notificationCallback = engineConfig.notificationCallback; + deviceConfig.periodSizeInFrames = engineConfig.periodSizeInFrames; + deviceConfig.periodSizeInMilliseconds = engineConfig.periodSizeInMilliseconds; + deviceConfig.noPreSilencedOutputBuffer = MA_TRUE; /* We'll always be outputting to every frame in the callback so there's no need for a pre-silenced buffer. */ + deviceConfig.noClip = MA_TRUE; /* The engine will do clipping itself. */ + + if (engineConfig.pContext == NULL) { + ma_context_config contextConfig = ma_context_config_init(); + contextConfig.allocationCallbacks = pEngine->allocationCallbacks; + contextConfig.pLog = engineConfig.pLog; + + /* If the engine config does not specify a log, use the resource manager's if we have one. */ + #ifndef MA_NO_RESOURCE_MANAGER + { + if (contextConfig.pLog == NULL && engineConfig.pResourceManager != NULL) { + contextConfig.pLog = ma_resource_manager_get_log(engineConfig.pResourceManager); + } + } + #endif + + result = ma_device_init_ex(NULL, 0, &contextConfig, &deviceConfig, pEngine->pDevice); + } else { + result = ma_device_init(engineConfig.pContext, &deviceConfig, pEngine->pDevice); + } + + if (result != MA_SUCCESS) { + ma_free(pEngine->pDevice, &pEngine->allocationCallbacks); + pEngine->pDevice = NULL; + return result; + } + + pEngine->ownsDevice = MA_TRUE; + } + + /* Update the channel count and sample rate of the engine config so we can reference it below. */ + if (pEngine->pDevice != NULL) { + engineConfig.channels = pEngine->pDevice->playback.channels; + engineConfig.sampleRate = pEngine->pDevice->sampleRate; + } + } + #endif + + if (engineConfig.channels == 0 || engineConfig.sampleRate == 0) { + return MA_INVALID_ARGS; + } + + pEngine->sampleRate = engineConfig.sampleRate; + + /* The engine always uses either the log that was passed into the config, or the context's log is available. */ + if (engineConfig.pLog != NULL) { + pEngine->pLog = engineConfig.pLog; + } else { + #if !defined(MA_NO_DEVICE_IO) + { + pEngine->pLog = ma_device_get_log(pEngine->pDevice); + } + #else + { + pEngine->pLog = NULL; + } + #endif + } + + + /* The engine is a node graph. This needs to be initialized after we have the device so we can can determine the channel count. */ + nodeGraphConfig = ma_node_graph_config_init(engineConfig.channels); + nodeGraphConfig.nodeCacheCapInFrames = (engineConfig.periodSizeInFrames > 0xFFFF) ? 0xFFFF : (ma_uint16)engineConfig.periodSizeInFrames; + + result = ma_node_graph_init(&nodeGraphConfig, &pEngine->allocationCallbacks, &pEngine->nodeGraph); + if (result != MA_SUCCESS) { + goto on_error_1; + } + + + /* We need at least one listener. */ + if (engineConfig.listenerCount == 0) { + engineConfig.listenerCount = 1; + } + + if (engineConfig.listenerCount > MA_ENGINE_MAX_LISTENERS) { + result = MA_INVALID_ARGS; /* Too many listeners. */ + goto on_error_1; + } + + for (iListener = 0; iListener < engineConfig.listenerCount; iListener += 1) { + listenerConfig = ma_spatializer_listener_config_init(ma_node_graph_get_channels(&pEngine->nodeGraph)); + + /* + If we're using a device, use the device's channel map for the listener. Otherwise just use + miniaudio's default channel map. + */ + #if !defined(MA_NO_DEVICE_IO) + { + if (pEngine->pDevice != NULL) { + /* + Temporarily disabled. There is a subtle bug here where front-left and front-right + will be used by the device's channel map, but this is not what we want to use for + spatialization. Instead we want to use side-left and side-right. I need to figure + out a better solution for this. For now, disabling the use of device channel maps. + */ + /*listenerConfig.pChannelMapOut = pEngine->pDevice->playback.channelMap;*/ + } + } + #endif + + result = ma_spatializer_listener_init(&listenerConfig, &pEngine->allocationCallbacks, &pEngine->listeners[iListener]); /* TODO: Change this to a pre-allocated heap. */ + if (result != MA_SUCCESS) { + goto on_error_2; + } + + pEngine->listenerCount += 1; + } + + + /* Gain smoothing for spatialized sounds. */ + pEngine->gainSmoothTimeInFrames = engineConfig.gainSmoothTimeInFrames; + if (pEngine->gainSmoothTimeInFrames == 0) { + ma_uint32 gainSmoothTimeInMilliseconds = engineConfig.gainSmoothTimeInMilliseconds; + if (gainSmoothTimeInMilliseconds == 0) { + gainSmoothTimeInMilliseconds = 8; + } + + pEngine->gainSmoothTimeInFrames = (gainSmoothTimeInMilliseconds * ma_engine_get_sample_rate(pEngine)) / 1000; /* 8ms by default. */ + } + + + /* We need a resource manager. */ + #ifndef MA_NO_RESOURCE_MANAGER + { + if (pEngine->pResourceManager == NULL) { + ma_resource_manager_config resourceManagerConfig; + + pEngine->pResourceManager = (ma_resource_manager*)ma_malloc(sizeof(*pEngine->pResourceManager), &pEngine->allocationCallbacks); + if (pEngine->pResourceManager == NULL) { + result = MA_OUT_OF_MEMORY; + goto on_error_2; + } + + resourceManagerConfig = ma_resource_manager_config_init(); + resourceManagerConfig.pLog = pEngine->pLog; /* Always use the engine's log for internally-managed resource managers. */ + resourceManagerConfig.decodedFormat = ma_format_f32; + resourceManagerConfig.decodedChannels = 0; /* Leave the decoded channel count as 0 so we can get good spatialization. */ + resourceManagerConfig.decodedSampleRate = ma_engine_get_sample_rate(pEngine); + ma_allocation_callbacks_init_copy(&resourceManagerConfig.allocationCallbacks, &pEngine->allocationCallbacks); + resourceManagerConfig.pVFS = engineConfig.pResourceManagerVFS; + + /* The Emscripten build cannot use threads. */ + #if defined(MA_EMSCRIPTEN) + { + resourceManagerConfig.jobThreadCount = 0; + resourceManagerConfig.flags |= MA_RESOURCE_MANAGER_FLAG_NO_THREADING; + } + #endif + + result = ma_resource_manager_init(&resourceManagerConfig, pEngine->pResourceManager); + if (result != MA_SUCCESS) { + goto on_error_3; + } + + pEngine->ownsResourceManager = MA_TRUE; + } + } + #endif + + /* Setup some stuff for inlined sounds. That is sounds played with ma_engine_play_sound(). */ + pEngine->inlinedSoundLock = 0; + pEngine->pInlinedSoundHead = NULL; + + /* Start the engine if required. This should always be the last step. */ + #if !defined(MA_NO_DEVICE_IO) + { + if (engineConfig.noAutoStart == MA_FALSE && pEngine->pDevice != NULL) { + result = ma_engine_start(pEngine); + if (result != MA_SUCCESS) { + goto on_error_4; /* Failed to start the engine. */ + } + } + } + #endif + + return MA_SUCCESS; + +#if !defined(MA_NO_DEVICE_IO) +on_error_4: +#endif +#if !defined(MA_NO_RESOURCE_MANAGER) +on_error_3: + if (pEngine->ownsResourceManager) { + ma_free(pEngine->pResourceManager, &pEngine->allocationCallbacks); + } +#endif /* MA_NO_RESOURCE_MANAGER */ +on_error_2: + for (iListener = 0; iListener < pEngine->listenerCount; iListener += 1) { + ma_spatializer_listener_uninit(&pEngine->listeners[iListener], &pEngine->allocationCallbacks); + } + + ma_node_graph_uninit(&pEngine->nodeGraph, &pEngine->allocationCallbacks); +on_error_1: + #if !defined(MA_NO_DEVICE_IO) + { + if (pEngine->ownsDevice) { + ma_device_uninit(pEngine->pDevice); + ma_free(pEngine->pDevice, &pEngine->allocationCallbacks); + } + } + #endif + + return result; +} + +MA_API void ma_engine_uninit(ma_engine* pEngine) +{ + ma_uint32 iListener; + + if (pEngine == NULL) { + return; + } + + /* The device must be uninitialized before the node graph to ensure the audio thread doesn't try accessing it. */ + #if !defined(MA_NO_DEVICE_IO) + { + if (pEngine->ownsDevice) { + ma_device_uninit(pEngine->pDevice); + ma_free(pEngine->pDevice, &pEngine->allocationCallbacks); + } else { + if (pEngine->pDevice != NULL) { + ma_device_stop(pEngine->pDevice); + } + } + } + #endif + + /* + All inlined sounds need to be deleted. I'm going to use a lock here just to future proof in case + I want to do some kind of garbage collection later on. + */ + ma_spinlock_lock(&pEngine->inlinedSoundLock); + { + for (;;) { + ma_sound_inlined* pSoundToDelete = pEngine->pInlinedSoundHead; + if (pSoundToDelete == NULL) { + break; /* Done. */ + } + + pEngine->pInlinedSoundHead = pSoundToDelete->pNext; + + ma_sound_uninit(&pSoundToDelete->sound); + ma_free(pSoundToDelete, &pEngine->allocationCallbacks); + } + } + ma_spinlock_unlock(&pEngine->inlinedSoundLock); + + for (iListener = 0; iListener < pEngine->listenerCount; iListener += 1) { + ma_spatializer_listener_uninit(&pEngine->listeners[iListener], &pEngine->allocationCallbacks); + } + + /* Make sure the node graph is uninitialized after the audio thread has been shutdown to prevent accessing of the node graph after being uninitialized. */ + ma_node_graph_uninit(&pEngine->nodeGraph, &pEngine->allocationCallbacks); + + /* Uninitialize the resource manager last to ensure we don't have a thread still trying to access it. */ +#ifndef MA_NO_RESOURCE_MANAGER + if (pEngine->ownsResourceManager) { + ma_resource_manager_uninit(pEngine->pResourceManager); + ma_free(pEngine->pResourceManager, &pEngine->allocationCallbacks); + } +#endif +} + +MA_API ma_result ma_engine_read_pcm_frames(ma_engine* pEngine, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead) +{ + ma_result result; + ma_uint64 framesRead = 0; + + if (pFramesRead != NULL) { + *pFramesRead = 0; + } + + result = ma_node_graph_read_pcm_frames(&pEngine->nodeGraph, pFramesOut, frameCount, &framesRead); + if (result != MA_SUCCESS) { + return result; + } + + if (pFramesRead != NULL) { + *pFramesRead = framesRead; + } + + if (pEngine->onProcess) { + pEngine->onProcess(pEngine->pProcessUserData, (float*)pFramesOut, framesRead); /* Safe cast to float* because the engine always works on floating point samples. */ + } + + return MA_SUCCESS; +} + +MA_API ma_node_graph* ma_engine_get_node_graph(ma_engine* pEngine) +{ + if (pEngine == NULL) { + return NULL; + } + + return &pEngine->nodeGraph; +} + +#if !defined(MA_NO_RESOURCE_MANAGER) +MA_API ma_resource_manager* ma_engine_get_resource_manager(ma_engine* pEngine) +{ + if (pEngine == NULL) { + return NULL; + } + + #if !defined(MA_NO_RESOURCE_MANAGER) + { + return pEngine->pResourceManager; + } + #else + { + return NULL; + } + #endif +} +#endif + +MA_API ma_device* ma_engine_get_device(ma_engine* pEngine) +{ + if (pEngine == NULL) { + return NULL; + } + + #if !defined(MA_NO_DEVICE_IO) + { + return pEngine->pDevice; + } + #else + { + return NULL; + } + #endif +} + +MA_API ma_log* ma_engine_get_log(ma_engine* pEngine) +{ + if (pEngine == NULL) { + return NULL; + } + + if (pEngine->pLog != NULL) { + return pEngine->pLog; + } else { + #if !defined(MA_NO_DEVICE_IO) + { + return ma_device_get_log(ma_engine_get_device(pEngine)); + } + #else + { + return NULL; + } + #endif + } +} + +MA_API ma_node* ma_engine_get_endpoint(ma_engine* pEngine) +{ + return ma_node_graph_get_endpoint(&pEngine->nodeGraph); +} + +MA_API ma_uint64 ma_engine_get_time_in_pcm_frames(const ma_engine* pEngine) +{ + return ma_node_graph_get_time(&pEngine->nodeGraph); +} + +MA_API ma_uint64 ma_engine_get_time_in_milliseconds(const ma_engine* pEngine) +{ + return ma_engine_get_time_in_pcm_frames(pEngine) * 1000 / ma_engine_get_sample_rate(pEngine); +} + +MA_API ma_result ma_engine_set_time_in_pcm_frames(ma_engine* pEngine, ma_uint64 globalTime) +{ + return ma_node_graph_set_time(&pEngine->nodeGraph, globalTime); +} + +MA_API ma_result ma_engine_set_time_in_milliseconds(ma_engine* pEngine, ma_uint64 globalTime) +{ + return ma_engine_set_time_in_pcm_frames(pEngine, globalTime * ma_engine_get_sample_rate(pEngine) / 1000); +} + +MA_API ma_uint64 ma_engine_get_time(const ma_engine* pEngine) +{ + return ma_engine_get_time_in_pcm_frames(pEngine); +} + +MA_API ma_result ma_engine_set_time(ma_engine* pEngine, ma_uint64 globalTime) +{ + return ma_engine_set_time_in_pcm_frames(pEngine, globalTime); +} + +MA_API ma_uint32 ma_engine_get_channels(const ma_engine* pEngine) +{ + return ma_node_graph_get_channels(&pEngine->nodeGraph); +} + +MA_API ma_uint32 ma_engine_get_sample_rate(const ma_engine* pEngine) +{ + if (pEngine == NULL) { + return 0; + } + + return pEngine->sampleRate; +} + + +MA_API ma_result ma_engine_start(ma_engine* pEngine) +{ + ma_result result; + + if (pEngine == NULL) { + return MA_INVALID_ARGS; + } + + #if !defined(MA_NO_DEVICE_IO) + { + if (pEngine->pDevice != NULL) { + result = ma_device_start(pEngine->pDevice); + } else { + result = MA_INVALID_OPERATION; /* The engine is running without a device which means there's no real notion of "starting" the engine. */ + } + } + #else + { + result = MA_INVALID_OPERATION; /* Device IO is disabled, so there's no real notion of "starting" the engine. */ + } + #endif + + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_engine_stop(ma_engine* pEngine) +{ + ma_result result; + + if (pEngine == NULL) { + return MA_INVALID_ARGS; + } + + #if !defined(MA_NO_DEVICE_IO) + { + if (pEngine->pDevice != NULL) { + result = ma_device_stop(pEngine->pDevice); + } else { + result = MA_INVALID_OPERATION; /* The engine is running without a device which means there's no real notion of "stopping" the engine. */ + } + } + #else + { + result = MA_INVALID_OPERATION; /* Device IO is disabled, so there's no real notion of "stopping" the engine. */ + } + #endif + + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +MA_API ma_result ma_engine_set_volume(ma_engine* pEngine, float volume) +{ + if (pEngine == NULL) { + return MA_INVALID_ARGS; + } + + return ma_node_set_output_bus_volume(ma_node_graph_get_endpoint(&pEngine->nodeGraph), 0, volume); +} + +MA_API float ma_engine_get_volume(ma_engine* pEngine) +{ + if (pEngine == NULL) { + return 0; + } + + return ma_node_get_output_bus_volume(ma_node_graph_get_endpoint(&pEngine->nodeGraph), 0); +} + +MA_API ma_result ma_engine_set_gain_db(ma_engine* pEngine, float gainDB) +{ + return ma_engine_set_volume(pEngine, ma_volume_db_to_linear(gainDB)); +} + +MA_API float ma_engine_get_gain_db(ma_engine* pEngine) +{ + return ma_volume_linear_to_db(ma_engine_get_volume(pEngine)); +} + + +MA_API ma_uint32 ma_engine_get_listener_count(const ma_engine* pEngine) +{ + if (pEngine == NULL) { + return 0; + } + + return pEngine->listenerCount; +} + +MA_API ma_uint32 ma_engine_find_closest_listener(const ma_engine* pEngine, float absolutePosX, float absolutePosY, float absolutePosZ) +{ + ma_uint32 iListener; + ma_uint32 iListenerClosest; + float closestLen2 = MA_FLT_MAX; + + if (pEngine == NULL || pEngine->listenerCount == 1) { + return 0; + } + + iListenerClosest = 0; + for (iListener = 0; iListener < pEngine->listenerCount; iListener += 1) { + if (ma_engine_listener_is_enabled(pEngine, iListener)) { + float len2 = ma_vec3f_len2(ma_vec3f_sub(ma_spatializer_listener_get_position(&pEngine->listeners[iListener]), ma_vec3f_init_3f(absolutePosX, absolutePosY, absolutePosZ))); + if (closestLen2 > len2) { + closestLen2 = len2; + iListenerClosest = iListener; + } + } + } + + MA_ASSERT(iListenerClosest < 255); + return iListenerClosest; +} + +MA_API void ma_engine_listener_set_position(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z) +{ + if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) { + return; + } + + ma_spatializer_listener_set_position(&pEngine->listeners[listenerIndex], x, y, z); +} + +MA_API ma_vec3f ma_engine_listener_get_position(const ma_engine* pEngine, ma_uint32 listenerIndex) +{ + if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) { + return ma_vec3f_init_3f(0, 0, 0); + } + + return ma_spatializer_listener_get_position(&pEngine->listeners[listenerIndex]); +} + +MA_API void ma_engine_listener_set_direction(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z) +{ + if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) { + return; + } + + ma_spatializer_listener_set_direction(&pEngine->listeners[listenerIndex], x, y, z); +} + +MA_API ma_vec3f ma_engine_listener_get_direction(const ma_engine* pEngine, ma_uint32 listenerIndex) +{ + if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) { + return ma_vec3f_init_3f(0, 0, -1); + } + + return ma_spatializer_listener_get_direction(&pEngine->listeners[listenerIndex]); +} + +MA_API void ma_engine_listener_set_velocity(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z) +{ + if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) { + return; + } + + ma_spatializer_listener_set_velocity(&pEngine->listeners[listenerIndex], x, y, z); +} + +MA_API ma_vec3f ma_engine_listener_get_velocity(const ma_engine* pEngine, ma_uint32 listenerIndex) +{ + if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) { + return ma_vec3f_init_3f(0, 0, 0); + } + + return ma_spatializer_listener_get_velocity(&pEngine->listeners[listenerIndex]); +} + +MA_API void ma_engine_listener_set_cone(ma_engine* pEngine, ma_uint32 listenerIndex, float innerAngleInRadians, float outerAngleInRadians, float outerGain) +{ + if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) { + return; + } + + ma_spatializer_listener_set_cone(&pEngine->listeners[listenerIndex], innerAngleInRadians, outerAngleInRadians, outerGain); +} + +MA_API void ma_engine_listener_get_cone(const ma_engine* pEngine, ma_uint32 listenerIndex, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain) +{ + if (pInnerAngleInRadians != NULL) { + *pInnerAngleInRadians = 0; + } + + if (pOuterAngleInRadians != NULL) { + *pOuterAngleInRadians = 0; + } + + if (pOuterGain != NULL) { + *pOuterGain = 0; + } + + if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) { + return; + } + + ma_spatializer_listener_get_cone(&pEngine->listeners[listenerIndex], pInnerAngleInRadians, pOuterAngleInRadians, pOuterGain); +} + +MA_API void ma_engine_listener_set_world_up(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z) +{ + if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) { + return; + } + + ma_spatializer_listener_set_world_up(&pEngine->listeners[listenerIndex], x, y, z); +} + +MA_API ma_vec3f ma_engine_listener_get_world_up(const ma_engine* pEngine, ma_uint32 listenerIndex) +{ + if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) { + return ma_vec3f_init_3f(0, 1, 0); + } + + return ma_spatializer_listener_get_world_up(&pEngine->listeners[listenerIndex]); +} + +MA_API void ma_engine_listener_set_enabled(ma_engine* pEngine, ma_uint32 listenerIndex, ma_bool32 isEnabled) +{ + if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) { + return; + } + + ma_spatializer_listener_set_enabled(&pEngine->listeners[listenerIndex], isEnabled); +} + +MA_API ma_bool32 ma_engine_listener_is_enabled(const ma_engine* pEngine, ma_uint32 listenerIndex) +{ + if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) { + return MA_FALSE; + } + + return ma_spatializer_listener_is_enabled(&pEngine->listeners[listenerIndex]); +} + + +#ifndef MA_NO_RESOURCE_MANAGER +MA_API ma_result ma_engine_play_sound_ex(ma_engine* pEngine, const char* pFilePath, ma_node* pNode, ma_uint32 nodeInputBusIndex) +{ + ma_result result = MA_SUCCESS; + ma_sound_inlined* pSound = NULL; + ma_sound_inlined* pNextSound = NULL; + + if (pEngine == NULL || pFilePath == NULL) { + return MA_INVALID_ARGS; + } + + /* Attach to the endpoint node if nothing is specicied. */ + if (pNode == NULL) { + pNode = ma_node_graph_get_endpoint(&pEngine->nodeGraph); + nodeInputBusIndex = 0; + } + + /* + We want to check if we can recycle an already-allocated inlined sound. Since this is just a + helper I'm not *too* concerned about performance here and I'm happy to use a lock to keep + the implementation simple. Maybe this can be optimized later if there's enough demand, but + if this function is being used it probably means the caller doesn't really care too much. + + What we do is check the atEnd flag. When this is true, we can recycle the sound. Otherwise + we just keep iterating. If we reach the end without finding a sound to recycle we just + allocate a new one. This doesn't scale well for a massive number of sounds being played + simultaneously as we don't ever actually free the sound objects. Some kind of garbage + collection routine might be valuable for this which I'll think about. + */ + ma_spinlock_lock(&pEngine->inlinedSoundLock); + { + ma_uint32 soundFlags = 0; + + for (pNextSound = pEngine->pInlinedSoundHead; pNextSound != NULL; pNextSound = pNextSound->pNext) { + if (ma_sound_at_end(&pNextSound->sound)) { + /* + The sound is at the end which means it's available for recycling. All we need to do + is uninitialize it and reinitialize it. All we're doing is recycling memory. + */ + pSound = pNextSound; + ma_atomic_fetch_sub_32(&pEngine->inlinedSoundCount, 1); + break; + } + } + + if (pSound != NULL) { + /* + We actually want to detach the sound from the list here. The reason is because we want the sound + to be in a consistent state at the non-recycled case to simplify the logic below. + */ + if (pEngine->pInlinedSoundHead == pSound) { + pEngine->pInlinedSoundHead = pSound->pNext; + } + + if (pSound->pPrev != NULL) { + pSound->pPrev->pNext = pSound->pNext; + } + if (pSound->pNext != NULL) { + pSound->pNext->pPrev = pSound->pPrev; + } + + /* Now the previous sound needs to be uninitialized. */ + ma_sound_uninit(&pNextSound->sound); + } else { + /* No sound available for recycling. Allocate one now. */ + pSound = (ma_sound_inlined*)ma_malloc(sizeof(*pSound), &pEngine->allocationCallbacks); + } + + if (pSound != NULL) { /* Safety check for the allocation above. */ + /* + At this point we should have memory allocated for the inlined sound. We just need + to initialize it like a normal sound now. + */ + soundFlags |= MA_SOUND_FLAG_ASYNC; /* For inlined sounds we don't want to be sitting around waiting for stuff to load so force an async load. */ + soundFlags |= MA_SOUND_FLAG_NO_DEFAULT_ATTACHMENT; /* We want specific control over where the sound is attached in the graph. We'll attach it manually just before playing the sound. */ + soundFlags |= MA_SOUND_FLAG_NO_PITCH; /* Pitching isn't usable with inlined sounds, so disable it to save on speed. */ + soundFlags |= MA_SOUND_FLAG_NO_SPATIALIZATION; /* Not currently doing spatialization with inlined sounds, but this might actually change later. For now disable spatialization. Will be removed if we ever add support for spatialization here. */ + + result = ma_sound_init_from_file(pEngine, pFilePath, soundFlags, NULL, NULL, &pSound->sound); + if (result == MA_SUCCESS) { + /* Now attach the sound to the graph. */ + result = ma_node_attach_output_bus(pSound, 0, pNode, nodeInputBusIndex); + if (result == MA_SUCCESS) { + /* At this point the sound should be loaded and we can go ahead and add it to the list. The new item becomes the new head. */ + pSound->pNext = pEngine->pInlinedSoundHead; + pSound->pPrev = NULL; + + pEngine->pInlinedSoundHead = pSound; /* <-- This is what attaches the sound to the list. */ + if (pSound->pNext != NULL) { + pSound->pNext->pPrev = pSound; + } + } else { + ma_free(pSound, &pEngine->allocationCallbacks); + } + } else { + ma_free(pSound, &pEngine->allocationCallbacks); + } + } else { + result = MA_OUT_OF_MEMORY; + } + } + ma_spinlock_unlock(&pEngine->inlinedSoundLock); + + if (result != MA_SUCCESS) { + return result; + } + + /* Finally we can start playing the sound. */ + result = ma_sound_start(&pSound->sound); + if (result != MA_SUCCESS) { + /* Failed to start the sound. We need to mark it for recycling and return an error. */ + ma_atomic_exchange_32(&pSound->sound.atEnd, MA_TRUE); + return result; + } + + ma_atomic_fetch_add_32(&pEngine->inlinedSoundCount, 1); + return result; +} + +MA_API ma_result ma_engine_play_sound(ma_engine* pEngine, const char* pFilePath, ma_sound_group* pGroup) +{ + return ma_engine_play_sound_ex(pEngine, pFilePath, pGroup, 0); +} +#endif + + +static ma_result ma_sound_preinit(ma_engine* pEngine, ma_sound* pSound) +{ + if (pSound == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pSound); + pSound->seekTarget = MA_SEEK_TARGET_NONE; + + if (pEngine == NULL) { + return MA_INVALID_ARGS; + } + + return MA_SUCCESS; +} + +static ma_result ma_sound_init_from_data_source_internal(ma_engine* pEngine, const ma_sound_config* pConfig, ma_sound* pSound) +{ + ma_result result; + ma_engine_node_config engineNodeConfig; + ma_engine_node_type type; /* Will be set to ma_engine_node_type_group if no data source is specified. */ + + /* Do not clear pSound to zero here - that's done at a higher level with ma_sound_preinit(). */ + MA_ASSERT(pEngine != NULL); + MA_ASSERT(pSound != NULL); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + pSound->pDataSource = pConfig->pDataSource; + + if (pConfig->pDataSource != NULL) { + type = ma_engine_node_type_sound; + } else { + type = ma_engine_node_type_group; + } + + /* + Sounds are engine nodes. Before we can initialize this we need to determine the channel count. + If we can't do this we need to abort. It's up to the caller to ensure they're using a data + source that provides this information upfront. + */ + engineNodeConfig = ma_engine_node_config_init(pEngine, type, pConfig->flags); + engineNodeConfig.channelsIn = pConfig->channelsIn; + engineNodeConfig.channelsOut = pConfig->channelsOut; + engineNodeConfig.volumeSmoothTimeInPCMFrames = pConfig->volumeSmoothTimeInPCMFrames; + engineNodeConfig.monoExpansionMode = pConfig->monoExpansionMode; + + if (engineNodeConfig.volumeSmoothTimeInPCMFrames == 0) { + engineNodeConfig.volumeSmoothTimeInPCMFrames = pEngine->defaultVolumeSmoothTimeInPCMFrames; + } + + /* If we're loading from a data source the input channel count needs to be the data source's native channel count. */ + if (pConfig->pDataSource != NULL) { + result = ma_data_source_get_data_format(pConfig->pDataSource, NULL, &engineNodeConfig.channelsIn, &engineNodeConfig.sampleRate, NULL, 0); + if (result != MA_SUCCESS) { + return result; /* Failed to retrieve the channel count. */ + } + + if (engineNodeConfig.channelsIn == 0) { + return MA_INVALID_OPERATION; /* Invalid channel count. */ + } + + if (engineNodeConfig.channelsOut == MA_SOUND_SOURCE_CHANNEL_COUNT) { + engineNodeConfig.channelsOut = engineNodeConfig.channelsIn; + } + } + + + /* Getting here means we should have a valid channel count and we can initialize the engine node. */ + result = ma_engine_node_init(&engineNodeConfig, &pEngine->allocationCallbacks, &pSound->engineNode); + if (result != MA_SUCCESS) { + return result; + } + + /* If no attachment is specified, attach the sound straight to the endpoint. */ + if (pConfig->pInitialAttachment == NULL) { + /* No group. Attach straight to the endpoint by default, unless the caller has requested that it not. */ + if ((pConfig->flags & MA_SOUND_FLAG_NO_DEFAULT_ATTACHMENT) == 0) { + result = ma_node_attach_output_bus(pSound, 0, ma_node_graph_get_endpoint(&pEngine->nodeGraph), 0); + } + } else { + /* An attachment is specified. Attach to it by default. The sound has only a single output bus, and the config will specify which input bus to attach to. */ + result = ma_node_attach_output_bus(pSound, 0, pConfig->pInitialAttachment, pConfig->initialAttachmentInputBusIndex); + } + + if (result != MA_SUCCESS) { + ma_engine_node_uninit(&pSound->engineNode, &pEngine->allocationCallbacks); + return result; + } + + + /* Apply initial range and looping state to the data source if applicable. */ + if (pConfig->rangeBegInPCMFrames != 0 || pConfig->rangeEndInPCMFrames != ~((ma_uint64)0)) { + ma_data_source_set_range_in_pcm_frames(ma_sound_get_data_source(pSound), pConfig->rangeBegInPCMFrames, pConfig->rangeEndInPCMFrames); + } + + if (pConfig->loopPointBegInPCMFrames != 0 || pConfig->loopPointEndInPCMFrames != ~((ma_uint64)0)) { + ma_data_source_set_range_in_pcm_frames(ma_sound_get_data_source(pSound), pConfig->loopPointBegInPCMFrames, pConfig->loopPointEndInPCMFrames); + } + + ma_sound_set_looping(pSound, pConfig->isLooping); + + return MA_SUCCESS; +} + +#ifndef MA_NO_RESOURCE_MANAGER +MA_API ma_result ma_sound_init_from_file_internal(ma_engine* pEngine, const ma_sound_config* pConfig, ma_sound* pSound) +{ + ma_result result = MA_SUCCESS; + ma_uint32 flags; + ma_sound_config config; + ma_resource_manager_pipeline_notifications notifications; + + /* + The engine requires knowledge of the channel count of the underlying data source before it can + initialize the sound. Therefore, we need to make the resource manager wait until initialization + of the underlying data source to be initialized so we can get access to the channel count. To + do this, the MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT is forced. + + Because we're initializing the data source before the sound, there's a chance the notification + will get triggered before this function returns. This is OK, so long as the caller is aware of + it and can avoid accessing the sound from within the notification. + */ + flags = pConfig->flags | MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT; + + pSound->pResourceManagerDataSource = (ma_resource_manager_data_source*)ma_malloc(sizeof(*pSound->pResourceManagerDataSource), &pEngine->allocationCallbacks); + if (pSound->pResourceManagerDataSource == NULL) { + return MA_OUT_OF_MEMORY; + } + + /* Removed in 0.12. Set pDoneFence on the notifications. */ + notifications = pConfig->initNotifications; + if (pConfig->pDoneFence != NULL && notifications.done.pFence == NULL) { + notifications.done.pFence = pConfig->pDoneFence; + } + + /* + We must wrap everything around the fence if one was specified. This ensures ma_fence_wait() does + not return prematurely before the sound has finished initializing. + */ + if (notifications.done.pFence) { ma_fence_acquire(notifications.done.pFence); } + { + ma_resource_manager_data_source_config resourceManagerDataSourceConfig = ma_resource_manager_data_source_config_init(); + resourceManagerDataSourceConfig.pFilePath = pConfig->pFilePath; + resourceManagerDataSourceConfig.pFilePathW = pConfig->pFilePathW; + resourceManagerDataSourceConfig.flags = flags; + resourceManagerDataSourceConfig.pNotifications = ¬ifications; + resourceManagerDataSourceConfig.initialSeekPointInPCMFrames = pConfig->initialSeekPointInPCMFrames; + resourceManagerDataSourceConfig.rangeBegInPCMFrames = pConfig->rangeBegInPCMFrames; + resourceManagerDataSourceConfig.rangeEndInPCMFrames = pConfig->rangeEndInPCMFrames; + resourceManagerDataSourceConfig.loopPointBegInPCMFrames = pConfig->loopPointBegInPCMFrames; + resourceManagerDataSourceConfig.loopPointEndInPCMFrames = pConfig->loopPointEndInPCMFrames; + resourceManagerDataSourceConfig.isLooping = pConfig->isLooping; + + result = ma_resource_manager_data_source_init_ex(pEngine->pResourceManager, &resourceManagerDataSourceConfig, pSound->pResourceManagerDataSource); + if (result != MA_SUCCESS) { + goto done; + } + + pSound->ownsDataSource = MA_TRUE; /* <-- Important. Not setting this will result in the resource manager data source never getting uninitialized. */ + + /* We need to use a slightly customized version of the config so we'll need to make a copy. */ + config = *pConfig; + config.pFilePath = NULL; + config.pFilePathW = NULL; + config.pDataSource = pSound->pResourceManagerDataSource; + + result = ma_sound_init_from_data_source_internal(pEngine, &config, pSound); + if (result != MA_SUCCESS) { + ma_resource_manager_data_source_uninit(pSound->pResourceManagerDataSource); + ma_free(pSound->pResourceManagerDataSource, &pEngine->allocationCallbacks); + MA_ZERO_OBJECT(pSound); + goto done; + } + } +done: + if (notifications.done.pFence) { ma_fence_release(notifications.done.pFence); } + return result; +} + +MA_API ma_result ma_sound_init_from_file(ma_engine* pEngine, const char* pFilePath, ma_uint32 flags, ma_sound_group* pGroup, ma_fence* pDoneFence, ma_sound* pSound) +{ + ma_sound_config config; + + if (pFilePath == NULL) { + return MA_INVALID_ARGS; + } + + config = ma_sound_config_init_2(pEngine); + config.pFilePath = pFilePath; + config.flags = flags; + config.pInitialAttachment = pGroup; + config.pDoneFence = pDoneFence; + + return ma_sound_init_ex(pEngine, &config, pSound); +} + +MA_API ma_result ma_sound_init_from_file_w(ma_engine* pEngine, const wchar_t* pFilePath, ma_uint32 flags, ma_sound_group* pGroup, ma_fence* pDoneFence, ma_sound* pSound) +{ + ma_sound_config config; + + if (pFilePath == NULL) { + return MA_INVALID_ARGS; + } + + config = ma_sound_config_init_2(pEngine); + config.pFilePathW = pFilePath; + config.flags = flags; + config.pInitialAttachment = pGroup; + config.pDoneFence = pDoneFence; + + return ma_sound_init_ex(pEngine, &config, pSound); +} + +MA_API ma_result ma_sound_init_copy(ma_engine* pEngine, const ma_sound* pExistingSound, ma_uint32 flags, ma_sound_group* pGroup, ma_sound* pSound) +{ + ma_result result; + ma_sound_config config; + + result = ma_sound_preinit(pEngine, pSound); + if (result != MA_SUCCESS) { + return result; + } + + if (pExistingSound == NULL) { + return MA_INVALID_ARGS; + } + + /* Cloning only works for data buffers (not streams) that are loaded from the resource manager. */ + if (pExistingSound->pResourceManagerDataSource == NULL) { + return MA_INVALID_OPERATION; + } + + /* + We need to make a clone of the data source. If the data source is not a data buffer (i.e. a stream) + this will fail. + */ + pSound->pResourceManagerDataSource = (ma_resource_manager_data_source*)ma_malloc(sizeof(*pSound->pResourceManagerDataSource), &pEngine->allocationCallbacks); + if (pSound->pResourceManagerDataSource == NULL) { + return MA_OUT_OF_MEMORY; + } + + result = ma_resource_manager_data_source_init_copy(pEngine->pResourceManager, pExistingSound->pResourceManagerDataSource, pSound->pResourceManagerDataSource); + if (result != MA_SUCCESS) { + ma_free(pSound->pResourceManagerDataSource, &pEngine->allocationCallbacks); + return result; + } + + config = ma_sound_config_init_2(pEngine); + config.pDataSource = pSound->pResourceManagerDataSource; + config.flags = flags; + config.pInitialAttachment = pGroup; + config.monoExpansionMode = pExistingSound->engineNode.monoExpansionMode; + config.volumeSmoothTimeInPCMFrames = pExistingSound->engineNode.volumeSmoothTimeInPCMFrames; + + result = ma_sound_init_from_data_source_internal(pEngine, &config, pSound); + if (result != MA_SUCCESS) { + ma_resource_manager_data_source_uninit(pSound->pResourceManagerDataSource); + ma_free(pSound->pResourceManagerDataSource, &pEngine->allocationCallbacks); + MA_ZERO_OBJECT(pSound); + return result; + } + + /* Make sure the sound is marked as the owner of the data source or else it will never get uninitialized. */ + pSound->ownsDataSource = MA_TRUE; + + return MA_SUCCESS; +} +#endif + +MA_API ma_result ma_sound_init_from_data_source(ma_engine* pEngine, ma_data_source* pDataSource, ma_uint32 flags, ma_sound_group* pGroup, ma_sound* pSound) +{ + ma_sound_config config = ma_sound_config_init_2(pEngine); + config.pDataSource = pDataSource; + config.flags = flags; + config.pInitialAttachment = pGroup; + return ma_sound_init_ex(pEngine, &config, pSound); +} + +MA_API ma_result ma_sound_init_ex(ma_engine* pEngine, const ma_sound_config* pConfig, ma_sound* pSound) +{ + ma_result result; + + result = ma_sound_preinit(pEngine, pSound); + if (result != MA_SUCCESS) { + return result; + } + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + pSound->endCallback = pConfig->endCallback; + pSound->pEndCallbackUserData = pConfig->pEndCallbackUserData; + + /* We need to load the sound differently depending on whether or not we're loading from a file. */ +#ifndef MA_NO_RESOURCE_MANAGER + if (pConfig->pFilePath != NULL || pConfig->pFilePathW != NULL) { + return ma_sound_init_from_file_internal(pEngine, pConfig, pSound); + } else +#endif + { + /* + Getting here means we're not loading from a file. We may be loading from an already-initialized + data source, or none at all. If we aren't specifying any data source, we'll be initializing the + the equivalent to a group. ma_data_source_init_from_data_source_internal() will deal with this + for us, so no special treatment required here. + */ + return ma_sound_init_from_data_source_internal(pEngine, pConfig, pSound); + } +} + +MA_API void ma_sound_uninit(ma_sound* pSound) +{ + if (pSound == NULL) { + return; + } + + /* + Always uninitialize the node first. This ensures it's detached from the graph and does not return until it has done + so which makes thread safety beyond this point trivial. + */ + ma_engine_node_uninit(&pSound->engineNode, &pSound->engineNode.pEngine->allocationCallbacks); + + /* Once the sound is detached from the group we can guarantee that it won't be referenced by the mixer thread which means it's safe for us to destroy the data source. */ +#ifndef MA_NO_RESOURCE_MANAGER + if (pSound->ownsDataSource) { + ma_resource_manager_data_source_uninit(pSound->pResourceManagerDataSource); + ma_free(pSound->pResourceManagerDataSource, &pSound->engineNode.pEngine->allocationCallbacks); + pSound->pDataSource = NULL; + } +#else + MA_ASSERT(pSound->ownsDataSource == MA_FALSE); +#endif +} + +MA_API ma_engine* ma_sound_get_engine(const ma_sound* pSound) +{ + if (pSound == NULL) { + return NULL; + } + + return pSound->engineNode.pEngine; +} + +MA_API ma_data_source* ma_sound_get_data_source(const ma_sound* pSound) +{ + if (pSound == NULL) { + return NULL; + } + + return pSound->pDataSource; +} + +MA_API ma_result ma_sound_start(ma_sound* pSound) +{ + if (pSound == NULL) { + return MA_INVALID_ARGS; + } + + /* If the sound is already playing, do nothing. */ + if (ma_sound_is_playing(pSound)) { + return MA_SUCCESS; + } + + /* If the sound is at the end it means we want to start from the start again. */ + if (ma_sound_at_end(pSound)) { + ma_result result = ma_data_source_seek_to_pcm_frame(pSound->pDataSource, 0); + if (result != MA_SUCCESS && result != MA_NOT_IMPLEMENTED) { + return result; /* Failed to seek back to the start. */ + } + + /* Make sure we clear the end indicator. */ + ma_atomic_exchange_32(&pSound->atEnd, MA_FALSE); + } + + /* Make sure the sound is started. If there's a start delay, the sound won't actually start until the start time is reached. */ + ma_node_set_state(pSound, ma_node_state_started); + + return MA_SUCCESS; +} + +MA_API ma_result ma_sound_stop(ma_sound* pSound) +{ + if (pSound == NULL) { + return MA_INVALID_ARGS; + } + + /* This will stop the sound immediately. Use ma_sound_set_stop_time() to stop the sound at a specific time. */ + ma_node_set_state(pSound, ma_node_state_stopped); + + return MA_SUCCESS; +} + +MA_API ma_result ma_sound_stop_with_fade_in_pcm_frames(ma_sound* pSound, ma_uint64 fadeLengthInFrames) +{ + if (pSound == NULL) { + return MA_INVALID_ARGS; + } + + /* Stopping with a fade out requires us to schedule the stop into the future by the fade length. */ + ma_sound_set_stop_time_with_fade_in_pcm_frames(pSound, ma_engine_get_time_in_pcm_frames(ma_sound_get_engine(pSound)) + fadeLengthInFrames, fadeLengthInFrames); + + return MA_SUCCESS; +} + +MA_API ma_result ma_sound_stop_with_fade_in_milliseconds(ma_sound* pSound, ma_uint64 fadeLengthInMilliseconds) +{ + ma_uint64 sampleRate; + + if (pSound == NULL) { + return MA_INVALID_ARGS; + } + + sampleRate = ma_engine_get_sample_rate(ma_sound_get_engine(pSound)); + + return ma_sound_stop_with_fade_in_pcm_frames(pSound, (fadeLengthInMilliseconds * sampleRate) / 1000); +} + +MA_API void ma_sound_set_volume(ma_sound* pSound, float volume) +{ + if (pSound == NULL) { + return; + } + + ma_engine_node_set_volume(&pSound->engineNode, volume); +} + +MA_API float ma_sound_get_volume(const ma_sound* pSound) +{ + float volume = 0; + + if (pSound == NULL) { + return 0; + } + + ma_engine_node_get_volume(&pSound->engineNode, &volume); + + return volume; +} + +MA_API void ma_sound_set_pan(ma_sound* pSound, float pan) +{ + if (pSound == NULL) { + return; + } + + ma_panner_set_pan(&pSound->engineNode.panner, pan); +} + +MA_API float ma_sound_get_pan(const ma_sound* pSound) +{ + if (pSound == NULL) { + return 0; + } + + return ma_panner_get_pan(&pSound->engineNode.panner); +} + +MA_API void ma_sound_set_pan_mode(ma_sound* pSound, ma_pan_mode panMode) +{ + if (pSound == NULL) { + return; + } + + ma_panner_set_mode(&pSound->engineNode.panner, panMode); +} + +MA_API ma_pan_mode ma_sound_get_pan_mode(const ma_sound* pSound) +{ + if (pSound == NULL) { + return ma_pan_mode_balance; + } + + return ma_panner_get_mode(&pSound->engineNode.panner); +} + +MA_API void ma_sound_set_pitch(ma_sound* pSound, float pitch) +{ + if (pSound == NULL) { + return; + } + + if (pitch <= 0) { + return; + } + + ma_atomic_exchange_explicit_f32(&pSound->engineNode.pitch, pitch, ma_atomic_memory_order_release); +} + +MA_API float ma_sound_get_pitch(const ma_sound* pSound) +{ + if (pSound == NULL) { + return 0; + } + + return ma_atomic_load_f32(&pSound->engineNode.pitch); /* Naughty const-cast for this. */ +} + +MA_API void ma_sound_set_spatialization_enabled(ma_sound* pSound, ma_bool32 enabled) +{ + if (pSound == NULL) { + return; + } + + ma_atomic_exchange_explicit_32(&pSound->engineNode.isSpatializationDisabled, !enabled, ma_atomic_memory_order_release); +} + +MA_API ma_bool32 ma_sound_is_spatialization_enabled(const ma_sound* pSound) +{ + if (pSound == NULL) { + return MA_FALSE; + } + + return ma_engine_node_is_spatialization_enabled(&pSound->engineNode); +} + +MA_API void ma_sound_set_pinned_listener_index(ma_sound* pSound, ma_uint32 listenerIndex) +{ + if (pSound == NULL || listenerIndex >= ma_engine_get_listener_count(ma_sound_get_engine(pSound))) { + return; + } + + ma_atomic_exchange_explicit_32(&pSound->engineNode.pinnedListenerIndex, listenerIndex, ma_atomic_memory_order_release); +} + +MA_API ma_uint32 ma_sound_get_pinned_listener_index(const ma_sound* pSound) +{ + if (pSound == NULL) { + return MA_LISTENER_INDEX_CLOSEST; + } + + return ma_atomic_load_explicit_32(&pSound->engineNode.pinnedListenerIndex, ma_atomic_memory_order_acquire); +} + +MA_API ma_uint32 ma_sound_get_listener_index(const ma_sound* pSound) +{ + ma_uint32 listenerIndex; + + if (pSound == NULL) { + return 0; + } + + listenerIndex = ma_sound_get_pinned_listener_index(pSound); + if (listenerIndex == MA_LISTENER_INDEX_CLOSEST) { + ma_vec3f position = ma_sound_get_position(pSound); + return ma_engine_find_closest_listener(ma_sound_get_engine(pSound), position.x, position.y, position.z); + } + + return listenerIndex; +} + +MA_API ma_vec3f ma_sound_get_direction_to_listener(const ma_sound* pSound) +{ + ma_vec3f relativePos; + ma_engine* pEngine; + + if (pSound == NULL) { + return ma_vec3f_init_3f(0, 0, -1); + } + + pEngine = ma_sound_get_engine(pSound); + if (pEngine == NULL) { + return ma_vec3f_init_3f(0, 0, -1); + } + + ma_spatializer_get_relative_position_and_direction(&pSound->engineNode.spatializer, &pEngine->listeners[ma_sound_get_listener_index(pSound)], &relativePos, NULL); + + return ma_vec3f_normalize(ma_vec3f_neg(relativePos)); +} + +MA_API void ma_sound_set_position(ma_sound* pSound, float x, float y, float z) +{ + if (pSound == NULL) { + return; + } + + ma_spatializer_set_position(&pSound->engineNode.spatializer, x, y, z); +} + +MA_API ma_vec3f ma_sound_get_position(const ma_sound* pSound) +{ + if (pSound == NULL) { + return ma_vec3f_init_3f(0, 0, 0); + } + + return ma_spatializer_get_position(&pSound->engineNode.spatializer); +} + +MA_API void ma_sound_set_direction(ma_sound* pSound, float x, float y, float z) +{ + if (pSound == NULL) { + return; + } + + ma_spatializer_set_direction(&pSound->engineNode.spatializer, x, y, z); +} + +MA_API ma_vec3f ma_sound_get_direction(const ma_sound* pSound) +{ + if (pSound == NULL) { + return ma_vec3f_init_3f(0, 0, 0); + } + + return ma_spatializer_get_direction(&pSound->engineNode.spatializer); +} + +MA_API void ma_sound_set_velocity(ma_sound* pSound, float x, float y, float z) +{ + if (pSound == NULL) { + return; + } + + ma_spatializer_set_velocity(&pSound->engineNode.spatializer, x, y, z); +} + +MA_API ma_vec3f ma_sound_get_velocity(const ma_sound* pSound) +{ + if (pSound == NULL) { + return ma_vec3f_init_3f(0, 0, 0); + } + + return ma_spatializer_get_velocity(&pSound->engineNode.spatializer); +} + +MA_API void ma_sound_set_attenuation_model(ma_sound* pSound, ma_attenuation_model attenuationModel) +{ + if (pSound == NULL) { + return; + } + + ma_spatializer_set_attenuation_model(&pSound->engineNode.spatializer, attenuationModel); +} + +MA_API ma_attenuation_model ma_sound_get_attenuation_model(const ma_sound* pSound) +{ + if (pSound == NULL) { + return ma_attenuation_model_none; + } + + return ma_spatializer_get_attenuation_model(&pSound->engineNode.spatializer); +} + +MA_API void ma_sound_set_positioning(ma_sound* pSound, ma_positioning positioning) +{ + if (pSound == NULL) { + return; + } + + ma_spatializer_set_positioning(&pSound->engineNode.spatializer, positioning); +} + +MA_API ma_positioning ma_sound_get_positioning(const ma_sound* pSound) +{ + if (pSound == NULL) { + return ma_positioning_absolute; + } + + return ma_spatializer_get_positioning(&pSound->engineNode.spatializer); +} + +MA_API void ma_sound_set_rolloff(ma_sound* pSound, float rolloff) +{ + if (pSound == NULL) { + return; + } + + ma_spatializer_set_rolloff(&pSound->engineNode.spatializer, rolloff); +} + +MA_API float ma_sound_get_rolloff(const ma_sound* pSound) +{ + if (pSound == NULL) { + return 0; + } + + return ma_spatializer_get_rolloff(&pSound->engineNode.spatializer); +} + +MA_API void ma_sound_set_min_gain(ma_sound* pSound, float minGain) +{ + if (pSound == NULL) { + return; + } + + ma_spatializer_set_min_gain(&pSound->engineNode.spatializer, minGain); +} + +MA_API float ma_sound_get_min_gain(const ma_sound* pSound) +{ + if (pSound == NULL) { + return 0; + } + + return ma_spatializer_get_min_gain(&pSound->engineNode.spatializer); +} + +MA_API void ma_sound_set_max_gain(ma_sound* pSound, float maxGain) +{ + if (pSound == NULL) { + return; + } + + ma_spatializer_set_max_gain(&pSound->engineNode.spatializer, maxGain); +} + +MA_API float ma_sound_get_max_gain(const ma_sound* pSound) +{ + if (pSound == NULL) { + return 0; + } + + return ma_spatializer_get_max_gain(&pSound->engineNode.spatializer); +} + +MA_API void ma_sound_set_min_distance(ma_sound* pSound, float minDistance) +{ + if (pSound == NULL) { + return; + } + + ma_spatializer_set_min_distance(&pSound->engineNode.spatializer, minDistance); +} + +MA_API float ma_sound_get_min_distance(const ma_sound* pSound) +{ + if (pSound == NULL) { + return 0; + } + + return ma_spatializer_get_min_distance(&pSound->engineNode.spatializer); +} + +MA_API void ma_sound_set_max_distance(ma_sound* pSound, float maxDistance) +{ + if (pSound == NULL) { + return; + } + + ma_spatializer_set_max_distance(&pSound->engineNode.spatializer, maxDistance); +} + +MA_API float ma_sound_get_max_distance(const ma_sound* pSound) +{ + if (pSound == NULL) { + return 0; + } + + return ma_spatializer_get_max_distance(&pSound->engineNode.spatializer); +} + +MA_API void ma_sound_set_cone(ma_sound* pSound, float innerAngleInRadians, float outerAngleInRadians, float outerGain) +{ + if (pSound == NULL) { + return; + } + + ma_spatializer_set_cone(&pSound->engineNode.spatializer, innerAngleInRadians, outerAngleInRadians, outerGain); +} + +MA_API void ma_sound_get_cone(const ma_sound* pSound, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain) +{ + if (pInnerAngleInRadians != NULL) { + *pInnerAngleInRadians = 0; + } + + if (pOuterAngleInRadians != NULL) { + *pOuterAngleInRadians = 0; + } + + if (pOuterGain != NULL) { + *pOuterGain = 0; + } + + if (pSound == NULL) { + return; + } + + ma_spatializer_get_cone(&pSound->engineNode.spatializer, pInnerAngleInRadians, pOuterAngleInRadians, pOuterGain); +} + +MA_API void ma_sound_set_doppler_factor(ma_sound* pSound, float dopplerFactor) +{ + if (pSound == NULL) { + return; + } + + ma_spatializer_set_doppler_factor(&pSound->engineNode.spatializer, dopplerFactor); +} + +MA_API float ma_sound_get_doppler_factor(const ma_sound* pSound) +{ + if (pSound == NULL) { + return 0; + } + + return ma_spatializer_get_doppler_factor(&pSound->engineNode.spatializer); +} + +MA_API void ma_sound_set_directional_attenuation_factor(ma_sound* pSound, float directionalAttenuationFactor) +{ + if (pSound == NULL) { + return; + } + + ma_spatializer_set_directional_attenuation_factor(&pSound->engineNode.spatializer, directionalAttenuationFactor); +} + +MA_API float ma_sound_get_directional_attenuation_factor(const ma_sound* pSound) +{ + if (pSound == NULL) { + return 1; + } + + return ma_spatializer_get_directional_attenuation_factor(&pSound->engineNode.spatializer); +} + + +MA_API void ma_sound_set_fade_in_pcm_frames(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInFrames) +{ + if (pSound == NULL) { + return; + } + + ma_sound_set_fade_start_in_pcm_frames(pSound, volumeBeg, volumeEnd, fadeLengthInFrames, (~(ma_uint64)0)); +} + +MA_API void ma_sound_set_fade_in_milliseconds(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInMilliseconds) +{ + if (pSound == NULL) { + return; + } + + ma_sound_set_fade_in_pcm_frames(pSound, volumeBeg, volumeEnd, (fadeLengthInMilliseconds * pSound->engineNode.fader.config.sampleRate) / 1000); +} + +MA_API void ma_sound_set_fade_start_in_pcm_frames(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInFrames, ma_uint64 absoluteGlobalTimeInFrames) +{ + if (pSound == NULL) { + return; + } + + /* + We don't want to update the fader at this point because we need to use the engine's current time + to derive the fader's start offset. The timer is being updated on the audio thread so in order to + do this as accurately as possible we'll need to defer this to the audio thread. + */ + ma_atomic_float_set(&pSound->engineNode.fadeSettings.volumeBeg, volumeBeg); + ma_atomic_float_set(&pSound->engineNode.fadeSettings.volumeEnd, volumeEnd); + ma_atomic_uint64_set(&pSound->engineNode.fadeSettings.fadeLengthInFrames, fadeLengthInFrames); + ma_atomic_uint64_set(&pSound->engineNode.fadeSettings.absoluteGlobalTimeInFrames, absoluteGlobalTimeInFrames); +} + +MA_API void ma_sound_set_fade_start_in_milliseconds(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInMilliseconds, ma_uint64 absoluteGlobalTimeInMilliseconds) +{ + ma_uint32 sampleRate; + + if (pSound == NULL) { + return; + } + + sampleRate = ma_engine_get_sample_rate(ma_sound_get_engine(pSound)); + + ma_sound_set_fade_start_in_pcm_frames(pSound, volumeBeg, volumeEnd, (fadeLengthInMilliseconds * sampleRate) / 1000, (absoluteGlobalTimeInMilliseconds * sampleRate) / 1000); +} + +MA_API float ma_sound_get_current_fade_volume(const ma_sound* pSound) +{ + if (pSound == NULL) { + return MA_INVALID_ARGS; + } + + return ma_fader_get_current_volume(&pSound->engineNode.fader); +} + +MA_API void ma_sound_set_start_time_in_pcm_frames(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInFrames) +{ + if (pSound == NULL) { + return; + } + + ma_node_set_state_time(pSound, ma_node_state_started, absoluteGlobalTimeInFrames); +} + +MA_API void ma_sound_set_start_time_in_milliseconds(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInMilliseconds) +{ + if (pSound == NULL) { + return; + } + + ma_sound_set_start_time_in_pcm_frames(pSound, absoluteGlobalTimeInMilliseconds * ma_engine_get_sample_rate(ma_sound_get_engine(pSound)) / 1000); +} + +MA_API void ma_sound_set_stop_time_in_pcm_frames(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInFrames) +{ + if (pSound == NULL) { + return; + } + + ma_sound_set_stop_time_with_fade_in_pcm_frames(pSound, absoluteGlobalTimeInFrames, 0); +} + +MA_API void ma_sound_set_stop_time_in_milliseconds(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInMilliseconds) +{ + if (pSound == NULL) { + return; + } + + ma_sound_set_stop_time_in_pcm_frames(pSound, absoluteGlobalTimeInMilliseconds * ma_engine_get_sample_rate(ma_sound_get_engine(pSound)) / 1000); +} + +MA_API void ma_sound_set_stop_time_with_fade_in_pcm_frames(ma_sound* pSound, ma_uint64 stopAbsoluteGlobalTimeInFrames, ma_uint64 fadeLengthInFrames) +{ + if (pSound == NULL) { + return; + } + + if (fadeLengthInFrames > 0) { + if (fadeLengthInFrames > stopAbsoluteGlobalTimeInFrames) { + fadeLengthInFrames = stopAbsoluteGlobalTimeInFrames; + } + + ma_sound_set_fade_start_in_pcm_frames(pSound, -1, 0, fadeLengthInFrames, stopAbsoluteGlobalTimeInFrames - fadeLengthInFrames); + } + + ma_node_set_state_time(pSound, ma_node_state_stopped, stopAbsoluteGlobalTimeInFrames); +} + +MA_API void ma_sound_set_stop_time_with_fade_in_milliseconds(ma_sound* pSound, ma_uint64 stopAbsoluteGlobalTimeInMilliseconds, ma_uint64 fadeLengthInMilliseconds) +{ + ma_uint32 sampleRate; + + if (pSound == NULL) { + return; + } + + sampleRate = ma_engine_get_sample_rate(ma_sound_get_engine(pSound)); + + ma_sound_set_stop_time_with_fade_in_pcm_frames(pSound, (stopAbsoluteGlobalTimeInMilliseconds * sampleRate) / 1000, (fadeLengthInMilliseconds * sampleRate) / 1000); +} + +MA_API ma_bool32 ma_sound_is_playing(const ma_sound* pSound) +{ + if (pSound == NULL) { + return MA_FALSE; + } + + return ma_node_get_state_by_time(pSound, ma_engine_get_time_in_pcm_frames(ma_sound_get_engine(pSound))) == ma_node_state_started; +} + +MA_API ma_uint64 ma_sound_get_time_in_pcm_frames(const ma_sound* pSound) +{ + if (pSound == NULL) { + return 0; + } + + return ma_node_get_time(pSound); +} + +MA_API ma_uint64 ma_sound_get_time_in_milliseconds(const ma_sound* pSound) +{ + return ma_sound_get_time_in_pcm_frames(pSound) * 1000 / ma_engine_get_sample_rate(ma_sound_get_engine(pSound)); +} + +MA_API void ma_sound_set_looping(ma_sound* pSound, ma_bool32 isLooping) +{ + if (pSound == NULL) { + return; + } + + /* Looping is only a valid concept if the sound is backed by a data source. */ + if (pSound->pDataSource == NULL) { + return; + } + + /* The looping state needs to be applied to the data source in order for any looping to actually happen. */ + ma_data_source_set_looping(pSound->pDataSource, isLooping); +} + +MA_API ma_bool32 ma_sound_is_looping(const ma_sound* pSound) +{ + if (pSound == NULL) { + return MA_FALSE; + } + + /* There is no notion of looping for sounds that are not backed by a data source. */ + if (pSound->pDataSource == NULL) { + return MA_FALSE; + } + + return ma_data_source_is_looping(pSound->pDataSource); +} + +MA_API ma_bool32 ma_sound_at_end(const ma_sound* pSound) +{ + if (pSound == NULL) { + return MA_FALSE; + } + + /* There is no notion of an end of a sound if it's not backed by a data source. */ + if (pSound->pDataSource == NULL) { + return MA_FALSE; + } + + return ma_sound_get_at_end(pSound); +} + +MA_API ma_result ma_sound_seek_to_pcm_frame(ma_sound* pSound, ma_uint64 frameIndex) +{ + if (pSound == NULL) { + return MA_INVALID_ARGS; + } + + /* Seeking is only valid for sounds that are backed by a data source. */ + if (pSound->pDataSource == NULL) { + return MA_INVALID_OPERATION; + } + + /* We can't be seeking while reading at the same time. We just set the seek target and get the mixing thread to do the actual seek. */ + ma_atomic_exchange_64(&pSound->seekTarget, frameIndex); + + return MA_SUCCESS; +} + +MA_API ma_result ma_sound_get_data_format(ma_sound* pSound, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap) +{ + if (pSound == NULL) { + return MA_INVALID_ARGS; + } + + /* The data format is retrieved directly from the data source if the sound is backed by one. Otherwise we pull it from the node. */ + if (pSound->pDataSource == NULL) { + ma_uint32 channels; + + if (pFormat != NULL) { + *pFormat = ma_format_f32; + } + + channels = ma_node_get_input_channels(&pSound->engineNode, 0); + if (pChannels != NULL) { + *pChannels = channels; + } + + if (pSampleRate != NULL) { + *pSampleRate = pSound->engineNode.resampler.config.sampleRateIn; + } + + if (pChannelMap != NULL) { + ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, channels); + } + + return MA_SUCCESS; + } else { + return ma_data_source_get_data_format(pSound->pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap); + } +} + +MA_API ma_result ma_sound_get_cursor_in_pcm_frames(ma_sound* pSound, ma_uint64* pCursor) +{ + ma_uint64 seekTarget; + + if (pSound == NULL) { + return MA_INVALID_ARGS; + } + + /* The notion of a cursor is only valid for sounds that are backed by a data source. */ + if (pSound->pDataSource == NULL) { + return MA_INVALID_OPERATION; + } + + seekTarget = ma_atomic_load_64(&pSound->seekTarget); + if (seekTarget != MA_SEEK_TARGET_NONE) { + *pCursor = seekTarget; + return MA_SUCCESS; + } else { + return ma_data_source_get_cursor_in_pcm_frames(pSound->pDataSource, pCursor); + } +} + +MA_API ma_result ma_sound_get_length_in_pcm_frames(ma_sound* pSound, ma_uint64* pLength) +{ + if (pSound == NULL) { + return MA_INVALID_ARGS; + } + + /* The notion of a sound length is only valid for sounds that are backed by a data source. */ + if (pSound->pDataSource == NULL) { + return MA_INVALID_OPERATION; + } + + return ma_data_source_get_length_in_pcm_frames(pSound->pDataSource, pLength); +} + +MA_API ma_result ma_sound_get_cursor_in_seconds(ma_sound* pSound, float* pCursor) +{ + ma_result result; + ma_uint64 cursorInPCMFrames; + ma_uint32 sampleRate; + + if (pCursor != NULL) { + *pCursor = 0; + } + + result = ma_sound_get_cursor_in_pcm_frames(pSound, &cursorInPCMFrames); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_sound_get_data_format(pSound, NULL, NULL, &sampleRate, NULL, 0); + if (result != MA_SUCCESS) { + return result; + } + + /* VC6 does not support division of unsigned 64-bit integers with floating point numbers. Need to use a signed number. This shouldn't effect anything in practice. */ + *pCursor = (ma_int64)cursorInPCMFrames / (float)sampleRate; + + return MA_SUCCESS; +} + +MA_API ma_result ma_sound_get_length_in_seconds(ma_sound* pSound, float* pLength) +{ + if (pSound == NULL) { + return MA_INVALID_ARGS; + } + + /* The notion of a sound length is only valid for sounds that are backed by a data source. */ + if (pSound->pDataSource == NULL) { + return MA_INVALID_OPERATION; + } + + return ma_data_source_get_length_in_seconds(pSound->pDataSource, pLength); +} + +MA_API ma_result ma_sound_set_end_callback(ma_sound* pSound, ma_sound_end_proc callback, void* pUserData) +{ + if (pSound == NULL) { + return MA_INVALID_ARGS; + } + + /* The notion of an end is only valid for sounds that are backed by a data source. */ + if (pSound->pDataSource == NULL) { + return MA_INVALID_OPERATION; + } + + pSound->endCallback = callback; + pSound->pEndCallbackUserData = pUserData; + + return MA_SUCCESS; +} + + +MA_API ma_result ma_sound_group_init(ma_engine* pEngine, ma_uint32 flags, ma_sound_group* pParentGroup, ma_sound_group* pGroup) +{ + ma_sound_group_config config = ma_sound_group_config_init_2(pEngine); + config.flags = flags; + config.pInitialAttachment = pParentGroup; + return ma_sound_group_init_ex(pEngine, &config, pGroup); +} + +MA_API ma_result ma_sound_group_init_ex(ma_engine* pEngine, const ma_sound_group_config* pConfig, ma_sound_group* pGroup) +{ + ma_sound_config soundConfig; + + if (pGroup == NULL) { + return MA_INVALID_ARGS; + } + + MA_ZERO_OBJECT(pGroup); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + /* A sound group is just a sound without a data source. */ + soundConfig = *pConfig; + soundConfig.pFilePath = NULL; + soundConfig.pFilePathW = NULL; + soundConfig.pDataSource = NULL; + + /* + Groups need to have spatialization disabled by default because I think it'll be pretty rare + that programs will want to spatialize groups (but not unheard of). Certainly it feels like + disabling this by default feels like the right option. Spatialization can be enabled with a + call to ma_sound_group_set_spatialization_enabled(). + */ + soundConfig.flags |= MA_SOUND_FLAG_NO_SPATIALIZATION; + + return ma_sound_init_ex(pEngine, &soundConfig, pGroup); +} + +MA_API void ma_sound_group_uninit(ma_sound_group* pGroup) +{ + ma_sound_uninit(pGroup); +} + +MA_API ma_engine* ma_sound_group_get_engine(const ma_sound_group* pGroup) +{ + return ma_sound_get_engine(pGroup); +} + +MA_API ma_result ma_sound_group_start(ma_sound_group* pGroup) +{ + return ma_sound_start(pGroup); +} + +MA_API ma_result ma_sound_group_stop(ma_sound_group* pGroup) +{ + return ma_sound_stop(pGroup); +} + +MA_API void ma_sound_group_set_volume(ma_sound_group* pGroup, float volume) +{ + ma_sound_set_volume(pGroup, volume); +} + +MA_API float ma_sound_group_get_volume(const ma_sound_group* pGroup) +{ + return ma_sound_get_volume(pGroup); +} + +MA_API void ma_sound_group_set_pan(ma_sound_group* pGroup, float pan) +{ + ma_sound_set_pan(pGroup, pan); +} + +MA_API float ma_sound_group_get_pan(const ma_sound_group* pGroup) +{ + return ma_sound_get_pan(pGroup); +} + +MA_API void ma_sound_group_set_pan_mode(ma_sound_group* pGroup, ma_pan_mode panMode) +{ + ma_sound_set_pan_mode(pGroup, panMode); +} + +MA_API ma_pan_mode ma_sound_group_get_pan_mode(const ma_sound_group* pGroup) +{ + return ma_sound_get_pan_mode(pGroup); +} + +MA_API void ma_sound_group_set_pitch(ma_sound_group* pGroup, float pitch) +{ + ma_sound_set_pitch(pGroup, pitch); +} + +MA_API float ma_sound_group_get_pitch(const ma_sound_group* pGroup) +{ + return ma_sound_get_pitch(pGroup); +} + +MA_API void ma_sound_group_set_spatialization_enabled(ma_sound_group* pGroup, ma_bool32 enabled) +{ + ma_sound_set_spatialization_enabled(pGroup, enabled); +} + +MA_API ma_bool32 ma_sound_group_is_spatialization_enabled(const ma_sound_group* pGroup) +{ + return ma_sound_is_spatialization_enabled(pGroup); +} + +MA_API void ma_sound_group_set_pinned_listener_index(ma_sound_group* pGroup, ma_uint32 listenerIndex) +{ + ma_sound_set_pinned_listener_index(pGroup, listenerIndex); +} + +MA_API ma_uint32 ma_sound_group_get_pinned_listener_index(const ma_sound_group* pGroup) +{ + return ma_sound_get_pinned_listener_index(pGroup); +} + +MA_API ma_uint32 ma_sound_group_get_listener_index(const ma_sound_group* pGroup) +{ + return ma_sound_get_listener_index(pGroup); +} + +MA_API ma_vec3f ma_sound_group_get_direction_to_listener(const ma_sound_group* pGroup) +{ + return ma_sound_get_direction_to_listener(pGroup); +} + +MA_API void ma_sound_group_set_position(ma_sound_group* pGroup, float x, float y, float z) +{ + ma_sound_set_position(pGroup, x, y, z); +} + +MA_API ma_vec3f ma_sound_group_get_position(const ma_sound_group* pGroup) +{ + return ma_sound_get_position(pGroup); +} + +MA_API void ma_sound_group_set_direction(ma_sound_group* pGroup, float x, float y, float z) +{ + ma_sound_set_direction(pGroup, x, y, z); +} + +MA_API ma_vec3f ma_sound_group_get_direction(const ma_sound_group* pGroup) +{ + return ma_sound_get_direction(pGroup); +} + +MA_API void ma_sound_group_set_velocity(ma_sound_group* pGroup, float x, float y, float z) +{ + ma_sound_set_velocity(pGroup, x, y, z); +} + +MA_API ma_vec3f ma_sound_group_get_velocity(const ma_sound_group* pGroup) +{ + return ma_sound_get_velocity(pGroup); +} + +MA_API void ma_sound_group_set_attenuation_model(ma_sound_group* pGroup, ma_attenuation_model attenuationModel) +{ + ma_sound_set_attenuation_model(pGroup, attenuationModel); +} + +MA_API ma_attenuation_model ma_sound_group_get_attenuation_model(const ma_sound_group* pGroup) +{ + return ma_sound_get_attenuation_model(pGroup); +} + +MA_API void ma_sound_group_set_positioning(ma_sound_group* pGroup, ma_positioning positioning) +{ + ma_sound_set_positioning(pGroup, positioning); +} + +MA_API ma_positioning ma_sound_group_get_positioning(const ma_sound_group* pGroup) +{ + return ma_sound_get_positioning(pGroup); +} + +MA_API void ma_sound_group_set_rolloff(ma_sound_group* pGroup, float rolloff) +{ + ma_sound_set_rolloff(pGroup, rolloff); +} + +MA_API float ma_sound_group_get_rolloff(const ma_sound_group* pGroup) +{ + return ma_sound_get_rolloff(pGroup); +} + +MA_API void ma_sound_group_set_min_gain(ma_sound_group* pGroup, float minGain) +{ + ma_sound_set_min_gain(pGroup, minGain); +} + +MA_API float ma_sound_group_get_min_gain(const ma_sound_group* pGroup) +{ + return ma_sound_get_min_gain(pGroup); +} + +MA_API void ma_sound_group_set_max_gain(ma_sound_group* pGroup, float maxGain) +{ + ma_sound_set_max_gain(pGroup, maxGain); +} + +MA_API float ma_sound_group_get_max_gain(const ma_sound_group* pGroup) +{ + return ma_sound_get_max_gain(pGroup); +} + +MA_API void ma_sound_group_set_min_distance(ma_sound_group* pGroup, float minDistance) +{ + ma_sound_set_min_distance(pGroup, minDistance); +} + +MA_API float ma_sound_group_get_min_distance(const ma_sound_group* pGroup) +{ + return ma_sound_get_min_distance(pGroup); +} + +MA_API void ma_sound_group_set_max_distance(ma_sound_group* pGroup, float maxDistance) +{ + ma_sound_set_max_distance(pGroup, maxDistance); +} + +MA_API float ma_sound_group_get_max_distance(const ma_sound_group* pGroup) +{ + return ma_sound_get_max_distance(pGroup); +} + +MA_API void ma_sound_group_set_cone(ma_sound_group* pGroup, float innerAngleInRadians, float outerAngleInRadians, float outerGain) +{ + ma_sound_set_cone(pGroup, innerAngleInRadians, outerAngleInRadians, outerGain); +} + +MA_API void ma_sound_group_get_cone(const ma_sound_group* pGroup, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain) +{ + ma_sound_get_cone(pGroup, pInnerAngleInRadians, pOuterAngleInRadians, pOuterGain); +} + +MA_API void ma_sound_group_set_doppler_factor(ma_sound_group* pGroup, float dopplerFactor) +{ + ma_sound_set_doppler_factor(pGroup, dopplerFactor); +} + +MA_API float ma_sound_group_get_doppler_factor(const ma_sound_group* pGroup) +{ + return ma_sound_get_doppler_factor(pGroup); +} + +MA_API void ma_sound_group_set_directional_attenuation_factor(ma_sound_group* pGroup, float directionalAttenuationFactor) +{ + ma_sound_set_directional_attenuation_factor(pGroup, directionalAttenuationFactor); +} + +MA_API float ma_sound_group_get_directional_attenuation_factor(const ma_sound_group* pGroup) +{ + return ma_sound_get_directional_attenuation_factor(pGroup); +} + +MA_API void ma_sound_group_set_fade_in_pcm_frames(ma_sound_group* pGroup, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInFrames) +{ + ma_sound_set_fade_in_pcm_frames(pGroup, volumeBeg, volumeEnd, fadeLengthInFrames); +} + +MA_API void ma_sound_group_set_fade_in_milliseconds(ma_sound_group* pGroup, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInMilliseconds) +{ + ma_sound_set_fade_in_milliseconds(pGroup, volumeBeg, volumeEnd, fadeLengthInMilliseconds); +} + +MA_API float ma_sound_group_get_current_fade_volume(ma_sound_group* pGroup) +{ + return ma_sound_get_current_fade_volume(pGroup); +} + +MA_API void ma_sound_group_set_start_time_in_pcm_frames(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInFrames) +{ + ma_sound_set_start_time_in_pcm_frames(pGroup, absoluteGlobalTimeInFrames); +} + +MA_API void ma_sound_group_set_start_time_in_milliseconds(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInMilliseconds) +{ + ma_sound_set_start_time_in_milliseconds(pGroup, absoluteGlobalTimeInMilliseconds); +} + +MA_API void ma_sound_group_set_stop_time_in_pcm_frames(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInFrames) +{ + ma_sound_set_stop_time_in_pcm_frames(pGroup, absoluteGlobalTimeInFrames); +} + +MA_API void ma_sound_group_set_stop_time_in_milliseconds(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInMilliseconds) +{ + ma_sound_set_stop_time_in_milliseconds(pGroup, absoluteGlobalTimeInMilliseconds); +} + +MA_API ma_bool32 ma_sound_group_is_playing(const ma_sound_group* pGroup) +{ + return ma_sound_is_playing(pGroup); +} + +MA_API ma_uint64 ma_sound_group_get_time_in_pcm_frames(const ma_sound_group* pGroup) +{ + return ma_sound_get_time_in_pcm_frames(pGroup); +} +#endif /* MA_NO_ENGINE */ +/* END SECTION: miniaudio_engine.c */ + + + +/************************************************************************************************************************************************************** +*************************************************************************************************************************************************************** + +Auto Generated +============== +All code below is auto-generated from a tool. This mostly consists of decoding backend implementations such as ma_dr_wav, ma_dr_flac, etc. If you find a bug in the +code below please report the bug to the respective repository for the relevant project (probably dr_libs). + +*************************************************************************************************************************************************************** +**************************************************************************************************************************************************************/ +#if !defined(MA_NO_WAV) && (!defined(MA_NO_DECODING) || !defined(MA_NO_ENCODING)) +#if !defined(MA_DR_WAV_IMPLEMENTATION) && !defined(MA_DR_WAV_IMPLEMENTATION) /* For backwards compatibility. Will be removed in version 0.11 for cleanliness. */ +/* dr_wav_c begin */ +#ifndef ma_dr_wav_c +#define ma_dr_wav_c +#ifdef __MRC__ +#pragma options opt off +#endif +#include +#include +#include +#ifndef MA_DR_WAV_NO_STDIO +#include +#ifndef MA_DR_WAV_NO_WCHAR +#include +#endif +#endif +#ifndef MA_DR_WAV_ASSERT +#include +#define MA_DR_WAV_ASSERT(expression) assert(expression) +#endif +#ifndef MA_DR_WAV_MALLOC +#define MA_DR_WAV_MALLOC(sz) malloc((sz)) +#endif +#ifndef MA_DR_WAV_REALLOC +#define MA_DR_WAV_REALLOC(p, sz) realloc((p), (sz)) +#endif +#ifndef MA_DR_WAV_FREE +#define MA_DR_WAV_FREE(p) free((p)) +#endif +#ifndef MA_DR_WAV_COPY_MEMORY +#define MA_DR_WAV_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz)) +#endif +#ifndef MA_DR_WAV_ZERO_MEMORY +#define MA_DR_WAV_ZERO_MEMORY(p, sz) memset((p), 0, (sz)) +#endif +#ifndef MA_DR_WAV_ZERO_OBJECT +#define MA_DR_WAV_ZERO_OBJECT(p) MA_DR_WAV_ZERO_MEMORY((p), sizeof(*p)) +#endif +#define ma_dr_wav_countof(x) (sizeof(x) / sizeof(x[0])) +#define ma_dr_wav_align(x, a) ((((x) + (a) - 1) / (a)) * (a)) +#define ma_dr_wav_min(a, b) (((a) < (b)) ? (a) : (b)) +#define ma_dr_wav_max(a, b) (((a) > (b)) ? (a) : (b)) +#define ma_dr_wav_clamp(x, lo, hi) (ma_dr_wav_max((lo), ma_dr_wav_min((hi), (x)))) +#define ma_dr_wav_offset_ptr(p, offset) (((ma_uint8*)(p)) + (offset)) +#define MA_DR_WAV_MAX_SIMD_VECTOR_SIZE 32 +#define MA_DR_WAV_INT64_MIN ((ma_int64) ((ma_uint64)0x80000000 << 32)) +#define MA_DR_WAV_INT64_MAX ((ma_int64)(((ma_uint64)0x7FFFFFFF << 32) | 0xFFFFFFFF)) +#if defined(_MSC_VER) && _MSC_VER >= 1400 + #define MA_DR_WAV_HAS_BYTESWAP16_INTRINSIC + #define MA_DR_WAV_HAS_BYTESWAP32_INTRINSIC + #define MA_DR_WAV_HAS_BYTESWAP64_INTRINSIC +#elif defined(__clang__) + #if defined(__has_builtin) + #if __has_builtin(__builtin_bswap16) + #define MA_DR_WAV_HAS_BYTESWAP16_INTRINSIC + #endif + #if __has_builtin(__builtin_bswap32) + #define MA_DR_WAV_HAS_BYTESWAP32_INTRINSIC + #endif + #if __has_builtin(__builtin_bswap64) + #define MA_DR_WAV_HAS_BYTESWAP64_INTRINSIC + #endif + #endif +#elif defined(__GNUC__) + #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) + #define MA_DR_WAV_HAS_BYTESWAP32_INTRINSIC + #define MA_DR_WAV_HAS_BYTESWAP64_INTRINSIC + #endif + #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)) + #define MA_DR_WAV_HAS_BYTESWAP16_INTRINSIC + #endif +#endif +MA_API void ma_dr_wav_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision) +{ + if (pMajor) { + *pMajor = MA_DR_WAV_VERSION_MAJOR; + } + if (pMinor) { + *pMinor = MA_DR_WAV_VERSION_MINOR; + } + if (pRevision) { + *pRevision = MA_DR_WAV_VERSION_REVISION; + } +} +MA_API const char* ma_dr_wav_version_string(void) +{ + return MA_DR_WAV_VERSION_STRING; +} +#ifndef MA_DR_WAV_MAX_SAMPLE_RATE +#define MA_DR_WAV_MAX_SAMPLE_RATE 384000 +#endif +#ifndef MA_DR_WAV_MAX_CHANNELS +#define MA_DR_WAV_MAX_CHANNELS 256 +#endif +#ifndef MA_DR_WAV_MAX_BITS_PER_SAMPLE +#define MA_DR_WAV_MAX_BITS_PER_SAMPLE 64 +#endif +static const ma_uint8 ma_dr_wavGUID_W64_RIFF[16] = {0x72,0x69,0x66,0x66, 0x2E,0x91, 0xCF,0x11, 0xA5,0xD6, 0x28,0xDB,0x04,0xC1,0x00,0x00}; +static const ma_uint8 ma_dr_wavGUID_W64_WAVE[16] = {0x77,0x61,0x76,0x65, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A}; +static const ma_uint8 ma_dr_wavGUID_W64_FMT [16] = {0x66,0x6D,0x74,0x20, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A}; +static const ma_uint8 ma_dr_wavGUID_W64_FACT[16] = {0x66,0x61,0x63,0x74, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A}; +static const ma_uint8 ma_dr_wavGUID_W64_DATA[16] = {0x64,0x61,0x74,0x61, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A}; +static MA_INLINE int ma_dr_wav__is_little_endian(void) +{ +#if defined(MA_X86) || defined(MA_X64) + return MA_TRUE; +#elif defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN + return MA_TRUE; +#else + int n = 1; + return (*(char*)&n) == 1; +#endif +} +static MA_INLINE void ma_dr_wav_bytes_to_guid(const ma_uint8* data, ma_uint8* guid) +{ + int i; + for (i = 0; i < 16; ++i) { + guid[i] = data[i]; + } +} +static MA_INLINE ma_uint16 ma_dr_wav__bswap16(ma_uint16 n) +{ +#ifdef MA_DR_WAV_HAS_BYTESWAP16_INTRINSIC + #if defined(_MSC_VER) + return _byteswap_ushort(n); + #elif defined(__GNUC__) || defined(__clang__) + return __builtin_bswap16(n); + #else + #error "This compiler does not support the byte swap intrinsic." + #endif +#else + return ((n & 0xFF00) >> 8) | + ((n & 0x00FF) << 8); +#endif +} +static MA_INLINE ma_uint32 ma_dr_wav__bswap32(ma_uint32 n) +{ +#ifdef MA_DR_WAV_HAS_BYTESWAP32_INTRINSIC + #if defined(_MSC_VER) + return _byteswap_ulong(n); + #elif defined(__GNUC__) || defined(__clang__) + #if defined(MA_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 6) && !defined(MA_64BIT) + ma_uint32 r; + __asm__ __volatile__ ( + #if defined(MA_64BIT) + "rev %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(n) + #else + "rev %[out], %[in]" : [out]"=r"(r) : [in]"r"(n) + #endif + ); + return r; + #else + return __builtin_bswap32(n); + #endif + #else + #error "This compiler does not support the byte swap intrinsic." + #endif +#else + return ((n & 0xFF000000) >> 24) | + ((n & 0x00FF0000) >> 8) | + ((n & 0x0000FF00) << 8) | + ((n & 0x000000FF) << 24); +#endif +} +static MA_INLINE ma_uint64 ma_dr_wav__bswap64(ma_uint64 n) +{ +#ifdef MA_DR_WAV_HAS_BYTESWAP64_INTRINSIC + #if defined(_MSC_VER) + return _byteswap_uint64(n); + #elif defined(__GNUC__) || defined(__clang__) + return __builtin_bswap64(n); + #else + #error "This compiler does not support the byte swap intrinsic." + #endif +#else + return ((n & ((ma_uint64)0xFF000000 << 32)) >> 56) | + ((n & ((ma_uint64)0x00FF0000 << 32)) >> 40) | + ((n & ((ma_uint64)0x0000FF00 << 32)) >> 24) | + ((n & ((ma_uint64)0x000000FF << 32)) >> 8) | + ((n & ((ma_uint64)0xFF000000 )) << 8) | + ((n & ((ma_uint64)0x00FF0000 )) << 24) | + ((n & ((ma_uint64)0x0000FF00 )) << 40) | + ((n & ((ma_uint64)0x000000FF )) << 56); +#endif +} +static MA_INLINE ma_int16 ma_dr_wav__bswap_s16(ma_int16 n) +{ + return (ma_int16)ma_dr_wav__bswap16((ma_uint16)n); +} +static MA_INLINE void ma_dr_wav__bswap_samples_s16(ma_int16* pSamples, ma_uint64 sampleCount) +{ + ma_uint64 iSample; + for (iSample = 0; iSample < sampleCount; iSample += 1) { + pSamples[iSample] = ma_dr_wav__bswap_s16(pSamples[iSample]); + } +} +static MA_INLINE void ma_dr_wav__bswap_s24(ma_uint8* p) +{ + ma_uint8 t; + t = p[0]; + p[0] = p[2]; + p[2] = t; +} +static MA_INLINE void ma_dr_wav__bswap_samples_s24(ma_uint8* pSamples, ma_uint64 sampleCount) +{ + ma_uint64 iSample; + for (iSample = 0; iSample < sampleCount; iSample += 1) { + ma_uint8* pSample = pSamples + (iSample*3); + ma_dr_wav__bswap_s24(pSample); + } +} +static MA_INLINE ma_int32 ma_dr_wav__bswap_s32(ma_int32 n) +{ + return (ma_int32)ma_dr_wav__bswap32((ma_uint32)n); +} +static MA_INLINE void ma_dr_wav__bswap_samples_s32(ma_int32* pSamples, ma_uint64 sampleCount) +{ + ma_uint64 iSample; + for (iSample = 0; iSample < sampleCount; iSample += 1) { + pSamples[iSample] = ma_dr_wav__bswap_s32(pSamples[iSample]); + } +} +static MA_INLINE ma_int64 ma_dr_wav__bswap_s64(ma_int64 n) +{ + return (ma_int64)ma_dr_wav__bswap64((ma_uint64)n); +} +static MA_INLINE void ma_dr_wav__bswap_samples_s64(ma_int64* pSamples, ma_uint64 sampleCount) +{ + ma_uint64 iSample; + for (iSample = 0; iSample < sampleCount; iSample += 1) { + pSamples[iSample] = ma_dr_wav__bswap_s64(pSamples[iSample]); + } +} +static MA_INLINE float ma_dr_wav__bswap_f32(float n) +{ + union { + ma_uint32 i; + float f; + } x; + x.f = n; + x.i = ma_dr_wav__bswap32(x.i); + return x.f; +} +static MA_INLINE void ma_dr_wav__bswap_samples_f32(float* pSamples, ma_uint64 sampleCount) +{ + ma_uint64 iSample; + for (iSample = 0; iSample < sampleCount; iSample += 1) { + pSamples[iSample] = ma_dr_wav__bswap_f32(pSamples[iSample]); + } +} +static MA_INLINE void ma_dr_wav__bswap_samples(void* pSamples, ma_uint64 sampleCount, ma_uint32 bytesPerSample) +{ + switch (bytesPerSample) + { + case 1: + { + } break; + case 2: + { + ma_dr_wav__bswap_samples_s16((ma_int16*)pSamples, sampleCount); + } break; + case 3: + { + ma_dr_wav__bswap_samples_s24((ma_uint8*)pSamples, sampleCount); + } break; + case 4: + { + ma_dr_wav__bswap_samples_s32((ma_int32*)pSamples, sampleCount); + } break; + case 8: + { + ma_dr_wav__bswap_samples_s64((ma_int64*)pSamples, sampleCount); + } break; + default: + { + MA_DR_WAV_ASSERT(MA_FALSE); + } break; + } +} +MA_PRIVATE MA_INLINE ma_bool32 ma_dr_wav_is_container_be(ma_dr_wav_container container) +{ + if (container == ma_dr_wav_container_rifx || container == ma_dr_wav_container_aiff) { + return MA_TRUE; + } else { + return MA_FALSE; + } +} +MA_PRIVATE MA_INLINE ma_uint16 ma_dr_wav_bytes_to_u16_le(const ma_uint8* data) +{ + return ((ma_uint16)data[0] << 0) | ((ma_uint16)data[1] << 8); +} +MA_PRIVATE MA_INLINE ma_uint16 ma_dr_wav_bytes_to_u16_be(const ma_uint8* data) +{ + return ((ma_uint16)data[1] << 0) | ((ma_uint16)data[0] << 8); +} +MA_PRIVATE MA_INLINE ma_uint16 ma_dr_wav_bytes_to_u16_ex(const ma_uint8* data, ma_dr_wav_container container) +{ + if (ma_dr_wav_is_container_be(container)) { + return ma_dr_wav_bytes_to_u16_be(data); + } else { + return ma_dr_wav_bytes_to_u16_le(data); + } +} +MA_PRIVATE MA_INLINE ma_uint32 ma_dr_wav_bytes_to_u32_le(const ma_uint8* data) +{ + return ((ma_uint32)data[0] << 0) | ((ma_uint32)data[1] << 8) | ((ma_uint32)data[2] << 16) | ((ma_uint32)data[3] << 24); +} +MA_PRIVATE MA_INLINE ma_uint32 ma_dr_wav_bytes_to_u32_be(const ma_uint8* data) +{ + return ((ma_uint32)data[3] << 0) | ((ma_uint32)data[2] << 8) | ((ma_uint32)data[1] << 16) | ((ma_uint32)data[0] << 24); +} +MA_PRIVATE MA_INLINE ma_uint32 ma_dr_wav_bytes_to_u32_ex(const ma_uint8* data, ma_dr_wav_container container) +{ + if (ma_dr_wav_is_container_be(container)) { + return ma_dr_wav_bytes_to_u32_be(data); + } else { + return ma_dr_wav_bytes_to_u32_le(data); + } +} +MA_PRIVATE ma_int64 ma_dr_wav_aiff_extented_to_s64(const ma_uint8* data) +{ + ma_uint32 exponent = ((ma_uint32)data[0] << 8) | data[1]; + ma_uint64 hi = ((ma_uint64)data[2] << 24) | ((ma_uint64)data[3] << 16) | ((ma_uint64)data[4] << 8) | ((ma_uint64)data[5] << 0); + ma_uint64 lo = ((ma_uint64)data[6] << 24) | ((ma_uint64)data[7] << 16) | ((ma_uint64)data[8] << 8) | ((ma_uint64)data[9] << 0); + ma_uint64 significand = (hi << 32) | lo; + int sign = exponent >> 15; + exponent &= 0x7FFF; + if (exponent == 0 && significand == 0) { + return 0; + } else if (exponent == 0x7FFF) { + return sign ? MA_DR_WAV_INT64_MIN : MA_DR_WAV_INT64_MAX; + } + exponent -= 16383; + if (exponent > 63) { + return sign ? MA_DR_WAV_INT64_MIN : MA_DR_WAV_INT64_MAX; + } else if (exponent < 1) { + return 0; + } + significand >>= (63 - exponent); + if (sign) { + return -(ma_int64)significand; + } else { + return (ma_int64)significand; + } +} +MA_PRIVATE void* ma_dr_wav__malloc_default(size_t sz, void* pUserData) +{ + (void)pUserData; + return MA_DR_WAV_MALLOC(sz); +} +MA_PRIVATE void* ma_dr_wav__realloc_default(void* p, size_t sz, void* pUserData) +{ + (void)pUserData; + return MA_DR_WAV_REALLOC(p, sz); +} +MA_PRIVATE void ma_dr_wav__free_default(void* p, void* pUserData) +{ + (void)pUserData; + MA_DR_WAV_FREE(p); +} +MA_PRIVATE void* ma_dr_wav__malloc_from_callbacks(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pAllocationCallbacks == NULL) { + return NULL; + } + if (pAllocationCallbacks->onMalloc != NULL) { + return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData); + } + if (pAllocationCallbacks->onRealloc != NULL) { + return pAllocationCallbacks->onRealloc(NULL, sz, pAllocationCallbacks->pUserData); + } + return NULL; +} +MA_PRIVATE void* ma_dr_wav__realloc_from_callbacks(void* p, size_t szNew, size_t szOld, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pAllocationCallbacks == NULL) { + return NULL; + } + if (pAllocationCallbacks->onRealloc != NULL) { + return pAllocationCallbacks->onRealloc(p, szNew, pAllocationCallbacks->pUserData); + } + if (pAllocationCallbacks->onMalloc != NULL && pAllocationCallbacks->onFree != NULL) { + void* p2; + p2 = pAllocationCallbacks->onMalloc(szNew, pAllocationCallbacks->pUserData); + if (p2 == NULL) { + return NULL; + } + if (p != NULL) { + MA_DR_WAV_COPY_MEMORY(p2, p, szOld); + pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData); + } + return p2; + } + return NULL; +} +MA_PRIVATE void ma_dr_wav__free_from_callbacks(void* p, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (p == NULL || pAllocationCallbacks == NULL) { + return; + } + if (pAllocationCallbacks->onFree != NULL) { + pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData); + } +} +MA_PRIVATE ma_allocation_callbacks ma_dr_wav_copy_allocation_callbacks_or_defaults(const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pAllocationCallbacks != NULL) { + return *pAllocationCallbacks; + } else { + ma_allocation_callbacks allocationCallbacks; + allocationCallbacks.pUserData = NULL; + allocationCallbacks.onMalloc = ma_dr_wav__malloc_default; + allocationCallbacks.onRealloc = ma_dr_wav__realloc_default; + allocationCallbacks.onFree = ma_dr_wav__free_default; + return allocationCallbacks; + } +} +static MA_INLINE ma_bool32 ma_dr_wav__is_compressed_format_tag(ma_uint16 formatTag) +{ + return + formatTag == MA_DR_WAVE_FORMAT_ADPCM || + formatTag == MA_DR_WAVE_FORMAT_DVI_ADPCM; +} +MA_PRIVATE unsigned int ma_dr_wav__chunk_padding_size_riff(ma_uint64 chunkSize) +{ + return (unsigned int)(chunkSize % 2); +} +MA_PRIVATE unsigned int ma_dr_wav__chunk_padding_size_w64(ma_uint64 chunkSize) +{ + return (unsigned int)(chunkSize % 8); +} +MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s16__msadpcm(ma_dr_wav* pWav, ma_uint64 samplesToRead, ma_int16* pBufferOut); +MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s16__ima(ma_dr_wav* pWav, ma_uint64 samplesToRead, ma_int16* pBufferOut); +MA_PRIVATE ma_bool32 ma_dr_wav_init_write__internal(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount); +MA_PRIVATE ma_result ma_dr_wav__read_chunk_header(ma_dr_wav_read_proc onRead, void* pUserData, ma_dr_wav_container container, ma_uint64* pRunningBytesReadOut, ma_dr_wav_chunk_header* pHeaderOut) +{ + if (container == ma_dr_wav_container_riff || container == ma_dr_wav_container_rifx || container == ma_dr_wav_container_rf64 || container == ma_dr_wav_container_aiff) { + ma_uint8 sizeInBytes[4]; + if (onRead(pUserData, pHeaderOut->id.fourcc, 4) != 4) { + return MA_AT_END; + } + if (onRead(pUserData, sizeInBytes, 4) != 4) { + return MA_INVALID_FILE; + } + pHeaderOut->sizeInBytes = ma_dr_wav_bytes_to_u32_ex(sizeInBytes, container); + pHeaderOut->paddingSize = ma_dr_wav__chunk_padding_size_riff(pHeaderOut->sizeInBytes); + *pRunningBytesReadOut += 8; + } else if (container == ma_dr_wav_container_w64) { + ma_uint8 sizeInBytes[8]; + if (onRead(pUserData, pHeaderOut->id.guid, 16) != 16) { + return MA_AT_END; + } + if (onRead(pUserData, sizeInBytes, 8) != 8) { + return MA_INVALID_FILE; + } + pHeaderOut->sizeInBytes = ma_dr_wav_bytes_to_u64(sizeInBytes) - 24; + pHeaderOut->paddingSize = ma_dr_wav__chunk_padding_size_w64(pHeaderOut->sizeInBytes); + *pRunningBytesReadOut += 24; + } else { + return MA_INVALID_FILE; + } + return MA_SUCCESS; +} +MA_PRIVATE ma_bool32 ma_dr_wav__seek_forward(ma_dr_wav_seek_proc onSeek, ma_uint64 offset, void* pUserData) +{ + ma_uint64 bytesRemainingToSeek = offset; + while (bytesRemainingToSeek > 0) { + if (bytesRemainingToSeek > 0x7FFFFFFF) { + if (!onSeek(pUserData, 0x7FFFFFFF, ma_dr_wav_seek_origin_current)) { + return MA_FALSE; + } + bytesRemainingToSeek -= 0x7FFFFFFF; + } else { + if (!onSeek(pUserData, (int)bytesRemainingToSeek, ma_dr_wav_seek_origin_current)) { + return MA_FALSE; + } + bytesRemainingToSeek = 0; + } + } + return MA_TRUE; +} +MA_PRIVATE ma_bool32 ma_dr_wav__seek_from_start(ma_dr_wav_seek_proc onSeek, ma_uint64 offset, void* pUserData) +{ + if (offset <= 0x7FFFFFFF) { + return onSeek(pUserData, (int)offset, ma_dr_wav_seek_origin_start); + } + if (!onSeek(pUserData, 0x7FFFFFFF, ma_dr_wav_seek_origin_start)) { + return MA_FALSE; + } + offset -= 0x7FFFFFFF; + for (;;) { + if (offset <= 0x7FFFFFFF) { + return onSeek(pUserData, (int)offset, ma_dr_wav_seek_origin_current); + } + if (!onSeek(pUserData, 0x7FFFFFFF, ma_dr_wav_seek_origin_current)) { + return MA_FALSE; + } + offset -= 0x7FFFFFFF; + } +} +MA_PRIVATE size_t ma_dr_wav__on_read(ma_dr_wav_read_proc onRead, void* pUserData, void* pBufferOut, size_t bytesToRead, ma_uint64* pCursor) +{ + size_t bytesRead; + MA_DR_WAV_ASSERT(onRead != NULL); + MA_DR_WAV_ASSERT(pCursor != NULL); + bytesRead = onRead(pUserData, pBufferOut, bytesToRead); + *pCursor += bytesRead; + return bytesRead; +} +#if 0 +MA_PRIVATE ma_bool32 ma_dr_wav__on_seek(ma_dr_wav_seek_proc onSeek, void* pUserData, int offset, ma_dr_wav_seek_origin origin, ma_uint64* pCursor) +{ + MA_DR_WAV_ASSERT(onSeek != NULL); + MA_DR_WAV_ASSERT(pCursor != NULL); + if (!onSeek(pUserData, offset, origin)) { + return MA_FALSE; + } + if (origin == ma_dr_wav_seek_origin_start) { + *pCursor = offset; + } else { + *pCursor += offset; + } + return MA_TRUE; +} +#endif +#define MA_DR_WAV_SMPL_BYTES 36 +#define MA_DR_WAV_SMPL_LOOP_BYTES 24 +#define MA_DR_WAV_INST_BYTES 7 +#define MA_DR_WAV_ACID_BYTES 24 +#define MA_DR_WAV_CUE_BYTES 4 +#define MA_DR_WAV_BEXT_BYTES 602 +#define MA_DR_WAV_BEXT_DESCRIPTION_BYTES 256 +#define MA_DR_WAV_BEXT_ORIGINATOR_NAME_BYTES 32 +#define MA_DR_WAV_BEXT_ORIGINATOR_REF_BYTES 32 +#define MA_DR_WAV_BEXT_RESERVED_BYTES 180 +#define MA_DR_WAV_BEXT_UMID_BYTES 64 +#define MA_DR_WAV_CUE_POINT_BYTES 24 +#define MA_DR_WAV_LIST_LABEL_OR_NOTE_BYTES 4 +#define MA_DR_WAV_LIST_LABELLED_TEXT_BYTES 20 +#define MA_DR_WAV_METADATA_ALIGNMENT 8 +typedef enum +{ + ma_dr_wav__metadata_parser_stage_count, + ma_dr_wav__metadata_parser_stage_read +} ma_dr_wav__metadata_parser_stage; +typedef struct +{ + ma_dr_wav_read_proc onRead; + ma_dr_wav_seek_proc onSeek; + void *pReadSeekUserData; + ma_dr_wav__metadata_parser_stage stage; + ma_dr_wav_metadata *pMetadata; + ma_uint32 metadataCount; + ma_uint8 *pData; + ma_uint8 *pDataCursor; + ma_uint64 metadataCursor; + ma_uint64 extraCapacity; +} ma_dr_wav__metadata_parser; +MA_PRIVATE size_t ma_dr_wav__metadata_memory_capacity(ma_dr_wav__metadata_parser* pParser) +{ + ma_uint64 cap = sizeof(ma_dr_wav_metadata) * (ma_uint64)pParser->metadataCount + pParser->extraCapacity; + if (cap > MA_SIZE_MAX) { + return 0; + } + return (size_t)cap; +} +MA_PRIVATE ma_uint8* ma_dr_wav__metadata_get_memory(ma_dr_wav__metadata_parser* pParser, size_t size, size_t align) +{ + ma_uint8* pResult; + if (align) { + ma_uintptr modulo = (ma_uintptr)pParser->pDataCursor % align; + if (modulo != 0) { + pParser->pDataCursor += align - modulo; + } + } + pResult = pParser->pDataCursor; + MA_DR_WAV_ASSERT((pResult + size) <= (pParser->pData + ma_dr_wav__metadata_memory_capacity(pParser))); + pParser->pDataCursor += size; + return pResult; +} +MA_PRIVATE void ma_dr_wav__metadata_request_extra_memory_for_stage_2(ma_dr_wav__metadata_parser* pParser, size_t bytes, size_t align) +{ + size_t extra = bytes + (align ? (align - 1) : 0); + pParser->extraCapacity += extra; +} +MA_PRIVATE ma_result ma_dr_wav__metadata_alloc(ma_dr_wav__metadata_parser* pParser, ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pParser->extraCapacity != 0 || pParser->metadataCount != 0) { + pAllocationCallbacks->onFree(pParser->pData, pAllocationCallbacks->pUserData); + pParser->pData = (ma_uint8*)pAllocationCallbacks->onMalloc(ma_dr_wav__metadata_memory_capacity(pParser), pAllocationCallbacks->pUserData); + pParser->pDataCursor = pParser->pData; + if (pParser->pData == NULL) { + return MA_OUT_OF_MEMORY; + } + pParser->pMetadata = (ma_dr_wav_metadata*)ma_dr_wav__metadata_get_memory(pParser, sizeof(ma_dr_wav_metadata) * pParser->metadataCount, 1); + pParser->metadataCursor = 0; + } + return MA_SUCCESS; +} +MA_PRIVATE size_t ma_dr_wav__metadata_parser_read(ma_dr_wav__metadata_parser* pParser, void* pBufferOut, size_t bytesToRead, ma_uint64* pCursor) +{ + if (pCursor != NULL) { + return ma_dr_wav__on_read(pParser->onRead, pParser->pReadSeekUserData, pBufferOut, bytesToRead, pCursor); + } else { + return pParser->onRead(pParser->pReadSeekUserData, pBufferOut, bytesToRead); + } +} +MA_PRIVATE ma_uint64 ma_dr_wav__read_smpl_to_metadata_obj(ma_dr_wav__metadata_parser* pParser, const ma_dr_wav_chunk_header* pChunkHeader, ma_dr_wav_metadata* pMetadata) +{ + ma_uint8 smplHeaderData[MA_DR_WAV_SMPL_BYTES]; + ma_uint64 totalBytesRead = 0; + size_t bytesJustRead; + if (pMetadata == NULL) { + return 0; + } + bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, smplHeaderData, sizeof(smplHeaderData), &totalBytesRead); + MA_DR_WAV_ASSERT(pParser->stage == ma_dr_wav__metadata_parser_stage_read); + MA_DR_WAV_ASSERT(pChunkHeader != NULL); + if (pMetadata != NULL && bytesJustRead == sizeof(smplHeaderData)) { + ma_uint32 iSampleLoop; + pMetadata->type = ma_dr_wav_metadata_type_smpl; + pMetadata->data.smpl.manufacturerId = ma_dr_wav_bytes_to_u32(smplHeaderData + 0); + pMetadata->data.smpl.productId = ma_dr_wav_bytes_to_u32(smplHeaderData + 4); + pMetadata->data.smpl.samplePeriodNanoseconds = ma_dr_wav_bytes_to_u32(smplHeaderData + 8); + pMetadata->data.smpl.midiUnityNote = ma_dr_wav_bytes_to_u32(smplHeaderData + 12); + pMetadata->data.smpl.midiPitchFraction = ma_dr_wav_bytes_to_u32(smplHeaderData + 16); + pMetadata->data.smpl.smpteFormat = ma_dr_wav_bytes_to_u32(smplHeaderData + 20); + pMetadata->data.smpl.smpteOffset = ma_dr_wav_bytes_to_u32(smplHeaderData + 24); + pMetadata->data.smpl.sampleLoopCount = ma_dr_wav_bytes_to_u32(smplHeaderData + 28); + pMetadata->data.smpl.samplerSpecificDataSizeInBytes = ma_dr_wav_bytes_to_u32(smplHeaderData + 32); + if (pMetadata->data.smpl.sampleLoopCount == (pChunkHeader->sizeInBytes - MA_DR_WAV_SMPL_BYTES) / MA_DR_WAV_SMPL_LOOP_BYTES) { + pMetadata->data.smpl.pLoops = (ma_dr_wav_smpl_loop*)ma_dr_wav__metadata_get_memory(pParser, sizeof(ma_dr_wav_smpl_loop) * pMetadata->data.smpl.sampleLoopCount, MA_DR_WAV_METADATA_ALIGNMENT); + for (iSampleLoop = 0; iSampleLoop < pMetadata->data.smpl.sampleLoopCount; ++iSampleLoop) { + ma_uint8 smplLoopData[MA_DR_WAV_SMPL_LOOP_BYTES]; + bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, smplLoopData, sizeof(smplLoopData), &totalBytesRead); + if (bytesJustRead == sizeof(smplLoopData)) { + pMetadata->data.smpl.pLoops[iSampleLoop].cuePointId = ma_dr_wav_bytes_to_u32(smplLoopData + 0); + pMetadata->data.smpl.pLoops[iSampleLoop].type = ma_dr_wav_bytes_to_u32(smplLoopData + 4); + pMetadata->data.smpl.pLoops[iSampleLoop].firstSampleByteOffset = ma_dr_wav_bytes_to_u32(smplLoopData + 8); + pMetadata->data.smpl.pLoops[iSampleLoop].lastSampleByteOffset = ma_dr_wav_bytes_to_u32(smplLoopData + 12); + pMetadata->data.smpl.pLoops[iSampleLoop].sampleFraction = ma_dr_wav_bytes_to_u32(smplLoopData + 16); + pMetadata->data.smpl.pLoops[iSampleLoop].playCount = ma_dr_wav_bytes_to_u32(smplLoopData + 20); + } else { + break; + } + } + if (pMetadata->data.smpl.samplerSpecificDataSizeInBytes > 0) { + pMetadata->data.smpl.pSamplerSpecificData = ma_dr_wav__metadata_get_memory(pParser, pMetadata->data.smpl.samplerSpecificDataSizeInBytes, 1); + MA_DR_WAV_ASSERT(pMetadata->data.smpl.pSamplerSpecificData != NULL); + ma_dr_wav__metadata_parser_read(pParser, pMetadata->data.smpl.pSamplerSpecificData, pMetadata->data.smpl.samplerSpecificDataSizeInBytes, &totalBytesRead); + } + } + } + return totalBytesRead; +} +MA_PRIVATE ma_uint64 ma_dr_wav__read_cue_to_metadata_obj(ma_dr_wav__metadata_parser* pParser, const ma_dr_wav_chunk_header* pChunkHeader, ma_dr_wav_metadata* pMetadata) +{ + ma_uint8 cueHeaderSectionData[MA_DR_WAV_CUE_BYTES]; + ma_uint64 totalBytesRead = 0; + size_t bytesJustRead; + if (pMetadata == NULL) { + return 0; + } + bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, cueHeaderSectionData, sizeof(cueHeaderSectionData), &totalBytesRead); + MA_DR_WAV_ASSERT(pParser->stage == ma_dr_wav__metadata_parser_stage_read); + if (bytesJustRead == sizeof(cueHeaderSectionData)) { + pMetadata->type = ma_dr_wav_metadata_type_cue; + pMetadata->data.cue.cuePointCount = ma_dr_wav_bytes_to_u32(cueHeaderSectionData); + if (pMetadata->data.cue.cuePointCount == (pChunkHeader->sizeInBytes - MA_DR_WAV_CUE_BYTES) / MA_DR_WAV_CUE_POINT_BYTES) { + pMetadata->data.cue.pCuePoints = (ma_dr_wav_cue_point*)ma_dr_wav__metadata_get_memory(pParser, sizeof(ma_dr_wav_cue_point) * pMetadata->data.cue.cuePointCount, MA_DR_WAV_METADATA_ALIGNMENT); + MA_DR_WAV_ASSERT(pMetadata->data.cue.pCuePoints != NULL); + if (pMetadata->data.cue.cuePointCount > 0) { + ma_uint32 iCuePoint; + for (iCuePoint = 0; iCuePoint < pMetadata->data.cue.cuePointCount; ++iCuePoint) { + ma_uint8 cuePointData[MA_DR_WAV_CUE_POINT_BYTES]; + bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, cuePointData, sizeof(cuePointData), &totalBytesRead); + if (bytesJustRead == sizeof(cuePointData)) { + pMetadata->data.cue.pCuePoints[iCuePoint].id = ma_dr_wav_bytes_to_u32(cuePointData + 0); + pMetadata->data.cue.pCuePoints[iCuePoint].playOrderPosition = ma_dr_wav_bytes_to_u32(cuePointData + 4); + pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId[0] = cuePointData[8]; + pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId[1] = cuePointData[9]; + pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId[2] = cuePointData[10]; + pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId[3] = cuePointData[11]; + pMetadata->data.cue.pCuePoints[iCuePoint].chunkStart = ma_dr_wav_bytes_to_u32(cuePointData + 12); + pMetadata->data.cue.pCuePoints[iCuePoint].blockStart = ma_dr_wav_bytes_to_u32(cuePointData + 16); + pMetadata->data.cue.pCuePoints[iCuePoint].sampleByteOffset = ma_dr_wav_bytes_to_u32(cuePointData + 20); + } else { + break; + } + } + } + } + } + return totalBytesRead; +} +MA_PRIVATE ma_uint64 ma_dr_wav__read_inst_to_metadata_obj(ma_dr_wav__metadata_parser* pParser, ma_dr_wav_metadata* pMetadata) +{ + ma_uint8 instData[MA_DR_WAV_INST_BYTES]; + ma_uint64 bytesRead; + if (pMetadata == NULL) { + return 0; + } + bytesRead = ma_dr_wav__metadata_parser_read(pParser, instData, sizeof(instData), NULL); + MA_DR_WAV_ASSERT(pParser->stage == ma_dr_wav__metadata_parser_stage_read); + if (bytesRead == sizeof(instData)) { + pMetadata->type = ma_dr_wav_metadata_type_inst; + pMetadata->data.inst.midiUnityNote = (ma_int8)instData[0]; + pMetadata->data.inst.fineTuneCents = (ma_int8)instData[1]; + pMetadata->data.inst.gainDecibels = (ma_int8)instData[2]; + pMetadata->data.inst.lowNote = (ma_int8)instData[3]; + pMetadata->data.inst.highNote = (ma_int8)instData[4]; + pMetadata->data.inst.lowVelocity = (ma_int8)instData[5]; + pMetadata->data.inst.highVelocity = (ma_int8)instData[6]; + } + return bytesRead; +} +MA_PRIVATE ma_uint64 ma_dr_wav__read_acid_to_metadata_obj(ma_dr_wav__metadata_parser* pParser, ma_dr_wav_metadata* pMetadata) +{ + ma_uint8 acidData[MA_DR_WAV_ACID_BYTES]; + ma_uint64 bytesRead; + if (pMetadata == NULL) { + return 0; + } + bytesRead = ma_dr_wav__metadata_parser_read(pParser, acidData, sizeof(acidData), NULL); + MA_DR_WAV_ASSERT(pParser->stage == ma_dr_wav__metadata_parser_stage_read); + if (bytesRead == sizeof(acidData)) { + pMetadata->type = ma_dr_wav_metadata_type_acid; + pMetadata->data.acid.flags = ma_dr_wav_bytes_to_u32(acidData + 0); + pMetadata->data.acid.midiUnityNote = ma_dr_wav_bytes_to_u16(acidData + 4); + pMetadata->data.acid.reserved1 = ma_dr_wav_bytes_to_u16(acidData + 6); + pMetadata->data.acid.reserved2 = ma_dr_wav_bytes_to_f32(acidData + 8); + pMetadata->data.acid.numBeats = ma_dr_wav_bytes_to_u32(acidData + 12); + pMetadata->data.acid.meterDenominator = ma_dr_wav_bytes_to_u16(acidData + 16); + pMetadata->data.acid.meterNumerator = ma_dr_wav_bytes_to_u16(acidData + 18); + pMetadata->data.acid.tempo = ma_dr_wav_bytes_to_f32(acidData + 20); + } + return bytesRead; +} +MA_PRIVATE size_t ma_dr_wav__strlen(const char* str) +{ + size_t result = 0; + while (*str++) { + result += 1; + } + return result; +} +MA_PRIVATE size_t ma_dr_wav__strlen_clamped(const char* str, size_t maxToRead) +{ + size_t result = 0; + while (*str++ && result < maxToRead) { + result += 1; + } + return result; +} +MA_PRIVATE char* ma_dr_wav__metadata_copy_string(ma_dr_wav__metadata_parser* pParser, const char* str, size_t maxToRead) +{ + size_t len = ma_dr_wav__strlen_clamped(str, maxToRead); + if (len) { + char* result = (char*)ma_dr_wav__metadata_get_memory(pParser, len + 1, 1); + MA_DR_WAV_ASSERT(result != NULL); + MA_DR_WAV_COPY_MEMORY(result, str, len); + result[len] = '\0'; + return result; + } else { + return NULL; + } +} +typedef struct +{ + const void* pBuffer; + size_t sizeInBytes; + size_t cursor; +} ma_dr_wav_buffer_reader; +MA_PRIVATE ma_result ma_dr_wav_buffer_reader_init(const void* pBuffer, size_t sizeInBytes, ma_dr_wav_buffer_reader* pReader) +{ + MA_DR_WAV_ASSERT(pBuffer != NULL); + MA_DR_WAV_ASSERT(pReader != NULL); + MA_DR_WAV_ZERO_OBJECT(pReader); + pReader->pBuffer = pBuffer; + pReader->sizeInBytes = sizeInBytes; + pReader->cursor = 0; + return MA_SUCCESS; +} +MA_PRIVATE const void* ma_dr_wav_buffer_reader_ptr(const ma_dr_wav_buffer_reader* pReader) +{ + MA_DR_WAV_ASSERT(pReader != NULL); + return ma_dr_wav_offset_ptr(pReader->pBuffer, pReader->cursor); +} +MA_PRIVATE ma_result ma_dr_wav_buffer_reader_seek(ma_dr_wav_buffer_reader* pReader, size_t bytesToSeek) +{ + MA_DR_WAV_ASSERT(pReader != NULL); + if (pReader->cursor + bytesToSeek > pReader->sizeInBytes) { + return MA_BAD_SEEK; + } + pReader->cursor += bytesToSeek; + return MA_SUCCESS; +} +MA_PRIVATE ma_result ma_dr_wav_buffer_reader_read(ma_dr_wav_buffer_reader* pReader, void* pDst, size_t bytesToRead, size_t* pBytesRead) +{ + ma_result result = MA_SUCCESS; + size_t bytesRemaining; + MA_DR_WAV_ASSERT(pReader != NULL); + if (pBytesRead != NULL) { + *pBytesRead = 0; + } + bytesRemaining = (pReader->sizeInBytes - pReader->cursor); + if (bytesToRead > bytesRemaining) { + bytesToRead = bytesRemaining; + } + if (pDst == NULL) { + result = ma_dr_wav_buffer_reader_seek(pReader, bytesToRead); + } else { + MA_DR_WAV_COPY_MEMORY(pDst, ma_dr_wav_buffer_reader_ptr(pReader), bytesToRead); + pReader->cursor += bytesToRead; + } + MA_DR_WAV_ASSERT(pReader->cursor <= pReader->sizeInBytes); + if (result == MA_SUCCESS) { + if (pBytesRead != NULL) { + *pBytesRead = bytesToRead; + } + } + return MA_SUCCESS; +} +MA_PRIVATE ma_result ma_dr_wav_buffer_reader_read_u16(ma_dr_wav_buffer_reader* pReader, ma_uint16* pDst) +{ + ma_result result; + size_t bytesRead; + ma_uint8 data[2]; + MA_DR_WAV_ASSERT(pReader != NULL); + MA_DR_WAV_ASSERT(pDst != NULL); + *pDst = 0; + result = ma_dr_wav_buffer_reader_read(pReader, data, sizeof(*pDst), &bytesRead); + if (result != MA_SUCCESS || bytesRead != sizeof(*pDst)) { + return result; + } + *pDst = ma_dr_wav_bytes_to_u16(data); + return MA_SUCCESS; +} +MA_PRIVATE ma_result ma_dr_wav_buffer_reader_read_u32(ma_dr_wav_buffer_reader* pReader, ma_uint32* pDst) +{ + ma_result result; + size_t bytesRead; + ma_uint8 data[4]; + MA_DR_WAV_ASSERT(pReader != NULL); + MA_DR_WAV_ASSERT(pDst != NULL); + *pDst = 0; + result = ma_dr_wav_buffer_reader_read(pReader, data, sizeof(*pDst), &bytesRead); + if (result != MA_SUCCESS || bytesRead != sizeof(*pDst)) { + return result; + } + *pDst = ma_dr_wav_bytes_to_u32(data); + return MA_SUCCESS; +} +MA_PRIVATE ma_uint64 ma_dr_wav__read_bext_to_metadata_obj(ma_dr_wav__metadata_parser* pParser, ma_dr_wav_metadata* pMetadata, ma_uint64 chunkSize) +{ + ma_uint8 bextData[MA_DR_WAV_BEXT_BYTES]; + size_t bytesRead = ma_dr_wav__metadata_parser_read(pParser, bextData, sizeof(bextData), NULL); + MA_DR_WAV_ASSERT(pParser->stage == ma_dr_wav__metadata_parser_stage_read); + if (bytesRead == sizeof(bextData)) { + ma_dr_wav_buffer_reader reader; + ma_uint32 timeReferenceLow; + ma_uint32 timeReferenceHigh; + size_t extraBytes; + pMetadata->type = ma_dr_wav_metadata_type_bext; + if (ma_dr_wav_buffer_reader_init(bextData, bytesRead, &reader) == MA_SUCCESS) { + pMetadata->data.bext.pDescription = ma_dr_wav__metadata_copy_string(pParser, (const char*)ma_dr_wav_buffer_reader_ptr(&reader), MA_DR_WAV_BEXT_DESCRIPTION_BYTES); + ma_dr_wav_buffer_reader_seek(&reader, MA_DR_WAV_BEXT_DESCRIPTION_BYTES); + pMetadata->data.bext.pOriginatorName = ma_dr_wav__metadata_copy_string(pParser, (const char*)ma_dr_wav_buffer_reader_ptr(&reader), MA_DR_WAV_BEXT_ORIGINATOR_NAME_BYTES); + ma_dr_wav_buffer_reader_seek(&reader, MA_DR_WAV_BEXT_ORIGINATOR_NAME_BYTES); + pMetadata->data.bext.pOriginatorReference = ma_dr_wav__metadata_copy_string(pParser, (const char*)ma_dr_wav_buffer_reader_ptr(&reader), MA_DR_WAV_BEXT_ORIGINATOR_REF_BYTES); + ma_dr_wav_buffer_reader_seek(&reader, MA_DR_WAV_BEXT_ORIGINATOR_REF_BYTES); + ma_dr_wav_buffer_reader_read(&reader, pMetadata->data.bext.pOriginationDate, sizeof(pMetadata->data.bext.pOriginationDate), NULL); + ma_dr_wav_buffer_reader_read(&reader, pMetadata->data.bext.pOriginationTime, sizeof(pMetadata->data.bext.pOriginationTime), NULL); + ma_dr_wav_buffer_reader_read_u32(&reader, &timeReferenceLow); + ma_dr_wav_buffer_reader_read_u32(&reader, &timeReferenceHigh); + pMetadata->data.bext.timeReference = ((ma_uint64)timeReferenceHigh << 32) + timeReferenceLow; + ma_dr_wav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.version); + pMetadata->data.bext.pUMID = ma_dr_wav__metadata_get_memory(pParser, MA_DR_WAV_BEXT_UMID_BYTES, 1); + ma_dr_wav_buffer_reader_read(&reader, pMetadata->data.bext.pUMID, MA_DR_WAV_BEXT_UMID_BYTES, NULL); + ma_dr_wav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.loudnessValue); + ma_dr_wav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.loudnessRange); + ma_dr_wav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.maxTruePeakLevel); + ma_dr_wav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.maxMomentaryLoudness); + ma_dr_wav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.maxShortTermLoudness); + MA_DR_WAV_ASSERT((ma_dr_wav_offset_ptr(ma_dr_wav_buffer_reader_ptr(&reader), MA_DR_WAV_BEXT_RESERVED_BYTES)) == (bextData + MA_DR_WAV_BEXT_BYTES)); + extraBytes = (size_t)(chunkSize - MA_DR_WAV_BEXT_BYTES); + if (extraBytes > 0) { + pMetadata->data.bext.pCodingHistory = (char*)ma_dr_wav__metadata_get_memory(pParser, extraBytes + 1, 1); + MA_DR_WAV_ASSERT(pMetadata->data.bext.pCodingHistory != NULL); + bytesRead += ma_dr_wav__metadata_parser_read(pParser, pMetadata->data.bext.pCodingHistory, extraBytes, NULL); + pMetadata->data.bext.codingHistorySize = (ma_uint32)ma_dr_wav__strlen(pMetadata->data.bext.pCodingHistory); + } else { + pMetadata->data.bext.pCodingHistory = NULL; + pMetadata->data.bext.codingHistorySize = 0; + } + } + } + return bytesRead; +} +MA_PRIVATE ma_uint64 ma_dr_wav__read_list_label_or_note_to_metadata_obj(ma_dr_wav__metadata_parser* pParser, ma_dr_wav_metadata* pMetadata, ma_uint64 chunkSize, ma_dr_wav_metadata_type type) +{ + ma_uint8 cueIDBuffer[MA_DR_WAV_LIST_LABEL_OR_NOTE_BYTES]; + ma_uint64 totalBytesRead = 0; + size_t bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, cueIDBuffer, sizeof(cueIDBuffer), &totalBytesRead); + MA_DR_WAV_ASSERT(pParser->stage == ma_dr_wav__metadata_parser_stage_read); + if (bytesJustRead == sizeof(cueIDBuffer)) { + ma_uint32 sizeIncludingNullTerminator; + pMetadata->type = type; + pMetadata->data.labelOrNote.cuePointId = ma_dr_wav_bytes_to_u32(cueIDBuffer); + sizeIncludingNullTerminator = (ma_uint32)chunkSize - MA_DR_WAV_LIST_LABEL_OR_NOTE_BYTES; + if (sizeIncludingNullTerminator > 0) { + pMetadata->data.labelOrNote.stringLength = sizeIncludingNullTerminator - 1; + pMetadata->data.labelOrNote.pString = (char*)ma_dr_wav__metadata_get_memory(pParser, sizeIncludingNullTerminator, 1); + MA_DR_WAV_ASSERT(pMetadata->data.labelOrNote.pString != NULL); + ma_dr_wav__metadata_parser_read(pParser, pMetadata->data.labelOrNote.pString, sizeIncludingNullTerminator, &totalBytesRead); + } else { + pMetadata->data.labelOrNote.stringLength = 0; + pMetadata->data.labelOrNote.pString = NULL; + } + } + return totalBytesRead; +} +MA_PRIVATE ma_uint64 ma_dr_wav__read_list_labelled_cue_region_to_metadata_obj(ma_dr_wav__metadata_parser* pParser, ma_dr_wav_metadata* pMetadata, ma_uint64 chunkSize) +{ + ma_uint8 buffer[MA_DR_WAV_LIST_LABELLED_TEXT_BYTES]; + ma_uint64 totalBytesRead = 0; + size_t bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, buffer, sizeof(buffer), &totalBytesRead); + MA_DR_WAV_ASSERT(pParser->stage == ma_dr_wav__metadata_parser_stage_read); + if (bytesJustRead == sizeof(buffer)) { + ma_uint32 sizeIncludingNullTerminator; + pMetadata->type = ma_dr_wav_metadata_type_list_labelled_cue_region; + pMetadata->data.labelledCueRegion.cuePointId = ma_dr_wav_bytes_to_u32(buffer + 0); + pMetadata->data.labelledCueRegion.sampleLength = ma_dr_wav_bytes_to_u32(buffer + 4); + pMetadata->data.labelledCueRegion.purposeId[0] = buffer[8]; + pMetadata->data.labelledCueRegion.purposeId[1] = buffer[9]; + pMetadata->data.labelledCueRegion.purposeId[2] = buffer[10]; + pMetadata->data.labelledCueRegion.purposeId[3] = buffer[11]; + pMetadata->data.labelledCueRegion.country = ma_dr_wav_bytes_to_u16(buffer + 12); + pMetadata->data.labelledCueRegion.language = ma_dr_wav_bytes_to_u16(buffer + 14); + pMetadata->data.labelledCueRegion.dialect = ma_dr_wav_bytes_to_u16(buffer + 16); + pMetadata->data.labelledCueRegion.codePage = ma_dr_wav_bytes_to_u16(buffer + 18); + sizeIncludingNullTerminator = (ma_uint32)chunkSize - MA_DR_WAV_LIST_LABELLED_TEXT_BYTES; + if (sizeIncludingNullTerminator > 0) { + pMetadata->data.labelledCueRegion.stringLength = sizeIncludingNullTerminator - 1; + pMetadata->data.labelledCueRegion.pString = (char*)ma_dr_wav__metadata_get_memory(pParser, sizeIncludingNullTerminator, 1); + MA_DR_WAV_ASSERT(pMetadata->data.labelledCueRegion.pString != NULL); + ma_dr_wav__metadata_parser_read(pParser, pMetadata->data.labelledCueRegion.pString, sizeIncludingNullTerminator, &totalBytesRead); + } else { + pMetadata->data.labelledCueRegion.stringLength = 0; + pMetadata->data.labelledCueRegion.pString = NULL; + } + } + return totalBytesRead; +} +MA_PRIVATE ma_uint64 ma_dr_wav__metadata_process_info_text_chunk(ma_dr_wav__metadata_parser* pParser, ma_uint64 chunkSize, ma_dr_wav_metadata_type type) +{ + ma_uint64 bytesRead = 0; + ma_uint32 stringSizeWithNullTerminator = (ma_uint32)chunkSize; + if (pParser->stage == ma_dr_wav__metadata_parser_stage_count) { + pParser->metadataCount += 1; + ma_dr_wav__metadata_request_extra_memory_for_stage_2(pParser, stringSizeWithNullTerminator, 1); + } else { + ma_dr_wav_metadata* pMetadata = &pParser->pMetadata[pParser->metadataCursor]; + pMetadata->type = type; + if (stringSizeWithNullTerminator > 0) { + pMetadata->data.infoText.stringLength = stringSizeWithNullTerminator - 1; + pMetadata->data.infoText.pString = (char*)ma_dr_wav__metadata_get_memory(pParser, stringSizeWithNullTerminator, 1); + MA_DR_WAV_ASSERT(pMetadata->data.infoText.pString != NULL); + bytesRead = ma_dr_wav__metadata_parser_read(pParser, pMetadata->data.infoText.pString, (size_t)stringSizeWithNullTerminator, NULL); + if (bytesRead == chunkSize) { + pParser->metadataCursor += 1; + } else { + } + } else { + pMetadata->data.infoText.stringLength = 0; + pMetadata->data.infoText.pString = NULL; + pParser->metadataCursor += 1; + } + } + return bytesRead; +} +MA_PRIVATE ma_uint64 ma_dr_wav__metadata_process_unknown_chunk(ma_dr_wav__metadata_parser* pParser, const ma_uint8* pChunkId, ma_uint64 chunkSize, ma_dr_wav_metadata_location location) +{ + ma_uint64 bytesRead = 0; + if (location == ma_dr_wav_metadata_location_invalid) { + return 0; + } + if (ma_dr_wav_fourcc_equal(pChunkId, "data") || ma_dr_wav_fourcc_equal(pChunkId, "fmt ") || ma_dr_wav_fourcc_equal(pChunkId, "fact")) { + return 0; + } + if (pParser->stage == ma_dr_wav__metadata_parser_stage_count) { + pParser->metadataCount += 1; + ma_dr_wav__metadata_request_extra_memory_for_stage_2(pParser, (size_t)chunkSize, 1); + } else { + ma_dr_wav_metadata* pMetadata = &pParser->pMetadata[pParser->metadataCursor]; + pMetadata->type = ma_dr_wav_metadata_type_unknown; + pMetadata->data.unknown.chunkLocation = location; + pMetadata->data.unknown.id[0] = pChunkId[0]; + pMetadata->data.unknown.id[1] = pChunkId[1]; + pMetadata->data.unknown.id[2] = pChunkId[2]; + pMetadata->data.unknown.id[3] = pChunkId[3]; + pMetadata->data.unknown.dataSizeInBytes = (ma_uint32)chunkSize; + pMetadata->data.unknown.pData = (ma_uint8 *)ma_dr_wav__metadata_get_memory(pParser, (size_t)chunkSize, 1); + MA_DR_WAV_ASSERT(pMetadata->data.unknown.pData != NULL); + bytesRead = ma_dr_wav__metadata_parser_read(pParser, pMetadata->data.unknown.pData, pMetadata->data.unknown.dataSizeInBytes, NULL); + if (bytesRead == pMetadata->data.unknown.dataSizeInBytes) { + pParser->metadataCursor += 1; + } else { + } + } + return bytesRead; +} +MA_PRIVATE ma_bool32 ma_dr_wav__chunk_matches(ma_dr_wav_metadata_type allowedMetadataTypes, const ma_uint8* pChunkID, ma_dr_wav_metadata_type type, const char* pID) +{ + return (allowedMetadataTypes & type) && ma_dr_wav_fourcc_equal(pChunkID, pID); +} +MA_PRIVATE ma_uint64 ma_dr_wav__metadata_process_chunk(ma_dr_wav__metadata_parser* pParser, const ma_dr_wav_chunk_header* pChunkHeader, ma_dr_wav_metadata_type allowedMetadataTypes) +{ + const ma_uint8 *pChunkID = pChunkHeader->id.fourcc; + ma_uint64 bytesRead = 0; + if (ma_dr_wav__chunk_matches(allowedMetadataTypes, pChunkID, ma_dr_wav_metadata_type_smpl, "smpl")) { + if (pChunkHeader->sizeInBytes >= MA_DR_WAV_SMPL_BYTES) { + if (pParser->stage == ma_dr_wav__metadata_parser_stage_count) { + ma_uint8 buffer[4]; + size_t bytesJustRead; + if (!pParser->onSeek(pParser->pReadSeekUserData, 28, ma_dr_wav_seek_origin_current)) { + return bytesRead; + } + bytesRead += 28; + bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, buffer, sizeof(buffer), &bytesRead); + if (bytesJustRead == sizeof(buffer)) { + ma_uint32 loopCount = ma_dr_wav_bytes_to_u32(buffer); + ma_uint64 calculatedLoopCount; + calculatedLoopCount = (pChunkHeader->sizeInBytes - MA_DR_WAV_SMPL_BYTES) / MA_DR_WAV_SMPL_LOOP_BYTES; + if (calculatedLoopCount == loopCount) { + bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, buffer, sizeof(buffer), &bytesRead); + if (bytesJustRead == sizeof(buffer)) { + ma_uint32 samplerSpecificDataSizeInBytes = ma_dr_wav_bytes_to_u32(buffer); + pParser->metadataCount += 1; + ma_dr_wav__metadata_request_extra_memory_for_stage_2(pParser, sizeof(ma_dr_wav_smpl_loop) * loopCount, MA_DR_WAV_METADATA_ALIGNMENT); + ma_dr_wav__metadata_request_extra_memory_for_stage_2(pParser, samplerSpecificDataSizeInBytes, 1); + } + } else { + } + } + } else { + bytesRead = ma_dr_wav__read_smpl_to_metadata_obj(pParser, pChunkHeader, &pParser->pMetadata[pParser->metadataCursor]); + if (bytesRead == pChunkHeader->sizeInBytes) { + pParser->metadataCursor += 1; + } else { + } + } + } else { + } + } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, pChunkID, ma_dr_wav_metadata_type_inst, "inst")) { + if (pChunkHeader->sizeInBytes == MA_DR_WAV_INST_BYTES) { + if (pParser->stage == ma_dr_wav__metadata_parser_stage_count) { + pParser->metadataCount += 1; + } else { + bytesRead = ma_dr_wav__read_inst_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor]); + if (bytesRead == pChunkHeader->sizeInBytes) { + pParser->metadataCursor += 1; + } else { + } + } + } else { + } + } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, pChunkID, ma_dr_wav_metadata_type_acid, "acid")) { + if (pChunkHeader->sizeInBytes == MA_DR_WAV_ACID_BYTES) { + if (pParser->stage == ma_dr_wav__metadata_parser_stage_count) { + pParser->metadataCount += 1; + } else { + bytesRead = ma_dr_wav__read_acid_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor]); + if (bytesRead == pChunkHeader->sizeInBytes) { + pParser->metadataCursor += 1; + } else { + } + } + } else { + } + } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, pChunkID, ma_dr_wav_metadata_type_cue, "cue ")) { + if (pChunkHeader->sizeInBytes >= MA_DR_WAV_CUE_BYTES) { + if (pParser->stage == ma_dr_wav__metadata_parser_stage_count) { + size_t cueCount; + pParser->metadataCount += 1; + cueCount = (size_t)(pChunkHeader->sizeInBytes - MA_DR_WAV_CUE_BYTES) / MA_DR_WAV_CUE_POINT_BYTES; + ma_dr_wav__metadata_request_extra_memory_for_stage_2(pParser, sizeof(ma_dr_wav_cue_point) * cueCount, MA_DR_WAV_METADATA_ALIGNMENT); + } else { + bytesRead = ma_dr_wav__read_cue_to_metadata_obj(pParser, pChunkHeader, &pParser->pMetadata[pParser->metadataCursor]); + if (bytesRead == pChunkHeader->sizeInBytes) { + pParser->metadataCursor += 1; + } else { + } + } + } else { + } + } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, pChunkID, ma_dr_wav_metadata_type_bext, "bext")) { + if (pChunkHeader->sizeInBytes >= MA_DR_WAV_BEXT_BYTES) { + if (pParser->stage == ma_dr_wav__metadata_parser_stage_count) { + char buffer[MA_DR_WAV_BEXT_DESCRIPTION_BYTES + 1]; + size_t allocSizeNeeded = MA_DR_WAV_BEXT_UMID_BYTES; + size_t bytesJustRead; + buffer[MA_DR_WAV_BEXT_DESCRIPTION_BYTES] = '\0'; + bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, buffer, MA_DR_WAV_BEXT_DESCRIPTION_BYTES, &bytesRead); + if (bytesJustRead != MA_DR_WAV_BEXT_DESCRIPTION_BYTES) { + return bytesRead; + } + allocSizeNeeded += ma_dr_wav__strlen(buffer) + 1; + buffer[MA_DR_WAV_BEXT_ORIGINATOR_NAME_BYTES] = '\0'; + bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, buffer, MA_DR_WAV_BEXT_ORIGINATOR_NAME_BYTES, &bytesRead); + if (bytesJustRead != MA_DR_WAV_BEXT_ORIGINATOR_NAME_BYTES) { + return bytesRead; + } + allocSizeNeeded += ma_dr_wav__strlen(buffer) + 1; + buffer[MA_DR_WAV_BEXT_ORIGINATOR_REF_BYTES] = '\0'; + bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, buffer, MA_DR_WAV_BEXT_ORIGINATOR_REF_BYTES, &bytesRead); + if (bytesJustRead != MA_DR_WAV_BEXT_ORIGINATOR_REF_BYTES) { + return bytesRead; + } + allocSizeNeeded += ma_dr_wav__strlen(buffer) + 1; + allocSizeNeeded += (size_t)pChunkHeader->sizeInBytes - MA_DR_WAV_BEXT_BYTES; + ma_dr_wav__metadata_request_extra_memory_for_stage_2(pParser, allocSizeNeeded, 1); + pParser->metadataCount += 1; + } else { + bytesRead = ma_dr_wav__read_bext_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor], pChunkHeader->sizeInBytes); + if (bytesRead == pChunkHeader->sizeInBytes) { + pParser->metadataCursor += 1; + } else { + } + } + } else { + } + } else if (ma_dr_wav_fourcc_equal(pChunkID, "LIST") || ma_dr_wav_fourcc_equal(pChunkID, "list")) { + ma_dr_wav_metadata_location listType = ma_dr_wav_metadata_location_invalid; + while (bytesRead < pChunkHeader->sizeInBytes) { + ma_uint8 subchunkId[4]; + ma_uint8 subchunkSizeBuffer[4]; + ma_uint64 subchunkDataSize; + ma_uint64 subchunkBytesRead = 0; + ma_uint64 bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, subchunkId, sizeof(subchunkId), &bytesRead); + if (bytesJustRead != sizeof(subchunkId)) { + break; + } + if (ma_dr_wav_fourcc_equal(subchunkId, "adtl")) { + listType = ma_dr_wav_metadata_location_inside_adtl_list; + continue; + } else if (ma_dr_wav_fourcc_equal(subchunkId, "INFO")) { + listType = ma_dr_wav_metadata_location_inside_info_list; + continue; + } + bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, subchunkSizeBuffer, sizeof(subchunkSizeBuffer), &bytesRead); + if (bytesJustRead != sizeof(subchunkSizeBuffer)) { + break; + } + subchunkDataSize = ma_dr_wav_bytes_to_u32(subchunkSizeBuffer); + if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_label, "labl") || ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_note, "note")) { + if (subchunkDataSize >= MA_DR_WAV_LIST_LABEL_OR_NOTE_BYTES) { + ma_uint64 stringSizeWithNullTerm = subchunkDataSize - MA_DR_WAV_LIST_LABEL_OR_NOTE_BYTES; + if (pParser->stage == ma_dr_wav__metadata_parser_stage_count) { + pParser->metadataCount += 1; + ma_dr_wav__metadata_request_extra_memory_for_stage_2(pParser, (size_t)stringSizeWithNullTerm, 1); + } else { + subchunkBytesRead = ma_dr_wav__read_list_label_or_note_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor], subchunkDataSize, ma_dr_wav_fourcc_equal(subchunkId, "labl") ? ma_dr_wav_metadata_type_list_label : ma_dr_wav_metadata_type_list_note); + if (subchunkBytesRead == subchunkDataSize) { + pParser->metadataCursor += 1; + } else { + } + } + } else { + } + } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_labelled_cue_region, "ltxt")) { + if (subchunkDataSize >= MA_DR_WAV_LIST_LABELLED_TEXT_BYTES) { + ma_uint64 stringSizeWithNullTerminator = subchunkDataSize - MA_DR_WAV_LIST_LABELLED_TEXT_BYTES; + if (pParser->stage == ma_dr_wav__metadata_parser_stage_count) { + pParser->metadataCount += 1; + ma_dr_wav__metadata_request_extra_memory_for_stage_2(pParser, (size_t)stringSizeWithNullTerminator, 1); + } else { + subchunkBytesRead = ma_dr_wav__read_list_labelled_cue_region_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor], subchunkDataSize); + if (subchunkBytesRead == subchunkDataSize) { + pParser->metadataCursor += 1; + } else { + } + } + } else { + } + } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_info_software, "ISFT")) { + subchunkBytesRead = ma_dr_wav__metadata_process_info_text_chunk(pParser, subchunkDataSize, ma_dr_wav_metadata_type_list_info_software); + } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_info_copyright, "ICOP")) { + subchunkBytesRead = ma_dr_wav__metadata_process_info_text_chunk(pParser, subchunkDataSize, ma_dr_wav_metadata_type_list_info_copyright); + } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_info_title, "INAM")) { + subchunkBytesRead = ma_dr_wav__metadata_process_info_text_chunk(pParser, subchunkDataSize, ma_dr_wav_metadata_type_list_info_title); + } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_info_artist, "IART")) { + subchunkBytesRead = ma_dr_wav__metadata_process_info_text_chunk(pParser, subchunkDataSize, ma_dr_wav_metadata_type_list_info_artist); + } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_info_comment, "ICMT")) { + subchunkBytesRead = ma_dr_wav__metadata_process_info_text_chunk(pParser, subchunkDataSize, ma_dr_wav_metadata_type_list_info_comment); + } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_info_date, "ICRD")) { + subchunkBytesRead = ma_dr_wav__metadata_process_info_text_chunk(pParser, subchunkDataSize, ma_dr_wav_metadata_type_list_info_date); + } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_info_genre, "IGNR")) { + subchunkBytesRead = ma_dr_wav__metadata_process_info_text_chunk(pParser, subchunkDataSize, ma_dr_wav_metadata_type_list_info_genre); + } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_info_album, "IPRD")) { + subchunkBytesRead = ma_dr_wav__metadata_process_info_text_chunk(pParser, subchunkDataSize, ma_dr_wav_metadata_type_list_info_album); + } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_info_tracknumber, "ITRK")) { + subchunkBytesRead = ma_dr_wav__metadata_process_info_text_chunk(pParser, subchunkDataSize, ma_dr_wav_metadata_type_list_info_tracknumber); + } else if ((allowedMetadataTypes & ma_dr_wav_metadata_type_unknown) != 0) { + subchunkBytesRead = ma_dr_wav__metadata_process_unknown_chunk(pParser, subchunkId, subchunkDataSize, listType); + } + bytesRead += subchunkBytesRead; + MA_DR_WAV_ASSERT(subchunkBytesRead <= subchunkDataSize); + if (subchunkBytesRead < subchunkDataSize) { + ma_uint64 bytesToSeek = subchunkDataSize - subchunkBytesRead; + if (!pParser->onSeek(pParser->pReadSeekUserData, (int)bytesToSeek, ma_dr_wav_seek_origin_current)) { + break; + } + bytesRead += bytesToSeek; + } + if ((subchunkDataSize % 2) == 1) { + if (!pParser->onSeek(pParser->pReadSeekUserData, 1, ma_dr_wav_seek_origin_current)) { + break; + } + bytesRead += 1; + } + } + } else if ((allowedMetadataTypes & ma_dr_wav_metadata_type_unknown) != 0) { + bytesRead = ma_dr_wav__metadata_process_unknown_chunk(pParser, pChunkID, pChunkHeader->sizeInBytes, ma_dr_wav_metadata_location_top_level); + } + return bytesRead; +} +MA_PRIVATE ma_uint32 ma_dr_wav_get_bytes_per_pcm_frame(ma_dr_wav* pWav) +{ + ma_uint32 bytesPerFrame; + if ((pWav->bitsPerSample & 0x7) == 0) { + bytesPerFrame = (pWav->bitsPerSample * pWav->fmt.channels) >> 3; + } else { + bytesPerFrame = pWav->fmt.blockAlign; + } + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ALAW || pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_MULAW) { + if (bytesPerFrame != pWav->fmt.channels) { + return 0; + } + } + return bytesPerFrame; +} +MA_API ma_uint16 ma_dr_wav_fmt_get_format(const ma_dr_wav_fmt* pFMT) +{ + if (pFMT == NULL) { + return 0; + } + if (pFMT->formatTag != MA_DR_WAVE_FORMAT_EXTENSIBLE) { + return pFMT->formatTag; + } else { + return ma_dr_wav_bytes_to_u16(pFMT->subFormat); + } +} +MA_PRIVATE ma_bool32 ma_dr_wav_preinit(ma_dr_wav* pWav, ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pReadSeekUserData, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pWav == NULL || onRead == NULL || onSeek == NULL) { + return MA_FALSE; + } + MA_DR_WAV_ZERO_MEMORY(pWav, sizeof(*pWav)); + pWav->onRead = onRead; + pWav->onSeek = onSeek; + pWav->pUserData = pReadSeekUserData; + pWav->allocationCallbacks = ma_dr_wav_copy_allocation_callbacks_or_defaults(pAllocationCallbacks); + if (pWav->allocationCallbacks.onFree == NULL || (pWav->allocationCallbacks.onMalloc == NULL && pWav->allocationCallbacks.onRealloc == NULL)) { + return MA_FALSE; + } + return MA_TRUE; +} +MA_PRIVATE ma_bool32 ma_dr_wav_init__internal(ma_dr_wav* pWav, ma_dr_wav_chunk_proc onChunk, void* pChunkUserData, ma_uint32 flags) +{ + ma_result result; + ma_uint64 cursor; + ma_bool32 sequential; + ma_uint8 riff[4]; + ma_dr_wav_fmt fmt; + unsigned short translatedFormatTag; + ma_uint64 dataChunkSize = 0; + ma_uint64 sampleCountFromFactChunk = 0; + ma_uint64 metadataStartPos; + ma_dr_wav__metadata_parser metadataParser; + ma_bool8 isProcessingMetadata = MA_FALSE; + ma_bool8 foundChunk_fmt = MA_FALSE; + ma_bool8 foundChunk_data = MA_FALSE; + ma_bool8 isAIFCFormType = MA_FALSE; + ma_uint64 aiffFrameCount = 0; + cursor = 0; + sequential = (flags & MA_DR_WAV_SEQUENTIAL) != 0; + MA_DR_WAV_ZERO_OBJECT(&fmt); + if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, riff, sizeof(riff), &cursor) != sizeof(riff)) { + return MA_FALSE; + } + if (ma_dr_wav_fourcc_equal(riff, "RIFF")) { + pWav->container = ma_dr_wav_container_riff; + } else if (ma_dr_wav_fourcc_equal(riff, "RIFX")) { + pWav->container = ma_dr_wav_container_rifx; + } else if (ma_dr_wav_fourcc_equal(riff, "riff")) { + int i; + ma_uint8 riff2[12]; + pWav->container = ma_dr_wav_container_w64; + if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, riff2, sizeof(riff2), &cursor) != sizeof(riff2)) { + return MA_FALSE; + } + for (i = 0; i < 12; ++i) { + if (riff2[i] != ma_dr_wavGUID_W64_RIFF[i+4]) { + return MA_FALSE; + } + } + } else if (ma_dr_wav_fourcc_equal(riff, "RF64")) { + pWav->container = ma_dr_wav_container_rf64; + } else if (ma_dr_wav_fourcc_equal(riff, "FORM")) { + pWav->container = ma_dr_wav_container_aiff; + } else { + return MA_FALSE; + } + if (pWav->container == ma_dr_wav_container_riff || pWav->container == ma_dr_wav_container_rifx || pWav->container == ma_dr_wav_container_rf64) { + ma_uint8 chunkSizeBytes[4]; + ma_uint8 wave[4]; + if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, chunkSizeBytes, sizeof(chunkSizeBytes), &cursor) != sizeof(chunkSizeBytes)) { + return MA_FALSE; + } + if (pWav->container == ma_dr_wav_container_riff || pWav->container == ma_dr_wav_container_rifx) { + if (ma_dr_wav_bytes_to_u32_ex(chunkSizeBytes, pWav->container) < 36) { + return MA_FALSE; + } + } else if (pWav->container == ma_dr_wav_container_rf64) { + if (ma_dr_wav_bytes_to_u32_le(chunkSizeBytes) != 0xFFFFFFFF) { + return MA_FALSE; + } + } else { + return MA_FALSE; + } + if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, wave, sizeof(wave), &cursor) != sizeof(wave)) { + return MA_FALSE; + } + if (!ma_dr_wav_fourcc_equal(wave, "WAVE")) { + return MA_FALSE; + } + } else if (pWav->container == ma_dr_wav_container_w64) { + ma_uint8 chunkSizeBytes[8]; + ma_uint8 wave[16]; + if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, chunkSizeBytes, sizeof(chunkSizeBytes), &cursor) != sizeof(chunkSizeBytes)) { + return MA_FALSE; + } + if (ma_dr_wav_bytes_to_u64(chunkSizeBytes) < 80) { + return MA_FALSE; + } + if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, wave, sizeof(wave), &cursor) != sizeof(wave)) { + return MA_FALSE; + } + if (!ma_dr_wav_guid_equal(wave, ma_dr_wavGUID_W64_WAVE)) { + return MA_FALSE; + } + } else if (pWav->container == ma_dr_wav_container_aiff) { + ma_uint8 chunkSizeBytes[4]; + ma_uint8 aiff[4]; + if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, chunkSizeBytes, sizeof(chunkSizeBytes), &cursor) != sizeof(chunkSizeBytes)) { + return MA_FALSE; + } + if (ma_dr_wav_bytes_to_u32_be(chunkSizeBytes) < 18) { + return MA_FALSE; + } + if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, aiff, sizeof(aiff), &cursor) != sizeof(aiff)) { + return MA_FALSE; + } + if (ma_dr_wav_fourcc_equal(aiff, "AIFF")) { + isAIFCFormType = MA_FALSE; + } else if (ma_dr_wav_fourcc_equal(aiff, "AIFC")) { + isAIFCFormType = MA_TRUE; + } else { + return MA_FALSE; + } + } else { + return MA_FALSE; + } + if (pWav->container == ma_dr_wav_container_rf64) { + ma_uint8 sizeBytes[8]; + ma_uint64 bytesRemainingInChunk; + ma_dr_wav_chunk_header header; + result = ma_dr_wav__read_chunk_header(pWav->onRead, pWav->pUserData, pWav->container, &cursor, &header); + if (result != MA_SUCCESS) { + return MA_FALSE; + } + if (!ma_dr_wav_fourcc_equal(header.id.fourcc, "ds64")) { + return MA_FALSE; + } + bytesRemainingInChunk = header.sizeInBytes + header.paddingSize; + if (!ma_dr_wav__seek_forward(pWav->onSeek, 8, pWav->pUserData)) { + return MA_FALSE; + } + bytesRemainingInChunk -= 8; + cursor += 8; + if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, sizeBytes, sizeof(sizeBytes), &cursor) != sizeof(sizeBytes)) { + return MA_FALSE; + } + bytesRemainingInChunk -= 8; + dataChunkSize = ma_dr_wav_bytes_to_u64(sizeBytes); + if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, sizeBytes, sizeof(sizeBytes), &cursor) != sizeof(sizeBytes)) { + return MA_FALSE; + } + bytesRemainingInChunk -= 8; + sampleCountFromFactChunk = ma_dr_wav_bytes_to_u64(sizeBytes); + if (!ma_dr_wav__seek_forward(pWav->onSeek, bytesRemainingInChunk, pWav->pUserData)) { + return MA_FALSE; + } + cursor += bytesRemainingInChunk; + } + metadataStartPos = cursor; + isProcessingMetadata = !sequential && ((flags & MA_DR_WAV_WITH_METADATA) != 0); + if (pWav->container != ma_dr_wav_container_riff && pWav->container != ma_dr_wav_container_rf64) { + isProcessingMetadata = MA_FALSE; + } + MA_DR_WAV_ZERO_MEMORY(&metadataParser, sizeof(metadataParser)); + if (isProcessingMetadata) { + metadataParser.onRead = pWav->onRead; + metadataParser.onSeek = pWav->onSeek; + metadataParser.pReadSeekUserData = pWav->pUserData; + metadataParser.stage = ma_dr_wav__metadata_parser_stage_count; + } + for (;;) { + ma_dr_wav_chunk_header header; + ma_uint64 chunkSize; + result = ma_dr_wav__read_chunk_header(pWav->onRead, pWav->pUserData, pWav->container, &cursor, &header); + if (result != MA_SUCCESS) { + break; + } + chunkSize = header.sizeInBytes; + if (!sequential && onChunk != NULL) { + ma_uint64 callbackBytesRead = onChunk(pChunkUserData, pWav->onRead, pWav->onSeek, pWav->pUserData, &header, pWav->container, &fmt); + if (callbackBytesRead > 0) { + if (ma_dr_wav__seek_from_start(pWav->onSeek, cursor, pWav->pUserData) == MA_FALSE) { + return MA_FALSE; + } + } + } + if (((pWav->container == ma_dr_wav_container_riff || pWav->container == ma_dr_wav_container_rifx || pWav->container == ma_dr_wav_container_rf64) && ma_dr_wav_fourcc_equal(header.id.fourcc, "fmt ")) || + ((pWav->container == ma_dr_wav_container_w64) && ma_dr_wav_guid_equal(header.id.guid, ma_dr_wavGUID_W64_FMT))) { + ma_uint8 fmtData[16]; + foundChunk_fmt = MA_TRUE; + if (pWav->onRead(pWav->pUserData, fmtData, sizeof(fmtData)) != sizeof(fmtData)) { + return MA_FALSE; + } + cursor += sizeof(fmtData); + fmt.formatTag = ma_dr_wav_bytes_to_u16_ex(fmtData + 0, pWav->container); + fmt.channels = ma_dr_wav_bytes_to_u16_ex(fmtData + 2, pWav->container); + fmt.sampleRate = ma_dr_wav_bytes_to_u32_ex(fmtData + 4, pWav->container); + fmt.avgBytesPerSec = ma_dr_wav_bytes_to_u32_ex(fmtData + 8, pWav->container); + fmt.blockAlign = ma_dr_wav_bytes_to_u16_ex(fmtData + 12, pWav->container); + fmt.bitsPerSample = ma_dr_wav_bytes_to_u16_ex(fmtData + 14, pWav->container); + fmt.extendedSize = 0; + fmt.validBitsPerSample = 0; + fmt.channelMask = 0; + MA_DR_WAV_ZERO_MEMORY(fmt.subFormat, sizeof(fmt.subFormat)); + if (header.sizeInBytes > 16) { + ma_uint8 fmt_cbSize[2]; + int bytesReadSoFar = 0; + if (pWav->onRead(pWav->pUserData, fmt_cbSize, sizeof(fmt_cbSize)) != sizeof(fmt_cbSize)) { + return MA_FALSE; + } + cursor += sizeof(fmt_cbSize); + bytesReadSoFar = 18; + fmt.extendedSize = ma_dr_wav_bytes_to_u16_ex(fmt_cbSize, pWav->container); + if (fmt.extendedSize > 0) { + if (fmt.formatTag == MA_DR_WAVE_FORMAT_EXTENSIBLE) { + if (fmt.extendedSize != 22) { + return MA_FALSE; + } + } + if (fmt.formatTag == MA_DR_WAVE_FORMAT_EXTENSIBLE) { + ma_uint8 fmtext[22]; + if (pWav->onRead(pWav->pUserData, fmtext, fmt.extendedSize) != fmt.extendedSize) { + return MA_FALSE; + } + fmt.validBitsPerSample = ma_dr_wav_bytes_to_u16_ex(fmtext + 0, pWav->container); + fmt.channelMask = ma_dr_wav_bytes_to_u32_ex(fmtext + 2, pWav->container); + ma_dr_wav_bytes_to_guid(fmtext + 6, fmt.subFormat); + } else { + if (pWav->onSeek(pWav->pUserData, fmt.extendedSize, ma_dr_wav_seek_origin_current) == MA_FALSE) { + return MA_FALSE; + } + } + cursor += fmt.extendedSize; + bytesReadSoFar += fmt.extendedSize; + } + if (pWav->onSeek(pWav->pUserData, (int)(header.sizeInBytes - bytesReadSoFar), ma_dr_wav_seek_origin_current) == MA_FALSE) { + return MA_FALSE; + } + cursor += (header.sizeInBytes - bytesReadSoFar); + } + if (header.paddingSize > 0) { + if (ma_dr_wav__seek_forward(pWav->onSeek, header.paddingSize, pWav->pUserData) == MA_FALSE) { + break; + } + cursor += header.paddingSize; + } + continue; + } + if (((pWav->container == ma_dr_wav_container_riff || pWav->container == ma_dr_wav_container_rifx || pWav->container == ma_dr_wav_container_rf64) && ma_dr_wav_fourcc_equal(header.id.fourcc, "data")) || + ((pWav->container == ma_dr_wav_container_w64) && ma_dr_wav_guid_equal(header.id.guid, ma_dr_wavGUID_W64_DATA))) { + foundChunk_data = MA_TRUE; + pWav->dataChunkDataPos = cursor; + if (pWav->container != ma_dr_wav_container_rf64) { + dataChunkSize = chunkSize; + } + if (sequential || !isProcessingMetadata) { + break; + } else { + chunkSize += header.paddingSize; + if (ma_dr_wav__seek_forward(pWav->onSeek, chunkSize, pWav->pUserData) == MA_FALSE) { + break; + } + cursor += chunkSize; + continue; + } + } + if (((pWav->container == ma_dr_wav_container_riff || pWav->container == ma_dr_wav_container_rifx || pWav->container == ma_dr_wav_container_rf64) && ma_dr_wav_fourcc_equal(header.id.fourcc, "fact")) || + ((pWav->container == ma_dr_wav_container_w64) && ma_dr_wav_guid_equal(header.id.guid, ma_dr_wavGUID_W64_FACT))) { + if (pWav->container == ma_dr_wav_container_riff || pWav->container == ma_dr_wav_container_rifx) { + ma_uint8 sampleCount[4]; + if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, &sampleCount, 4, &cursor) != 4) { + return MA_FALSE; + } + chunkSize -= 4; + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ADPCM) { + sampleCountFromFactChunk = ma_dr_wav_bytes_to_u32_ex(sampleCount, pWav->container); + } else { + sampleCountFromFactChunk = 0; + } + } else if (pWav->container == ma_dr_wav_container_w64) { + if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, &sampleCountFromFactChunk, 8, &cursor) != 8) { + return MA_FALSE; + } + chunkSize -= 8; + } else if (pWav->container == ma_dr_wav_container_rf64) { + } + chunkSize += header.paddingSize; + if (ma_dr_wav__seek_forward(pWav->onSeek, chunkSize, pWav->pUserData) == MA_FALSE) { + break; + } + cursor += chunkSize; + continue; + } + if (pWav->container == ma_dr_wav_container_aiff && ma_dr_wav_fourcc_equal(header.id.fourcc, "COMM")) { + ma_uint8 commData[24]; + ma_uint32 commDataBytesToRead; + ma_uint16 channels; + ma_uint32 frameCount; + ma_uint16 sampleSizeInBits; + ma_int64 sampleRate; + ma_uint16 compressionFormat; + foundChunk_fmt = MA_TRUE; + if (isAIFCFormType) { + commDataBytesToRead = 24; + if (header.sizeInBytes < commDataBytesToRead) { + return MA_FALSE; + } + } else { + commDataBytesToRead = 18; + if (header.sizeInBytes != commDataBytesToRead) { + return MA_FALSE; + } + } + if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, commData, commDataBytesToRead, &cursor) != commDataBytesToRead) { + return MA_FALSE; + } + channels = ma_dr_wav_bytes_to_u16_ex (commData + 0, pWav->container); + frameCount = ma_dr_wav_bytes_to_u32_ex (commData + 2, pWav->container); + sampleSizeInBits = ma_dr_wav_bytes_to_u16_ex (commData + 6, pWav->container); + sampleRate = ma_dr_wav_aiff_extented_to_s64(commData + 8); + if (sampleRate < 0 || sampleRate > 0xFFFFFFFF) { + return MA_FALSE; + } + if (isAIFCFormType) { + const ma_uint8* type = commData + 18; + if (ma_dr_wav_fourcc_equal(type, "NONE")) { + compressionFormat = MA_DR_WAVE_FORMAT_PCM; + } else if (ma_dr_wav_fourcc_equal(type, "raw ")) { + compressionFormat = MA_DR_WAVE_FORMAT_PCM; + if (sampleSizeInBits == 8) { + pWav->aiff.isUnsigned = MA_TRUE; + } + } else if (ma_dr_wav_fourcc_equal(type, "sowt")) { + compressionFormat = MA_DR_WAVE_FORMAT_PCM; + pWav->aiff.isLE = MA_TRUE; + } else if (ma_dr_wav_fourcc_equal(type, "fl32") || ma_dr_wav_fourcc_equal(type, "fl64") || ma_dr_wav_fourcc_equal(type, "FL32") || ma_dr_wav_fourcc_equal(type, "FL64")) { + compressionFormat = MA_DR_WAVE_FORMAT_IEEE_FLOAT; + } else if (ma_dr_wav_fourcc_equal(type, "alaw") || ma_dr_wav_fourcc_equal(type, "ALAW")) { + compressionFormat = MA_DR_WAVE_FORMAT_ALAW; + } else if (ma_dr_wav_fourcc_equal(type, "ulaw") || ma_dr_wav_fourcc_equal(type, "ULAW")) { + compressionFormat = MA_DR_WAVE_FORMAT_MULAW; + } else if (ma_dr_wav_fourcc_equal(type, "ima4")) { + compressionFormat = MA_DR_WAVE_FORMAT_DVI_ADPCM; + sampleSizeInBits = 4; + return MA_FALSE; + } else { + return MA_FALSE; + } + } else { + compressionFormat = MA_DR_WAVE_FORMAT_PCM; + } + aiffFrameCount = frameCount; + fmt.formatTag = compressionFormat; + fmt.channels = channels; + fmt.sampleRate = (ma_uint32)sampleRate; + fmt.bitsPerSample = sampleSizeInBits; + fmt.blockAlign = (ma_uint16)(fmt.channels * fmt.bitsPerSample / 8); + fmt.avgBytesPerSec = fmt.blockAlign * fmt.sampleRate; + if (fmt.blockAlign == 0 && compressionFormat == MA_DR_WAVE_FORMAT_DVI_ADPCM) { + fmt.blockAlign = 34 * fmt.channels; + } + if (compressionFormat == MA_DR_WAVE_FORMAT_ALAW || compressionFormat == MA_DR_WAVE_FORMAT_MULAW) { + if (fmt.bitsPerSample > 8) { + fmt.bitsPerSample = 8; + fmt.blockAlign = fmt.channels; + } + } + fmt.bitsPerSample += (fmt.bitsPerSample & 7); + if (isAIFCFormType) { + if (ma_dr_wav__seek_forward(pWav->onSeek, (chunkSize - commDataBytesToRead), pWav->pUserData) == MA_FALSE) { + return MA_FALSE; + } + cursor += (chunkSize - commDataBytesToRead); + } + continue; + } + if (pWav->container == ma_dr_wav_container_aiff && ma_dr_wav_fourcc_equal(header.id.fourcc, "SSND")) { + ma_uint8 offsetAndBlockSizeData[8]; + ma_uint32 offset; + foundChunk_data = MA_TRUE; + if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, offsetAndBlockSizeData, sizeof(offsetAndBlockSizeData), &cursor) != sizeof(offsetAndBlockSizeData)) { + return MA_FALSE; + } + offset = ma_dr_wav_bytes_to_u32_ex(offsetAndBlockSizeData + 0, pWav->container); + if (ma_dr_wav__seek_forward(pWav->onSeek, offset, pWav->pUserData) == MA_FALSE) { + return MA_FALSE; + } + cursor += offset; + pWav->dataChunkDataPos = cursor; + dataChunkSize = chunkSize; + if (sequential || !isProcessingMetadata) { + break; + } else { + if (ma_dr_wav__seek_forward(pWav->onSeek, chunkSize, pWav->pUserData) == MA_FALSE) { + break; + } + cursor += chunkSize; + continue; + } + } + if (isProcessingMetadata) { + ma_uint64 metadataBytesRead; + metadataBytesRead = ma_dr_wav__metadata_process_chunk(&metadataParser, &header, ma_dr_wav_metadata_type_all_including_unknown); + MA_DR_WAV_ASSERT(metadataBytesRead <= header.sizeInBytes); + if (ma_dr_wav__seek_from_start(pWav->onSeek, cursor, pWav->pUserData) == MA_FALSE) { + break; + } + } + chunkSize += header.paddingSize; + if (ma_dr_wav__seek_forward(pWav->onSeek, chunkSize, pWav->pUserData) == MA_FALSE) { + break; + } + cursor += chunkSize; + } + if (!foundChunk_fmt || !foundChunk_data) { + return MA_FALSE; + } + if ((fmt.sampleRate == 0 || fmt.sampleRate > MA_DR_WAV_MAX_SAMPLE_RATE ) || + (fmt.channels == 0 || fmt.channels > MA_DR_WAV_MAX_CHANNELS ) || + (fmt.bitsPerSample == 0 || fmt.bitsPerSample > MA_DR_WAV_MAX_BITS_PER_SAMPLE) || + fmt.blockAlign == 0) { + return MA_FALSE; + } + translatedFormatTag = fmt.formatTag; + if (translatedFormatTag == MA_DR_WAVE_FORMAT_EXTENSIBLE) { + translatedFormatTag = ma_dr_wav_bytes_to_u16_ex(fmt.subFormat + 0, pWav->container); + } + if (!sequential) { + if (!ma_dr_wav__seek_from_start(pWav->onSeek, pWav->dataChunkDataPos, pWav->pUserData)) { + return MA_FALSE; + } + cursor = pWav->dataChunkDataPos; + } + if (isProcessingMetadata && metadataParser.metadataCount > 0) { + if (ma_dr_wav__seek_from_start(pWav->onSeek, metadataStartPos, pWav->pUserData) == MA_FALSE) { + return MA_FALSE; + } + result = ma_dr_wav__metadata_alloc(&metadataParser, &pWav->allocationCallbacks); + if (result != MA_SUCCESS) { + return MA_FALSE; + } + metadataParser.stage = ma_dr_wav__metadata_parser_stage_read; + for (;;) { + ma_dr_wav_chunk_header header; + ma_uint64 metadataBytesRead; + result = ma_dr_wav__read_chunk_header(pWav->onRead, pWav->pUserData, pWav->container, &cursor, &header); + if (result != MA_SUCCESS) { + break; + } + metadataBytesRead = ma_dr_wav__metadata_process_chunk(&metadataParser, &header, ma_dr_wav_metadata_type_all_including_unknown); + if (ma_dr_wav__seek_forward(pWav->onSeek, (header.sizeInBytes + header.paddingSize) - metadataBytesRead, pWav->pUserData) == MA_FALSE) { + ma_dr_wav_free(metadataParser.pMetadata, &pWav->allocationCallbacks); + return MA_FALSE; + } + } + pWav->pMetadata = metadataParser.pMetadata; + pWav->metadataCount = metadataParser.metadataCount; + } + if (dataChunkSize == 0xFFFFFFFF && (pWav->container == ma_dr_wav_container_riff || pWav->container == ma_dr_wav_container_rifx) && pWav->isSequentialWrite == MA_FALSE) { + dataChunkSize = 0; + for (;;) { + ma_uint8 temp[4096]; + size_t bytesRead = pWav->onRead(pWav->pUserData, temp, sizeof(temp)); + dataChunkSize += bytesRead; + if (bytesRead < sizeof(temp)) { + break; + } + } + } + if (ma_dr_wav__seek_from_start(pWav->onSeek, pWav->dataChunkDataPos, pWav->pUserData) == MA_FALSE) { + ma_dr_wav_free(pWav->pMetadata, &pWav->allocationCallbacks); + return MA_FALSE; + } + pWav->fmt = fmt; + pWav->sampleRate = fmt.sampleRate; + pWav->channels = fmt.channels; + pWav->bitsPerSample = fmt.bitsPerSample; + pWav->bytesRemaining = dataChunkSize; + pWav->translatedFormatTag = translatedFormatTag; + pWav->dataChunkDataSize = dataChunkSize; + if (sampleCountFromFactChunk != 0) { + pWav->totalPCMFrameCount = sampleCountFromFactChunk; + } else if (aiffFrameCount != 0) { + pWav->totalPCMFrameCount = aiffFrameCount; + } else { + ma_uint32 bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav); + if (bytesPerFrame == 0) { + ma_dr_wav_free(pWav->pMetadata, &pWav->allocationCallbacks); + return MA_FALSE; + } + pWav->totalPCMFrameCount = dataChunkSize / bytesPerFrame; + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ADPCM) { + ma_uint64 totalBlockHeaderSizeInBytes; + ma_uint64 blockCount = dataChunkSize / fmt.blockAlign; + if ((blockCount * fmt.blockAlign) < dataChunkSize) { + blockCount += 1; + } + totalBlockHeaderSizeInBytes = blockCount * (6*fmt.channels); + pWav->totalPCMFrameCount = ((dataChunkSize - totalBlockHeaderSizeInBytes) * 2) / fmt.channels; + } + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_DVI_ADPCM) { + ma_uint64 totalBlockHeaderSizeInBytes; + ma_uint64 blockCount = dataChunkSize / fmt.blockAlign; + if ((blockCount * fmt.blockAlign) < dataChunkSize) { + blockCount += 1; + } + totalBlockHeaderSizeInBytes = blockCount * (4*fmt.channels); + pWav->totalPCMFrameCount = ((dataChunkSize - totalBlockHeaderSizeInBytes) * 2) / fmt.channels; + pWav->totalPCMFrameCount += blockCount; + } + } + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ADPCM || pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_DVI_ADPCM) { + if (pWav->channels > 2) { + ma_dr_wav_free(pWav->pMetadata, &pWav->allocationCallbacks); + return MA_FALSE; + } + } + if (ma_dr_wav_get_bytes_per_pcm_frame(pWav) == 0) { + ma_dr_wav_free(pWav->pMetadata, &pWav->allocationCallbacks); + return MA_FALSE; + } +#ifdef MA_DR_WAV_LIBSNDFILE_COMPAT + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ADPCM) { + ma_uint64 blockCount = dataChunkSize / fmt.blockAlign; + pWav->totalPCMFrameCount = (((blockCount * (fmt.blockAlign - (6*pWav->channels))) * 2)) / fmt.channels; + } + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_DVI_ADPCM) { + ma_uint64 blockCount = dataChunkSize / fmt.blockAlign; + pWav->totalPCMFrameCount = (((blockCount * (fmt.blockAlign - (4*pWav->channels))) * 2) + (blockCount * pWav->channels)) / fmt.channels; + } +#endif + return MA_TRUE; +} +MA_API ma_bool32 ma_dr_wav_init(ma_dr_wav* pWav, ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks) +{ + return ma_dr_wav_init_ex(pWav, onRead, onSeek, NULL, pUserData, NULL, 0, pAllocationCallbacks); +} +MA_API ma_bool32 ma_dr_wav_init_ex(ma_dr_wav* pWav, ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, ma_dr_wav_chunk_proc onChunk, void* pReadSeekUserData, void* pChunkUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (!ma_dr_wav_preinit(pWav, onRead, onSeek, pReadSeekUserData, pAllocationCallbacks)) { + return MA_FALSE; + } + return ma_dr_wav_init__internal(pWav, onChunk, pChunkUserData, flags); +} +MA_API ma_bool32 ma_dr_wav_init_with_metadata(ma_dr_wav* pWav, ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (!ma_dr_wav_preinit(pWav, onRead, onSeek, pUserData, pAllocationCallbacks)) { + return MA_FALSE; + } + return ma_dr_wav_init__internal(pWav, NULL, NULL, flags | MA_DR_WAV_WITH_METADATA); +} +MA_API ma_dr_wav_metadata* ma_dr_wav_take_ownership_of_metadata(ma_dr_wav* pWav) +{ + ma_dr_wav_metadata *result = pWav->pMetadata; + pWav->pMetadata = NULL; + pWav->metadataCount = 0; + return result; +} +MA_PRIVATE size_t ma_dr_wav__write(ma_dr_wav* pWav, const void* pData, size_t dataSize) +{ + MA_DR_WAV_ASSERT(pWav != NULL); + MA_DR_WAV_ASSERT(pWav->onWrite != NULL); + return pWav->onWrite(pWav->pUserData, pData, dataSize); +} +MA_PRIVATE size_t ma_dr_wav__write_byte(ma_dr_wav* pWav, ma_uint8 byte) +{ + MA_DR_WAV_ASSERT(pWav != NULL); + MA_DR_WAV_ASSERT(pWav->onWrite != NULL); + return pWav->onWrite(pWav->pUserData, &byte, 1); +} +MA_PRIVATE size_t ma_dr_wav__write_u16ne_to_le(ma_dr_wav* pWav, ma_uint16 value) +{ + MA_DR_WAV_ASSERT(pWav != NULL); + MA_DR_WAV_ASSERT(pWav->onWrite != NULL); + if (!ma_dr_wav__is_little_endian()) { + value = ma_dr_wav__bswap16(value); + } + return ma_dr_wav__write(pWav, &value, 2); +} +MA_PRIVATE size_t ma_dr_wav__write_u32ne_to_le(ma_dr_wav* pWav, ma_uint32 value) +{ + MA_DR_WAV_ASSERT(pWav != NULL); + MA_DR_WAV_ASSERT(pWav->onWrite != NULL); + if (!ma_dr_wav__is_little_endian()) { + value = ma_dr_wav__bswap32(value); + } + return ma_dr_wav__write(pWav, &value, 4); +} +MA_PRIVATE size_t ma_dr_wav__write_u64ne_to_le(ma_dr_wav* pWav, ma_uint64 value) +{ + MA_DR_WAV_ASSERT(pWav != NULL); + MA_DR_WAV_ASSERT(pWav->onWrite != NULL); + if (!ma_dr_wav__is_little_endian()) { + value = ma_dr_wav__bswap64(value); + } + return ma_dr_wav__write(pWav, &value, 8); +} +MA_PRIVATE size_t ma_dr_wav__write_f32ne_to_le(ma_dr_wav* pWav, float value) +{ + union { + ma_uint32 u32; + float f32; + } u; + MA_DR_WAV_ASSERT(pWav != NULL); + MA_DR_WAV_ASSERT(pWav->onWrite != NULL); + u.f32 = value; + if (!ma_dr_wav__is_little_endian()) { + u.u32 = ma_dr_wav__bswap32(u.u32); + } + return ma_dr_wav__write(pWav, &u.u32, 4); +} +MA_PRIVATE size_t ma_dr_wav__write_or_count(ma_dr_wav* pWav, const void* pData, size_t dataSize) +{ + if (pWav == NULL) { + return dataSize; + } + return ma_dr_wav__write(pWav, pData, dataSize); +} +MA_PRIVATE size_t ma_dr_wav__write_or_count_byte(ma_dr_wav* pWav, ma_uint8 byte) +{ + if (pWav == NULL) { + return 1; + } + return ma_dr_wav__write_byte(pWav, byte); +} +MA_PRIVATE size_t ma_dr_wav__write_or_count_u16ne_to_le(ma_dr_wav* pWav, ma_uint16 value) +{ + if (pWav == NULL) { + return 2; + } + return ma_dr_wav__write_u16ne_to_le(pWav, value); +} +MA_PRIVATE size_t ma_dr_wav__write_or_count_u32ne_to_le(ma_dr_wav* pWav, ma_uint32 value) +{ + if (pWav == NULL) { + return 4; + } + return ma_dr_wav__write_u32ne_to_le(pWav, value); +} +#if 0 +MA_PRIVATE size_t ma_dr_wav__write_or_count_u64ne_to_le(ma_dr_wav* pWav, ma_uint64 value) +{ + if (pWav == NULL) { + return 8; + } + return ma_dr_wav__write_u64ne_to_le(pWav, value); +} +#endif +MA_PRIVATE size_t ma_dr_wav__write_or_count_f32ne_to_le(ma_dr_wav* pWav, float value) +{ + if (pWav == NULL) { + return 4; + } + return ma_dr_wav__write_f32ne_to_le(pWav, value); +} +MA_PRIVATE size_t ma_dr_wav__write_or_count_string_to_fixed_size_buf(ma_dr_wav* pWav, char* str, size_t bufFixedSize) +{ + size_t len; + if (pWav == NULL) { + return bufFixedSize; + } + len = ma_dr_wav__strlen_clamped(str, bufFixedSize); + ma_dr_wav__write_or_count(pWav, str, len); + if (len < bufFixedSize) { + size_t i; + for (i = 0; i < bufFixedSize - len; ++i) { + ma_dr_wav__write_byte(pWav, 0); + } + } + return bufFixedSize; +} +MA_PRIVATE size_t ma_dr_wav__write_or_count_metadata(ma_dr_wav* pWav, ma_dr_wav_metadata* pMetadatas, ma_uint32 metadataCount) +{ + size_t bytesWritten = 0; + ma_bool32 hasListAdtl = MA_FALSE; + ma_bool32 hasListInfo = MA_FALSE; + ma_uint32 iMetadata; + if (pMetadatas == NULL || metadataCount == 0) { + return 0; + } + for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) { + ma_dr_wav_metadata* pMetadata = &pMetadatas[iMetadata]; + ma_uint32 chunkSize = 0; + if ((pMetadata->type & ma_dr_wav_metadata_type_list_all_info_strings) || (pMetadata->type == ma_dr_wav_metadata_type_unknown && pMetadata->data.unknown.chunkLocation == ma_dr_wav_metadata_location_inside_info_list)) { + hasListInfo = MA_TRUE; + } + if ((pMetadata->type & ma_dr_wav_metadata_type_list_all_adtl) || (pMetadata->type == ma_dr_wav_metadata_type_unknown && pMetadata->data.unknown.chunkLocation == ma_dr_wav_metadata_location_inside_adtl_list)) { + hasListAdtl = MA_TRUE; + } + switch (pMetadata->type) { + case ma_dr_wav_metadata_type_smpl: + { + ma_uint32 iLoop; + chunkSize = MA_DR_WAV_SMPL_BYTES + MA_DR_WAV_SMPL_LOOP_BYTES * pMetadata->data.smpl.sampleLoopCount + pMetadata->data.smpl.samplerSpecificDataSizeInBytes; + bytesWritten += ma_dr_wav__write_or_count(pWav, "smpl", 4); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, chunkSize); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.manufacturerId); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.productId); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.samplePeriodNanoseconds); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.midiUnityNote); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.midiPitchFraction); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.smpteFormat); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.smpteOffset); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.sampleLoopCount); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.samplerSpecificDataSizeInBytes); + for (iLoop = 0; iLoop < pMetadata->data.smpl.sampleLoopCount; ++iLoop) { + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].cuePointId); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].type); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].firstSampleByteOffset); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].lastSampleByteOffset); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].sampleFraction); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].playCount); + } + if (pMetadata->data.smpl.samplerSpecificDataSizeInBytes > 0) { + bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.smpl.pSamplerSpecificData, pMetadata->data.smpl.samplerSpecificDataSizeInBytes); + } + } break; + case ma_dr_wav_metadata_type_inst: + { + chunkSize = MA_DR_WAV_INST_BYTES; + bytesWritten += ma_dr_wav__write_or_count(pWav, "inst", 4); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, chunkSize); + bytesWritten += ma_dr_wav__write_or_count(pWav, &pMetadata->data.inst.midiUnityNote, 1); + bytesWritten += ma_dr_wav__write_or_count(pWav, &pMetadata->data.inst.fineTuneCents, 1); + bytesWritten += ma_dr_wav__write_or_count(pWav, &pMetadata->data.inst.gainDecibels, 1); + bytesWritten += ma_dr_wav__write_or_count(pWav, &pMetadata->data.inst.lowNote, 1); + bytesWritten += ma_dr_wav__write_or_count(pWav, &pMetadata->data.inst.highNote, 1); + bytesWritten += ma_dr_wav__write_or_count(pWav, &pMetadata->data.inst.lowVelocity, 1); + bytesWritten += ma_dr_wav__write_or_count(pWav, &pMetadata->data.inst.highVelocity, 1); + } break; + case ma_dr_wav_metadata_type_cue: + { + ma_uint32 iCuePoint; + chunkSize = MA_DR_WAV_CUE_BYTES + MA_DR_WAV_CUE_POINT_BYTES * pMetadata->data.cue.cuePointCount; + bytesWritten += ma_dr_wav__write_or_count(pWav, "cue ", 4); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, chunkSize); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.cuePointCount); + for (iCuePoint = 0; iCuePoint < pMetadata->data.cue.cuePointCount; ++iCuePoint) { + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].id); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].playOrderPosition); + bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId, 4); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].chunkStart); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].blockStart); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].sampleByteOffset); + } + } break; + case ma_dr_wav_metadata_type_acid: + { + chunkSize = MA_DR_WAV_ACID_BYTES; + bytesWritten += ma_dr_wav__write_or_count(pWav, "acid", 4); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, chunkSize); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.acid.flags); + bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.acid.midiUnityNote); + bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.acid.reserved1); + bytesWritten += ma_dr_wav__write_or_count_f32ne_to_le(pWav, pMetadata->data.acid.reserved2); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.acid.numBeats); + bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.acid.meterDenominator); + bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.acid.meterNumerator); + bytesWritten += ma_dr_wav__write_or_count_f32ne_to_le(pWav, pMetadata->data.acid.tempo); + } break; + case ma_dr_wav_metadata_type_bext: + { + char reservedBuf[MA_DR_WAV_BEXT_RESERVED_BYTES]; + ma_uint32 timeReferenceLow; + ma_uint32 timeReferenceHigh; + chunkSize = MA_DR_WAV_BEXT_BYTES + pMetadata->data.bext.codingHistorySize; + bytesWritten += ma_dr_wav__write_or_count(pWav, "bext", 4); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, chunkSize); + bytesWritten += ma_dr_wav__write_or_count_string_to_fixed_size_buf(pWav, pMetadata->data.bext.pDescription, MA_DR_WAV_BEXT_DESCRIPTION_BYTES); + bytesWritten += ma_dr_wav__write_or_count_string_to_fixed_size_buf(pWav, pMetadata->data.bext.pOriginatorName, MA_DR_WAV_BEXT_ORIGINATOR_NAME_BYTES); + bytesWritten += ma_dr_wav__write_or_count_string_to_fixed_size_buf(pWav, pMetadata->data.bext.pOriginatorReference, MA_DR_WAV_BEXT_ORIGINATOR_REF_BYTES); + bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.bext.pOriginationDate, sizeof(pMetadata->data.bext.pOriginationDate)); + bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.bext.pOriginationTime, sizeof(pMetadata->data.bext.pOriginationTime)); + timeReferenceLow = (ma_uint32)(pMetadata->data.bext.timeReference & 0xFFFFFFFF); + timeReferenceHigh = (ma_uint32)(pMetadata->data.bext.timeReference >> 32); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, timeReferenceLow); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, timeReferenceHigh); + bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.version); + bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.bext.pUMID, MA_DR_WAV_BEXT_UMID_BYTES); + bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.loudnessValue); + bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.loudnessRange); + bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.maxTruePeakLevel); + bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.maxMomentaryLoudness); + bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.maxShortTermLoudness); + MA_DR_WAV_ZERO_MEMORY(reservedBuf, sizeof(reservedBuf)); + bytesWritten += ma_dr_wav__write_or_count(pWav, reservedBuf, sizeof(reservedBuf)); + if (pMetadata->data.bext.codingHistorySize > 0) { + bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.bext.pCodingHistory, pMetadata->data.bext.codingHistorySize); + } + } break; + case ma_dr_wav_metadata_type_unknown: + { + if (pMetadata->data.unknown.chunkLocation == ma_dr_wav_metadata_location_top_level) { + chunkSize = pMetadata->data.unknown.dataSizeInBytes; + bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.unknown.id, 4); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, chunkSize); + bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.unknown.pData, pMetadata->data.unknown.dataSizeInBytes); + } + } break; + default: break; + } + if ((chunkSize % 2) != 0) { + bytesWritten += ma_dr_wav__write_or_count_byte(pWav, 0); + } + } + if (hasListInfo) { + ma_uint32 chunkSize = 4; + for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) { + ma_dr_wav_metadata* pMetadata = &pMetadatas[iMetadata]; + if ((pMetadata->type & ma_dr_wav_metadata_type_list_all_info_strings)) { + chunkSize += 8; + chunkSize += pMetadata->data.infoText.stringLength + 1; + } else if (pMetadata->type == ma_dr_wav_metadata_type_unknown && pMetadata->data.unknown.chunkLocation == ma_dr_wav_metadata_location_inside_info_list) { + chunkSize += 8; + chunkSize += pMetadata->data.unknown.dataSizeInBytes; + } + if ((chunkSize % 2) != 0) { + chunkSize += 1; + } + } + bytesWritten += ma_dr_wav__write_or_count(pWav, "LIST", 4); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, chunkSize); + bytesWritten += ma_dr_wav__write_or_count(pWav, "INFO", 4); + for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) { + ma_dr_wav_metadata* pMetadata = &pMetadatas[iMetadata]; + ma_uint32 subchunkSize = 0; + if (pMetadata->type & ma_dr_wav_metadata_type_list_all_info_strings) { + const char* pID = NULL; + switch (pMetadata->type) { + case ma_dr_wav_metadata_type_list_info_software: pID = "ISFT"; break; + case ma_dr_wav_metadata_type_list_info_copyright: pID = "ICOP"; break; + case ma_dr_wav_metadata_type_list_info_title: pID = "INAM"; break; + case ma_dr_wav_metadata_type_list_info_artist: pID = "IART"; break; + case ma_dr_wav_metadata_type_list_info_comment: pID = "ICMT"; break; + case ma_dr_wav_metadata_type_list_info_date: pID = "ICRD"; break; + case ma_dr_wav_metadata_type_list_info_genre: pID = "IGNR"; break; + case ma_dr_wav_metadata_type_list_info_album: pID = "IPRD"; break; + case ma_dr_wav_metadata_type_list_info_tracknumber: pID = "ITRK"; break; + default: break; + } + MA_DR_WAV_ASSERT(pID != NULL); + if (pMetadata->data.infoText.stringLength) { + subchunkSize = pMetadata->data.infoText.stringLength + 1; + bytesWritten += ma_dr_wav__write_or_count(pWav, pID, 4); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, subchunkSize); + bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.infoText.pString, pMetadata->data.infoText.stringLength); + bytesWritten += ma_dr_wav__write_or_count_byte(pWav, '\0'); + } + } else if (pMetadata->type == ma_dr_wav_metadata_type_unknown && pMetadata->data.unknown.chunkLocation == ma_dr_wav_metadata_location_inside_info_list) { + if (pMetadata->data.unknown.dataSizeInBytes) { + subchunkSize = pMetadata->data.unknown.dataSizeInBytes; + bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.unknown.id, 4); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.unknown.dataSizeInBytes); + bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.unknown.pData, subchunkSize); + } + } + if ((subchunkSize % 2) != 0) { + bytesWritten += ma_dr_wav__write_or_count_byte(pWav, 0); + } + } + } + if (hasListAdtl) { + ma_uint32 chunkSize = 4; + for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) { + ma_dr_wav_metadata* pMetadata = &pMetadatas[iMetadata]; + switch (pMetadata->type) + { + case ma_dr_wav_metadata_type_list_label: + case ma_dr_wav_metadata_type_list_note: + { + chunkSize += 8; + chunkSize += MA_DR_WAV_LIST_LABEL_OR_NOTE_BYTES; + if (pMetadata->data.labelOrNote.stringLength > 0) { + chunkSize += pMetadata->data.labelOrNote.stringLength + 1; + } + } break; + case ma_dr_wav_metadata_type_list_labelled_cue_region: + { + chunkSize += 8; + chunkSize += MA_DR_WAV_LIST_LABELLED_TEXT_BYTES; + if (pMetadata->data.labelledCueRegion.stringLength > 0) { + chunkSize += pMetadata->data.labelledCueRegion.stringLength + 1; + } + } break; + case ma_dr_wav_metadata_type_unknown: + { + if (pMetadata->data.unknown.chunkLocation == ma_dr_wav_metadata_location_inside_adtl_list) { + chunkSize += 8; + chunkSize += pMetadata->data.unknown.dataSizeInBytes; + } + } break; + default: break; + } + if ((chunkSize % 2) != 0) { + chunkSize += 1; + } + } + bytesWritten += ma_dr_wav__write_or_count(pWav, "LIST", 4); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, chunkSize); + bytesWritten += ma_dr_wav__write_or_count(pWav, "adtl", 4); + for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) { + ma_dr_wav_metadata* pMetadata = &pMetadatas[iMetadata]; + ma_uint32 subchunkSize = 0; + switch (pMetadata->type) + { + case ma_dr_wav_metadata_type_list_label: + case ma_dr_wav_metadata_type_list_note: + { + if (pMetadata->data.labelOrNote.stringLength > 0) { + const char *pID = NULL; + if (pMetadata->type == ma_dr_wav_metadata_type_list_label) { + pID = "labl"; + } + else if (pMetadata->type == ma_dr_wav_metadata_type_list_note) { + pID = "note"; + } + MA_DR_WAV_ASSERT(pID != NULL); + MA_DR_WAV_ASSERT(pMetadata->data.labelOrNote.pString != NULL); + subchunkSize = MA_DR_WAV_LIST_LABEL_OR_NOTE_BYTES; + bytesWritten += ma_dr_wav__write_or_count(pWav, pID, 4); + subchunkSize += pMetadata->data.labelOrNote.stringLength + 1; + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, subchunkSize); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.labelOrNote.cuePointId); + bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.labelOrNote.pString, pMetadata->data.labelOrNote.stringLength); + bytesWritten += ma_dr_wav__write_or_count_byte(pWav, '\0'); + } + } break; + case ma_dr_wav_metadata_type_list_labelled_cue_region: + { + subchunkSize = MA_DR_WAV_LIST_LABELLED_TEXT_BYTES; + bytesWritten += ma_dr_wav__write_or_count(pWav, "ltxt", 4); + if (pMetadata->data.labelledCueRegion.stringLength > 0) { + subchunkSize += pMetadata->data.labelledCueRegion.stringLength + 1; + } + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, subchunkSize); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.labelledCueRegion.cuePointId); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.labelledCueRegion.sampleLength); + bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.labelledCueRegion.purposeId, 4); + bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.labelledCueRegion.country); + bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.labelledCueRegion.language); + bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.labelledCueRegion.dialect); + bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.labelledCueRegion.codePage); + if (pMetadata->data.labelledCueRegion.stringLength > 0) { + MA_DR_WAV_ASSERT(pMetadata->data.labelledCueRegion.pString != NULL); + bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.labelledCueRegion.pString, pMetadata->data.labelledCueRegion.stringLength); + bytesWritten += ma_dr_wav__write_or_count_byte(pWav, '\0'); + } + } break; + case ma_dr_wav_metadata_type_unknown: + { + if (pMetadata->data.unknown.chunkLocation == ma_dr_wav_metadata_location_inside_adtl_list) { + subchunkSize = pMetadata->data.unknown.dataSizeInBytes; + MA_DR_WAV_ASSERT(pMetadata->data.unknown.pData != NULL); + bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.unknown.id, 4); + bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, subchunkSize); + bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.unknown.pData, subchunkSize); + } + } break; + default: break; + } + if ((subchunkSize % 2) != 0) { + bytesWritten += ma_dr_wav__write_or_count_byte(pWav, 0); + } + } + } + MA_DR_WAV_ASSERT((bytesWritten % 2) == 0); + return bytesWritten; +} +MA_PRIVATE ma_uint32 ma_dr_wav__riff_chunk_size_riff(ma_uint64 dataChunkSize, ma_dr_wav_metadata* pMetadata, ma_uint32 metadataCount) +{ + ma_uint64 chunkSize = 4 + 24 + (ma_uint64)ma_dr_wav__write_or_count_metadata(NULL, pMetadata, metadataCount) + 8 + dataChunkSize + ma_dr_wav__chunk_padding_size_riff(dataChunkSize); + if (chunkSize > 0xFFFFFFFFUL) { + chunkSize = 0xFFFFFFFFUL; + } + return (ma_uint32)chunkSize; +} +MA_PRIVATE ma_uint32 ma_dr_wav__data_chunk_size_riff(ma_uint64 dataChunkSize) +{ + if (dataChunkSize <= 0xFFFFFFFFUL) { + return (ma_uint32)dataChunkSize; + } else { + return 0xFFFFFFFFUL; + } +} +MA_PRIVATE ma_uint64 ma_dr_wav__riff_chunk_size_w64(ma_uint64 dataChunkSize) +{ + ma_uint64 dataSubchunkPaddingSize = ma_dr_wav__chunk_padding_size_w64(dataChunkSize); + return 80 + 24 + dataChunkSize + dataSubchunkPaddingSize; +} +MA_PRIVATE ma_uint64 ma_dr_wav__data_chunk_size_w64(ma_uint64 dataChunkSize) +{ + return 24 + dataChunkSize; +} +MA_PRIVATE ma_uint64 ma_dr_wav__riff_chunk_size_rf64(ma_uint64 dataChunkSize, ma_dr_wav_metadata *metadata, ma_uint32 numMetadata) +{ + ma_uint64 chunkSize = 4 + 36 + 24 + (ma_uint64)ma_dr_wav__write_or_count_metadata(NULL, metadata, numMetadata) + 8 + dataChunkSize + ma_dr_wav__chunk_padding_size_riff(dataChunkSize); + if (chunkSize > 0xFFFFFFFFUL) { + chunkSize = 0xFFFFFFFFUL; + } + return chunkSize; +} +MA_PRIVATE ma_uint64 ma_dr_wav__data_chunk_size_rf64(ma_uint64 dataChunkSize) +{ + return dataChunkSize; +} +MA_PRIVATE ma_bool32 ma_dr_wav_preinit_write(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_bool32 isSequential, ma_dr_wav_write_proc onWrite, ma_dr_wav_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pWav == NULL || onWrite == NULL) { + return MA_FALSE; + } + if (!isSequential && onSeek == NULL) { + return MA_FALSE; + } + if (pFormat->format == MA_DR_WAVE_FORMAT_EXTENSIBLE) { + return MA_FALSE; + } + if (pFormat->format == MA_DR_WAVE_FORMAT_ADPCM || pFormat->format == MA_DR_WAVE_FORMAT_DVI_ADPCM) { + return MA_FALSE; + } + MA_DR_WAV_ZERO_MEMORY(pWav, sizeof(*pWav)); + pWav->onWrite = onWrite; + pWav->onSeek = onSeek; + pWav->pUserData = pUserData; + pWav->allocationCallbacks = ma_dr_wav_copy_allocation_callbacks_or_defaults(pAllocationCallbacks); + if (pWav->allocationCallbacks.onFree == NULL || (pWav->allocationCallbacks.onMalloc == NULL && pWav->allocationCallbacks.onRealloc == NULL)) { + return MA_FALSE; + } + pWav->fmt.formatTag = (ma_uint16)pFormat->format; + pWav->fmt.channels = (ma_uint16)pFormat->channels; + pWav->fmt.sampleRate = pFormat->sampleRate; + pWav->fmt.avgBytesPerSec = (ma_uint32)((pFormat->bitsPerSample * pFormat->sampleRate * pFormat->channels) / 8); + pWav->fmt.blockAlign = (ma_uint16)((pFormat->channels * pFormat->bitsPerSample) / 8); + pWav->fmt.bitsPerSample = (ma_uint16)pFormat->bitsPerSample; + pWav->fmt.extendedSize = 0; + pWav->isSequentialWrite = isSequential; + return MA_TRUE; +} +MA_PRIVATE ma_bool32 ma_dr_wav_init_write__internal(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount) +{ + size_t runningPos = 0; + ma_uint64 initialDataChunkSize = 0; + ma_uint64 chunkSizeFMT; + if (pWav->isSequentialWrite) { + initialDataChunkSize = (totalSampleCount * pWav->fmt.bitsPerSample) / 8; + if (pFormat->container == ma_dr_wav_container_riff) { + if (initialDataChunkSize > (0xFFFFFFFFUL - 36)) { + return MA_FALSE; + } + } + } + pWav->dataChunkDataSizeTargetWrite = initialDataChunkSize; + if (pFormat->container == ma_dr_wav_container_riff) { + ma_uint32 chunkSizeRIFF = 28 + (ma_uint32)initialDataChunkSize; + runningPos += ma_dr_wav__write(pWav, "RIFF", 4); + runningPos += ma_dr_wav__write_u32ne_to_le(pWav, chunkSizeRIFF); + runningPos += ma_dr_wav__write(pWav, "WAVE", 4); + } else if (pFormat->container == ma_dr_wav_container_w64) { + ma_uint64 chunkSizeRIFF = 80 + 24 + initialDataChunkSize; + runningPos += ma_dr_wav__write(pWav, ma_dr_wavGUID_W64_RIFF, 16); + runningPos += ma_dr_wav__write_u64ne_to_le(pWav, chunkSizeRIFF); + runningPos += ma_dr_wav__write(pWav, ma_dr_wavGUID_W64_WAVE, 16); + } else if (pFormat->container == ma_dr_wav_container_rf64) { + runningPos += ma_dr_wav__write(pWav, "RF64", 4); + runningPos += ma_dr_wav__write_u32ne_to_le(pWav, 0xFFFFFFFF); + runningPos += ma_dr_wav__write(pWav, "WAVE", 4); + } else { + return MA_FALSE; + } + if (pFormat->container == ma_dr_wav_container_rf64) { + ma_uint32 initialds64ChunkSize = 28; + ma_uint64 initialRiffChunkSize = 8 + initialds64ChunkSize + initialDataChunkSize; + runningPos += ma_dr_wav__write(pWav, "ds64", 4); + runningPos += ma_dr_wav__write_u32ne_to_le(pWav, initialds64ChunkSize); + runningPos += ma_dr_wav__write_u64ne_to_le(pWav, initialRiffChunkSize); + runningPos += ma_dr_wav__write_u64ne_to_le(pWav, initialDataChunkSize); + runningPos += ma_dr_wav__write_u64ne_to_le(pWav, totalSampleCount); + runningPos += ma_dr_wav__write_u32ne_to_le(pWav, 0); + } + if (pFormat->container == ma_dr_wav_container_riff || pFormat->container == ma_dr_wav_container_rf64) { + chunkSizeFMT = 16; + runningPos += ma_dr_wav__write(pWav, "fmt ", 4); + runningPos += ma_dr_wav__write_u32ne_to_le(pWav, (ma_uint32)chunkSizeFMT); + } else if (pFormat->container == ma_dr_wav_container_w64) { + chunkSizeFMT = 40; + runningPos += ma_dr_wav__write(pWav, ma_dr_wavGUID_W64_FMT, 16); + runningPos += ma_dr_wav__write_u64ne_to_le(pWav, chunkSizeFMT); + } + runningPos += ma_dr_wav__write_u16ne_to_le(pWav, pWav->fmt.formatTag); + runningPos += ma_dr_wav__write_u16ne_to_le(pWav, pWav->fmt.channels); + runningPos += ma_dr_wav__write_u32ne_to_le(pWav, pWav->fmt.sampleRate); + runningPos += ma_dr_wav__write_u32ne_to_le(pWav, pWav->fmt.avgBytesPerSec); + runningPos += ma_dr_wav__write_u16ne_to_le(pWav, pWav->fmt.blockAlign); + runningPos += ma_dr_wav__write_u16ne_to_le(pWav, pWav->fmt.bitsPerSample); + if (!pWav->isSequentialWrite && pWav->pMetadata != NULL && pWav->metadataCount > 0 && (pFormat->container == ma_dr_wav_container_riff || pFormat->container == ma_dr_wav_container_rf64)) { + runningPos += ma_dr_wav__write_or_count_metadata(pWav, pWav->pMetadata, pWav->metadataCount); + } + pWav->dataChunkDataPos = runningPos; + if (pFormat->container == ma_dr_wav_container_riff) { + ma_uint32 chunkSizeDATA = (ma_uint32)initialDataChunkSize; + runningPos += ma_dr_wav__write(pWav, "data", 4); + runningPos += ma_dr_wav__write_u32ne_to_le(pWav, chunkSizeDATA); + } else if (pFormat->container == ma_dr_wav_container_w64) { + ma_uint64 chunkSizeDATA = 24 + initialDataChunkSize; + runningPos += ma_dr_wav__write(pWav, ma_dr_wavGUID_W64_DATA, 16); + runningPos += ma_dr_wav__write_u64ne_to_le(pWav, chunkSizeDATA); + } else if (pFormat->container == ma_dr_wav_container_rf64) { + runningPos += ma_dr_wav__write(pWav, "data", 4); + runningPos += ma_dr_wav__write_u32ne_to_le(pWav, 0xFFFFFFFF); + } + pWav->container = pFormat->container; + pWav->channels = (ma_uint16)pFormat->channels; + pWav->sampleRate = pFormat->sampleRate; + pWav->bitsPerSample = (ma_uint16)pFormat->bitsPerSample; + pWav->translatedFormatTag = (ma_uint16)pFormat->format; + pWav->dataChunkDataPos = runningPos; + return MA_TRUE; +} +MA_API ma_bool32 ma_dr_wav_init_write(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_dr_wav_write_proc onWrite, ma_dr_wav_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (!ma_dr_wav_preinit_write(pWav, pFormat, MA_FALSE, onWrite, onSeek, pUserData, pAllocationCallbacks)) { + return MA_FALSE; + } + return ma_dr_wav_init_write__internal(pWav, pFormat, 0); +} +MA_API ma_bool32 ma_dr_wav_init_write_sequential(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, ma_dr_wav_write_proc onWrite, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (!ma_dr_wav_preinit_write(pWav, pFormat, MA_TRUE, onWrite, NULL, pUserData, pAllocationCallbacks)) { + return MA_FALSE; + } + return ma_dr_wav_init_write__internal(pWav, pFormat, totalSampleCount); +} +MA_API ma_bool32 ma_dr_wav_init_write_sequential_pcm_frames(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_uint64 totalPCMFrameCount, ma_dr_wav_write_proc onWrite, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pFormat == NULL) { + return MA_FALSE; + } + return ma_dr_wav_init_write_sequential(pWav, pFormat, totalPCMFrameCount*pFormat->channels, onWrite, pUserData, pAllocationCallbacks); +} +MA_API ma_bool32 ma_dr_wav_init_write_with_metadata(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_dr_wav_write_proc onWrite, ma_dr_wav_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks, ma_dr_wav_metadata* pMetadata, ma_uint32 metadataCount) +{ + if (!ma_dr_wav_preinit_write(pWav, pFormat, MA_FALSE, onWrite, onSeek, pUserData, pAllocationCallbacks)) { + return MA_FALSE; + } + pWav->pMetadata = pMetadata; + pWav->metadataCount = metadataCount; + return ma_dr_wav_init_write__internal(pWav, pFormat, 0); +} +MA_API ma_uint64 ma_dr_wav_target_write_size_bytes(const ma_dr_wav_data_format* pFormat, ma_uint64 totalFrameCount, ma_dr_wav_metadata* pMetadata, ma_uint32 metadataCount) +{ + ma_uint64 targetDataSizeBytes = (ma_uint64)((ma_int64)totalFrameCount * pFormat->channels * pFormat->bitsPerSample/8.0); + ma_uint64 riffChunkSizeBytes; + ma_uint64 fileSizeBytes = 0; + if (pFormat->container == ma_dr_wav_container_riff) { + riffChunkSizeBytes = ma_dr_wav__riff_chunk_size_riff(targetDataSizeBytes, pMetadata, metadataCount); + fileSizeBytes = (8 + riffChunkSizeBytes); + } else if (pFormat->container == ma_dr_wav_container_w64) { + riffChunkSizeBytes = ma_dr_wav__riff_chunk_size_w64(targetDataSizeBytes); + fileSizeBytes = riffChunkSizeBytes; + } else if (pFormat->container == ma_dr_wav_container_rf64) { + riffChunkSizeBytes = ma_dr_wav__riff_chunk_size_rf64(targetDataSizeBytes, pMetadata, metadataCount); + fileSizeBytes = (8 + riffChunkSizeBytes); + } + return fileSizeBytes; +} +#ifndef MA_DR_WAV_NO_STDIO +MA_PRIVATE size_t ma_dr_wav__on_read_stdio(void* pUserData, void* pBufferOut, size_t bytesToRead) +{ + return fread(pBufferOut, 1, bytesToRead, (FILE*)pUserData); +} +MA_PRIVATE size_t ma_dr_wav__on_write_stdio(void* pUserData, const void* pData, size_t bytesToWrite) +{ + return fwrite(pData, 1, bytesToWrite, (FILE*)pUserData); +} +MA_PRIVATE ma_bool32 ma_dr_wav__on_seek_stdio(void* pUserData, int offset, ma_dr_wav_seek_origin origin) +{ + return fseek((FILE*)pUserData, offset, (origin == ma_dr_wav_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0; +} +MA_API ma_bool32 ma_dr_wav_init_file(ma_dr_wav* pWav, const char* filename, const ma_allocation_callbacks* pAllocationCallbacks) +{ + return ma_dr_wav_init_file_ex(pWav, filename, NULL, NULL, 0, pAllocationCallbacks); +} +MA_PRIVATE ma_bool32 ma_dr_wav_init_file__internal_FILE(ma_dr_wav* pWav, FILE* pFile, ma_dr_wav_chunk_proc onChunk, void* pChunkUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_bool32 result; + result = ma_dr_wav_preinit(pWav, ma_dr_wav__on_read_stdio, ma_dr_wav__on_seek_stdio, (void*)pFile, pAllocationCallbacks); + if (result != MA_TRUE) { + fclose(pFile); + return result; + } + result = ma_dr_wav_init__internal(pWav, onChunk, pChunkUserData, flags); + if (result != MA_TRUE) { + fclose(pFile); + return result; + } + return MA_TRUE; +} +MA_API ma_bool32 ma_dr_wav_init_file_ex(ma_dr_wav* pWav, const char* filename, ma_dr_wav_chunk_proc onChunk, void* pChunkUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks) +{ + FILE* pFile; + if (ma_fopen(&pFile, filename, "rb") != MA_SUCCESS) { + return MA_FALSE; + } + return ma_dr_wav_init_file__internal_FILE(pWav, pFile, onChunk, pChunkUserData, flags, pAllocationCallbacks); +} +#ifndef MA_DR_WAV_NO_WCHAR +MA_API ma_bool32 ma_dr_wav_init_file_w(ma_dr_wav* pWav, const wchar_t* filename, const ma_allocation_callbacks* pAllocationCallbacks) +{ + return ma_dr_wav_init_file_ex_w(pWav, filename, NULL, NULL, 0, pAllocationCallbacks); +} +MA_API ma_bool32 ma_dr_wav_init_file_ex_w(ma_dr_wav* pWav, const wchar_t* filename, ma_dr_wav_chunk_proc onChunk, void* pChunkUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks) +{ + FILE* pFile; + if (ma_wfopen(&pFile, filename, L"rb", pAllocationCallbacks) != MA_SUCCESS) { + return MA_FALSE; + } + return ma_dr_wav_init_file__internal_FILE(pWav, pFile, onChunk, pChunkUserData, flags, pAllocationCallbacks); +} +#endif +MA_API ma_bool32 ma_dr_wav_init_file_with_metadata(ma_dr_wav* pWav, const char* filename, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks) +{ + FILE* pFile; + if (ma_fopen(&pFile, filename, "rb") != MA_SUCCESS) { + return MA_FALSE; + } + return ma_dr_wav_init_file__internal_FILE(pWav, pFile, NULL, NULL, flags | MA_DR_WAV_WITH_METADATA, pAllocationCallbacks); +} +#ifndef MA_DR_WAV_NO_WCHAR +MA_API ma_bool32 ma_dr_wav_init_file_with_metadata_w(ma_dr_wav* pWav, const wchar_t* filename, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks) +{ + FILE* pFile; + if (ma_wfopen(&pFile, filename, L"rb", pAllocationCallbacks) != MA_SUCCESS) { + return MA_FALSE; + } + return ma_dr_wav_init_file__internal_FILE(pWav, pFile, NULL, NULL, flags | MA_DR_WAV_WITH_METADATA, pAllocationCallbacks); +} +#endif +MA_PRIVATE ma_bool32 ma_dr_wav_init_file_write__internal_FILE(ma_dr_wav* pWav, FILE* pFile, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, ma_bool32 isSequential, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_bool32 result; + result = ma_dr_wav_preinit_write(pWav, pFormat, isSequential, ma_dr_wav__on_write_stdio, ma_dr_wav__on_seek_stdio, (void*)pFile, pAllocationCallbacks); + if (result != MA_TRUE) { + fclose(pFile); + return result; + } + result = ma_dr_wav_init_write__internal(pWav, pFormat, totalSampleCount); + if (result != MA_TRUE) { + fclose(pFile); + return result; + } + return MA_TRUE; +} +MA_PRIVATE ma_bool32 ma_dr_wav_init_file_write__internal(ma_dr_wav* pWav, const char* filename, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, ma_bool32 isSequential, const ma_allocation_callbacks* pAllocationCallbacks) +{ + FILE* pFile; + if (ma_fopen(&pFile, filename, "wb") != MA_SUCCESS) { + return MA_FALSE; + } + return ma_dr_wav_init_file_write__internal_FILE(pWav, pFile, pFormat, totalSampleCount, isSequential, pAllocationCallbacks); +} +#ifndef MA_DR_WAV_NO_WCHAR +MA_PRIVATE ma_bool32 ma_dr_wav_init_file_write_w__internal(ma_dr_wav* pWav, const wchar_t* filename, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, ma_bool32 isSequential, const ma_allocation_callbacks* pAllocationCallbacks) +{ + FILE* pFile; + if (ma_wfopen(&pFile, filename, L"wb", pAllocationCallbacks) != MA_SUCCESS) { + return MA_FALSE; + } + return ma_dr_wav_init_file_write__internal_FILE(pWav, pFile, pFormat, totalSampleCount, isSequential, pAllocationCallbacks); +} +#endif +MA_API ma_bool32 ma_dr_wav_init_file_write(ma_dr_wav* pWav, const char* filename, const ma_dr_wav_data_format* pFormat, const ma_allocation_callbacks* pAllocationCallbacks) +{ + return ma_dr_wav_init_file_write__internal(pWav, filename, pFormat, 0, MA_FALSE, pAllocationCallbacks); +} +MA_API ma_bool32 ma_dr_wav_init_file_write_sequential(ma_dr_wav* pWav, const char* filename, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, const ma_allocation_callbacks* pAllocationCallbacks) +{ + return ma_dr_wav_init_file_write__internal(pWav, filename, pFormat, totalSampleCount, MA_TRUE, pAllocationCallbacks); +} +MA_API ma_bool32 ma_dr_wav_init_file_write_sequential_pcm_frames(ma_dr_wav* pWav, const char* filename, const ma_dr_wav_data_format* pFormat, ma_uint64 totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pFormat == NULL) { + return MA_FALSE; + } + return ma_dr_wav_init_file_write_sequential(pWav, filename, pFormat, totalPCMFrameCount*pFormat->channels, pAllocationCallbacks); +} +#ifndef MA_DR_WAV_NO_WCHAR +MA_API ma_bool32 ma_dr_wav_init_file_write_w(ma_dr_wav* pWav, const wchar_t* filename, const ma_dr_wav_data_format* pFormat, const ma_allocation_callbacks* pAllocationCallbacks) +{ + return ma_dr_wav_init_file_write_w__internal(pWav, filename, pFormat, 0, MA_FALSE, pAllocationCallbacks); +} +MA_API ma_bool32 ma_dr_wav_init_file_write_sequential_w(ma_dr_wav* pWav, const wchar_t* filename, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, const ma_allocation_callbacks* pAllocationCallbacks) +{ + return ma_dr_wav_init_file_write_w__internal(pWav, filename, pFormat, totalSampleCount, MA_TRUE, pAllocationCallbacks); +} +MA_API ma_bool32 ma_dr_wav_init_file_write_sequential_pcm_frames_w(ma_dr_wav* pWav, const wchar_t* filename, const ma_dr_wav_data_format* pFormat, ma_uint64 totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pFormat == NULL) { + return MA_FALSE; + } + return ma_dr_wav_init_file_write_sequential_w(pWav, filename, pFormat, totalPCMFrameCount*pFormat->channels, pAllocationCallbacks); +} +#endif +#endif +MA_PRIVATE size_t ma_dr_wav__on_read_memory(void* pUserData, void* pBufferOut, size_t bytesToRead) +{ + ma_dr_wav* pWav = (ma_dr_wav*)pUserData; + size_t bytesRemaining; + MA_DR_WAV_ASSERT(pWav != NULL); + MA_DR_WAV_ASSERT(pWav->memoryStream.dataSize >= pWav->memoryStream.currentReadPos); + bytesRemaining = pWav->memoryStream.dataSize - pWav->memoryStream.currentReadPos; + if (bytesToRead > bytesRemaining) { + bytesToRead = bytesRemaining; + } + if (bytesToRead > 0) { + MA_DR_WAV_COPY_MEMORY(pBufferOut, pWav->memoryStream.data + pWav->memoryStream.currentReadPos, bytesToRead); + pWav->memoryStream.currentReadPos += bytesToRead; + } + return bytesToRead; +} +MA_PRIVATE ma_bool32 ma_dr_wav__on_seek_memory(void* pUserData, int offset, ma_dr_wav_seek_origin origin) +{ + ma_dr_wav* pWav = (ma_dr_wav*)pUserData; + MA_DR_WAV_ASSERT(pWav != NULL); + if (origin == ma_dr_wav_seek_origin_current) { + if (offset > 0) { + if (pWav->memoryStream.currentReadPos + offset > pWav->memoryStream.dataSize) { + return MA_FALSE; + } + } else { + if (pWav->memoryStream.currentReadPos < (size_t)-offset) { + return MA_FALSE; + } + } + pWav->memoryStream.currentReadPos += offset; + } else { + if ((ma_uint32)offset <= pWav->memoryStream.dataSize) { + pWav->memoryStream.currentReadPos = offset; + } else { + return MA_FALSE; + } + } + return MA_TRUE; +} +MA_PRIVATE size_t ma_dr_wav__on_write_memory(void* pUserData, const void* pDataIn, size_t bytesToWrite) +{ + ma_dr_wav* pWav = (ma_dr_wav*)pUserData; + size_t bytesRemaining; + MA_DR_WAV_ASSERT(pWav != NULL); + MA_DR_WAV_ASSERT(pWav->memoryStreamWrite.dataCapacity >= pWav->memoryStreamWrite.currentWritePos); + bytesRemaining = pWav->memoryStreamWrite.dataCapacity - pWav->memoryStreamWrite.currentWritePos; + if (bytesRemaining < bytesToWrite) { + void* pNewData; + size_t newDataCapacity = (pWav->memoryStreamWrite.dataCapacity == 0) ? 256 : pWav->memoryStreamWrite.dataCapacity * 2; + if ((newDataCapacity - pWav->memoryStreamWrite.currentWritePos) < bytesToWrite) { + newDataCapacity = pWav->memoryStreamWrite.currentWritePos + bytesToWrite; + } + pNewData = ma_dr_wav__realloc_from_callbacks(*pWav->memoryStreamWrite.ppData, newDataCapacity, pWav->memoryStreamWrite.dataCapacity, &pWav->allocationCallbacks); + if (pNewData == NULL) { + return 0; + } + *pWav->memoryStreamWrite.ppData = pNewData; + pWav->memoryStreamWrite.dataCapacity = newDataCapacity; + } + MA_DR_WAV_COPY_MEMORY(((ma_uint8*)(*pWav->memoryStreamWrite.ppData)) + pWav->memoryStreamWrite.currentWritePos, pDataIn, bytesToWrite); + pWav->memoryStreamWrite.currentWritePos += bytesToWrite; + if (pWav->memoryStreamWrite.dataSize < pWav->memoryStreamWrite.currentWritePos) { + pWav->memoryStreamWrite.dataSize = pWav->memoryStreamWrite.currentWritePos; + } + *pWav->memoryStreamWrite.pDataSize = pWav->memoryStreamWrite.dataSize; + return bytesToWrite; +} +MA_PRIVATE ma_bool32 ma_dr_wav__on_seek_memory_write(void* pUserData, int offset, ma_dr_wav_seek_origin origin) +{ + ma_dr_wav* pWav = (ma_dr_wav*)pUserData; + MA_DR_WAV_ASSERT(pWav != NULL); + if (origin == ma_dr_wav_seek_origin_current) { + if (offset > 0) { + if (pWav->memoryStreamWrite.currentWritePos + offset > pWav->memoryStreamWrite.dataSize) { + offset = (int)(pWav->memoryStreamWrite.dataSize - pWav->memoryStreamWrite.currentWritePos); + } + } else { + if (pWav->memoryStreamWrite.currentWritePos < (size_t)-offset) { + offset = -(int)pWav->memoryStreamWrite.currentWritePos; + } + } + pWav->memoryStreamWrite.currentWritePos += offset; + } else { + if ((ma_uint32)offset <= pWav->memoryStreamWrite.dataSize) { + pWav->memoryStreamWrite.currentWritePos = offset; + } else { + pWav->memoryStreamWrite.currentWritePos = pWav->memoryStreamWrite.dataSize; + } + } + return MA_TRUE; +} +MA_API ma_bool32 ma_dr_wav_init_memory(ma_dr_wav* pWav, const void* data, size_t dataSize, const ma_allocation_callbacks* pAllocationCallbacks) +{ + return ma_dr_wav_init_memory_ex(pWav, data, dataSize, NULL, NULL, 0, pAllocationCallbacks); +} +MA_API ma_bool32 ma_dr_wav_init_memory_ex(ma_dr_wav* pWav, const void* data, size_t dataSize, ma_dr_wav_chunk_proc onChunk, void* pChunkUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (data == NULL || dataSize == 0) { + return MA_FALSE; + } + if (!ma_dr_wav_preinit(pWav, ma_dr_wav__on_read_memory, ma_dr_wav__on_seek_memory, pWav, pAllocationCallbacks)) { + return MA_FALSE; + } + pWav->memoryStream.data = (const ma_uint8*)data; + pWav->memoryStream.dataSize = dataSize; + pWav->memoryStream.currentReadPos = 0; + return ma_dr_wav_init__internal(pWav, onChunk, pChunkUserData, flags); +} +MA_API ma_bool32 ma_dr_wav_init_memory_with_metadata(ma_dr_wav* pWav, const void* data, size_t dataSize, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (data == NULL || dataSize == 0) { + return MA_FALSE; + } + if (!ma_dr_wav_preinit(pWav, ma_dr_wav__on_read_memory, ma_dr_wav__on_seek_memory, pWav, pAllocationCallbacks)) { + return MA_FALSE; + } + pWav->memoryStream.data = (const ma_uint8*)data; + pWav->memoryStream.dataSize = dataSize; + pWav->memoryStream.currentReadPos = 0; + return ma_dr_wav_init__internal(pWav, NULL, NULL, flags | MA_DR_WAV_WITH_METADATA); +} +MA_PRIVATE ma_bool32 ma_dr_wav_init_memory_write__internal(ma_dr_wav* pWav, void** ppData, size_t* pDataSize, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, ma_bool32 isSequential, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (ppData == NULL || pDataSize == NULL) { + return MA_FALSE; + } + *ppData = NULL; + *pDataSize = 0; + if (!ma_dr_wav_preinit_write(pWav, pFormat, isSequential, ma_dr_wav__on_write_memory, ma_dr_wav__on_seek_memory_write, pWav, pAllocationCallbacks)) { + return MA_FALSE; + } + pWav->memoryStreamWrite.ppData = ppData; + pWav->memoryStreamWrite.pDataSize = pDataSize; + pWav->memoryStreamWrite.dataSize = 0; + pWav->memoryStreamWrite.dataCapacity = 0; + pWav->memoryStreamWrite.currentWritePos = 0; + return ma_dr_wav_init_write__internal(pWav, pFormat, totalSampleCount); +} +MA_API ma_bool32 ma_dr_wav_init_memory_write(ma_dr_wav* pWav, void** ppData, size_t* pDataSize, const ma_dr_wav_data_format* pFormat, const ma_allocation_callbacks* pAllocationCallbacks) +{ + return ma_dr_wav_init_memory_write__internal(pWav, ppData, pDataSize, pFormat, 0, MA_FALSE, pAllocationCallbacks); +} +MA_API ma_bool32 ma_dr_wav_init_memory_write_sequential(ma_dr_wav* pWav, void** ppData, size_t* pDataSize, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, const ma_allocation_callbacks* pAllocationCallbacks) +{ + return ma_dr_wav_init_memory_write__internal(pWav, ppData, pDataSize, pFormat, totalSampleCount, MA_TRUE, pAllocationCallbacks); +} +MA_API ma_bool32 ma_dr_wav_init_memory_write_sequential_pcm_frames(ma_dr_wav* pWav, void** ppData, size_t* pDataSize, const ma_dr_wav_data_format* pFormat, ma_uint64 totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pFormat == NULL) { + return MA_FALSE; + } + return ma_dr_wav_init_memory_write_sequential(pWav, ppData, pDataSize, pFormat, totalPCMFrameCount*pFormat->channels, pAllocationCallbacks); +} +MA_API ma_result ma_dr_wav_uninit(ma_dr_wav* pWav) +{ + ma_result result = MA_SUCCESS; + if (pWav == NULL) { + return MA_INVALID_ARGS; + } + if (pWav->onWrite != NULL) { + ma_uint32 paddingSize = 0; + if (pWav->container == ma_dr_wav_container_riff || pWav->container == ma_dr_wav_container_rf64) { + paddingSize = ma_dr_wav__chunk_padding_size_riff(pWav->dataChunkDataSize); + } else { + paddingSize = ma_dr_wav__chunk_padding_size_w64(pWav->dataChunkDataSize); + } + if (paddingSize > 0) { + ma_uint64 paddingData = 0; + ma_dr_wav__write(pWav, &paddingData, paddingSize); + } + if (pWav->onSeek && !pWav->isSequentialWrite) { + if (pWav->container == ma_dr_wav_container_riff) { + if (pWav->onSeek(pWav->pUserData, 4, ma_dr_wav_seek_origin_start)) { + ma_uint32 riffChunkSize = ma_dr_wav__riff_chunk_size_riff(pWav->dataChunkDataSize, pWav->pMetadata, pWav->metadataCount); + ma_dr_wav__write_u32ne_to_le(pWav, riffChunkSize); + } + if (pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos - 4, ma_dr_wav_seek_origin_start)) { + ma_uint32 dataChunkSize = ma_dr_wav__data_chunk_size_riff(pWav->dataChunkDataSize); + ma_dr_wav__write_u32ne_to_le(pWav, dataChunkSize); + } + } else if (pWav->container == ma_dr_wav_container_w64) { + if (pWav->onSeek(pWav->pUserData, 16, ma_dr_wav_seek_origin_start)) { + ma_uint64 riffChunkSize = ma_dr_wav__riff_chunk_size_w64(pWav->dataChunkDataSize); + ma_dr_wav__write_u64ne_to_le(pWav, riffChunkSize); + } + if (pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos - 8, ma_dr_wav_seek_origin_start)) { + ma_uint64 dataChunkSize = ma_dr_wav__data_chunk_size_w64(pWav->dataChunkDataSize); + ma_dr_wav__write_u64ne_to_le(pWav, dataChunkSize); + } + } else if (pWav->container == ma_dr_wav_container_rf64) { + int ds64BodyPos = 12 + 8; + if (pWav->onSeek(pWav->pUserData, ds64BodyPos + 0, ma_dr_wav_seek_origin_start)) { + ma_uint64 riffChunkSize = ma_dr_wav__riff_chunk_size_rf64(pWav->dataChunkDataSize, pWav->pMetadata, pWav->metadataCount); + ma_dr_wav__write_u64ne_to_le(pWav, riffChunkSize); + } + if (pWav->onSeek(pWav->pUserData, ds64BodyPos + 8, ma_dr_wav_seek_origin_start)) { + ma_uint64 dataChunkSize = ma_dr_wav__data_chunk_size_rf64(pWav->dataChunkDataSize); + ma_dr_wav__write_u64ne_to_le(pWav, dataChunkSize); + } + } + } + if (pWav->isSequentialWrite) { + if (pWav->dataChunkDataSize != pWav->dataChunkDataSizeTargetWrite) { + result = MA_INVALID_FILE; + } + } + } else { + ma_dr_wav_free(pWav->pMetadata, &pWav->allocationCallbacks); + } +#ifndef MA_DR_WAV_NO_STDIO + if (pWav->onRead == ma_dr_wav__on_read_stdio || pWav->onWrite == ma_dr_wav__on_write_stdio) { + fclose((FILE*)pWav->pUserData); + } +#endif + return result; +} +MA_API size_t ma_dr_wav_read_raw(ma_dr_wav* pWav, size_t bytesToRead, void* pBufferOut) +{ + size_t bytesRead; + ma_uint32 bytesPerFrame; + if (pWav == NULL || bytesToRead == 0) { + return 0; + } + if (bytesToRead > pWav->bytesRemaining) { + bytesToRead = (size_t)pWav->bytesRemaining; + } + if (bytesToRead == 0) { + return 0; + } + bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav); + if (bytesPerFrame == 0) { + return 0; + } + if (pBufferOut != NULL) { + bytesRead = pWav->onRead(pWav->pUserData, pBufferOut, bytesToRead); + } else { + bytesRead = 0; + while (bytesRead < bytesToRead) { + size_t bytesToSeek = (bytesToRead - bytesRead); + if (bytesToSeek > 0x7FFFFFFF) { + bytesToSeek = 0x7FFFFFFF; + } + if (pWav->onSeek(pWav->pUserData, (int)bytesToSeek, ma_dr_wav_seek_origin_current) == MA_FALSE) { + break; + } + bytesRead += bytesToSeek; + } + while (bytesRead < bytesToRead) { + ma_uint8 buffer[4096]; + size_t bytesSeeked; + size_t bytesToSeek = (bytesToRead - bytesRead); + if (bytesToSeek > sizeof(buffer)) { + bytesToSeek = sizeof(buffer); + } + bytesSeeked = pWav->onRead(pWav->pUserData, buffer, bytesToSeek); + bytesRead += bytesSeeked; + if (bytesSeeked < bytesToSeek) { + break; + } + } + } + pWav->readCursorInPCMFrames += bytesRead / bytesPerFrame; + pWav->bytesRemaining -= bytesRead; + return bytesRead; +} +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_le(ma_dr_wav* pWav, ma_uint64 framesToRead, void* pBufferOut) +{ + ma_uint32 bytesPerFrame; + ma_uint64 bytesToRead; + ma_uint64 framesRemainingInFile; + if (pWav == NULL || framesToRead == 0) { + return 0; + } + if (ma_dr_wav__is_compressed_format_tag(pWav->translatedFormatTag)) { + return 0; + } + framesRemainingInFile = pWav->totalPCMFrameCount - pWav->readCursorInPCMFrames; + if (framesToRead > framesRemainingInFile) { + framesToRead = framesRemainingInFile; + } + bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav); + if (bytesPerFrame == 0) { + return 0; + } + bytesToRead = framesToRead * bytesPerFrame; + if (bytesToRead > MA_SIZE_MAX) { + bytesToRead = (MA_SIZE_MAX / bytesPerFrame) * bytesPerFrame; + } + if (bytesToRead == 0) { + return 0; + } + return ma_dr_wav_read_raw(pWav, (size_t)bytesToRead, pBufferOut) / bytesPerFrame; +} +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_be(ma_dr_wav* pWav, ma_uint64 framesToRead, void* pBufferOut) +{ + ma_uint64 framesRead = ma_dr_wav_read_pcm_frames_le(pWav, framesToRead, pBufferOut); + if (pBufferOut != NULL) { + ma_uint32 bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav); + if (bytesPerFrame == 0) { + return 0; + } + ma_dr_wav__bswap_samples(pBufferOut, framesRead*pWav->channels, bytesPerFrame/pWav->channels); + } + return framesRead; +} +MA_API ma_uint64 ma_dr_wav_read_pcm_frames(ma_dr_wav* pWav, ma_uint64 framesToRead, void* pBufferOut) +{ + ma_uint64 framesRead = 0; + if (ma_dr_wav_is_container_be(pWav->container)) { + if (pWav->container != ma_dr_wav_container_aiff || pWav->aiff.isLE == MA_FALSE) { + if (ma_dr_wav__is_little_endian()) { + framesRead = ma_dr_wav_read_pcm_frames_be(pWav, framesToRead, pBufferOut); + } else { + framesRead = ma_dr_wav_read_pcm_frames_le(pWav, framesToRead, pBufferOut); + } + goto post_process; + } + } + if (ma_dr_wav__is_little_endian()) { + framesRead = ma_dr_wav_read_pcm_frames_le(pWav, framesToRead, pBufferOut); + } else { + framesRead = ma_dr_wav_read_pcm_frames_be(pWav, framesToRead, pBufferOut); + } + post_process: + { + if (pWav->container == ma_dr_wav_container_aiff && pWav->bitsPerSample == 8 && pWav->aiff.isUnsigned == MA_FALSE) { + if (pBufferOut != NULL) { + ma_uint64 iSample; + for (iSample = 0; iSample < framesRead * pWav->channels; iSample += 1) { + ((ma_uint8*)pBufferOut)[iSample] += 128; + } + } + } + } + return framesRead; +} +MA_PRIVATE ma_bool32 ma_dr_wav_seek_to_first_pcm_frame(ma_dr_wav* pWav) +{ + if (pWav->onWrite != NULL) { + return MA_FALSE; + } + if (!pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos, ma_dr_wav_seek_origin_start)) { + return MA_FALSE; + } + if (ma_dr_wav__is_compressed_format_tag(pWav->translatedFormatTag)) { + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ADPCM) { + MA_DR_WAV_ZERO_OBJECT(&pWav->msadpcm); + } else if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_DVI_ADPCM) { + MA_DR_WAV_ZERO_OBJECT(&pWav->ima); + } else { + MA_DR_WAV_ASSERT(MA_FALSE); + } + } + pWav->readCursorInPCMFrames = 0; + pWav->bytesRemaining = pWav->dataChunkDataSize; + return MA_TRUE; +} +MA_API ma_bool32 ma_dr_wav_seek_to_pcm_frame(ma_dr_wav* pWav, ma_uint64 targetFrameIndex) +{ + if (pWav == NULL || pWav->onSeek == NULL) { + return MA_FALSE; + } + if (pWav->onWrite != NULL) { + return MA_FALSE; + } + if (pWav->totalPCMFrameCount == 0) { + return MA_TRUE; + } + if (targetFrameIndex > pWav->totalPCMFrameCount) { + targetFrameIndex = pWav->totalPCMFrameCount; + } + if (ma_dr_wav__is_compressed_format_tag(pWav->translatedFormatTag)) { + if (targetFrameIndex < pWav->readCursorInPCMFrames) { + if (!ma_dr_wav_seek_to_first_pcm_frame(pWav)) { + return MA_FALSE; + } + } + if (targetFrameIndex > pWav->readCursorInPCMFrames) { + ma_uint64 offsetInFrames = targetFrameIndex - pWav->readCursorInPCMFrames; + ma_int16 devnull[2048]; + while (offsetInFrames > 0) { + ma_uint64 framesRead = 0; + ma_uint64 framesToRead = offsetInFrames; + if (framesToRead > ma_dr_wav_countof(devnull)/pWav->channels) { + framesToRead = ma_dr_wav_countof(devnull)/pWav->channels; + } + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ADPCM) { + framesRead = ma_dr_wav_read_pcm_frames_s16__msadpcm(pWav, framesToRead, devnull); + } else if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_DVI_ADPCM) { + framesRead = ma_dr_wav_read_pcm_frames_s16__ima(pWav, framesToRead, devnull); + } else { + MA_DR_WAV_ASSERT(MA_FALSE); + } + if (framesRead != framesToRead) { + return MA_FALSE; + } + offsetInFrames -= framesRead; + } + } + } else { + ma_uint64 totalSizeInBytes; + ma_uint64 currentBytePos; + ma_uint64 targetBytePos; + ma_uint64 offset; + ma_uint32 bytesPerFrame; + bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav); + if (bytesPerFrame == 0) { + return MA_FALSE; + } + totalSizeInBytes = pWav->totalPCMFrameCount * bytesPerFrame; + currentBytePos = totalSizeInBytes - pWav->bytesRemaining; + targetBytePos = targetFrameIndex * bytesPerFrame; + if (currentBytePos < targetBytePos) { + offset = (targetBytePos - currentBytePos); + } else { + if (!ma_dr_wav_seek_to_first_pcm_frame(pWav)) { + return MA_FALSE; + } + offset = targetBytePos; + } + while (offset > 0) { + int offset32 = ((offset > INT_MAX) ? INT_MAX : (int)offset); + if (!pWav->onSeek(pWav->pUserData, offset32, ma_dr_wav_seek_origin_current)) { + return MA_FALSE; + } + pWav->readCursorInPCMFrames += offset32 / bytesPerFrame; + pWav->bytesRemaining -= offset32; + offset -= offset32; + } + } + return MA_TRUE; +} +MA_API ma_result ma_dr_wav_get_cursor_in_pcm_frames(ma_dr_wav* pWav, ma_uint64* pCursor) +{ + if (pCursor == NULL) { + return MA_INVALID_ARGS; + } + *pCursor = 0; + if (pWav == NULL) { + return MA_INVALID_ARGS; + } + *pCursor = pWav->readCursorInPCMFrames; + return MA_SUCCESS; +} +MA_API ma_result ma_dr_wav_get_length_in_pcm_frames(ma_dr_wav* pWav, ma_uint64* pLength) +{ + if (pLength == NULL) { + return MA_INVALID_ARGS; + } + *pLength = 0; + if (pWav == NULL) { + return MA_INVALID_ARGS; + } + *pLength = pWav->totalPCMFrameCount; + return MA_SUCCESS; +} +MA_API size_t ma_dr_wav_write_raw(ma_dr_wav* pWav, size_t bytesToWrite, const void* pData) +{ + size_t bytesWritten; + if (pWav == NULL || bytesToWrite == 0 || pData == NULL) { + return 0; + } + bytesWritten = pWav->onWrite(pWav->pUserData, pData, bytesToWrite); + pWav->dataChunkDataSize += bytesWritten; + return bytesWritten; +} +MA_API ma_uint64 ma_dr_wav_write_pcm_frames_le(ma_dr_wav* pWav, ma_uint64 framesToWrite, const void* pData) +{ + ma_uint64 bytesToWrite; + ma_uint64 bytesWritten; + const ma_uint8* pRunningData; + if (pWav == NULL || framesToWrite == 0 || pData == NULL) { + return 0; + } + bytesToWrite = ((framesToWrite * pWav->channels * pWav->bitsPerSample) / 8); + if (bytesToWrite > MA_SIZE_MAX) { + return 0; + } + bytesWritten = 0; + pRunningData = (const ma_uint8*)pData; + while (bytesToWrite > 0) { + size_t bytesJustWritten; + ma_uint64 bytesToWriteThisIteration; + bytesToWriteThisIteration = bytesToWrite; + MA_DR_WAV_ASSERT(bytesToWriteThisIteration <= MA_SIZE_MAX); + bytesJustWritten = ma_dr_wav_write_raw(pWav, (size_t)bytesToWriteThisIteration, pRunningData); + if (bytesJustWritten == 0) { + break; + } + bytesToWrite -= bytesJustWritten; + bytesWritten += bytesJustWritten; + pRunningData += bytesJustWritten; + } + return (bytesWritten * 8) / pWav->bitsPerSample / pWav->channels; +} +MA_API ma_uint64 ma_dr_wav_write_pcm_frames_be(ma_dr_wav* pWav, ma_uint64 framesToWrite, const void* pData) +{ + ma_uint64 bytesToWrite; + ma_uint64 bytesWritten; + ma_uint32 bytesPerSample; + const ma_uint8* pRunningData; + if (pWav == NULL || framesToWrite == 0 || pData == NULL) { + return 0; + } + bytesToWrite = ((framesToWrite * pWav->channels * pWav->bitsPerSample) / 8); + if (bytesToWrite > MA_SIZE_MAX) { + return 0; + } + bytesWritten = 0; + pRunningData = (const ma_uint8*)pData; + bytesPerSample = ma_dr_wav_get_bytes_per_pcm_frame(pWav) / pWav->channels; + if (bytesPerSample == 0) { + return 0; + } + while (bytesToWrite > 0) { + ma_uint8 temp[4096]; + ma_uint32 sampleCount; + size_t bytesJustWritten; + ma_uint64 bytesToWriteThisIteration; + bytesToWriteThisIteration = bytesToWrite; + MA_DR_WAV_ASSERT(bytesToWriteThisIteration <= MA_SIZE_MAX); + sampleCount = sizeof(temp)/bytesPerSample; + if (bytesToWriteThisIteration > ((ma_uint64)sampleCount)*bytesPerSample) { + bytesToWriteThisIteration = ((ma_uint64)sampleCount)*bytesPerSample; + } + MA_DR_WAV_COPY_MEMORY(temp, pRunningData, (size_t)bytesToWriteThisIteration); + ma_dr_wav__bswap_samples(temp, sampleCount, bytesPerSample); + bytesJustWritten = ma_dr_wav_write_raw(pWav, (size_t)bytesToWriteThisIteration, temp); + if (bytesJustWritten == 0) { + break; + } + bytesToWrite -= bytesJustWritten; + bytesWritten += bytesJustWritten; + pRunningData += bytesJustWritten; + } + return (bytesWritten * 8) / pWav->bitsPerSample / pWav->channels; +} +MA_API ma_uint64 ma_dr_wav_write_pcm_frames(ma_dr_wav* pWav, ma_uint64 framesToWrite, const void* pData) +{ + if (ma_dr_wav__is_little_endian()) { + return ma_dr_wav_write_pcm_frames_le(pWav, framesToWrite, pData); + } else { + return ma_dr_wav_write_pcm_frames_be(pWav, framesToWrite, pData); + } +} +MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s16__msadpcm(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut) +{ + ma_uint64 totalFramesRead = 0; + MA_DR_WAV_ASSERT(pWav != NULL); + MA_DR_WAV_ASSERT(framesToRead > 0); + while (pWav->readCursorInPCMFrames < pWav->totalPCMFrameCount) { + MA_DR_WAV_ASSERT(framesToRead > 0); + if (pWav->msadpcm.cachedFrameCount == 0 && pWav->msadpcm.bytesRemainingInBlock == 0) { + if (pWav->channels == 1) { + ma_uint8 header[7]; + if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) { + return totalFramesRead; + } + pWav->msadpcm.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header); + pWav->msadpcm.predictor[0] = header[0]; + pWav->msadpcm.delta[0] = ma_dr_wav_bytes_to_s16(header + 1); + pWav->msadpcm.prevFrames[0][1] = (ma_int32)ma_dr_wav_bytes_to_s16(header + 3); + pWav->msadpcm.prevFrames[0][0] = (ma_int32)ma_dr_wav_bytes_to_s16(header + 5); + pWav->msadpcm.cachedFrames[2] = pWav->msadpcm.prevFrames[0][0]; + pWav->msadpcm.cachedFrames[3] = pWav->msadpcm.prevFrames[0][1]; + pWav->msadpcm.cachedFrameCount = 2; + } else { + ma_uint8 header[14]; + if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) { + return totalFramesRead; + } + pWav->msadpcm.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header); + pWav->msadpcm.predictor[0] = header[0]; + pWav->msadpcm.predictor[1] = header[1]; + pWav->msadpcm.delta[0] = ma_dr_wav_bytes_to_s16(header + 2); + pWav->msadpcm.delta[1] = ma_dr_wav_bytes_to_s16(header + 4); + pWav->msadpcm.prevFrames[0][1] = (ma_int32)ma_dr_wav_bytes_to_s16(header + 6); + pWav->msadpcm.prevFrames[1][1] = (ma_int32)ma_dr_wav_bytes_to_s16(header + 8); + pWav->msadpcm.prevFrames[0][0] = (ma_int32)ma_dr_wav_bytes_to_s16(header + 10); + pWav->msadpcm.prevFrames[1][0] = (ma_int32)ma_dr_wav_bytes_to_s16(header + 12); + pWav->msadpcm.cachedFrames[0] = pWav->msadpcm.prevFrames[0][0]; + pWav->msadpcm.cachedFrames[1] = pWav->msadpcm.prevFrames[1][0]; + pWav->msadpcm.cachedFrames[2] = pWav->msadpcm.prevFrames[0][1]; + pWav->msadpcm.cachedFrames[3] = pWav->msadpcm.prevFrames[1][1]; + pWav->msadpcm.cachedFrameCount = 2; + } + } + while (framesToRead > 0 && pWav->msadpcm.cachedFrameCount > 0 && pWav->readCursorInPCMFrames < pWav->totalPCMFrameCount) { + if (pBufferOut != NULL) { + ma_uint32 iSample = 0; + for (iSample = 0; iSample < pWav->channels; iSample += 1) { + pBufferOut[iSample] = (ma_int16)pWav->msadpcm.cachedFrames[(ma_dr_wav_countof(pWav->msadpcm.cachedFrames) - (pWav->msadpcm.cachedFrameCount*pWav->channels)) + iSample]; + } + pBufferOut += pWav->channels; + } + framesToRead -= 1; + totalFramesRead += 1; + pWav->readCursorInPCMFrames += 1; + pWav->msadpcm.cachedFrameCount -= 1; + } + if (framesToRead == 0) { + break; + } + if (pWav->msadpcm.cachedFrameCount == 0) { + if (pWav->msadpcm.bytesRemainingInBlock == 0) { + continue; + } else { + static ma_int32 adaptationTable[] = { + 230, 230, 230, 230, 307, 409, 512, 614, + 768, 614, 512, 409, 307, 230, 230, 230 + }; + static ma_int32 coeff1Table[] = { 256, 512, 0, 192, 240, 460, 392 }; + static ma_int32 coeff2Table[] = { 0, -256, 0, 64, 0, -208, -232 }; + ma_uint8 nibbles; + ma_int32 nibble0; + ma_int32 nibble1; + if (pWav->onRead(pWav->pUserData, &nibbles, 1) != 1) { + return totalFramesRead; + } + pWav->msadpcm.bytesRemainingInBlock -= 1; + nibble0 = ((nibbles & 0xF0) >> 4); if ((nibbles & 0x80)) { nibble0 |= 0xFFFFFFF0UL; } + nibble1 = ((nibbles & 0x0F) >> 0); if ((nibbles & 0x08)) { nibble1 |= 0xFFFFFFF0UL; } + if (pWav->channels == 1) { + ma_int32 newSample0; + ma_int32 newSample1; + newSample0 = ((pWav->msadpcm.prevFrames[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevFrames[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8; + newSample0 += nibble0 * pWav->msadpcm.delta[0]; + newSample0 = ma_dr_wav_clamp(newSample0, -32768, 32767); + pWav->msadpcm.delta[0] = (adaptationTable[((nibbles & 0xF0) >> 4)] * pWav->msadpcm.delta[0]) >> 8; + if (pWav->msadpcm.delta[0] < 16) { + pWav->msadpcm.delta[0] = 16; + } + pWav->msadpcm.prevFrames[0][0] = pWav->msadpcm.prevFrames[0][1]; + pWav->msadpcm.prevFrames[0][1] = newSample0; + newSample1 = ((pWav->msadpcm.prevFrames[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevFrames[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8; + newSample1 += nibble1 * pWav->msadpcm.delta[0]; + newSample1 = ma_dr_wav_clamp(newSample1, -32768, 32767); + pWav->msadpcm.delta[0] = (adaptationTable[((nibbles & 0x0F) >> 0)] * pWav->msadpcm.delta[0]) >> 8; + if (pWav->msadpcm.delta[0] < 16) { + pWav->msadpcm.delta[0] = 16; + } + pWav->msadpcm.prevFrames[0][0] = pWav->msadpcm.prevFrames[0][1]; + pWav->msadpcm.prevFrames[0][1] = newSample1; + pWav->msadpcm.cachedFrames[2] = newSample0; + pWav->msadpcm.cachedFrames[3] = newSample1; + pWav->msadpcm.cachedFrameCount = 2; + } else { + ma_int32 newSample0; + ma_int32 newSample1; + newSample0 = ((pWav->msadpcm.prevFrames[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevFrames[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8; + newSample0 += nibble0 * pWav->msadpcm.delta[0]; + newSample0 = ma_dr_wav_clamp(newSample0, -32768, 32767); + pWav->msadpcm.delta[0] = (adaptationTable[((nibbles & 0xF0) >> 4)] * pWav->msadpcm.delta[0]) >> 8; + if (pWav->msadpcm.delta[0] < 16) { + pWav->msadpcm.delta[0] = 16; + } + pWav->msadpcm.prevFrames[0][0] = pWav->msadpcm.prevFrames[0][1]; + pWav->msadpcm.prevFrames[0][1] = newSample0; + newSample1 = ((pWav->msadpcm.prevFrames[1][1] * coeff1Table[pWav->msadpcm.predictor[1]]) + (pWav->msadpcm.prevFrames[1][0] * coeff2Table[pWav->msadpcm.predictor[1]])) >> 8; + newSample1 += nibble1 * pWav->msadpcm.delta[1]; + newSample1 = ma_dr_wav_clamp(newSample1, -32768, 32767); + pWav->msadpcm.delta[1] = (adaptationTable[((nibbles & 0x0F) >> 0)] * pWav->msadpcm.delta[1]) >> 8; + if (pWav->msadpcm.delta[1] < 16) { + pWav->msadpcm.delta[1] = 16; + } + pWav->msadpcm.prevFrames[1][0] = pWav->msadpcm.prevFrames[1][1]; + pWav->msadpcm.prevFrames[1][1] = newSample1; + pWav->msadpcm.cachedFrames[2] = newSample0; + pWav->msadpcm.cachedFrames[3] = newSample1; + pWav->msadpcm.cachedFrameCount = 1; + } + } + } + } + return totalFramesRead; +} +MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s16__ima(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut) +{ + ma_uint64 totalFramesRead = 0; + ma_uint32 iChannel; + static ma_int32 indexTable[16] = { + -1, -1, -1, -1, 2, 4, 6, 8, + -1, -1, -1, -1, 2, 4, 6, 8 + }; + static ma_int32 stepTable[89] = { + 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, + 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, + 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, + 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, + 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, + 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, + 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, + 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, + 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767 + }; + MA_DR_WAV_ASSERT(pWav != NULL); + MA_DR_WAV_ASSERT(framesToRead > 0); + while (pWav->readCursorInPCMFrames < pWav->totalPCMFrameCount) { + MA_DR_WAV_ASSERT(framesToRead > 0); + if (pWav->ima.cachedFrameCount == 0 && pWav->ima.bytesRemainingInBlock == 0) { + if (pWav->channels == 1) { + ma_uint8 header[4]; + if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) { + return totalFramesRead; + } + pWav->ima.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header); + if (header[2] >= ma_dr_wav_countof(stepTable)) { + pWav->onSeek(pWav->pUserData, pWav->ima.bytesRemainingInBlock, ma_dr_wav_seek_origin_current); + pWav->ima.bytesRemainingInBlock = 0; + return totalFramesRead; + } + pWav->ima.predictor[0] = (ma_int16)ma_dr_wav_bytes_to_u16(header + 0); + pWav->ima.stepIndex[0] = ma_dr_wav_clamp(header[2], 0, (ma_int32)ma_dr_wav_countof(stepTable)-1); + pWav->ima.cachedFrames[ma_dr_wav_countof(pWav->ima.cachedFrames) - 1] = pWav->ima.predictor[0]; + pWav->ima.cachedFrameCount = 1; + } else { + ma_uint8 header[8]; + if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) { + return totalFramesRead; + } + pWav->ima.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header); + if (header[2] >= ma_dr_wav_countof(stepTable) || header[6] >= ma_dr_wav_countof(stepTable)) { + pWav->onSeek(pWav->pUserData, pWav->ima.bytesRemainingInBlock, ma_dr_wav_seek_origin_current); + pWav->ima.bytesRemainingInBlock = 0; + return totalFramesRead; + } + pWav->ima.predictor[0] = ma_dr_wav_bytes_to_s16(header + 0); + pWav->ima.stepIndex[0] = ma_dr_wav_clamp(header[2], 0, (ma_int32)ma_dr_wav_countof(stepTable)-1); + pWav->ima.predictor[1] = ma_dr_wav_bytes_to_s16(header + 4); + pWav->ima.stepIndex[1] = ma_dr_wav_clamp(header[6], 0, (ma_int32)ma_dr_wav_countof(stepTable)-1); + pWav->ima.cachedFrames[ma_dr_wav_countof(pWav->ima.cachedFrames) - 2] = pWav->ima.predictor[0]; + pWav->ima.cachedFrames[ma_dr_wav_countof(pWav->ima.cachedFrames) - 1] = pWav->ima.predictor[1]; + pWav->ima.cachedFrameCount = 1; + } + } + while (framesToRead > 0 && pWav->ima.cachedFrameCount > 0 && pWav->readCursorInPCMFrames < pWav->totalPCMFrameCount) { + if (pBufferOut != NULL) { + ma_uint32 iSample; + for (iSample = 0; iSample < pWav->channels; iSample += 1) { + pBufferOut[iSample] = (ma_int16)pWav->ima.cachedFrames[(ma_dr_wav_countof(pWav->ima.cachedFrames) - (pWav->ima.cachedFrameCount*pWav->channels)) + iSample]; + } + pBufferOut += pWav->channels; + } + framesToRead -= 1; + totalFramesRead += 1; + pWav->readCursorInPCMFrames += 1; + pWav->ima.cachedFrameCount -= 1; + } + if (framesToRead == 0) { + break; + } + if (pWav->ima.cachedFrameCount == 0) { + if (pWav->ima.bytesRemainingInBlock == 0) { + continue; + } else { + pWav->ima.cachedFrameCount = 8; + for (iChannel = 0; iChannel < pWav->channels; ++iChannel) { + ma_uint32 iByte; + ma_uint8 nibbles[4]; + if (pWav->onRead(pWav->pUserData, &nibbles, 4) != 4) { + pWav->ima.cachedFrameCount = 0; + return totalFramesRead; + } + pWav->ima.bytesRemainingInBlock -= 4; + for (iByte = 0; iByte < 4; ++iByte) { + ma_uint8 nibble0 = ((nibbles[iByte] & 0x0F) >> 0); + ma_uint8 nibble1 = ((nibbles[iByte] & 0xF0) >> 4); + ma_int32 step = stepTable[pWav->ima.stepIndex[iChannel]]; + ma_int32 predictor = pWav->ima.predictor[iChannel]; + ma_int32 diff = step >> 3; + if (nibble0 & 1) diff += step >> 2; + if (nibble0 & 2) diff += step >> 1; + if (nibble0 & 4) diff += step; + if (nibble0 & 8) diff = -diff; + predictor = ma_dr_wav_clamp(predictor + diff, -32768, 32767); + pWav->ima.predictor[iChannel] = predictor; + pWav->ima.stepIndex[iChannel] = ma_dr_wav_clamp(pWav->ima.stepIndex[iChannel] + indexTable[nibble0], 0, (ma_int32)ma_dr_wav_countof(stepTable)-1); + pWav->ima.cachedFrames[(ma_dr_wav_countof(pWav->ima.cachedFrames) - (pWav->ima.cachedFrameCount*pWav->channels)) + (iByte*2+0)*pWav->channels + iChannel] = predictor; + step = stepTable[pWav->ima.stepIndex[iChannel]]; + predictor = pWav->ima.predictor[iChannel]; + diff = step >> 3; + if (nibble1 & 1) diff += step >> 2; + if (nibble1 & 2) diff += step >> 1; + if (nibble1 & 4) diff += step; + if (nibble1 & 8) diff = -diff; + predictor = ma_dr_wav_clamp(predictor + diff, -32768, 32767); + pWav->ima.predictor[iChannel] = predictor; + pWav->ima.stepIndex[iChannel] = ma_dr_wav_clamp(pWav->ima.stepIndex[iChannel] + indexTable[nibble1], 0, (ma_int32)ma_dr_wav_countof(stepTable)-1); + pWav->ima.cachedFrames[(ma_dr_wav_countof(pWav->ima.cachedFrames) - (pWav->ima.cachedFrameCount*pWav->channels)) + (iByte*2+1)*pWav->channels + iChannel] = predictor; + } + } + } + } + } + return totalFramesRead; +} +#ifndef MA_DR_WAV_NO_CONVERSION_API +static unsigned short g_ma_dr_wavAlawTable[256] = { + 0xEA80, 0xEB80, 0xE880, 0xE980, 0xEE80, 0xEF80, 0xEC80, 0xED80, 0xE280, 0xE380, 0xE080, 0xE180, 0xE680, 0xE780, 0xE480, 0xE580, + 0xF540, 0xF5C0, 0xF440, 0xF4C0, 0xF740, 0xF7C0, 0xF640, 0xF6C0, 0xF140, 0xF1C0, 0xF040, 0xF0C0, 0xF340, 0xF3C0, 0xF240, 0xF2C0, + 0xAA00, 0xAE00, 0xA200, 0xA600, 0xBA00, 0xBE00, 0xB200, 0xB600, 0x8A00, 0x8E00, 0x8200, 0x8600, 0x9A00, 0x9E00, 0x9200, 0x9600, + 0xD500, 0xD700, 0xD100, 0xD300, 0xDD00, 0xDF00, 0xD900, 0xDB00, 0xC500, 0xC700, 0xC100, 0xC300, 0xCD00, 0xCF00, 0xC900, 0xCB00, + 0xFEA8, 0xFEB8, 0xFE88, 0xFE98, 0xFEE8, 0xFEF8, 0xFEC8, 0xFED8, 0xFE28, 0xFE38, 0xFE08, 0xFE18, 0xFE68, 0xFE78, 0xFE48, 0xFE58, + 0xFFA8, 0xFFB8, 0xFF88, 0xFF98, 0xFFE8, 0xFFF8, 0xFFC8, 0xFFD8, 0xFF28, 0xFF38, 0xFF08, 0xFF18, 0xFF68, 0xFF78, 0xFF48, 0xFF58, + 0xFAA0, 0xFAE0, 0xFA20, 0xFA60, 0xFBA0, 0xFBE0, 0xFB20, 0xFB60, 0xF8A0, 0xF8E0, 0xF820, 0xF860, 0xF9A0, 0xF9E0, 0xF920, 0xF960, + 0xFD50, 0xFD70, 0xFD10, 0xFD30, 0xFDD0, 0xFDF0, 0xFD90, 0xFDB0, 0xFC50, 0xFC70, 0xFC10, 0xFC30, 0xFCD0, 0xFCF0, 0xFC90, 0xFCB0, + 0x1580, 0x1480, 0x1780, 0x1680, 0x1180, 0x1080, 0x1380, 0x1280, 0x1D80, 0x1C80, 0x1F80, 0x1E80, 0x1980, 0x1880, 0x1B80, 0x1A80, + 0x0AC0, 0x0A40, 0x0BC0, 0x0B40, 0x08C0, 0x0840, 0x09C0, 0x0940, 0x0EC0, 0x0E40, 0x0FC0, 0x0F40, 0x0CC0, 0x0C40, 0x0DC0, 0x0D40, + 0x5600, 0x5200, 0x5E00, 0x5A00, 0x4600, 0x4200, 0x4E00, 0x4A00, 0x7600, 0x7200, 0x7E00, 0x7A00, 0x6600, 0x6200, 0x6E00, 0x6A00, + 0x2B00, 0x2900, 0x2F00, 0x2D00, 0x2300, 0x2100, 0x2700, 0x2500, 0x3B00, 0x3900, 0x3F00, 0x3D00, 0x3300, 0x3100, 0x3700, 0x3500, + 0x0158, 0x0148, 0x0178, 0x0168, 0x0118, 0x0108, 0x0138, 0x0128, 0x01D8, 0x01C8, 0x01F8, 0x01E8, 0x0198, 0x0188, 0x01B8, 0x01A8, + 0x0058, 0x0048, 0x0078, 0x0068, 0x0018, 0x0008, 0x0038, 0x0028, 0x00D8, 0x00C8, 0x00F8, 0x00E8, 0x0098, 0x0088, 0x00B8, 0x00A8, + 0x0560, 0x0520, 0x05E0, 0x05A0, 0x0460, 0x0420, 0x04E0, 0x04A0, 0x0760, 0x0720, 0x07E0, 0x07A0, 0x0660, 0x0620, 0x06E0, 0x06A0, + 0x02B0, 0x0290, 0x02F0, 0x02D0, 0x0230, 0x0210, 0x0270, 0x0250, 0x03B0, 0x0390, 0x03F0, 0x03D0, 0x0330, 0x0310, 0x0370, 0x0350 +}; +static unsigned short g_ma_dr_wavMulawTable[256] = { + 0x8284, 0x8684, 0x8A84, 0x8E84, 0x9284, 0x9684, 0x9A84, 0x9E84, 0xA284, 0xA684, 0xAA84, 0xAE84, 0xB284, 0xB684, 0xBA84, 0xBE84, + 0xC184, 0xC384, 0xC584, 0xC784, 0xC984, 0xCB84, 0xCD84, 0xCF84, 0xD184, 0xD384, 0xD584, 0xD784, 0xD984, 0xDB84, 0xDD84, 0xDF84, + 0xE104, 0xE204, 0xE304, 0xE404, 0xE504, 0xE604, 0xE704, 0xE804, 0xE904, 0xEA04, 0xEB04, 0xEC04, 0xED04, 0xEE04, 0xEF04, 0xF004, + 0xF0C4, 0xF144, 0xF1C4, 0xF244, 0xF2C4, 0xF344, 0xF3C4, 0xF444, 0xF4C4, 0xF544, 0xF5C4, 0xF644, 0xF6C4, 0xF744, 0xF7C4, 0xF844, + 0xF8A4, 0xF8E4, 0xF924, 0xF964, 0xF9A4, 0xF9E4, 0xFA24, 0xFA64, 0xFAA4, 0xFAE4, 0xFB24, 0xFB64, 0xFBA4, 0xFBE4, 0xFC24, 0xFC64, + 0xFC94, 0xFCB4, 0xFCD4, 0xFCF4, 0xFD14, 0xFD34, 0xFD54, 0xFD74, 0xFD94, 0xFDB4, 0xFDD4, 0xFDF4, 0xFE14, 0xFE34, 0xFE54, 0xFE74, + 0xFE8C, 0xFE9C, 0xFEAC, 0xFEBC, 0xFECC, 0xFEDC, 0xFEEC, 0xFEFC, 0xFF0C, 0xFF1C, 0xFF2C, 0xFF3C, 0xFF4C, 0xFF5C, 0xFF6C, 0xFF7C, + 0xFF88, 0xFF90, 0xFF98, 0xFFA0, 0xFFA8, 0xFFB0, 0xFFB8, 0xFFC0, 0xFFC8, 0xFFD0, 0xFFD8, 0xFFE0, 0xFFE8, 0xFFF0, 0xFFF8, 0x0000, + 0x7D7C, 0x797C, 0x757C, 0x717C, 0x6D7C, 0x697C, 0x657C, 0x617C, 0x5D7C, 0x597C, 0x557C, 0x517C, 0x4D7C, 0x497C, 0x457C, 0x417C, + 0x3E7C, 0x3C7C, 0x3A7C, 0x387C, 0x367C, 0x347C, 0x327C, 0x307C, 0x2E7C, 0x2C7C, 0x2A7C, 0x287C, 0x267C, 0x247C, 0x227C, 0x207C, + 0x1EFC, 0x1DFC, 0x1CFC, 0x1BFC, 0x1AFC, 0x19FC, 0x18FC, 0x17FC, 0x16FC, 0x15FC, 0x14FC, 0x13FC, 0x12FC, 0x11FC, 0x10FC, 0x0FFC, + 0x0F3C, 0x0EBC, 0x0E3C, 0x0DBC, 0x0D3C, 0x0CBC, 0x0C3C, 0x0BBC, 0x0B3C, 0x0ABC, 0x0A3C, 0x09BC, 0x093C, 0x08BC, 0x083C, 0x07BC, + 0x075C, 0x071C, 0x06DC, 0x069C, 0x065C, 0x061C, 0x05DC, 0x059C, 0x055C, 0x051C, 0x04DC, 0x049C, 0x045C, 0x041C, 0x03DC, 0x039C, + 0x036C, 0x034C, 0x032C, 0x030C, 0x02EC, 0x02CC, 0x02AC, 0x028C, 0x026C, 0x024C, 0x022C, 0x020C, 0x01EC, 0x01CC, 0x01AC, 0x018C, + 0x0174, 0x0164, 0x0154, 0x0144, 0x0134, 0x0124, 0x0114, 0x0104, 0x00F4, 0x00E4, 0x00D4, 0x00C4, 0x00B4, 0x00A4, 0x0094, 0x0084, + 0x0078, 0x0070, 0x0068, 0x0060, 0x0058, 0x0050, 0x0048, 0x0040, 0x0038, 0x0030, 0x0028, 0x0020, 0x0018, 0x0010, 0x0008, 0x0000 +}; +static MA_INLINE ma_int16 ma_dr_wav__alaw_to_s16(ma_uint8 sampleIn) +{ + return (short)g_ma_dr_wavAlawTable[sampleIn]; +} +static MA_INLINE ma_int16 ma_dr_wav__mulaw_to_s16(ma_uint8 sampleIn) +{ + return (short)g_ma_dr_wavMulawTable[sampleIn]; +} +MA_PRIVATE void ma_dr_wav__pcm_to_s16(ma_int16* pOut, const ma_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample) +{ + size_t i; + if (bytesPerSample == 1) { + ma_dr_wav_u8_to_s16(pOut, pIn, totalSampleCount); + return; + } + if (bytesPerSample == 2) { + for (i = 0; i < totalSampleCount; ++i) { + *pOut++ = ((const ma_int16*)pIn)[i]; + } + return; + } + if (bytesPerSample == 3) { + ma_dr_wav_s24_to_s16(pOut, pIn, totalSampleCount); + return; + } + if (bytesPerSample == 4) { + ma_dr_wav_s32_to_s16(pOut, (const ma_int32*)pIn, totalSampleCount); + return; + } + if (bytesPerSample > 8) { + MA_DR_WAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut)); + return; + } + for (i = 0; i < totalSampleCount; ++i) { + ma_uint64 sample = 0; + unsigned int shift = (8 - bytesPerSample) * 8; + unsigned int j; + for (j = 0; j < bytesPerSample; j += 1) { + MA_DR_WAV_ASSERT(j < 8); + sample |= (ma_uint64)(pIn[j]) << shift; + shift += 8; + } + pIn += j; + *pOut++ = (ma_int16)((ma_int64)sample >> 48); + } +} +MA_PRIVATE void ma_dr_wav__ieee_to_s16(ma_int16* pOut, const ma_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample) +{ + if (bytesPerSample == 4) { + ma_dr_wav_f32_to_s16(pOut, (const float*)pIn, totalSampleCount); + return; + } else if (bytesPerSample == 8) { + ma_dr_wav_f64_to_s16(pOut, (const double*)pIn, totalSampleCount); + return; + } else { + MA_DR_WAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut)); + return; + } +} +MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s16__pcm(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut) +{ + ma_uint64 totalFramesRead; + ma_uint8 sampleData[4096] = {0}; + ma_uint32 bytesPerFrame; + ma_uint32 bytesPerSample; + ma_uint64 samplesRead; + if ((pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_PCM && pWav->bitsPerSample == 16) || pBufferOut == NULL) { + return ma_dr_wav_read_pcm_frames(pWav, framesToRead, pBufferOut); + } + bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav); + if (bytesPerFrame == 0) { + return 0; + } + bytesPerSample = bytesPerFrame / pWav->channels; + if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) { + return 0; + } + totalFramesRead = 0; + while (framesToRead > 0) { + ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame); + ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData); + if (framesRead == 0) { + break; + } + MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration); + samplesRead = framesRead * pWav->channels; + if ((samplesRead * bytesPerSample) > sizeof(sampleData)) { + MA_DR_WAV_ASSERT(MA_FALSE); + break; + } + ma_dr_wav__pcm_to_s16(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample); + pBufferOut += samplesRead; + framesToRead -= framesRead; + totalFramesRead += framesRead; + } + return totalFramesRead; +} +MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s16__ieee(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut) +{ + ma_uint64 totalFramesRead; + ma_uint8 sampleData[4096] = {0}; + ma_uint32 bytesPerFrame; + ma_uint32 bytesPerSample; + ma_uint64 samplesRead; + if (pBufferOut == NULL) { + return ma_dr_wav_read_pcm_frames(pWav, framesToRead, NULL); + } + bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav); + if (bytesPerFrame == 0) { + return 0; + } + bytesPerSample = bytesPerFrame / pWav->channels; + if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) { + return 0; + } + totalFramesRead = 0; + while (framesToRead > 0) { + ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame); + ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData); + if (framesRead == 0) { + break; + } + MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration); + samplesRead = framesRead * pWav->channels; + if ((samplesRead * bytesPerSample) > sizeof(sampleData)) { + MA_DR_WAV_ASSERT(MA_FALSE); + break; + } + ma_dr_wav__ieee_to_s16(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample); + pBufferOut += samplesRead; + framesToRead -= framesRead; + totalFramesRead += framesRead; + } + return totalFramesRead; +} +MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s16__alaw(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut) +{ + ma_uint64 totalFramesRead; + ma_uint8 sampleData[4096] = {0}; + ma_uint32 bytesPerFrame; + ma_uint32 bytesPerSample; + ma_uint64 samplesRead; + if (pBufferOut == NULL) { + return ma_dr_wav_read_pcm_frames(pWav, framesToRead, NULL); + } + bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav); + if (bytesPerFrame == 0) { + return 0; + } + bytesPerSample = bytesPerFrame / pWav->channels; + if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) { + return 0; + } + totalFramesRead = 0; + while (framesToRead > 0) { + ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame); + ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData); + if (framesRead == 0) { + break; + } + MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration); + samplesRead = framesRead * pWav->channels; + if ((samplesRead * bytesPerSample) > sizeof(sampleData)) { + MA_DR_WAV_ASSERT(MA_FALSE); + break; + } + ma_dr_wav_alaw_to_s16(pBufferOut, sampleData, (size_t)samplesRead); + #ifdef MA_DR_WAV_LIBSNDFILE_COMPAT + { + if (pWav->container == ma_dr_wav_container_aiff) { + ma_uint64 iSample; + for (iSample = 0; iSample < samplesRead; iSample += 1) { + pBufferOut[iSample] = -pBufferOut[iSample]; + } + } + } + #endif + pBufferOut += samplesRead; + framesToRead -= framesRead; + totalFramesRead += framesRead; + } + return totalFramesRead; +} +MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s16__mulaw(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut) +{ + ma_uint64 totalFramesRead; + ma_uint8 sampleData[4096] = {0}; + ma_uint32 bytesPerFrame; + ma_uint32 bytesPerSample; + ma_uint64 samplesRead; + if (pBufferOut == NULL) { + return ma_dr_wav_read_pcm_frames(pWav, framesToRead, NULL); + } + bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav); + if (bytesPerFrame == 0) { + return 0; + } + bytesPerSample = bytesPerFrame / pWav->channels; + if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) { + return 0; + } + totalFramesRead = 0; + while (framesToRead > 0) { + ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame); + ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData); + if (framesRead == 0) { + break; + } + MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration); + samplesRead = framesRead * pWav->channels; + if ((samplesRead * bytesPerSample) > sizeof(sampleData)) { + MA_DR_WAV_ASSERT(MA_FALSE); + break; + } + ma_dr_wav_mulaw_to_s16(pBufferOut, sampleData, (size_t)samplesRead); + #ifdef MA_DR_WAV_LIBSNDFILE_COMPAT + { + if (pWav->container == ma_dr_wav_container_aiff) { + ma_uint64 iSample; + for (iSample = 0; iSample < samplesRead; iSample += 1) { + pBufferOut[iSample] = -pBufferOut[iSample]; + } + } + } + #endif + pBufferOut += samplesRead; + framesToRead -= framesRead; + totalFramesRead += framesRead; + } + return totalFramesRead; +} +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s16(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut) +{ + if (pWav == NULL || framesToRead == 0) { + return 0; + } + if (pBufferOut == NULL) { + return ma_dr_wav_read_pcm_frames(pWav, framesToRead, NULL); + } + if (framesToRead * pWav->channels * sizeof(ma_int16) > MA_SIZE_MAX) { + framesToRead = MA_SIZE_MAX / sizeof(ma_int16) / pWav->channels; + } + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_PCM) { + return ma_dr_wav_read_pcm_frames_s16__pcm(pWav, framesToRead, pBufferOut); + } + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_IEEE_FLOAT) { + return ma_dr_wav_read_pcm_frames_s16__ieee(pWav, framesToRead, pBufferOut); + } + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ALAW) { + return ma_dr_wav_read_pcm_frames_s16__alaw(pWav, framesToRead, pBufferOut); + } + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_MULAW) { + return ma_dr_wav_read_pcm_frames_s16__mulaw(pWav, framesToRead, pBufferOut); + } + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ADPCM) { + return ma_dr_wav_read_pcm_frames_s16__msadpcm(pWav, framesToRead, pBufferOut); + } + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_DVI_ADPCM) { + return ma_dr_wav_read_pcm_frames_s16__ima(pWav, framesToRead, pBufferOut); + } + return 0; +} +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s16le(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut) +{ + ma_uint64 framesRead = ma_dr_wav_read_pcm_frames_s16(pWav, framesToRead, pBufferOut); + if (pBufferOut != NULL && ma_dr_wav__is_little_endian() == MA_FALSE) { + ma_dr_wav__bswap_samples_s16(pBufferOut, framesRead*pWav->channels); + } + return framesRead; +} +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s16be(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut) +{ + ma_uint64 framesRead = ma_dr_wav_read_pcm_frames_s16(pWav, framesToRead, pBufferOut); + if (pBufferOut != NULL && ma_dr_wav__is_little_endian() == MA_TRUE) { + ma_dr_wav__bswap_samples_s16(pBufferOut, framesRead*pWav->channels); + } + return framesRead; +} +MA_API void ma_dr_wav_u8_to_s16(ma_int16* pOut, const ma_uint8* pIn, size_t sampleCount) +{ + int r; + size_t i; + for (i = 0; i < sampleCount; ++i) { + int x = pIn[i]; + r = x << 8; + r = r - 32768; + pOut[i] = (short)r; + } +} +MA_API void ma_dr_wav_s24_to_s16(ma_int16* pOut, const ma_uint8* pIn, size_t sampleCount) +{ + int r; + size_t i; + for (i = 0; i < sampleCount; ++i) { + int x = ((int)(((unsigned int)(((const ma_uint8*)pIn)[i*3+0]) << 8) | ((unsigned int)(((const ma_uint8*)pIn)[i*3+1]) << 16) | ((unsigned int)(((const ma_uint8*)pIn)[i*3+2])) << 24)) >> 8; + r = x >> 8; + pOut[i] = (short)r; + } +} +MA_API void ma_dr_wav_s32_to_s16(ma_int16* pOut, const ma_int32* pIn, size_t sampleCount) +{ + int r; + size_t i; + for (i = 0; i < sampleCount; ++i) { + int x = pIn[i]; + r = x >> 16; + pOut[i] = (short)r; + } +} +MA_API void ma_dr_wav_f32_to_s16(ma_int16* pOut, const float* pIn, size_t sampleCount) +{ + int r; + size_t i; + for (i = 0; i < sampleCount; ++i) { + float x = pIn[i]; + float c; + c = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); + c = c + 1; + r = (int)(c * 32767.5f); + r = r - 32768; + pOut[i] = (short)r; + } +} +MA_API void ma_dr_wav_f64_to_s16(ma_int16* pOut, const double* pIn, size_t sampleCount) +{ + int r; + size_t i; + for (i = 0; i < sampleCount; ++i) { + double x = pIn[i]; + double c; + c = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); + c = c + 1; + r = (int)(c * 32767.5); + r = r - 32768; + pOut[i] = (short)r; + } +} +MA_API void ma_dr_wav_alaw_to_s16(ma_int16* pOut, const ma_uint8* pIn, size_t sampleCount) +{ + size_t i; + for (i = 0; i < sampleCount; ++i) { + pOut[i] = ma_dr_wav__alaw_to_s16(pIn[i]); + } +} +MA_API void ma_dr_wav_mulaw_to_s16(ma_int16* pOut, const ma_uint8* pIn, size_t sampleCount) +{ + size_t i; + for (i = 0; i < sampleCount; ++i) { + pOut[i] = ma_dr_wav__mulaw_to_s16(pIn[i]); + } +} +MA_PRIVATE void ma_dr_wav__pcm_to_f32(float* pOut, const ma_uint8* pIn, size_t sampleCount, unsigned int bytesPerSample) +{ + unsigned int i; + if (bytesPerSample == 1) { + ma_dr_wav_u8_to_f32(pOut, pIn, sampleCount); + return; + } + if (bytesPerSample == 2) { + ma_dr_wav_s16_to_f32(pOut, (const ma_int16*)pIn, sampleCount); + return; + } + if (bytesPerSample == 3) { + ma_dr_wav_s24_to_f32(pOut, pIn, sampleCount); + return; + } + if (bytesPerSample == 4) { + ma_dr_wav_s32_to_f32(pOut, (const ma_int32*)pIn, sampleCount); + return; + } + if (bytesPerSample > 8) { + MA_DR_WAV_ZERO_MEMORY(pOut, sampleCount * sizeof(*pOut)); + return; + } + for (i = 0; i < sampleCount; ++i) { + ma_uint64 sample = 0; + unsigned int shift = (8 - bytesPerSample) * 8; + unsigned int j; + for (j = 0; j < bytesPerSample; j += 1) { + MA_DR_WAV_ASSERT(j < 8); + sample |= (ma_uint64)(pIn[j]) << shift; + shift += 8; + } + pIn += j; + *pOut++ = (float)((ma_int64)sample / 9223372036854775807.0); + } +} +MA_PRIVATE void ma_dr_wav__ieee_to_f32(float* pOut, const ma_uint8* pIn, size_t sampleCount, unsigned int bytesPerSample) +{ + if (bytesPerSample == 4) { + unsigned int i; + for (i = 0; i < sampleCount; ++i) { + *pOut++ = ((const float*)pIn)[i]; + } + return; + } else if (bytesPerSample == 8) { + ma_dr_wav_f64_to_f32(pOut, (const double*)pIn, sampleCount); + return; + } else { + MA_DR_WAV_ZERO_MEMORY(pOut, sampleCount * sizeof(*pOut)); + return; + } +} +MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_f32__pcm(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut) +{ + ma_uint64 totalFramesRead; + ma_uint8 sampleData[4096] = {0}; + ma_uint32 bytesPerFrame; + ma_uint32 bytesPerSample; + ma_uint64 samplesRead; + bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav); + if (bytesPerFrame == 0) { + return 0; + } + bytesPerSample = bytesPerFrame / pWav->channels; + if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) { + return 0; + } + totalFramesRead = 0; + while (framesToRead > 0) { + ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame); + ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData); + if (framesRead == 0) { + break; + } + MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration); + samplesRead = framesRead * pWav->channels; + if ((samplesRead * bytesPerSample) > sizeof(sampleData)) { + MA_DR_WAV_ASSERT(MA_FALSE); + break; + } + ma_dr_wav__pcm_to_f32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample); + pBufferOut += samplesRead; + framesToRead -= framesRead; + totalFramesRead += framesRead; + } + return totalFramesRead; +} +MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_f32__msadpcm_ima(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut) +{ + ma_uint64 totalFramesRead; + ma_int16 samples16[2048]; + totalFramesRead = 0; + while (framesToRead > 0) { + ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, ma_dr_wav_countof(samples16)/pWav->channels); + ma_uint64 framesRead = ma_dr_wav_read_pcm_frames_s16(pWav, framesToReadThisIteration, samples16); + if (framesRead == 0) { + break; + } + MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration); + ma_dr_wav_s16_to_f32(pBufferOut, samples16, (size_t)(framesRead*pWav->channels)); + pBufferOut += framesRead*pWav->channels; + framesToRead -= framesRead; + totalFramesRead += framesRead; + } + return totalFramesRead; +} +MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_f32__ieee(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut) +{ + ma_uint64 totalFramesRead; + ma_uint8 sampleData[4096] = {0}; + ma_uint32 bytesPerFrame; + ma_uint32 bytesPerSample; + ma_uint64 samplesRead; + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_IEEE_FLOAT && pWav->bitsPerSample == 32) { + return ma_dr_wav_read_pcm_frames(pWav, framesToRead, pBufferOut); + } + bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav); + if (bytesPerFrame == 0) { + return 0; + } + bytesPerSample = bytesPerFrame / pWav->channels; + if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) { + return 0; + } + totalFramesRead = 0; + while (framesToRead > 0) { + ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame); + ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData); + if (framesRead == 0) { + break; + } + MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration); + samplesRead = framesRead * pWav->channels; + if ((samplesRead * bytesPerSample) > sizeof(sampleData)) { + MA_DR_WAV_ASSERT(MA_FALSE); + break; + } + ma_dr_wav__ieee_to_f32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample); + pBufferOut += samplesRead; + framesToRead -= framesRead; + totalFramesRead += framesRead; + } + return totalFramesRead; +} +MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_f32__alaw(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut) +{ + ma_uint64 totalFramesRead; + ma_uint8 sampleData[4096] = {0}; + ma_uint32 bytesPerFrame; + ma_uint32 bytesPerSample; + ma_uint64 samplesRead; + bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav); + if (bytesPerFrame == 0) { + return 0; + } + bytesPerSample = bytesPerFrame / pWav->channels; + if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) { + return 0; + } + totalFramesRead = 0; + while (framesToRead > 0) { + ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame); + ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData); + if (framesRead == 0) { + break; + } + MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration); + samplesRead = framesRead * pWav->channels; + if ((samplesRead * bytesPerSample) > sizeof(sampleData)) { + MA_DR_WAV_ASSERT(MA_FALSE); + break; + } + ma_dr_wav_alaw_to_f32(pBufferOut, sampleData, (size_t)samplesRead); + #ifdef MA_DR_WAV_LIBSNDFILE_COMPAT + { + if (pWav->container == ma_dr_wav_container_aiff) { + ma_uint64 iSample; + for (iSample = 0; iSample < samplesRead; iSample += 1) { + pBufferOut[iSample] = -pBufferOut[iSample]; + } + } + } + #endif + pBufferOut += samplesRead; + framesToRead -= framesRead; + totalFramesRead += framesRead; + } + return totalFramesRead; +} +MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_f32__mulaw(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut) +{ + ma_uint64 totalFramesRead; + ma_uint8 sampleData[4096] = {0}; + ma_uint32 bytesPerFrame; + ma_uint32 bytesPerSample; + ma_uint64 samplesRead; + bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav); + if (bytesPerFrame == 0) { + return 0; + } + bytesPerSample = bytesPerFrame / pWav->channels; + if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) { + return 0; + } + totalFramesRead = 0; + while (framesToRead > 0) { + ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame); + ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData); + if (framesRead == 0) { + break; + } + MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration); + samplesRead = framesRead * pWav->channels; + if ((samplesRead * bytesPerSample) > sizeof(sampleData)) { + MA_DR_WAV_ASSERT(MA_FALSE); + break; + } + ma_dr_wav_mulaw_to_f32(pBufferOut, sampleData, (size_t)samplesRead); + #ifdef MA_DR_WAV_LIBSNDFILE_COMPAT + { + if (pWav->container == ma_dr_wav_container_aiff) { + ma_uint64 iSample; + for (iSample = 0; iSample < samplesRead; iSample += 1) { + pBufferOut[iSample] = -pBufferOut[iSample]; + } + } + } + #endif + pBufferOut += samplesRead; + framesToRead -= framesRead; + totalFramesRead += framesRead; + } + return totalFramesRead; +} +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_f32(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut) +{ + if (pWav == NULL || framesToRead == 0) { + return 0; + } + if (pBufferOut == NULL) { + return ma_dr_wav_read_pcm_frames(pWav, framesToRead, NULL); + } + if (framesToRead * pWav->channels * sizeof(float) > MA_SIZE_MAX) { + framesToRead = MA_SIZE_MAX / sizeof(float) / pWav->channels; + } + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_PCM) { + return ma_dr_wav_read_pcm_frames_f32__pcm(pWav, framesToRead, pBufferOut); + } + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ADPCM || pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_DVI_ADPCM) { + return ma_dr_wav_read_pcm_frames_f32__msadpcm_ima(pWav, framesToRead, pBufferOut); + } + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_IEEE_FLOAT) { + return ma_dr_wav_read_pcm_frames_f32__ieee(pWav, framesToRead, pBufferOut); + } + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ALAW) { + return ma_dr_wav_read_pcm_frames_f32__alaw(pWav, framesToRead, pBufferOut); + } + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_MULAW) { + return ma_dr_wav_read_pcm_frames_f32__mulaw(pWav, framesToRead, pBufferOut); + } + return 0; +} +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_f32le(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut) +{ + ma_uint64 framesRead = ma_dr_wav_read_pcm_frames_f32(pWav, framesToRead, pBufferOut); + if (pBufferOut != NULL && ma_dr_wav__is_little_endian() == MA_FALSE) { + ma_dr_wav__bswap_samples_f32(pBufferOut, framesRead*pWav->channels); + } + return framesRead; +} +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_f32be(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut) +{ + ma_uint64 framesRead = ma_dr_wav_read_pcm_frames_f32(pWav, framesToRead, pBufferOut); + if (pBufferOut != NULL && ma_dr_wav__is_little_endian() == MA_TRUE) { + ma_dr_wav__bswap_samples_f32(pBufferOut, framesRead*pWav->channels); + } + return framesRead; +} +MA_API void ma_dr_wav_u8_to_f32(float* pOut, const ma_uint8* pIn, size_t sampleCount) +{ + size_t i; + if (pOut == NULL || pIn == NULL) { + return; + } +#ifdef MA_DR_WAV_LIBSNDFILE_COMPAT + for (i = 0; i < sampleCount; ++i) { + *pOut++ = (pIn[i] / 256.0f) * 2 - 1; + } +#else + for (i = 0; i < sampleCount; ++i) { + float x = pIn[i]; + x = x * 0.00784313725490196078f; + x = x - 1; + *pOut++ = x; + } +#endif +} +MA_API void ma_dr_wav_s16_to_f32(float* pOut, const ma_int16* pIn, size_t sampleCount) +{ + size_t i; + if (pOut == NULL || pIn == NULL) { + return; + } + for (i = 0; i < sampleCount; ++i) { + *pOut++ = pIn[i] * 0.000030517578125f; + } +} +MA_API void ma_dr_wav_s24_to_f32(float* pOut, const ma_uint8* pIn, size_t sampleCount) +{ + size_t i; + if (pOut == NULL || pIn == NULL) { + return; + } + for (i = 0; i < sampleCount; ++i) { + double x; + ma_uint32 a = ((ma_uint32)(pIn[i*3+0]) << 8); + ma_uint32 b = ((ma_uint32)(pIn[i*3+1]) << 16); + ma_uint32 c = ((ma_uint32)(pIn[i*3+2]) << 24); + x = (double)((ma_int32)(a | b | c) >> 8); + *pOut++ = (float)(x * 0.00000011920928955078125); + } +} +MA_API void ma_dr_wav_s32_to_f32(float* pOut, const ma_int32* pIn, size_t sampleCount) +{ + size_t i; + if (pOut == NULL || pIn == NULL) { + return; + } + for (i = 0; i < sampleCount; ++i) { + *pOut++ = (float)(pIn[i] / 2147483648.0); + } +} +MA_API void ma_dr_wav_f64_to_f32(float* pOut, const double* pIn, size_t sampleCount) +{ + size_t i; + if (pOut == NULL || pIn == NULL) { + return; + } + for (i = 0; i < sampleCount; ++i) { + *pOut++ = (float)pIn[i]; + } +} +MA_API void ma_dr_wav_alaw_to_f32(float* pOut, const ma_uint8* pIn, size_t sampleCount) +{ + size_t i; + if (pOut == NULL || pIn == NULL) { + return; + } + for (i = 0; i < sampleCount; ++i) { + *pOut++ = ma_dr_wav__alaw_to_s16(pIn[i]) / 32768.0f; + } +} +MA_API void ma_dr_wav_mulaw_to_f32(float* pOut, const ma_uint8* pIn, size_t sampleCount) +{ + size_t i; + if (pOut == NULL || pIn == NULL) { + return; + } + for (i = 0; i < sampleCount; ++i) { + *pOut++ = ma_dr_wav__mulaw_to_s16(pIn[i]) / 32768.0f; + } +} +MA_PRIVATE void ma_dr_wav__pcm_to_s32(ma_int32* pOut, const ma_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample) +{ + unsigned int i; + if (bytesPerSample == 1) { + ma_dr_wav_u8_to_s32(pOut, pIn, totalSampleCount); + return; + } + if (bytesPerSample == 2) { + ma_dr_wav_s16_to_s32(pOut, (const ma_int16*)pIn, totalSampleCount); + return; + } + if (bytesPerSample == 3) { + ma_dr_wav_s24_to_s32(pOut, pIn, totalSampleCount); + return; + } + if (bytesPerSample == 4) { + for (i = 0; i < totalSampleCount; ++i) { + *pOut++ = ((const ma_int32*)pIn)[i]; + } + return; + } + if (bytesPerSample > 8) { + MA_DR_WAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut)); + return; + } + for (i = 0; i < totalSampleCount; ++i) { + ma_uint64 sample = 0; + unsigned int shift = (8 - bytesPerSample) * 8; + unsigned int j; + for (j = 0; j < bytesPerSample; j += 1) { + MA_DR_WAV_ASSERT(j < 8); + sample |= (ma_uint64)(pIn[j]) << shift; + shift += 8; + } + pIn += j; + *pOut++ = (ma_int32)((ma_int64)sample >> 32); + } +} +MA_PRIVATE void ma_dr_wav__ieee_to_s32(ma_int32* pOut, const ma_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample) +{ + if (bytesPerSample == 4) { + ma_dr_wav_f32_to_s32(pOut, (const float*)pIn, totalSampleCount); + return; + } else if (bytesPerSample == 8) { + ma_dr_wav_f64_to_s32(pOut, (const double*)pIn, totalSampleCount); + return; + } else { + MA_DR_WAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut)); + return; + } +} +MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s32__pcm(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut) +{ + ma_uint64 totalFramesRead; + ma_uint8 sampleData[4096] = {0}; + ma_uint32 bytesPerFrame; + ma_uint32 bytesPerSample; + ma_uint64 samplesRead; + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_PCM && pWav->bitsPerSample == 32) { + return ma_dr_wav_read_pcm_frames(pWav, framesToRead, pBufferOut); + } + bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav); + if (bytesPerFrame == 0) { + return 0; + } + bytesPerSample = bytesPerFrame / pWav->channels; + if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) { + return 0; + } + totalFramesRead = 0; + while (framesToRead > 0) { + ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame); + ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData); + if (framesRead == 0) { + break; + } + MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration); + samplesRead = framesRead * pWav->channels; + if ((samplesRead * bytesPerSample) > sizeof(sampleData)) { + MA_DR_WAV_ASSERT(MA_FALSE); + break; + } + ma_dr_wav__pcm_to_s32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample); + pBufferOut += samplesRead; + framesToRead -= framesRead; + totalFramesRead += framesRead; + } + return totalFramesRead; +} +MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s32__msadpcm_ima(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut) +{ + ma_uint64 totalFramesRead = 0; + ma_int16 samples16[2048]; + while (framesToRead > 0) { + ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, ma_dr_wav_countof(samples16)/pWav->channels); + ma_uint64 framesRead = ma_dr_wav_read_pcm_frames_s16(pWav, framesToReadThisIteration, samples16); + if (framesRead == 0) { + break; + } + MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration); + ma_dr_wav_s16_to_s32(pBufferOut, samples16, (size_t)(framesRead*pWav->channels)); + pBufferOut += framesRead*pWav->channels; + framesToRead -= framesRead; + totalFramesRead += framesRead; + } + return totalFramesRead; +} +MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s32__ieee(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut) +{ + ma_uint64 totalFramesRead; + ma_uint8 sampleData[4096] = {0}; + ma_uint32 bytesPerFrame; + ma_uint32 bytesPerSample; + ma_uint64 samplesRead; + bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav); + if (bytesPerFrame == 0) { + return 0; + } + bytesPerSample = bytesPerFrame / pWav->channels; + if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) { + return 0; + } + totalFramesRead = 0; + while (framesToRead > 0) { + ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame); + ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData); + if (framesRead == 0) { + break; + } + MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration); + samplesRead = framesRead * pWav->channels; + if ((samplesRead * bytesPerSample) > sizeof(sampleData)) { + MA_DR_WAV_ASSERT(MA_FALSE); + break; + } + ma_dr_wav__ieee_to_s32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample); + pBufferOut += samplesRead; + framesToRead -= framesRead; + totalFramesRead += framesRead; + } + return totalFramesRead; +} +MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s32__alaw(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut) +{ + ma_uint64 totalFramesRead; + ma_uint8 sampleData[4096] = {0}; + ma_uint32 bytesPerFrame; + ma_uint32 bytesPerSample; + ma_uint64 samplesRead; + bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav); + if (bytesPerFrame == 0) { + return 0; + } + bytesPerSample = bytesPerFrame / pWav->channels; + if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) { + return 0; + } + totalFramesRead = 0; + while (framesToRead > 0) { + ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame); + ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData); + if (framesRead == 0) { + break; + } + MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration); + samplesRead = framesRead * pWav->channels; + if ((samplesRead * bytesPerSample) > sizeof(sampleData)) { + MA_DR_WAV_ASSERT(MA_FALSE); + break; + } + ma_dr_wav_alaw_to_s32(pBufferOut, sampleData, (size_t)samplesRead); + #ifdef MA_DR_WAV_LIBSNDFILE_COMPAT + { + if (pWav->container == ma_dr_wav_container_aiff) { + ma_uint64 iSample; + for (iSample = 0; iSample < samplesRead; iSample += 1) { + pBufferOut[iSample] = -pBufferOut[iSample]; + } + } + } + #endif + pBufferOut += samplesRead; + framesToRead -= framesRead; + totalFramesRead += framesRead; + } + return totalFramesRead; +} +MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s32__mulaw(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut) +{ + ma_uint64 totalFramesRead; + ma_uint8 sampleData[4096] = {0}; + ma_uint32 bytesPerFrame; + ma_uint32 bytesPerSample; + ma_uint64 samplesRead; + bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav); + if (bytesPerFrame == 0) { + return 0; + } + bytesPerSample = bytesPerFrame / pWav->channels; + if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) { + return 0; + } + totalFramesRead = 0; + while (framesToRead > 0) { + ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame); + ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData); + if (framesRead == 0) { + break; + } + MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration); + samplesRead = framesRead * pWav->channels; + if ((samplesRead * bytesPerSample) > sizeof(sampleData)) { + MA_DR_WAV_ASSERT(MA_FALSE); + break; + } + ma_dr_wav_mulaw_to_s32(pBufferOut, sampleData, (size_t)samplesRead); + #ifdef MA_DR_WAV_LIBSNDFILE_COMPAT + { + if (pWav->container == ma_dr_wav_container_aiff) { + ma_uint64 iSample; + for (iSample = 0; iSample < samplesRead; iSample += 1) { + pBufferOut[iSample] = -pBufferOut[iSample]; + } + } + } + #endif + pBufferOut += samplesRead; + framesToRead -= framesRead; + totalFramesRead += framesRead; + } + return totalFramesRead; +} +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s32(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut) +{ + if (pWav == NULL || framesToRead == 0) { + return 0; + } + if (pBufferOut == NULL) { + return ma_dr_wav_read_pcm_frames(pWav, framesToRead, NULL); + } + if (framesToRead * pWav->channels * sizeof(ma_int32) > MA_SIZE_MAX) { + framesToRead = MA_SIZE_MAX / sizeof(ma_int32) / pWav->channels; + } + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_PCM) { + return ma_dr_wav_read_pcm_frames_s32__pcm(pWav, framesToRead, pBufferOut); + } + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ADPCM || pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_DVI_ADPCM) { + return ma_dr_wav_read_pcm_frames_s32__msadpcm_ima(pWav, framesToRead, pBufferOut); + } + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_IEEE_FLOAT) { + return ma_dr_wav_read_pcm_frames_s32__ieee(pWav, framesToRead, pBufferOut); + } + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ALAW) { + return ma_dr_wav_read_pcm_frames_s32__alaw(pWav, framesToRead, pBufferOut); + } + if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_MULAW) { + return ma_dr_wav_read_pcm_frames_s32__mulaw(pWav, framesToRead, pBufferOut); + } + return 0; +} +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s32le(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut) +{ + ma_uint64 framesRead = ma_dr_wav_read_pcm_frames_s32(pWav, framesToRead, pBufferOut); + if (pBufferOut != NULL && ma_dr_wav__is_little_endian() == MA_FALSE) { + ma_dr_wav__bswap_samples_s32(pBufferOut, framesRead*pWav->channels); + } + return framesRead; +} +MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s32be(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut) +{ + ma_uint64 framesRead = ma_dr_wav_read_pcm_frames_s32(pWav, framesToRead, pBufferOut); + if (pBufferOut != NULL && ma_dr_wav__is_little_endian() == MA_TRUE) { + ma_dr_wav__bswap_samples_s32(pBufferOut, framesRead*pWav->channels); + } + return framesRead; +} +MA_API void ma_dr_wav_u8_to_s32(ma_int32* pOut, const ma_uint8* pIn, size_t sampleCount) +{ + size_t i; + if (pOut == NULL || pIn == NULL) { + return; + } + for (i = 0; i < sampleCount; ++i) { + *pOut++ = ((int)pIn[i] - 128) << 24; + } +} +MA_API void ma_dr_wav_s16_to_s32(ma_int32* pOut, const ma_int16* pIn, size_t sampleCount) +{ + size_t i; + if (pOut == NULL || pIn == NULL) { + return; + } + for (i = 0; i < sampleCount; ++i) { + *pOut++ = pIn[i] << 16; + } +} +MA_API void ma_dr_wav_s24_to_s32(ma_int32* pOut, const ma_uint8* pIn, size_t sampleCount) +{ + size_t i; + if (pOut == NULL || pIn == NULL) { + return; + } + 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]; + ma_int32 sample32 = (ma_int32)((s0 << 8) | (s1 << 16) | (s2 << 24)); + *pOut++ = sample32; + } +} +MA_API void ma_dr_wav_f32_to_s32(ma_int32* pOut, const float* pIn, size_t sampleCount) +{ + size_t i; + if (pOut == NULL || pIn == NULL) { + return; + } + for (i = 0; i < sampleCount; ++i) { + *pOut++ = (ma_int32)(2147483648.0 * pIn[i]); + } +} +MA_API void ma_dr_wav_f64_to_s32(ma_int32* pOut, const double* pIn, size_t sampleCount) +{ + size_t i; + if (pOut == NULL || pIn == NULL) { + return; + } + for (i = 0; i < sampleCount; ++i) { + *pOut++ = (ma_int32)(2147483648.0 * pIn[i]); + } +} +MA_API void ma_dr_wav_alaw_to_s32(ma_int32* pOut, const ma_uint8* pIn, size_t sampleCount) +{ + size_t i; + if (pOut == NULL || pIn == NULL) { + return; + } + for (i = 0; i < sampleCount; ++i) { + *pOut++ = ((ma_int32)ma_dr_wav__alaw_to_s16(pIn[i])) << 16; + } +} +MA_API void ma_dr_wav_mulaw_to_s32(ma_int32* pOut, const ma_uint8* pIn, size_t sampleCount) +{ + size_t i; + if (pOut == NULL || pIn == NULL) { + return; + } + for (i= 0; i < sampleCount; ++i) { + *pOut++ = ((ma_int32)ma_dr_wav__mulaw_to_s16(pIn[i])) << 16; + } +} +MA_PRIVATE ma_int16* ma_dr_wav__read_pcm_frames_and_close_s16(ma_dr_wav* pWav, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalFrameCount) +{ + ma_uint64 sampleDataSize; + ma_int16* pSampleData; + ma_uint64 framesRead; + MA_DR_WAV_ASSERT(pWav != NULL); + sampleDataSize = pWav->totalPCMFrameCount * pWav->channels * sizeof(ma_int16); + if (sampleDataSize > MA_SIZE_MAX) { + ma_dr_wav_uninit(pWav); + return NULL; + } + pSampleData = (ma_int16*)ma_dr_wav__malloc_from_callbacks((size_t)sampleDataSize, &pWav->allocationCallbacks); + if (pSampleData == NULL) { + ma_dr_wav_uninit(pWav); + return NULL; + } + framesRead = ma_dr_wav_read_pcm_frames_s16(pWav, (size_t)pWav->totalPCMFrameCount, pSampleData); + if (framesRead != pWav->totalPCMFrameCount) { + ma_dr_wav__free_from_callbacks(pSampleData, &pWav->allocationCallbacks); + ma_dr_wav_uninit(pWav); + return NULL; + } + ma_dr_wav_uninit(pWav); + if (sampleRate) { + *sampleRate = pWav->sampleRate; + } + if (channels) { + *channels = pWav->channels; + } + if (totalFrameCount) { + *totalFrameCount = pWav->totalPCMFrameCount; + } + return pSampleData; +} +MA_PRIVATE float* ma_dr_wav__read_pcm_frames_and_close_f32(ma_dr_wav* pWav, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalFrameCount) +{ + ma_uint64 sampleDataSize; + float* pSampleData; + ma_uint64 framesRead; + MA_DR_WAV_ASSERT(pWav != NULL); + sampleDataSize = pWav->totalPCMFrameCount * pWav->channels * sizeof(float); + if (sampleDataSize > MA_SIZE_MAX) { + ma_dr_wav_uninit(pWav); + return NULL; + } + pSampleData = (float*)ma_dr_wav__malloc_from_callbacks((size_t)sampleDataSize, &pWav->allocationCallbacks); + if (pSampleData == NULL) { + ma_dr_wav_uninit(pWav); + return NULL; + } + framesRead = ma_dr_wav_read_pcm_frames_f32(pWav, (size_t)pWav->totalPCMFrameCount, pSampleData); + if (framesRead != pWav->totalPCMFrameCount) { + ma_dr_wav__free_from_callbacks(pSampleData, &pWav->allocationCallbacks); + ma_dr_wav_uninit(pWav); + return NULL; + } + ma_dr_wav_uninit(pWav); + if (sampleRate) { + *sampleRate = pWav->sampleRate; + } + if (channels) { + *channels = pWav->channels; + } + if (totalFrameCount) { + *totalFrameCount = pWav->totalPCMFrameCount; + } + return pSampleData; +} +MA_PRIVATE ma_int32* ma_dr_wav__read_pcm_frames_and_close_s32(ma_dr_wav* pWav, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalFrameCount) +{ + ma_uint64 sampleDataSize; + ma_int32* pSampleData; + ma_uint64 framesRead; + MA_DR_WAV_ASSERT(pWav != NULL); + sampleDataSize = pWav->totalPCMFrameCount * pWav->channels * sizeof(ma_int32); + if (sampleDataSize > MA_SIZE_MAX) { + ma_dr_wav_uninit(pWav); + return NULL; + } + pSampleData = (ma_int32*)ma_dr_wav__malloc_from_callbacks((size_t)sampleDataSize, &pWav->allocationCallbacks); + if (pSampleData == NULL) { + ma_dr_wav_uninit(pWav); + return NULL; + } + framesRead = ma_dr_wav_read_pcm_frames_s32(pWav, (size_t)pWav->totalPCMFrameCount, pSampleData); + if (framesRead != pWav->totalPCMFrameCount) { + ma_dr_wav__free_from_callbacks(pSampleData, &pWav->allocationCallbacks); + ma_dr_wav_uninit(pWav); + return NULL; + } + ma_dr_wav_uninit(pWav); + if (sampleRate) { + *sampleRate = pWav->sampleRate; + } + if (channels) { + *channels = pWav->channels; + } + if (totalFrameCount) { + *totalFrameCount = pWav->totalPCMFrameCount; + } + return pSampleData; +} +MA_API ma_int16* ma_dr_wav_open_and_read_pcm_frames_s16(ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_wav wav; + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalFrameCountOut) { + *totalFrameCountOut = 0; + } + if (!ma_dr_wav_init(&wav, onRead, onSeek, pUserData, pAllocationCallbacks)) { + return NULL; + } + return ma_dr_wav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut); +} +MA_API float* ma_dr_wav_open_and_read_pcm_frames_f32(ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_wav wav; + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalFrameCountOut) { + *totalFrameCountOut = 0; + } + if (!ma_dr_wav_init(&wav, onRead, onSeek, pUserData, pAllocationCallbacks)) { + return NULL; + } + return ma_dr_wav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut); +} +MA_API ma_int32* ma_dr_wav_open_and_read_pcm_frames_s32(ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_wav wav; + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalFrameCountOut) { + *totalFrameCountOut = 0; + } + if (!ma_dr_wav_init(&wav, onRead, onSeek, pUserData, pAllocationCallbacks)) { + return NULL; + } + return ma_dr_wav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut); +} +#ifndef MA_DR_WAV_NO_STDIO +MA_API ma_int16* ma_dr_wav_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_wav wav; + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalFrameCountOut) { + *totalFrameCountOut = 0; + } + if (!ma_dr_wav_init_file(&wav, filename, pAllocationCallbacks)) { + return NULL; + } + return ma_dr_wav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut); +} +MA_API float* ma_dr_wav_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_wav wav; + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalFrameCountOut) { + *totalFrameCountOut = 0; + } + if (!ma_dr_wav_init_file(&wav, filename, pAllocationCallbacks)) { + return NULL; + } + return ma_dr_wav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut); +} +MA_API ma_int32* ma_dr_wav_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_wav wav; + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalFrameCountOut) { + *totalFrameCountOut = 0; + } + if (!ma_dr_wav_init_file(&wav, filename, pAllocationCallbacks)) { + return NULL; + } + return ma_dr_wav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut); +} +#ifndef MA_DR_WAV_NO_WCHAR +MA_API ma_int16* ma_dr_wav_open_file_and_read_pcm_frames_s16_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_wav wav; + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (channelsOut) { + *channelsOut = 0; + } + if (totalFrameCountOut) { + *totalFrameCountOut = 0; + } + if (!ma_dr_wav_init_file_w(&wav, filename, pAllocationCallbacks)) { + return NULL; + } + return ma_dr_wav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut); +} +MA_API float* ma_dr_wav_open_file_and_read_pcm_frames_f32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_wav wav; + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (channelsOut) { + *channelsOut = 0; + } + if (totalFrameCountOut) { + *totalFrameCountOut = 0; + } + if (!ma_dr_wav_init_file_w(&wav, filename, pAllocationCallbacks)) { + return NULL; + } + return ma_dr_wav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut); +} +MA_API ma_int32* ma_dr_wav_open_file_and_read_pcm_frames_s32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_wav wav; + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (channelsOut) { + *channelsOut = 0; + } + if (totalFrameCountOut) { + *totalFrameCountOut = 0; + } + if (!ma_dr_wav_init_file_w(&wav, filename, pAllocationCallbacks)) { + return NULL; + } + return ma_dr_wav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut); +} +#endif +#endif +MA_API ma_int16* ma_dr_wav_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_wav wav; + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalFrameCountOut) { + *totalFrameCountOut = 0; + } + if (!ma_dr_wav_init_memory(&wav, data, dataSize, pAllocationCallbacks)) { + return NULL; + } + return ma_dr_wav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut); +} +MA_API float* ma_dr_wav_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_wav wav; + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalFrameCountOut) { + *totalFrameCountOut = 0; + } + if (!ma_dr_wav_init_memory(&wav, data, dataSize, pAllocationCallbacks)) { + return NULL; + } + return ma_dr_wav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut); +} +MA_API ma_int32* ma_dr_wav_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_wav wav; + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalFrameCountOut) { + *totalFrameCountOut = 0; + } + if (!ma_dr_wav_init_memory(&wav, data, dataSize, pAllocationCallbacks)) { + return NULL; + } + return ma_dr_wav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut); +} +#endif +MA_API void ma_dr_wav_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pAllocationCallbacks != NULL) { + ma_dr_wav__free_from_callbacks(p, pAllocationCallbacks); + } else { + ma_dr_wav__free_default(p, NULL); + } +} +MA_API ma_uint16 ma_dr_wav_bytes_to_u16(const ma_uint8* data) +{ + return ((ma_uint16)data[0] << 0) | ((ma_uint16)data[1] << 8); +} +MA_API ma_int16 ma_dr_wav_bytes_to_s16(const ma_uint8* data) +{ + return (ma_int16)ma_dr_wav_bytes_to_u16(data); +} +MA_API ma_uint32 ma_dr_wav_bytes_to_u32(const ma_uint8* data) +{ + return ma_dr_wav_bytes_to_u32_le(data); +} +MA_API float ma_dr_wav_bytes_to_f32(const ma_uint8* data) +{ + union { + ma_uint32 u32; + float f32; + } value; + value.u32 = ma_dr_wav_bytes_to_u32(data); + return value.f32; +} +MA_API ma_int32 ma_dr_wav_bytes_to_s32(const ma_uint8* data) +{ + return (ma_int32)ma_dr_wav_bytes_to_u32(data); +} +MA_API ma_uint64 ma_dr_wav_bytes_to_u64(const ma_uint8* data) +{ + return + ((ma_uint64)data[0] << 0) | ((ma_uint64)data[1] << 8) | ((ma_uint64)data[2] << 16) | ((ma_uint64)data[3] << 24) | + ((ma_uint64)data[4] << 32) | ((ma_uint64)data[5] << 40) | ((ma_uint64)data[6] << 48) | ((ma_uint64)data[7] << 56); +} +MA_API ma_int64 ma_dr_wav_bytes_to_s64(const ma_uint8* data) +{ + return (ma_int64)ma_dr_wav_bytes_to_u64(data); +} +MA_API ma_bool32 ma_dr_wav_guid_equal(const ma_uint8 a[16], const ma_uint8 b[16]) +{ + int i; + for (i = 0; i < 16; i += 1) { + if (a[i] != b[i]) { + return MA_FALSE; + } + } + return MA_TRUE; +} +MA_API ma_bool32 ma_dr_wav_fourcc_equal(const ma_uint8* a, const char* b) +{ + return + a[0] == b[0] && + a[1] == b[1] && + a[2] == b[2] && + a[3] == b[3]; +} +#ifdef __MRC__ +#pragma options opt reset +#endif +#endif +/* dr_wav_c end */ +#endif /* MA_DR_WAV_IMPLEMENTATION */ +#endif /* MA_NO_WAV */ + +#if !defined(MA_NO_FLAC) && !defined(MA_NO_DECODING) +#if !defined(MA_DR_FLAC_IMPLEMENTATION) && !defined(MA_DR_FLAC_IMPLEMENTATION) /* For backwards compatibility. Will be removed in version 0.11 for cleanliness. */ +/* dr_flac_c begin */ +#ifndef ma_dr_flac_c +#define ma_dr_flac_c +#if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))) + #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 _DEFAULT_SOURCE + #define _DEFAULT_SOURCE + #endif + #ifndef __USE_BSD + #define __USE_BSD + #endif + #include +#endif +#include +#include +#if !defined(MA_DR_FLAC_NO_SIMD) + #if defined(MA_X64) || defined(MA_X86) + #if defined(_MSC_VER) && !defined(__clang__) + #if _MSC_VER >= 1400 && !defined(MA_DR_FLAC_NO_SSE2) + #define MA_DR_FLAC_SUPPORT_SSE2 + #endif + #if _MSC_VER >= 1600 && !defined(MA_DR_FLAC_NO_SSE41) + #define MA_DR_FLAC_SUPPORT_SSE41 + #endif + #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))) + #if defined(__SSE2__) && !defined(MA_DR_FLAC_NO_SSE2) + #define MA_DR_FLAC_SUPPORT_SSE2 + #endif + #if defined(__SSE4_1__) && !defined(MA_DR_FLAC_NO_SSE41) + #define MA_DR_FLAC_SUPPORT_SSE41 + #endif + #endif + #if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include) + #if !defined(MA_DR_FLAC_SUPPORT_SSE2) && !defined(MA_DR_FLAC_NO_SSE2) && __has_include() + #define MA_DR_FLAC_SUPPORT_SSE2 + #endif + #if !defined(MA_DR_FLAC_SUPPORT_SSE41) && !defined(MA_DR_FLAC_NO_SSE41) && __has_include() + #define MA_DR_FLAC_SUPPORT_SSE41 + #endif + #endif + #if defined(MA_DR_FLAC_SUPPORT_SSE41) + #include + #elif defined(MA_DR_FLAC_SUPPORT_SSE2) + #include + #endif + #endif + #if defined(MA_ARM) + #if !defined(MA_DR_FLAC_NO_NEON) && (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64)) + #define MA_DR_FLAC_SUPPORT_NEON + #include + #endif + #endif +#endif +#if !defined(MA_DR_FLAC_NO_SIMD) && (defined(MA_X86) || defined(MA_X64)) + #if defined(_MSC_VER) && !defined(__clang__) + #if _MSC_VER >= 1400 + #include + static void ma_dr_flac__cpuid(int info[4], int fid) + { + __cpuid(info, fid); + } + #else + #define MA_DR_FLAC_NO_CPUID + #endif + #else + #if defined(__GNUC__) || defined(__clang__) + static void ma_dr_flac__cpuid(int info[4], int fid) + { + #if defined(MA_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 MA_DR_FLAC_NO_CPUID + #endif + #endif +#else + #define MA_DR_FLAC_NO_CPUID +#endif +static MA_INLINE ma_bool32 ma_dr_flac_has_sse2(void) +{ +#if defined(MA_DR_FLAC_SUPPORT_SSE2) + #if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_DR_FLAC_NO_SSE2) + #if defined(MA_X64) + return MA_TRUE; + #elif (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__) + return MA_TRUE; + #else + #if defined(MA_DR_FLAC_NO_CPUID) + return MA_FALSE; + #else + int info[4]; + ma_dr_flac__cpuid(info, 1); + return (info[3] & (1 << 26)) != 0; + #endif + #endif + #else + return MA_FALSE; + #endif +#else + return MA_FALSE; +#endif +} +static MA_INLINE ma_bool32 ma_dr_flac_has_sse41(void) +{ +#if defined(MA_DR_FLAC_SUPPORT_SSE41) + #if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_DR_FLAC_NO_SSE41) + #if defined(__SSE4_1__) || defined(__AVX__) + return MA_TRUE; + #else + #if defined(MA_DR_FLAC_NO_CPUID) + return MA_FALSE; + #else + int info[4]; + ma_dr_flac__cpuid(info, 1); + return (info[2] & (1 << 19)) != 0; + #endif + #endif + #else + return MA_FALSE; + #endif +#else + return MA_FALSE; +#endif +} +#if defined(_MSC_VER) && _MSC_VER >= 1500 && (defined(MA_X86) || defined(MA_X64)) && !defined(__clang__) + #define MA_DR_FLAC_HAS_LZCNT_INTRINSIC +#elif (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7))) + #define MA_DR_FLAC_HAS_LZCNT_INTRINSIC +#elif defined(__clang__) + #if defined(__has_builtin) + #if __has_builtin(__builtin_clzll) || __has_builtin(__builtin_clzl) + #define MA_DR_FLAC_HAS_LZCNT_INTRINSIC + #endif + #endif +#endif +#if defined(_MSC_VER) && _MSC_VER >= 1400 && !defined(__clang__) + #define MA_DR_FLAC_HAS_BYTESWAP16_INTRINSIC + #define MA_DR_FLAC_HAS_BYTESWAP32_INTRINSIC + #define MA_DR_FLAC_HAS_BYTESWAP64_INTRINSIC +#elif defined(__clang__) + #if defined(__has_builtin) + #if __has_builtin(__builtin_bswap16) + #define MA_DR_FLAC_HAS_BYTESWAP16_INTRINSIC + #endif + #if __has_builtin(__builtin_bswap32) + #define MA_DR_FLAC_HAS_BYTESWAP32_INTRINSIC + #endif + #if __has_builtin(__builtin_bswap64) + #define MA_DR_FLAC_HAS_BYTESWAP64_INTRINSIC + #endif + #endif +#elif defined(__GNUC__) + #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) + #define MA_DR_FLAC_HAS_BYTESWAP32_INTRINSIC + #define MA_DR_FLAC_HAS_BYTESWAP64_INTRINSIC + #endif + #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)) + #define MA_DR_FLAC_HAS_BYTESWAP16_INTRINSIC + #endif +#elif defined(__WATCOMC__) && defined(__386__) + #define MA_DR_FLAC_HAS_BYTESWAP16_INTRINSIC + #define MA_DR_FLAC_HAS_BYTESWAP32_INTRINSIC + #define MA_DR_FLAC_HAS_BYTESWAP64_INTRINSIC + extern __inline ma_uint16 _watcom_bswap16(ma_uint16); + extern __inline ma_uint32 _watcom_bswap32(ma_uint32); + extern __inline ma_uint64 _watcom_bswap64(ma_uint64); +#pragma aux _watcom_bswap16 = \ + "xchg al, ah" \ + parm [ax] \ + value [ax] \ + modify nomemory; +#pragma aux _watcom_bswap32 = \ + "bswap eax" \ + parm [eax] \ + value [eax] \ + modify nomemory; +#pragma aux _watcom_bswap64 = \ + "bswap eax" \ + "bswap edx" \ + "xchg eax,edx" \ + parm [eax edx] \ + value [eax edx] \ + modify nomemory; +#endif +#ifndef MA_DR_FLAC_ASSERT +#include +#define MA_DR_FLAC_ASSERT(expression) assert(expression) +#endif +#ifndef MA_DR_FLAC_MALLOC +#define MA_DR_FLAC_MALLOC(sz) malloc((sz)) +#endif +#ifndef MA_DR_FLAC_REALLOC +#define MA_DR_FLAC_REALLOC(p, sz) realloc((p), (sz)) +#endif +#ifndef MA_DR_FLAC_FREE +#define MA_DR_FLAC_FREE(p) free((p)) +#endif +#ifndef MA_DR_FLAC_COPY_MEMORY +#define MA_DR_FLAC_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz)) +#endif +#ifndef MA_DR_FLAC_ZERO_MEMORY +#define MA_DR_FLAC_ZERO_MEMORY(p, sz) memset((p), 0, (sz)) +#endif +#ifndef MA_DR_FLAC_ZERO_OBJECT +#define MA_DR_FLAC_ZERO_OBJECT(p) MA_DR_FLAC_ZERO_MEMORY((p), sizeof(*(p))) +#endif +#define MA_DR_FLAC_MAX_SIMD_VECTOR_SIZE 64 +#define MA_DR_FLAC_SUBFRAME_CONSTANT 0 +#define MA_DR_FLAC_SUBFRAME_VERBATIM 1 +#define MA_DR_FLAC_SUBFRAME_FIXED 8 +#define MA_DR_FLAC_SUBFRAME_LPC 32 +#define MA_DR_FLAC_SUBFRAME_RESERVED 255 +#define MA_DR_FLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE 0 +#define MA_DR_FLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2 1 +#define MA_DR_FLAC_CHANNEL_ASSIGNMENT_INDEPENDENT 0 +#define MA_DR_FLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE 8 +#define MA_DR_FLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE 9 +#define MA_DR_FLAC_CHANNEL_ASSIGNMENT_MID_SIDE 10 +#define MA_DR_FLAC_SEEKPOINT_SIZE_IN_BYTES 18 +#define MA_DR_FLAC_CUESHEET_TRACK_SIZE_IN_BYTES 36 +#define MA_DR_FLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES 12 +#define ma_dr_flac_align(x, a) ((((x) + (a) - 1) / (a)) * (a)) +MA_API void ma_dr_flac_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision) +{ + if (pMajor) { + *pMajor = MA_DR_FLAC_VERSION_MAJOR; + } + if (pMinor) { + *pMinor = MA_DR_FLAC_VERSION_MINOR; + } + if (pRevision) { + *pRevision = MA_DR_FLAC_VERSION_REVISION; + } +} +MA_API const char* ma_dr_flac_version_string(void) +{ + return MA_DR_FLAC_VERSION_STRING; +} +#if defined(__has_feature) + #if __has_feature(thread_sanitizer) + #define MA_DR_FLAC_NO_THREAD_SANITIZE __attribute__((no_sanitize("thread"))) + #else + #define MA_DR_FLAC_NO_THREAD_SANITIZE + #endif +#else + #define MA_DR_FLAC_NO_THREAD_SANITIZE +#endif +#if defined(MA_DR_FLAC_HAS_LZCNT_INTRINSIC) +static ma_bool32 ma_dr_flac__gIsLZCNTSupported = MA_FALSE; +#endif +#ifndef MA_DR_FLAC_NO_CPUID +static ma_bool32 ma_dr_flac__gIsSSE2Supported = MA_FALSE; +static ma_bool32 ma_dr_flac__gIsSSE41Supported = MA_FALSE; +MA_DR_FLAC_NO_THREAD_SANITIZE static void ma_dr_flac__init_cpu_caps(void) +{ + static ma_bool32 isCPUCapsInitialized = MA_FALSE; + if (!isCPUCapsInitialized) { +#if defined(MA_DR_FLAC_HAS_LZCNT_INTRINSIC) + int info[4] = {0}; + ma_dr_flac__cpuid(info, 0x80000001); + ma_dr_flac__gIsLZCNTSupported = (info[2] & (1 << 5)) != 0; +#endif + ma_dr_flac__gIsSSE2Supported = ma_dr_flac_has_sse2(); + ma_dr_flac__gIsSSE41Supported = ma_dr_flac_has_sse41(); + isCPUCapsInitialized = MA_TRUE; + } +} +#else +static ma_bool32 ma_dr_flac__gIsNEONSupported = MA_FALSE; +static MA_INLINE ma_bool32 ma_dr_flac__has_neon(void) +{ +#if defined(MA_DR_FLAC_SUPPORT_NEON) + #if defined(MA_ARM) && !defined(MA_DR_FLAC_NO_NEON) + #if (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64)) + return MA_TRUE; + #else + return MA_FALSE; + #endif + #else + return MA_FALSE; + #endif +#else + return MA_FALSE; +#endif +} +MA_DR_FLAC_NO_THREAD_SANITIZE static void ma_dr_flac__init_cpu_caps(void) +{ + ma_dr_flac__gIsNEONSupported = ma_dr_flac__has_neon(); +#if defined(MA_DR_FLAC_HAS_LZCNT_INTRINSIC) && defined(MA_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5) + ma_dr_flac__gIsLZCNTSupported = MA_TRUE; +#endif +} +#endif +static MA_INLINE ma_bool32 ma_dr_flac__is_little_endian(void) +{ +#if defined(MA_X86) || defined(MA_X64) + return MA_TRUE; +#elif defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN + return MA_TRUE; +#else + int n = 1; + return (*(char*)&n) == 1; +#endif +} +static MA_INLINE ma_uint16 ma_dr_flac__swap_endian_uint16(ma_uint16 n) +{ +#ifdef MA_DR_FLAC_HAS_BYTESWAP16_INTRINSIC + #if defined(_MSC_VER) && !defined(__clang__) + return _byteswap_ushort(n); + #elif defined(__GNUC__) || defined(__clang__) + return __builtin_bswap16(n); + #elif defined(__WATCOMC__) && defined(__386__) + return _watcom_bswap16(n); + #else + #error "This compiler does not support the byte swap intrinsic." + #endif +#else + return ((n & 0xFF00) >> 8) | + ((n & 0x00FF) << 8); +#endif +} +static MA_INLINE ma_uint32 ma_dr_flac__swap_endian_uint32(ma_uint32 n) +{ +#ifdef MA_DR_FLAC_HAS_BYTESWAP32_INTRINSIC + #if defined(_MSC_VER) && !defined(__clang__) + return _byteswap_ulong(n); + #elif defined(__GNUC__) || defined(__clang__) + #if defined(MA_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 6) && !defined(__ARM_ARCH_6M__) && !defined(MA_64BIT) + ma_uint32 r; + __asm__ __volatile__ ( + #if defined(MA_64BIT) + "rev %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(n) + #else + "rev %[out], %[in]" : [out]"=r"(r) : [in]"r"(n) + #endif + ); + return r; + #else + return __builtin_bswap32(n); + #endif + #elif defined(__WATCOMC__) && defined(__386__) + return _watcom_bswap32(n); + #else + #error "This compiler does not support the byte swap intrinsic." + #endif +#else + return ((n & 0xFF000000) >> 24) | + ((n & 0x00FF0000) >> 8) | + ((n & 0x0000FF00) << 8) | + ((n & 0x000000FF) << 24); +#endif +} +static MA_INLINE ma_uint64 ma_dr_flac__swap_endian_uint64(ma_uint64 n) +{ +#ifdef MA_DR_FLAC_HAS_BYTESWAP64_INTRINSIC + #if defined(_MSC_VER) && !defined(__clang__) + return _byteswap_uint64(n); + #elif defined(__GNUC__) || defined(__clang__) + return __builtin_bswap64(n); + #elif defined(__WATCOMC__) && defined(__386__) + return _watcom_bswap64(n); + #else + #error "This compiler does not support the byte swap intrinsic." + #endif +#else + return ((n & ((ma_uint64)0xFF000000 << 32)) >> 56) | + ((n & ((ma_uint64)0x00FF0000 << 32)) >> 40) | + ((n & ((ma_uint64)0x0000FF00 << 32)) >> 24) | + ((n & ((ma_uint64)0x000000FF << 32)) >> 8) | + ((n & ((ma_uint64)0xFF000000 )) << 8) | + ((n & ((ma_uint64)0x00FF0000 )) << 24) | + ((n & ((ma_uint64)0x0000FF00 )) << 40) | + ((n & ((ma_uint64)0x000000FF )) << 56); +#endif +} +static MA_INLINE ma_uint16 ma_dr_flac__be2host_16(ma_uint16 n) +{ + if (ma_dr_flac__is_little_endian()) { + return ma_dr_flac__swap_endian_uint16(n); + } + return n; +} +static MA_INLINE ma_uint32 ma_dr_flac__be2host_32(ma_uint32 n) +{ + if (ma_dr_flac__is_little_endian()) { + return ma_dr_flac__swap_endian_uint32(n); + } + return n; +} +static MA_INLINE ma_uint32 ma_dr_flac__be2host_32_ptr_unaligned(const void* pData) +{ + const ma_uint8* pNum = (ma_uint8*)pData; + return *(pNum) << 24 | *(pNum+1) << 16 | *(pNum+2) << 8 | *(pNum+3); +} +static MA_INLINE ma_uint64 ma_dr_flac__be2host_64(ma_uint64 n) +{ + if (ma_dr_flac__is_little_endian()) { + return ma_dr_flac__swap_endian_uint64(n); + } + return n; +} +static MA_INLINE ma_uint32 ma_dr_flac__le2host_32(ma_uint32 n) +{ + if (!ma_dr_flac__is_little_endian()) { + return ma_dr_flac__swap_endian_uint32(n); + } + return n; +} +static MA_INLINE ma_uint32 ma_dr_flac__le2host_32_ptr_unaligned(const void* pData) +{ + const ma_uint8* pNum = (ma_uint8*)pData; + return *pNum | *(pNum+1) << 8 | *(pNum+2) << 16 | *(pNum+3) << 24; +} +static MA_INLINE ma_uint32 ma_dr_flac__unsynchsafe_32(ma_uint32 n) +{ + ma_uint32 result = 0; + result |= (n & 0x7F000000) >> 3; + result |= (n & 0x007F0000) >> 2; + result |= (n & 0x00007F00) >> 1; + result |= (n & 0x0000007F) >> 0; + return result; +} +static ma_uint8 ma_dr_flac__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, + 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5, 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD, + 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85, 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD, + 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2, 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA, + 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2, 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A, + 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32, 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A, + 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42, 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A, + 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C, 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4, + 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC, 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4, + 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C, 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44, + 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C, 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34, + 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B, 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63, + 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B, 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13, + 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB, 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83, + 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB, 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3 +}; +static ma_uint16 ma_dr_flac__crc16_table[] = { + 0x0000, 0x8005, 0x800F, 0x000A, 0x801B, 0x001E, 0x0014, 0x8011, + 0x8033, 0x0036, 0x003C, 0x8039, 0x0028, 0x802D, 0x8027, 0x0022, + 0x8063, 0x0066, 0x006C, 0x8069, 0x0078, 0x807D, 0x8077, 0x0072, + 0x0050, 0x8055, 0x805F, 0x005A, 0x804B, 0x004E, 0x0044, 0x8041, + 0x80C3, 0x00C6, 0x00CC, 0x80C9, 0x00D8, 0x80DD, 0x80D7, 0x00D2, + 0x00F0, 0x80F5, 0x80FF, 0x00FA, 0x80EB, 0x00EE, 0x00E4, 0x80E1, + 0x00A0, 0x80A5, 0x80AF, 0x00AA, 0x80BB, 0x00BE, 0x00B4, 0x80B1, + 0x8093, 0x0096, 0x009C, 0x8099, 0x0088, 0x808D, 0x8087, 0x0082, + 0x8183, 0x0186, 0x018C, 0x8189, 0x0198, 0x819D, 0x8197, 0x0192, + 0x01B0, 0x81B5, 0x81BF, 0x01BA, 0x81AB, 0x01AE, 0x01A4, 0x81A1, + 0x01E0, 0x81E5, 0x81EF, 0x01EA, 0x81FB, 0x01FE, 0x01F4, 0x81F1, + 0x81D3, 0x01D6, 0x01DC, 0x81D9, 0x01C8, 0x81CD, 0x81C7, 0x01C2, + 0x0140, 0x8145, 0x814F, 0x014A, 0x815B, 0x015E, 0x0154, 0x8151, + 0x8173, 0x0176, 0x017C, 0x8179, 0x0168, 0x816D, 0x8167, 0x0162, + 0x8123, 0x0126, 0x012C, 0x8129, 0x0138, 0x813D, 0x8137, 0x0132, + 0x0110, 0x8115, 0x811F, 0x011A, 0x810B, 0x010E, 0x0104, 0x8101, + 0x8303, 0x0306, 0x030C, 0x8309, 0x0318, 0x831D, 0x8317, 0x0312, + 0x0330, 0x8335, 0x833F, 0x033A, 0x832B, 0x032E, 0x0324, 0x8321, + 0x0360, 0x8365, 0x836F, 0x036A, 0x837B, 0x037E, 0x0374, 0x8371, + 0x8353, 0x0356, 0x035C, 0x8359, 0x0348, 0x834D, 0x8347, 0x0342, + 0x03C0, 0x83C5, 0x83CF, 0x03CA, 0x83DB, 0x03DE, 0x03D4, 0x83D1, + 0x83F3, 0x03F6, 0x03FC, 0x83F9, 0x03E8, 0x83ED, 0x83E7, 0x03E2, + 0x83A3, 0x03A6, 0x03AC, 0x83A9, 0x03B8, 0x83BD, 0x83B7, 0x03B2, + 0x0390, 0x8395, 0x839F, 0x039A, 0x838B, 0x038E, 0x0384, 0x8381, + 0x0280, 0x8285, 0x828F, 0x028A, 0x829B, 0x029E, 0x0294, 0x8291, + 0x82B3, 0x02B6, 0x02BC, 0x82B9, 0x02A8, 0x82AD, 0x82A7, 0x02A2, + 0x82E3, 0x02E6, 0x02EC, 0x82E9, 0x02F8, 0x82FD, 0x82F7, 0x02F2, + 0x02D0, 0x82D5, 0x82DF, 0x02DA, 0x82CB, 0x02CE, 0x02C4, 0x82C1, + 0x8243, 0x0246, 0x024C, 0x8249, 0x0258, 0x825D, 0x8257, 0x0252, + 0x0270, 0x8275, 0x827F, 0x027A, 0x826B, 0x026E, 0x0264, 0x8261, + 0x0220, 0x8225, 0x822F, 0x022A, 0x823B, 0x023E, 0x0234, 0x8231, + 0x8213, 0x0216, 0x021C, 0x8219, 0x0208, 0x820D, 0x8207, 0x0202 +}; +static MA_INLINE ma_uint8 ma_dr_flac_crc8_byte(ma_uint8 crc, ma_uint8 data) +{ + return ma_dr_flac__crc8_table[crc ^ data]; +} +static MA_INLINE ma_uint8 ma_dr_flac_crc8(ma_uint8 crc, ma_uint32 data, ma_uint32 count) +{ +#ifdef MA_DR_FLAC_NO_CRC + (void)crc; + (void)data; + (void)count; + return 0; +#else +#if 0 + ma_uint8 p = 0x07; + for (int i = count-1; i >= 0; --i) { + ma_uint8 bit = (data & (1 << i)) >> i; + if (crc & 0x80) { + crc = ((crc << 1) | bit) ^ p; + } else { + crc = ((crc << 1) | bit); + } + } + return crc; +#else + ma_uint32 wholeBytes; + ma_uint32 leftoverBits; + ma_uint64 leftoverDataMask; + static ma_uint64 leftoverDataMaskTable[8] = { + 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F + }; + MA_DR_FLAC_ASSERT(count <= 32); + wholeBytes = count >> 3; + leftoverBits = count - (wholeBytes*8); + leftoverDataMask = leftoverDataMaskTable[leftoverBits]; + switch (wholeBytes) { + case 4: crc = ma_dr_flac_crc8_byte(crc, (ma_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits))); + case 3: crc = ma_dr_flac_crc8_byte(crc, (ma_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits))); + case 2: crc = ma_dr_flac_crc8_byte(crc, (ma_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits))); + case 1: crc = ma_dr_flac_crc8_byte(crc, (ma_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits))); + case 0: if (leftoverBits > 0) crc = (ma_uint8)((crc << leftoverBits) ^ ma_dr_flac__crc8_table[(crc >> (8 - leftoverBits)) ^ (data & leftoverDataMask)]); + } + return crc; +#endif +#endif +} +static MA_INLINE ma_uint16 ma_dr_flac_crc16_byte(ma_uint16 crc, ma_uint8 data) +{ + return (crc << 8) ^ ma_dr_flac__crc16_table[(ma_uint8)(crc >> 8) ^ data]; +} +static MA_INLINE ma_uint16 ma_dr_flac_crc16_cache(ma_uint16 crc, ma_dr_flac_cache_t data) +{ +#ifdef MA_64BIT + crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 56) & 0xFF)); + crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 48) & 0xFF)); + crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 40) & 0xFF)); + crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 32) & 0xFF)); +#endif + crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 24) & 0xFF)); + crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 16) & 0xFF)); + crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 8) & 0xFF)); + crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 0) & 0xFF)); + return crc; +} +static MA_INLINE ma_uint16 ma_dr_flac_crc16_bytes(ma_uint16 crc, ma_dr_flac_cache_t data, ma_uint32 byteCount) +{ + switch (byteCount) + { +#ifdef MA_64BIT + case 8: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 56) & 0xFF)); + case 7: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 48) & 0xFF)); + case 6: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 40) & 0xFF)); + case 5: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 32) & 0xFF)); +#endif + case 4: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 24) & 0xFF)); + case 3: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 16) & 0xFF)); + case 2: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 8) & 0xFF)); + case 1: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 0) & 0xFF)); + } + return crc; +} +#if 0 +static MA_INLINE ma_uint16 ma_dr_flac_crc16__32bit(ma_uint16 crc, ma_uint32 data, ma_uint32 count) +{ +#ifdef MA_DR_FLAC_NO_CRC + (void)crc; + (void)data; + (void)count; + return 0; +#else +#if 0 + ma_uint16 p = 0x8005; + for (int i = count-1; i >= 0; --i) { + ma_uint16 bit = (data & (1ULL << i)) >> i; + if (r & 0x8000) { + r = ((r << 1) | bit) ^ p; + } else { + r = ((r << 1) | bit); + } + } + return crc; +#else + ma_uint32 wholeBytes; + ma_uint32 leftoverBits; + ma_uint64 leftoverDataMask; + static ma_uint64 leftoverDataMaskTable[8] = { + 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F + }; + MA_DR_FLAC_ASSERT(count <= 64); + wholeBytes = count >> 3; + leftoverBits = count & 7; + leftoverDataMask = leftoverDataMaskTable[leftoverBits]; + switch (wholeBytes) { + default: + case 4: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits))); + case 3: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits))); + case 2: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits))); + case 1: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits))); + case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ ma_dr_flac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)]; + } + return crc; +#endif +#endif +} +static MA_INLINE ma_uint16 ma_dr_flac_crc16__64bit(ma_uint16 crc, ma_uint64 data, ma_uint32 count) +{ +#ifdef MA_DR_FLAC_NO_CRC + (void)crc; + (void)data; + (void)count; + return 0; +#else + ma_uint32 wholeBytes; + ma_uint32 leftoverBits; + ma_uint64 leftoverDataMask; + static ma_uint64 leftoverDataMaskTable[8] = { + 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F + }; + MA_DR_FLAC_ASSERT(count <= 64); + wholeBytes = count >> 3; + leftoverBits = count & 7; + leftoverDataMask = leftoverDataMaskTable[leftoverBits]; + switch (wholeBytes) { + default: + case 8: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (((ma_uint64)0xFF000000 << 32) << leftoverBits)) >> (56 + leftoverBits))); + case 7: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (((ma_uint64)0x00FF0000 << 32) << leftoverBits)) >> (48 + leftoverBits))); + case 6: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (((ma_uint64)0x0000FF00 << 32) << leftoverBits)) >> (40 + leftoverBits))); + case 5: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (((ma_uint64)0x000000FF << 32) << leftoverBits)) >> (32 + leftoverBits))); + case 4: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (((ma_uint64)0xFF000000 ) << leftoverBits)) >> (24 + leftoverBits))); + case 3: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (((ma_uint64)0x00FF0000 ) << leftoverBits)) >> (16 + leftoverBits))); + case 2: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (((ma_uint64)0x0000FF00 ) << leftoverBits)) >> ( 8 + leftoverBits))); + case 1: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (((ma_uint64)0x000000FF ) << leftoverBits)) >> ( 0 + leftoverBits))); + case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ ma_dr_flac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)]; + } + return crc; +#endif +} +static MA_INLINE ma_uint16 ma_dr_flac_crc16(ma_uint16 crc, ma_dr_flac_cache_t data, ma_uint32 count) +{ +#ifdef MA_64BIT + return ma_dr_flac_crc16__64bit(crc, data, count); +#else + return ma_dr_flac_crc16__32bit(crc, data, count); +#endif +} +#endif +#ifdef MA_64BIT +#define ma_dr_flac__be2host__cache_line ma_dr_flac__be2host_64 +#else +#define ma_dr_flac__be2host__cache_line ma_dr_flac__be2host_32 +#endif +#define MA_DR_FLAC_CACHE_L1_SIZE_BYTES(bs) (sizeof((bs)->cache)) +#define MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs) (sizeof((bs)->cache)*8) +#define MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs) (MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs) - (bs)->consumedBits) +#define MA_DR_FLAC_CACHE_L1_SELECTION_MASK(_bitCount) (~((~(ma_dr_flac_cache_t)0) >> (_bitCount))) +#define MA_DR_FLAC_CACHE_L1_SELECTION_SHIFT(bs, _bitCount) (MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs) - (_bitCount)) +#define MA_DR_FLAC_CACHE_L1_SELECT(bs, _bitCount) (((bs)->cache) & MA_DR_FLAC_CACHE_L1_SELECTION_MASK(_bitCount)) +#define MA_DR_FLAC_CACHE_L1_SELECT_AND_SHIFT(bs, _bitCount) (MA_DR_FLAC_CACHE_L1_SELECT((bs), (_bitCount)) >> MA_DR_FLAC_CACHE_L1_SELECTION_SHIFT((bs), (_bitCount))) +#define MA_DR_FLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, _bitCount)(MA_DR_FLAC_CACHE_L1_SELECT((bs), (_bitCount)) >> (MA_DR_FLAC_CACHE_L1_SELECTION_SHIFT((bs), (_bitCount)) & (MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs)-1))) +#define MA_DR_FLAC_CACHE_L2_SIZE_BYTES(bs) (sizeof((bs)->cacheL2)) +#define MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs) (MA_DR_FLAC_CACHE_L2_SIZE_BYTES(bs) / sizeof((bs)->cacheL2[0])) +#define MA_DR_FLAC_CACHE_L2_LINES_REMAINING(bs) (MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs) - (bs)->nextL2Line) +#ifndef MA_DR_FLAC_NO_CRC +static MA_INLINE void ma_dr_flac__reset_crc16(ma_dr_flac_bs* bs) +{ + bs->crc16 = 0; + bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3; +} +static MA_INLINE void ma_dr_flac__update_crc16(ma_dr_flac_bs* bs) +{ + if (bs->crc16CacheIgnoredBytes == 0) { + bs->crc16 = ma_dr_flac_crc16_cache(bs->crc16, bs->crc16Cache); + } else { + bs->crc16 = ma_dr_flac_crc16_bytes(bs->crc16, bs->crc16Cache, MA_DR_FLAC_CACHE_L1_SIZE_BYTES(bs) - bs->crc16CacheIgnoredBytes); + bs->crc16CacheIgnoredBytes = 0; + } +} +static MA_INLINE ma_uint16 ma_dr_flac__flush_crc16(ma_dr_flac_bs* bs) +{ + MA_DR_FLAC_ASSERT((MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs) & 7) == 0); + if (MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs) == 0) { + ma_dr_flac__update_crc16(bs); + } else { + bs->crc16 = ma_dr_flac_crc16_bytes(bs->crc16, bs->crc16Cache >> MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs), (bs->consumedBits >> 3) - bs->crc16CacheIgnoredBytes); + bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3; + } + return bs->crc16; +} +#endif +static MA_INLINE ma_bool32 ma_dr_flac__reload_l1_cache_from_l2(ma_dr_flac_bs* bs) +{ + size_t bytesRead; + size_t alignedL1LineCount; + if (bs->nextL2Line < MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs)) { + bs->cache = bs->cacheL2[bs->nextL2Line++]; + return MA_TRUE; + } + if (bs->unalignedByteCount > 0) { + return MA_FALSE; + } + bytesRead = bs->onRead(bs->pUserData, bs->cacheL2, MA_DR_FLAC_CACHE_L2_SIZE_BYTES(bs)); + bs->nextL2Line = 0; + if (bytesRead == MA_DR_FLAC_CACHE_L2_SIZE_BYTES(bs)) { + bs->cache = bs->cacheL2[bs->nextL2Line++]; + return MA_TRUE; + } + alignedL1LineCount = bytesRead / MA_DR_FLAC_CACHE_L1_SIZE_BYTES(bs); + bs->unalignedByteCount = bytesRead - (alignedL1LineCount * MA_DR_FLAC_CACHE_L1_SIZE_BYTES(bs)); + if (bs->unalignedByteCount > 0) { + bs->unalignedCache = bs->cacheL2[alignedL1LineCount]; + } + if (alignedL1LineCount > 0) { + size_t offset = MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs) - alignedL1LineCount; + size_t i; + for (i = alignedL1LineCount; i > 0; --i) { + bs->cacheL2[i-1 + offset] = bs->cacheL2[i-1]; + } + bs->nextL2Line = (ma_uint32)offset; + bs->cache = bs->cacheL2[bs->nextL2Line++]; + return MA_TRUE; + } else { + bs->nextL2Line = MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs); + return MA_FALSE; + } +} +static ma_bool32 ma_dr_flac__reload_cache(ma_dr_flac_bs* bs) +{ + size_t bytesRead; +#ifndef MA_DR_FLAC_NO_CRC + ma_dr_flac__update_crc16(bs); +#endif + if (ma_dr_flac__reload_l1_cache_from_l2(bs)) { + bs->cache = ma_dr_flac__be2host__cache_line(bs->cache); + bs->consumedBits = 0; +#ifndef MA_DR_FLAC_NO_CRC + bs->crc16Cache = bs->cache; +#endif + return MA_TRUE; + } + bytesRead = bs->unalignedByteCount; + if (bytesRead == 0) { + bs->consumedBits = MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs); + return MA_FALSE; + } + MA_DR_FLAC_ASSERT(bytesRead < MA_DR_FLAC_CACHE_L1_SIZE_BYTES(bs)); + bs->consumedBits = (ma_uint32)(MA_DR_FLAC_CACHE_L1_SIZE_BYTES(bs) - bytesRead) * 8; + bs->cache = ma_dr_flac__be2host__cache_line(bs->unalignedCache); + bs->cache &= MA_DR_FLAC_CACHE_L1_SELECTION_MASK(MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs)); + bs->unalignedByteCount = 0; +#ifndef MA_DR_FLAC_NO_CRC + bs->crc16Cache = bs->cache >> bs->consumedBits; + bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3; +#endif + return MA_TRUE; +} +static void ma_dr_flac__reset_cache(ma_dr_flac_bs* bs) +{ + bs->nextL2Line = MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs); + bs->consumedBits = MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs); + bs->cache = 0; + bs->unalignedByteCount = 0; + bs->unalignedCache = 0; +#ifndef MA_DR_FLAC_NO_CRC + bs->crc16Cache = 0; + bs->crc16CacheIgnoredBytes = 0; +#endif +} +static MA_INLINE ma_bool32 ma_dr_flac__read_uint32(ma_dr_flac_bs* bs, unsigned int bitCount, ma_uint32* pResultOut) +{ + MA_DR_FLAC_ASSERT(bs != NULL); + MA_DR_FLAC_ASSERT(pResultOut != NULL); + MA_DR_FLAC_ASSERT(bitCount > 0); + MA_DR_FLAC_ASSERT(bitCount <= 32); + if (bs->consumedBits == MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs)) { + if (!ma_dr_flac__reload_cache(bs)) { + return MA_FALSE; + } + } + if (bitCount <= MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs)) { +#ifdef MA_64BIT + *pResultOut = (ma_uint32)MA_DR_FLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount); + bs->consumedBits += bitCount; + bs->cache <<= bitCount; +#else + if (bitCount < MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs)) { + *pResultOut = (ma_uint32)MA_DR_FLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount); + bs->consumedBits += bitCount; + bs->cache <<= bitCount; + } else { + *pResultOut = (ma_uint32)bs->cache; + bs->consumedBits = MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs); + bs->cache = 0; + } +#endif + return MA_TRUE; + } else { + ma_uint32 bitCountHi = MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs); + ma_uint32 bitCountLo = bitCount - bitCountHi; + ma_uint32 resultHi; + MA_DR_FLAC_ASSERT(bitCountHi > 0); + MA_DR_FLAC_ASSERT(bitCountHi < 32); + resultHi = (ma_uint32)MA_DR_FLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountHi); + if (!ma_dr_flac__reload_cache(bs)) { + return MA_FALSE; + } + if (bitCountLo > MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs)) { + return MA_FALSE; + } + *pResultOut = (resultHi << bitCountLo) | (ma_uint32)MA_DR_FLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountLo); + bs->consumedBits += bitCountLo; + bs->cache <<= bitCountLo; + return MA_TRUE; + } +} +static ma_bool32 ma_dr_flac__read_int32(ma_dr_flac_bs* bs, unsigned int bitCount, ma_int32* pResult) +{ + ma_uint32 result; + MA_DR_FLAC_ASSERT(bs != NULL); + MA_DR_FLAC_ASSERT(pResult != NULL); + MA_DR_FLAC_ASSERT(bitCount > 0); + MA_DR_FLAC_ASSERT(bitCount <= 32); + if (!ma_dr_flac__read_uint32(bs, bitCount, &result)) { + return MA_FALSE; + } + if (bitCount < 32) { + ma_uint32 signbit; + signbit = ((result >> (bitCount-1)) & 0x01); + result |= (~signbit + 1) << bitCount; + } + *pResult = (ma_int32)result; + return MA_TRUE; +} +#ifdef MA_64BIT +static ma_bool32 ma_dr_flac__read_uint64(ma_dr_flac_bs* bs, unsigned int bitCount, ma_uint64* pResultOut) +{ + ma_uint32 resultHi; + ma_uint32 resultLo; + MA_DR_FLAC_ASSERT(bitCount <= 64); + MA_DR_FLAC_ASSERT(bitCount > 32); + if (!ma_dr_flac__read_uint32(bs, bitCount - 32, &resultHi)) { + return MA_FALSE; + } + if (!ma_dr_flac__read_uint32(bs, 32, &resultLo)) { + return MA_FALSE; + } + *pResultOut = (((ma_uint64)resultHi) << 32) | ((ma_uint64)resultLo); + return MA_TRUE; +} +#endif +#if 0 +static ma_bool32 ma_dr_flac__read_int64(ma_dr_flac_bs* bs, unsigned int bitCount, ma_int64* pResultOut) +{ + ma_uint64 result; + ma_uint64 signbit; + MA_DR_FLAC_ASSERT(bitCount <= 64); + if (!ma_dr_flac__read_uint64(bs, bitCount, &result)) { + return MA_FALSE; + } + signbit = ((result >> (bitCount-1)) & 0x01); + result |= (~signbit + 1) << bitCount; + *pResultOut = (ma_int64)result; + return MA_TRUE; +} +#endif +static ma_bool32 ma_dr_flac__read_uint16(ma_dr_flac_bs* bs, unsigned int bitCount, ma_uint16* pResult) +{ + ma_uint32 result; + MA_DR_FLAC_ASSERT(bs != NULL); + MA_DR_FLAC_ASSERT(pResult != NULL); + MA_DR_FLAC_ASSERT(bitCount > 0); + MA_DR_FLAC_ASSERT(bitCount <= 16); + if (!ma_dr_flac__read_uint32(bs, bitCount, &result)) { + return MA_FALSE; + } + *pResult = (ma_uint16)result; + return MA_TRUE; +} +#if 0 +static ma_bool32 ma_dr_flac__read_int16(ma_dr_flac_bs* bs, unsigned int bitCount, ma_int16* pResult) +{ + ma_int32 result; + MA_DR_FLAC_ASSERT(bs != NULL); + MA_DR_FLAC_ASSERT(pResult != NULL); + MA_DR_FLAC_ASSERT(bitCount > 0); + MA_DR_FLAC_ASSERT(bitCount <= 16); + if (!ma_dr_flac__read_int32(bs, bitCount, &result)) { + return MA_FALSE; + } + *pResult = (ma_int16)result; + return MA_TRUE; +} +#endif +static ma_bool32 ma_dr_flac__read_uint8(ma_dr_flac_bs* bs, unsigned int bitCount, ma_uint8* pResult) +{ + ma_uint32 result; + MA_DR_FLAC_ASSERT(bs != NULL); + MA_DR_FLAC_ASSERT(pResult != NULL); + MA_DR_FLAC_ASSERT(bitCount > 0); + MA_DR_FLAC_ASSERT(bitCount <= 8); + if (!ma_dr_flac__read_uint32(bs, bitCount, &result)) { + return MA_FALSE; + } + *pResult = (ma_uint8)result; + return MA_TRUE; +} +static ma_bool32 ma_dr_flac__read_int8(ma_dr_flac_bs* bs, unsigned int bitCount, ma_int8* pResult) +{ + ma_int32 result; + MA_DR_FLAC_ASSERT(bs != NULL); + MA_DR_FLAC_ASSERT(pResult != NULL); + MA_DR_FLAC_ASSERT(bitCount > 0); + MA_DR_FLAC_ASSERT(bitCount <= 8); + if (!ma_dr_flac__read_int32(bs, bitCount, &result)) { + return MA_FALSE; + } + *pResult = (ma_int8)result; + return MA_TRUE; +} +static ma_bool32 ma_dr_flac__seek_bits(ma_dr_flac_bs* bs, size_t bitsToSeek) +{ + if (bitsToSeek <= MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs)) { + bs->consumedBits += (ma_uint32)bitsToSeek; + bs->cache <<= bitsToSeek; + return MA_TRUE; + } else { + bitsToSeek -= MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs); + bs->consumedBits += MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs); + bs->cache = 0; +#ifdef MA_64BIT + while (bitsToSeek >= MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs)) { + ma_uint64 bin; + if (!ma_dr_flac__read_uint64(bs, MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs), &bin)) { + return MA_FALSE; + } + bitsToSeek -= MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs); + } +#else + while (bitsToSeek >= MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs)) { + ma_uint32 bin; + if (!ma_dr_flac__read_uint32(bs, MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs), &bin)) { + return MA_FALSE; + } + bitsToSeek -= MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs); + } +#endif + while (bitsToSeek >= 8) { + ma_uint8 bin; + if (!ma_dr_flac__read_uint8(bs, 8, &bin)) { + return MA_FALSE; + } + bitsToSeek -= 8; + } + if (bitsToSeek > 0) { + ma_uint8 bin; + if (!ma_dr_flac__read_uint8(bs, (ma_uint32)bitsToSeek, &bin)) { + return MA_FALSE; + } + bitsToSeek = 0; + } + MA_DR_FLAC_ASSERT(bitsToSeek == 0); + return MA_TRUE; + } +} +static ma_bool32 ma_dr_flac__find_and_seek_to_next_sync_code(ma_dr_flac_bs* bs) +{ + MA_DR_FLAC_ASSERT(bs != NULL); + if (!ma_dr_flac__seek_bits(bs, MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs) & 7)) { + return MA_FALSE; + } + for (;;) { + ma_uint8 hi; +#ifndef MA_DR_FLAC_NO_CRC + ma_dr_flac__reset_crc16(bs); +#endif + if (!ma_dr_flac__read_uint8(bs, 8, &hi)) { + return MA_FALSE; + } + if (hi == 0xFF) { + ma_uint8 lo; + if (!ma_dr_flac__read_uint8(bs, 6, &lo)) { + return MA_FALSE; + } + if (lo == 0x3E) { + return MA_TRUE; + } else { + if (!ma_dr_flac__seek_bits(bs, MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs) & 7)) { + return MA_FALSE; + } + } + } + } +} +#if defined(MA_DR_FLAC_HAS_LZCNT_INTRINSIC) +#define MA_DR_FLAC_IMPLEMENT_CLZ_LZCNT +#endif +#if defined(_MSC_VER) && _MSC_VER >= 1400 && (defined(MA_X64) || defined(MA_X86)) && !defined(__clang__) +#define MA_DR_FLAC_IMPLEMENT_CLZ_MSVC +#endif +#if defined(__WATCOMC__) && defined(__386__) +#define MA_DR_FLAC_IMPLEMENT_CLZ_WATCOM +#endif +#ifdef __MRC__ +#include +#define MA_DR_FLAC_IMPLEMENT_CLZ_MRC +#endif +static MA_INLINE ma_uint32 ma_dr_flac__clz_software(ma_dr_flac_cache_t x) +{ + ma_uint32 n; + static ma_uint32 clz_table_4[] = { + 0, + 4, + 3, 3, + 2, 2, 2, 2, + 1, 1, 1, 1, 1, 1, 1, 1 + }; + if (x == 0) { + return sizeof(x)*8; + } + n = clz_table_4[x >> (sizeof(x)*8 - 4)]; + if (n == 0) { +#ifdef MA_64BIT + if ((x & ((ma_uint64)0xFFFFFFFF << 32)) == 0) { n = 32; x <<= 32; } + if ((x & ((ma_uint64)0xFFFF0000 << 32)) == 0) { n += 16; x <<= 16; } + if ((x & ((ma_uint64)0xFF000000 << 32)) == 0) { n += 8; x <<= 8; } + if ((x & ((ma_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; } + if ((x & 0xF0000000) == 0) { n += 4; x <<= 4; } +#endif + n += clz_table_4[x >> (sizeof(x)*8 - 4)]; + } + return n - 1; +} +#ifdef MA_DR_FLAC_IMPLEMENT_CLZ_LZCNT +static MA_INLINE ma_bool32 ma_dr_flac__is_lzcnt_supported(void) +{ +#if defined(MA_DR_FLAC_HAS_LZCNT_INTRINSIC) && defined(MA_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5) + return MA_TRUE; +#elif defined(__MRC__) + return MA_TRUE; +#else + #ifdef MA_DR_FLAC_HAS_LZCNT_INTRINSIC + return ma_dr_flac__gIsLZCNTSupported; + #else + return MA_FALSE; + #endif +#endif +} +static MA_INLINE ma_uint32 ma_dr_flac__clz_lzcnt(ma_dr_flac_cache_t x) +{ +#if defined(_MSC_VER) + #ifdef MA_64BIT + return (ma_uint32)__lzcnt64(x); + #else + return (ma_uint32)__lzcnt(x); + #endif +#else + #if defined(__GNUC__) || defined(__clang__) + #if defined(MA_X64) + { + ma_uint64 r; + __asm__ __volatile__ ( + "lzcnt{ %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc" + ); + return (ma_uint32)r; + } + #elif defined(MA_X86) + { + ma_uint32 r; + __asm__ __volatile__ ( + "lzcnt{l %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc" + ); + return r; + } + #elif defined(MA_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5) && !defined(__ARM_ARCH_6M__) && !defined(MA_64BIT) + { + unsigned int r; + __asm__ __volatile__ ( + #if defined(MA_64BIT) + "clz %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(x) + #else + "clz %[out], %[in]" : [out]"=r"(r) : [in]"r"(x) + #endif + ); + return r; + } + #else + if (x == 0) { + return sizeof(x)*8; + } + #ifdef MA_64BIT + return (ma_uint32)__builtin_clzll((ma_uint64)x); + #else + return (ma_uint32)__builtin_clzl((ma_uint32)x); + #endif + #endif + #else + #error "This compiler does not support the lzcnt intrinsic." + #endif +#endif +} +#endif +#ifdef MA_DR_FLAC_IMPLEMENT_CLZ_MSVC +#include +static MA_INLINE ma_uint32 ma_dr_flac__clz_msvc(ma_dr_flac_cache_t x) +{ + ma_uint32 n; + if (x == 0) { + return sizeof(x)*8; + } +#ifdef MA_64BIT + _BitScanReverse64((unsigned long*)&n, x); +#else + _BitScanReverse((unsigned long*)&n, x); +#endif + return sizeof(x)*8 - n - 1; +} +#endif +#ifdef MA_DR_FLAC_IMPLEMENT_CLZ_WATCOM +static __inline ma_uint32 ma_dr_flac__clz_watcom (ma_uint32); +#ifdef MA_DR_FLAC_IMPLEMENT_CLZ_WATCOM_LZCNT +#pragma aux ma_dr_flac__clz_watcom_lzcnt = \ + "db 0F3h, 0Fh, 0BDh, 0C0h" \ + parm [eax] \ + value [eax] \ + modify nomemory; +#else +#pragma aux ma_dr_flac__clz_watcom = \ + "bsr eax, eax" \ + "xor eax, 31" \ + parm [eax] nomemory \ + value [eax] \ + modify exact [eax] nomemory; +#endif +#endif +static MA_INLINE ma_uint32 ma_dr_flac__clz(ma_dr_flac_cache_t x) +{ +#ifdef MA_DR_FLAC_IMPLEMENT_CLZ_LZCNT + if (ma_dr_flac__is_lzcnt_supported()) { + return ma_dr_flac__clz_lzcnt(x); + } else +#endif + { +#ifdef MA_DR_FLAC_IMPLEMENT_CLZ_MSVC + return ma_dr_flac__clz_msvc(x); +#elif defined(MA_DR_FLAC_IMPLEMENT_CLZ_WATCOM_LZCNT) + return ma_dr_flac__clz_watcom_lzcnt(x); +#elif defined(MA_DR_FLAC_IMPLEMENT_CLZ_WATCOM) + return (x == 0) ? sizeof(x)*8 : ma_dr_flac__clz_watcom(x); +#elif defined(__MRC__) + return __cntlzw(x); +#else + return ma_dr_flac__clz_software(x); +#endif + } +} +static MA_INLINE ma_bool32 ma_dr_flac__seek_past_next_set_bit(ma_dr_flac_bs* bs, unsigned int* pOffsetOut) +{ + ma_uint32 zeroCounter = 0; + ma_uint32 setBitOffsetPlus1; + while (bs->cache == 0) { + zeroCounter += (ma_uint32)MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs); + if (!ma_dr_flac__reload_cache(bs)) { + return MA_FALSE; + } + } + if (bs->cache == 1) { + *pOffsetOut = zeroCounter + (ma_uint32)MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs) - 1; + if (!ma_dr_flac__reload_cache(bs)) { + return MA_FALSE; + } + return MA_TRUE; + } + setBitOffsetPlus1 = ma_dr_flac__clz(bs->cache); + setBitOffsetPlus1 += 1; + if (setBitOffsetPlus1 > MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs)) { + return MA_FALSE; + } + bs->consumedBits += setBitOffsetPlus1; + bs->cache <<= setBitOffsetPlus1; + *pOffsetOut = zeroCounter + setBitOffsetPlus1 - 1; + return MA_TRUE; +} +static ma_bool32 ma_dr_flac__seek_to_byte(ma_dr_flac_bs* bs, ma_uint64 offsetFromStart) +{ + MA_DR_FLAC_ASSERT(bs != NULL); + MA_DR_FLAC_ASSERT(offsetFromStart > 0); + if (offsetFromStart > 0x7FFFFFFF) { + ma_uint64 bytesRemaining = offsetFromStart; + if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, ma_dr_flac_seek_origin_start)) { + return MA_FALSE; + } + bytesRemaining -= 0x7FFFFFFF; + while (bytesRemaining > 0x7FFFFFFF) { + if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, ma_dr_flac_seek_origin_current)) { + return MA_FALSE; + } + bytesRemaining -= 0x7FFFFFFF; + } + if (bytesRemaining > 0) { + if (!bs->onSeek(bs->pUserData, (int)bytesRemaining, ma_dr_flac_seek_origin_current)) { + return MA_FALSE; + } + } + } else { + if (!bs->onSeek(bs->pUserData, (int)offsetFromStart, ma_dr_flac_seek_origin_start)) { + return MA_FALSE; + } + } + ma_dr_flac__reset_cache(bs); + return MA_TRUE; +} +static ma_result ma_dr_flac__read_utf8_coded_number(ma_dr_flac_bs* bs, ma_uint64* pNumberOut, ma_uint8* pCRCOut) +{ + ma_uint8 crc; + ma_uint64 result; + ma_uint8 utf8[7] = {0}; + int byteCount; + int i; + MA_DR_FLAC_ASSERT(bs != NULL); + MA_DR_FLAC_ASSERT(pNumberOut != NULL); + MA_DR_FLAC_ASSERT(pCRCOut != NULL); + crc = *pCRCOut; + if (!ma_dr_flac__read_uint8(bs, 8, utf8)) { + *pNumberOut = 0; + return MA_AT_END; + } + crc = ma_dr_flac_crc8(crc, utf8[0], 8); + if ((utf8[0] & 0x80) == 0) { + *pNumberOut = utf8[0]; + *pCRCOut = crc; + return MA_SUCCESS; + } + if ((utf8[0] & 0xE0) == 0xC0) { + byteCount = 2; + } else if ((utf8[0] & 0xF0) == 0xE0) { + byteCount = 3; + } else if ((utf8[0] & 0xF8) == 0xF0) { + byteCount = 4; + } else if ((utf8[0] & 0xFC) == 0xF8) { + byteCount = 5; + } else if ((utf8[0] & 0xFE) == 0xFC) { + byteCount = 6; + } else if ((utf8[0] & 0xFF) == 0xFE) { + byteCount = 7; + } else { + *pNumberOut = 0; + return MA_CRC_MISMATCH; + } + MA_DR_FLAC_ASSERT(byteCount > 1); + result = (ma_uint64)(utf8[0] & (0xFF >> (byteCount + 1))); + for (i = 1; i < byteCount; ++i) { + if (!ma_dr_flac__read_uint8(bs, 8, utf8 + i)) { + *pNumberOut = 0; + return MA_AT_END; + } + crc = ma_dr_flac_crc8(crc, utf8[i], 8); + result = (result << 6) | (utf8[i] & 0x3F); + } + *pNumberOut = result; + *pCRCOut = crc; + return MA_SUCCESS; +} +static MA_INLINE ma_uint32 ma_dr_flac__ilog2_u32(ma_uint32 x) +{ +#if 1 + ma_uint32 result = 0; + while (x > 0) { + result += 1; + x >>= 1; + } + return result; +#endif +} +static MA_INLINE ma_bool32 ma_dr_flac__use_64_bit_prediction(ma_uint32 bitsPerSample, ma_uint32 order, ma_uint32 precision) +{ + return bitsPerSample + precision + ma_dr_flac__ilog2_u32(order) > 32; +} +#if defined(__clang__) +__attribute__((no_sanitize("signed-integer-overflow"))) +#endif +static MA_INLINE ma_int32 ma_dr_flac__calculate_prediction_32(ma_uint32 order, ma_int32 shift, const ma_int32* coefficients, ma_int32* pDecodedSamples) +{ + ma_int32 prediction = 0; + MA_DR_FLAC_ASSERT(order <= 32); + switch (order) + { + case 32: prediction += coefficients[31] * pDecodedSamples[-32]; + case 31: prediction += coefficients[30] * pDecodedSamples[-31]; + case 30: prediction += coefficients[29] * pDecodedSamples[-30]; + case 29: prediction += coefficients[28] * pDecodedSamples[-29]; + case 28: prediction += coefficients[27] * pDecodedSamples[-28]; + case 27: prediction += coefficients[26] * pDecodedSamples[-27]; + case 26: prediction += coefficients[25] * pDecodedSamples[-26]; + case 25: prediction += coefficients[24] * pDecodedSamples[-25]; + case 24: prediction += coefficients[23] * pDecodedSamples[-24]; + case 23: prediction += coefficients[22] * pDecodedSamples[-23]; + case 22: prediction += coefficients[21] * pDecodedSamples[-22]; + case 21: prediction += coefficients[20] * pDecodedSamples[-21]; + case 20: prediction += coefficients[19] * pDecodedSamples[-20]; + case 19: prediction += coefficients[18] * pDecodedSamples[-19]; + case 18: prediction += coefficients[17] * pDecodedSamples[-18]; + case 17: prediction += coefficients[16] * pDecodedSamples[-17]; + case 16: prediction += coefficients[15] * pDecodedSamples[-16]; + case 15: prediction += coefficients[14] * pDecodedSamples[-15]; + case 14: prediction += coefficients[13] * pDecodedSamples[-14]; + case 13: prediction += coefficients[12] * pDecodedSamples[-13]; + case 12: prediction += coefficients[11] * pDecodedSamples[-12]; + case 11: prediction += coefficients[10] * pDecodedSamples[-11]; + case 10: prediction += coefficients[ 9] * pDecodedSamples[-10]; + case 9: prediction += coefficients[ 8] * pDecodedSamples[- 9]; + case 8: prediction += coefficients[ 7] * pDecodedSamples[- 8]; + case 7: prediction += coefficients[ 6] * pDecodedSamples[- 7]; + case 6: prediction += coefficients[ 5] * pDecodedSamples[- 6]; + case 5: prediction += coefficients[ 4] * pDecodedSamples[- 5]; + case 4: prediction += coefficients[ 3] * pDecodedSamples[- 4]; + case 3: prediction += coefficients[ 2] * pDecodedSamples[- 3]; + case 2: prediction += coefficients[ 1] * pDecodedSamples[- 2]; + case 1: prediction += coefficients[ 0] * pDecodedSamples[- 1]; + } + return (ma_int32)(prediction >> shift); +} +static MA_INLINE ma_int32 ma_dr_flac__calculate_prediction_64(ma_uint32 order, ma_int32 shift, const ma_int32* coefficients, ma_int32* pDecodedSamples) +{ + ma_int64 prediction; + MA_DR_FLAC_ASSERT(order <= 32); +#ifndef MA_64BIT + if (order == 8) + { + prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2]; + prediction += coefficients[2] * (ma_int64)pDecodedSamples[-3]; + prediction += coefficients[3] * (ma_int64)pDecodedSamples[-4]; + prediction += coefficients[4] * (ma_int64)pDecodedSamples[-5]; + prediction += coefficients[5] * (ma_int64)pDecodedSamples[-6]; + prediction += coefficients[6] * (ma_int64)pDecodedSamples[-7]; + prediction += coefficients[7] * (ma_int64)pDecodedSamples[-8]; + } + else if (order == 7) + { + prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2]; + prediction += coefficients[2] * (ma_int64)pDecodedSamples[-3]; + prediction += coefficients[3] * (ma_int64)pDecodedSamples[-4]; + prediction += coefficients[4] * (ma_int64)pDecodedSamples[-5]; + prediction += coefficients[5] * (ma_int64)pDecodedSamples[-6]; + prediction += coefficients[6] * (ma_int64)pDecodedSamples[-7]; + } + else if (order == 3) + { + prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2]; + prediction += coefficients[2] * (ma_int64)pDecodedSamples[-3]; + } + else if (order == 6) + { + prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2]; + prediction += coefficients[2] * (ma_int64)pDecodedSamples[-3]; + prediction += coefficients[3] * (ma_int64)pDecodedSamples[-4]; + prediction += coefficients[4] * (ma_int64)pDecodedSamples[-5]; + prediction += coefficients[5] * (ma_int64)pDecodedSamples[-6]; + } + else if (order == 5) + { + prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2]; + prediction += coefficients[2] * (ma_int64)pDecodedSamples[-3]; + prediction += coefficients[3] * (ma_int64)pDecodedSamples[-4]; + prediction += coefficients[4] * (ma_int64)pDecodedSamples[-5]; + } + else if (order == 4) + { + prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2]; + prediction += coefficients[2] * (ma_int64)pDecodedSamples[-3]; + prediction += coefficients[3] * (ma_int64)pDecodedSamples[-4]; + } + else if (order == 12) + { + prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2]; + prediction += coefficients[2] * (ma_int64)pDecodedSamples[-3]; + prediction += coefficients[3] * (ma_int64)pDecodedSamples[-4]; + prediction += coefficients[4] * (ma_int64)pDecodedSamples[-5]; + prediction += coefficients[5] * (ma_int64)pDecodedSamples[-6]; + prediction += coefficients[6] * (ma_int64)pDecodedSamples[-7]; + prediction += coefficients[7] * (ma_int64)pDecodedSamples[-8]; + prediction += coefficients[8] * (ma_int64)pDecodedSamples[-9]; + prediction += coefficients[9] * (ma_int64)pDecodedSamples[-10]; + prediction += coefficients[10] * (ma_int64)pDecodedSamples[-11]; + prediction += coefficients[11] * (ma_int64)pDecodedSamples[-12]; + } + else if (order == 2) + { + prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2]; + } + else if (order == 1) + { + prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1]; + } + else if (order == 10) + { + prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2]; + prediction += coefficients[2] * (ma_int64)pDecodedSamples[-3]; + prediction += coefficients[3] * (ma_int64)pDecodedSamples[-4]; + prediction += coefficients[4] * (ma_int64)pDecodedSamples[-5]; + prediction += coefficients[5] * (ma_int64)pDecodedSamples[-6]; + prediction += coefficients[6] * (ma_int64)pDecodedSamples[-7]; + prediction += coefficients[7] * (ma_int64)pDecodedSamples[-8]; + prediction += coefficients[8] * (ma_int64)pDecodedSamples[-9]; + prediction += coefficients[9] * (ma_int64)pDecodedSamples[-10]; + } + else if (order == 9) + { + prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2]; + prediction += coefficients[2] * (ma_int64)pDecodedSamples[-3]; + prediction += coefficients[3] * (ma_int64)pDecodedSamples[-4]; + prediction += coefficients[4] * (ma_int64)pDecodedSamples[-5]; + prediction += coefficients[5] * (ma_int64)pDecodedSamples[-6]; + prediction += coefficients[6] * (ma_int64)pDecodedSamples[-7]; + prediction += coefficients[7] * (ma_int64)pDecodedSamples[-8]; + prediction += coefficients[8] * (ma_int64)pDecodedSamples[-9]; + } + else if (order == 11) + { + prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2]; + prediction += coefficients[2] * (ma_int64)pDecodedSamples[-3]; + prediction += coefficients[3] * (ma_int64)pDecodedSamples[-4]; + prediction += coefficients[4] * (ma_int64)pDecodedSamples[-5]; + prediction += coefficients[5] * (ma_int64)pDecodedSamples[-6]; + prediction += coefficients[6] * (ma_int64)pDecodedSamples[-7]; + prediction += coefficients[7] * (ma_int64)pDecodedSamples[-8]; + prediction += coefficients[8] * (ma_int64)pDecodedSamples[-9]; + prediction += coefficients[9] * (ma_int64)pDecodedSamples[-10]; + prediction += coefficients[10] * (ma_int64)pDecodedSamples[-11]; + } + else + { + int j; + prediction = 0; + for (j = 0; j < (int)order; ++j) { + prediction += coefficients[j] * (ma_int64)pDecodedSamples[-j-1]; + } + } +#endif +#ifdef MA_64BIT + prediction = 0; + switch (order) + { + case 32: prediction += coefficients[31] * (ma_int64)pDecodedSamples[-32]; + case 31: prediction += coefficients[30] * (ma_int64)pDecodedSamples[-31]; + case 30: prediction += coefficients[29] * (ma_int64)pDecodedSamples[-30]; + case 29: prediction += coefficients[28] * (ma_int64)pDecodedSamples[-29]; + case 28: prediction += coefficients[27] * (ma_int64)pDecodedSamples[-28]; + case 27: prediction += coefficients[26] * (ma_int64)pDecodedSamples[-27]; + case 26: prediction += coefficients[25] * (ma_int64)pDecodedSamples[-26]; + case 25: prediction += coefficients[24] * (ma_int64)pDecodedSamples[-25]; + case 24: prediction += coefficients[23] * (ma_int64)pDecodedSamples[-24]; + case 23: prediction += coefficients[22] * (ma_int64)pDecodedSamples[-23]; + case 22: prediction += coefficients[21] * (ma_int64)pDecodedSamples[-22]; + case 21: prediction += coefficients[20] * (ma_int64)pDecodedSamples[-21]; + case 20: prediction += coefficients[19] * (ma_int64)pDecodedSamples[-20]; + case 19: prediction += coefficients[18] * (ma_int64)pDecodedSamples[-19]; + case 18: prediction += coefficients[17] * (ma_int64)pDecodedSamples[-18]; + case 17: prediction += coefficients[16] * (ma_int64)pDecodedSamples[-17]; + case 16: prediction += coefficients[15] * (ma_int64)pDecodedSamples[-16]; + case 15: prediction += coefficients[14] * (ma_int64)pDecodedSamples[-15]; + case 14: prediction += coefficients[13] * (ma_int64)pDecodedSamples[-14]; + case 13: prediction += coefficients[12] * (ma_int64)pDecodedSamples[-13]; + case 12: prediction += coefficients[11] * (ma_int64)pDecodedSamples[-12]; + case 11: prediction += coefficients[10] * (ma_int64)pDecodedSamples[-11]; + case 10: prediction += coefficients[ 9] * (ma_int64)pDecodedSamples[-10]; + case 9: prediction += coefficients[ 8] * (ma_int64)pDecodedSamples[- 9]; + case 8: prediction += coefficients[ 7] * (ma_int64)pDecodedSamples[- 8]; + case 7: prediction += coefficients[ 6] * (ma_int64)pDecodedSamples[- 7]; + case 6: prediction += coefficients[ 5] * (ma_int64)pDecodedSamples[- 6]; + case 5: prediction += coefficients[ 4] * (ma_int64)pDecodedSamples[- 5]; + case 4: prediction += coefficients[ 3] * (ma_int64)pDecodedSamples[- 4]; + case 3: prediction += coefficients[ 2] * (ma_int64)pDecodedSamples[- 3]; + case 2: prediction += coefficients[ 1] * (ma_int64)pDecodedSamples[- 2]; + case 1: prediction += coefficients[ 0] * (ma_int64)pDecodedSamples[- 1]; + } +#endif + return (ma_int32)(prediction >> shift); +} +#if 0 +static ma_bool32 ma_dr_flac__decode_samples_with_residual__rice__reference(ma_dr_flac_bs* bs, ma_uint32 bitsPerSample, ma_uint32 count, ma_uint8 riceParam, ma_uint32 lpcOrder, ma_int32 lpcShift, ma_uint32 lpcPrecision, const ma_int32* coefficients, ma_int32* pSamplesOut) +{ + ma_uint32 i; + MA_DR_FLAC_ASSERT(bs != NULL); + MA_DR_FLAC_ASSERT(pSamplesOut != NULL); + for (i = 0; i < count; ++i) { + ma_uint32 zeroCounter = 0; + for (;;) { + ma_uint8 bit; + if (!ma_dr_flac__read_uint8(bs, 1, &bit)) { + return MA_FALSE; + } + if (bit == 0) { + zeroCounter += 1; + } else { + break; + } + } + ma_uint32 decodedRice; + if (riceParam > 0) { + if (!ma_dr_flac__read_uint32(bs, riceParam, &decodedRice)) { + return MA_FALSE; + } + } else { + decodedRice = 0; + } + decodedRice |= (zeroCounter << riceParam); + if ((decodedRice & 0x01)) { + decodedRice = ~(decodedRice >> 1); + } else { + decodedRice = (decodedRice >> 1); + } + if (ma_dr_flac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) { + pSamplesOut[i] = decodedRice + ma_dr_flac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + i); + } else { + pSamplesOut[i] = decodedRice + ma_dr_flac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + i); + } + } + return MA_TRUE; +} +#endif +#if 0 +static ma_bool32 ma_dr_flac__read_rice_parts__reference(ma_dr_flac_bs* bs, ma_uint8 riceParam, ma_uint32* pZeroCounterOut, ma_uint32* pRiceParamPartOut) +{ + ma_uint32 zeroCounter = 0; + ma_uint32 decodedRice; + for (;;) { + ma_uint8 bit; + if (!ma_dr_flac__read_uint8(bs, 1, &bit)) { + return MA_FALSE; + } + if (bit == 0) { + zeroCounter += 1; + } else { + break; + } + } + if (riceParam > 0) { + if (!ma_dr_flac__read_uint32(bs, riceParam, &decodedRice)) { + return MA_FALSE; + } + } else { + decodedRice = 0; + } + *pZeroCounterOut = zeroCounter; + *pRiceParamPartOut = decodedRice; + return MA_TRUE; +} +#endif +#if 0 +static MA_INLINE ma_bool32 ma_dr_flac__read_rice_parts(ma_dr_flac_bs* bs, ma_uint8 riceParam, ma_uint32* pZeroCounterOut, ma_uint32* pRiceParamPartOut) +{ + ma_dr_flac_cache_t riceParamMask; + ma_uint32 zeroCounter; + ma_uint32 setBitOffsetPlus1; + ma_uint32 riceParamPart; + ma_uint32 riceLength; + MA_DR_FLAC_ASSERT(riceParam > 0); + riceParamMask = MA_DR_FLAC_CACHE_L1_SELECTION_MASK(riceParam); + zeroCounter = 0; + while (bs->cache == 0) { + zeroCounter += (ma_uint32)MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs); + if (!ma_dr_flac__reload_cache(bs)) { + return MA_FALSE; + } + } + setBitOffsetPlus1 = ma_dr_flac__clz(bs->cache); + zeroCounter += setBitOffsetPlus1; + setBitOffsetPlus1 += 1; + riceLength = setBitOffsetPlus1 + riceParam; + if (riceLength < MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs)) { + riceParamPart = (ma_uint32)((bs->cache & (riceParamMask >> setBitOffsetPlus1)) >> MA_DR_FLAC_CACHE_L1_SELECTION_SHIFT(bs, riceLength)); + bs->consumedBits += riceLength; + bs->cache <<= riceLength; + } else { + ma_uint32 bitCountLo; + ma_dr_flac_cache_t resultHi; + bs->consumedBits += riceLength; + bs->cache <<= setBitOffsetPlus1 & (MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs)-1); + bitCountLo = bs->consumedBits - MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs); + resultHi = MA_DR_FLAC_CACHE_L1_SELECT_AND_SHIFT(bs, riceParam); + if (bs->nextL2Line < MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs)) { +#ifndef MA_DR_FLAC_NO_CRC + ma_dr_flac__update_crc16(bs); +#endif + bs->cache = ma_dr_flac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]); + bs->consumedBits = 0; +#ifndef MA_DR_FLAC_NO_CRC + bs->crc16Cache = bs->cache; +#endif + } else { + if (!ma_dr_flac__reload_cache(bs)) { + return MA_FALSE; + } + if (bitCountLo > MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs)) { + return MA_FALSE; + } + } + riceParamPart = (ma_uint32)(resultHi | MA_DR_FLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, bitCountLo)); + bs->consumedBits += bitCountLo; + bs->cache <<= bitCountLo; + } + pZeroCounterOut[0] = zeroCounter; + pRiceParamPartOut[0] = riceParamPart; + return MA_TRUE; +} +#endif +static MA_INLINE ma_bool32 ma_dr_flac__read_rice_parts_x1(ma_dr_flac_bs* bs, ma_uint8 riceParam, ma_uint32* pZeroCounterOut, ma_uint32* pRiceParamPartOut) +{ + ma_uint32 riceParamPlus1 = riceParam + 1; + ma_uint32 riceParamPlus1Shift = MA_DR_FLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPlus1); + ma_uint32 riceParamPlus1MaxConsumedBits = MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1; + ma_dr_flac_cache_t bs_cache = bs->cache; + ma_uint32 bs_consumedBits = bs->consumedBits; + ma_uint32 lzcount = ma_dr_flac__clz(bs_cache); + if (lzcount < sizeof(bs_cache)*8) { + pZeroCounterOut[0] = lzcount; + extract_rice_param_part: + bs_cache <<= lzcount; + bs_consumedBits += lzcount; + if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) { + pRiceParamPartOut[0] = (ma_uint32)(bs_cache >> riceParamPlus1Shift); + bs_cache <<= riceParamPlus1; + bs_consumedBits += riceParamPlus1; + } else { + ma_uint32 riceParamPartHi; + ma_uint32 riceParamPartLo; + ma_uint32 riceParamPartLoBitCount; + riceParamPartHi = (ma_uint32)(bs_cache >> riceParamPlus1Shift); + riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits; + MA_DR_FLAC_ASSERT(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32); + if (bs->nextL2Line < MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs)) { + #ifndef MA_DR_FLAC_NO_CRC + ma_dr_flac__update_crc16(bs); + #endif + bs_cache = ma_dr_flac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]); + bs_consumedBits = riceParamPartLoBitCount; + #ifndef MA_DR_FLAC_NO_CRC + bs->crc16Cache = bs_cache; + #endif + } else { + if (!ma_dr_flac__reload_cache(bs)) { + return MA_FALSE; + } + if (riceParamPartLoBitCount > MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs)) { + return MA_FALSE; + } + bs_cache = bs->cache; + bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount; + } + riceParamPartLo = (ma_uint32)(bs_cache >> (MA_DR_FLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPartLoBitCount))); + pRiceParamPartOut[0] = riceParamPartHi | riceParamPartLo; + bs_cache <<= riceParamPartLoBitCount; + } + } else { + ma_uint32 zeroCounter = (ma_uint32)(MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs) - bs_consumedBits); + for (;;) { + if (bs->nextL2Line < MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs)) { + #ifndef MA_DR_FLAC_NO_CRC + ma_dr_flac__update_crc16(bs); + #endif + bs_cache = ma_dr_flac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]); + bs_consumedBits = 0; + #ifndef MA_DR_FLAC_NO_CRC + bs->crc16Cache = bs_cache; + #endif + } else { + if (!ma_dr_flac__reload_cache(bs)) { + return MA_FALSE; + } + bs_cache = bs->cache; + bs_consumedBits = bs->consumedBits; + } + lzcount = ma_dr_flac__clz(bs_cache); + zeroCounter += lzcount; + if (lzcount < sizeof(bs_cache)*8) { + break; + } + } + pZeroCounterOut[0] = zeroCounter; + goto extract_rice_param_part; + } + bs->cache = bs_cache; + bs->consumedBits = bs_consumedBits; + return MA_TRUE; +} +static MA_INLINE ma_bool32 ma_dr_flac__seek_rice_parts(ma_dr_flac_bs* bs, ma_uint8 riceParam) +{ + ma_uint32 riceParamPlus1 = riceParam + 1; + ma_uint32 riceParamPlus1MaxConsumedBits = MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1; + ma_dr_flac_cache_t bs_cache = bs->cache; + ma_uint32 bs_consumedBits = bs->consumedBits; + ma_uint32 lzcount = ma_dr_flac__clz(bs_cache); + if (lzcount < sizeof(bs_cache)*8) { + extract_rice_param_part: + bs_cache <<= lzcount; + bs_consumedBits += lzcount; + if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) { + bs_cache <<= riceParamPlus1; + bs_consumedBits += riceParamPlus1; + } else { + ma_uint32 riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits; + MA_DR_FLAC_ASSERT(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32); + if (bs->nextL2Line < MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs)) { + #ifndef MA_DR_FLAC_NO_CRC + ma_dr_flac__update_crc16(bs); + #endif + bs_cache = ma_dr_flac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]); + bs_consumedBits = riceParamPartLoBitCount; + #ifndef MA_DR_FLAC_NO_CRC + bs->crc16Cache = bs_cache; + #endif + } else { + if (!ma_dr_flac__reload_cache(bs)) { + return MA_FALSE; + } + if (riceParamPartLoBitCount > MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs)) { + return MA_FALSE; + } + bs_cache = bs->cache; + bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount; + } + bs_cache <<= riceParamPartLoBitCount; + } + } else { + for (;;) { + if (bs->nextL2Line < MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs)) { + #ifndef MA_DR_FLAC_NO_CRC + ma_dr_flac__update_crc16(bs); + #endif + bs_cache = ma_dr_flac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]); + bs_consumedBits = 0; + #ifndef MA_DR_FLAC_NO_CRC + bs->crc16Cache = bs_cache; + #endif + } else { + if (!ma_dr_flac__reload_cache(bs)) { + return MA_FALSE; + } + bs_cache = bs->cache; + bs_consumedBits = bs->consumedBits; + } + lzcount = ma_dr_flac__clz(bs_cache); + if (lzcount < sizeof(bs_cache)*8) { + break; + } + } + goto extract_rice_param_part; + } + bs->cache = bs_cache; + bs->consumedBits = bs_consumedBits; + return MA_TRUE; +} +static ma_bool32 ma_dr_flac__decode_samples_with_residual__rice__scalar_zeroorder(ma_dr_flac_bs* bs, ma_uint32 bitsPerSample, ma_uint32 count, ma_uint8 riceParam, ma_uint32 order, ma_int32 shift, const ma_int32* coefficients, ma_int32* pSamplesOut) +{ + ma_uint32 t[2] = {0x00000000, 0xFFFFFFFF}; + ma_uint32 zeroCountPart0; + ma_uint32 riceParamPart0; + ma_uint32 riceParamMask; + ma_uint32 i; + MA_DR_FLAC_ASSERT(bs != NULL); + MA_DR_FLAC_ASSERT(pSamplesOut != NULL); + (void)bitsPerSample; + (void)order; + (void)shift; + (void)coefficients; + riceParamMask = (ma_uint32)~((~0UL) << riceParam); + i = 0; + while (i < count) { + if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0)) { + return MA_FALSE; + } + riceParamPart0 &= riceParamMask; + riceParamPart0 |= (zeroCountPart0 << riceParam); + riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01]; + pSamplesOut[i] = riceParamPart0; + i += 1; + } + return MA_TRUE; +} +static ma_bool32 ma_dr_flac__decode_samples_with_residual__rice__scalar(ma_dr_flac_bs* bs, ma_uint32 bitsPerSample, ma_uint32 count, ma_uint8 riceParam, ma_uint32 lpcOrder, ma_int32 lpcShift, ma_uint32 lpcPrecision, const ma_int32* coefficients, ma_int32* pSamplesOut) +{ + ma_uint32 t[2] = {0x00000000, 0xFFFFFFFF}; + ma_uint32 zeroCountPart0 = 0; + ma_uint32 zeroCountPart1 = 0; + ma_uint32 zeroCountPart2 = 0; + ma_uint32 zeroCountPart3 = 0; + ma_uint32 riceParamPart0 = 0; + ma_uint32 riceParamPart1 = 0; + ma_uint32 riceParamPart2 = 0; + ma_uint32 riceParamPart3 = 0; + ma_uint32 riceParamMask; + const ma_int32* pSamplesOutEnd; + ma_uint32 i; + MA_DR_FLAC_ASSERT(bs != NULL); + MA_DR_FLAC_ASSERT(pSamplesOut != NULL); + if (lpcOrder == 0) { + return ma_dr_flac__decode_samples_with_residual__rice__scalar_zeroorder(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut); + } + riceParamMask = (ma_uint32)~((~0UL) << riceParam); + pSamplesOutEnd = pSamplesOut + (count & ~3); + if (ma_dr_flac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) { + while (pSamplesOut < pSamplesOutEnd) { + if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) || + !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) || + !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) || + !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) { + return MA_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 + ma_dr_flac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 0); + pSamplesOut[1] = riceParamPart1 + ma_dr_flac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 1); + pSamplesOut[2] = riceParamPart2 + ma_dr_flac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 2); + pSamplesOut[3] = riceParamPart3 + ma_dr_flac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 3); + pSamplesOut += 4; + } + } else { + while (pSamplesOut < pSamplesOutEnd) { + if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) || + !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) || + !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) || + !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) { + return MA_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 + ma_dr_flac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 0); + pSamplesOut[1] = riceParamPart1 + ma_dr_flac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 1); + pSamplesOut[2] = riceParamPart2 + ma_dr_flac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 2); + pSamplesOut[3] = riceParamPart3 + ma_dr_flac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 3); + pSamplesOut += 4; + } + } + i = (count & ~3); + while (i < count) { + if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0)) { + return MA_FALSE; + } + riceParamPart0 &= riceParamMask; + riceParamPart0 |= (zeroCountPart0 << riceParam); + riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01]; + if (ma_dr_flac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) { + pSamplesOut[0] = riceParamPart0 + ma_dr_flac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 0); + } else { + pSamplesOut[0] = riceParamPart0 + ma_dr_flac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 0); + } + i += 1; + pSamplesOut += 1; + } + return MA_TRUE; +} +#if defined(MA_DR_FLAC_SUPPORT_SSE2) +static MA_INLINE __m128i ma_dr_flac__mm_packs_interleaved_epi32(__m128i a, __m128i b) +{ + __m128i r; + r = _mm_packs_epi32(a, b); + r = _mm_shuffle_epi32(r, _MM_SHUFFLE(3, 1, 2, 0)); + r = _mm_shufflehi_epi16(r, _MM_SHUFFLE(3, 1, 2, 0)); + r = _mm_shufflelo_epi16(r, _MM_SHUFFLE(3, 1, 2, 0)); + return r; +} +#endif +#if defined(MA_DR_FLAC_SUPPORT_SSE41) +static MA_INLINE __m128i ma_dr_flac__mm_not_si128(__m128i a) +{ + return _mm_xor_si128(a, _mm_cmpeq_epi32(_mm_setzero_si128(), _mm_setzero_si128())); +} +static MA_INLINE __m128i ma_dr_flac__mm_hadd_epi32(__m128i x) +{ + __m128i x64 = _mm_add_epi32(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2))); + __m128i x32 = _mm_shufflelo_epi16(x64, _MM_SHUFFLE(1, 0, 3, 2)); + return _mm_add_epi32(x64, x32); +} +static MA_INLINE __m128i ma_dr_flac__mm_hadd_epi64(__m128i x) +{ + return _mm_add_epi64(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2))); +} +static MA_INLINE __m128i ma_dr_flac__mm_srai_epi64(__m128i x, int count) +{ + __m128i lo = _mm_srli_epi64(x, count); + __m128i hi = _mm_srai_epi32(x, count); + hi = _mm_and_si128(hi, _mm_set_epi32(0xFFFFFFFF, 0, 0xFFFFFFFF, 0)); + return _mm_or_si128(lo, hi); +} +static ma_bool32 ma_dr_flac__decode_samples_with_residual__rice__sse41_32(ma_dr_flac_bs* bs, ma_uint32 count, ma_uint8 riceParam, ma_uint32 order, ma_int32 shift, const ma_int32* coefficients, ma_int32* pSamplesOut) +{ + int i; + ma_uint32 riceParamMask; + ma_int32* pDecodedSamples = pSamplesOut; + ma_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3); + ma_uint32 zeroCountParts0 = 0; + ma_uint32 zeroCountParts1 = 0; + ma_uint32 zeroCountParts2 = 0; + ma_uint32 zeroCountParts3 = 0; + ma_uint32 riceParamParts0 = 0; + ma_uint32 riceParamParts1 = 0; + ma_uint32 riceParamParts2 = 0; + ma_uint32 riceParamParts3 = 0; + __m128i coefficients128_0; + __m128i coefficients128_4; + __m128i coefficients128_8; + __m128i samples128_0; + __m128i samples128_4; + __m128i samples128_8; + __m128i riceParamMask128; + const ma_uint32 t[2] = {0x00000000, 0xFFFFFFFF}; + riceParamMask = (ma_uint32)~((~0UL) << riceParam); + riceParamMask128 = _mm_set1_epi32(riceParamMask); + coefficients128_0 = _mm_setzero_si128(); + coefficients128_4 = _mm_setzero_si128(); + coefficients128_8 = _mm_setzero_si128(); + samples128_0 = _mm_setzero_si128(); + samples128_4 = _mm_setzero_si128(); + samples128_8 = _mm_setzero_si128(); +#if 1 + { + int runningOrder = order; + if (runningOrder >= 4) { + coefficients128_0 = _mm_loadu_si128((const __m128i*)(coefficients + 0)); + samples128_0 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 4)); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: coefficients128_0 = _mm_set_epi32(0, coefficients[2], coefficients[1], coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], pSamplesOut[-2], pSamplesOut[-3], 0); break; + case 2: coefficients128_0 = _mm_set_epi32(0, 0, coefficients[1], coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], pSamplesOut[-2], 0, 0); break; + case 1: coefficients128_0 = _mm_set_epi32(0, 0, 0, coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], 0, 0, 0); break; + } + runningOrder = 0; + } + if (runningOrder >= 4) { + coefficients128_4 = _mm_loadu_si128((const __m128i*)(coefficients + 4)); + samples128_4 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 8)); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: coefficients128_4 = _mm_set_epi32(0, coefficients[6], coefficients[5], coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], pSamplesOut[-6], pSamplesOut[-7], 0); break; + case 2: coefficients128_4 = _mm_set_epi32(0, 0, coefficients[5], coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], pSamplesOut[-6], 0, 0); break; + case 1: coefficients128_4 = _mm_set_epi32(0, 0, 0, coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], 0, 0, 0); break; + } + runningOrder = 0; + } + if (runningOrder == 4) { + coefficients128_8 = _mm_loadu_si128((const __m128i*)(coefficients + 8)); + samples128_8 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 12)); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: coefficients128_8 = _mm_set_epi32(0, coefficients[10], coefficients[9], coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], pSamplesOut[-10], pSamplesOut[-11], 0); break; + case 2: coefficients128_8 = _mm_set_epi32(0, 0, coefficients[9], coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], pSamplesOut[-10], 0, 0); break; + case 1: coefficients128_8 = _mm_set_epi32(0, 0, 0, coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], 0, 0, 0); break; + } + runningOrder = 0; + } + coefficients128_0 = _mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(0, 1, 2, 3)); + coefficients128_4 = _mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(0, 1, 2, 3)); + coefficients128_8 = _mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(0, 1, 2, 3)); + } +#else + switch (order) + { + case 12: ((ma_int32*)&coefficients128_8)[0] = coefficients[11]; ((ma_int32*)&samples128_8)[0] = pDecodedSamples[-12]; + case 11: ((ma_int32*)&coefficients128_8)[1] = coefficients[10]; ((ma_int32*)&samples128_8)[1] = pDecodedSamples[-11]; + case 10: ((ma_int32*)&coefficients128_8)[2] = coefficients[ 9]; ((ma_int32*)&samples128_8)[2] = pDecodedSamples[-10]; + case 9: ((ma_int32*)&coefficients128_8)[3] = coefficients[ 8]; ((ma_int32*)&samples128_8)[3] = pDecodedSamples[- 9]; + case 8: ((ma_int32*)&coefficients128_4)[0] = coefficients[ 7]; ((ma_int32*)&samples128_4)[0] = pDecodedSamples[- 8]; + case 7: ((ma_int32*)&coefficients128_4)[1] = coefficients[ 6]; ((ma_int32*)&samples128_4)[1] = pDecodedSamples[- 7]; + case 6: ((ma_int32*)&coefficients128_4)[2] = coefficients[ 5]; ((ma_int32*)&samples128_4)[2] = pDecodedSamples[- 6]; + case 5: ((ma_int32*)&coefficients128_4)[3] = coefficients[ 4]; ((ma_int32*)&samples128_4)[3] = pDecodedSamples[- 5]; + case 4: ((ma_int32*)&coefficients128_0)[0] = coefficients[ 3]; ((ma_int32*)&samples128_0)[0] = pDecodedSamples[- 4]; + case 3: ((ma_int32*)&coefficients128_0)[1] = coefficients[ 2]; ((ma_int32*)&samples128_0)[1] = pDecodedSamples[- 3]; + case 2: ((ma_int32*)&coefficients128_0)[2] = coefficients[ 1]; ((ma_int32*)&samples128_0)[2] = pDecodedSamples[- 2]; + case 1: ((ma_int32*)&coefficients128_0)[3] = coefficients[ 0]; ((ma_int32*)&samples128_0)[3] = pDecodedSamples[- 1]; + } +#endif + while (pDecodedSamples < pDecodedSamplesEnd) { + __m128i prediction128; + __m128i zeroCountPart128; + __m128i riceParamPart128; + if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0) || + !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts1, &riceParamParts1) || + !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts2, &riceParamParts2) || + !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts3, &riceParamParts3)) { + return MA_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_add_epi32(ma_dr_flac__mm_not_si128(_mm_and_si128(riceParamPart128, _mm_set1_epi32(0x01))), _mm_set1_epi32(0x01))); + if (order <= 4) { + for (i = 0; i < 4; i += 1) { + prediction128 = _mm_mullo_epi32(coefficients128_0, samples128_0); + prediction128 = ma_dr_flac__mm_hadd_epi32(prediction128); + prediction128 = _mm_srai_epi32(prediction128, shift); + prediction128 = _mm_add_epi32(riceParamPart128, prediction128); + samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4); + riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4); + } + } else if (order <= 8) { + for (i = 0; i < 4; i += 1) { + prediction128 = _mm_mullo_epi32(coefficients128_4, samples128_4); + prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_0, samples128_0)); + prediction128 = ma_dr_flac__mm_hadd_epi32(prediction128); + prediction128 = _mm_srai_epi32(prediction128, shift); + prediction128 = _mm_add_epi32(riceParamPart128, prediction128); + samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4); + samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4); + riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4); + } + } else { + for (i = 0; i < 4; i += 1) { + prediction128 = _mm_mullo_epi32(coefficients128_8, samples128_8); + prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_4, samples128_4)); + prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_0, samples128_0)); + prediction128 = ma_dr_flac__mm_hadd_epi32(prediction128); + prediction128 = _mm_srai_epi32(prediction128, shift); + prediction128 = _mm_add_epi32(riceParamPart128, prediction128); + samples128_8 = _mm_alignr_epi8(samples128_4, samples128_8, 4); + samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4); + samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4); + riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4); + } + } + _mm_storeu_si128((__m128i*)pDecodedSamples, samples128_0); + pDecodedSamples += 4; + } + i = (count & ~3); + while (i < (int)count) { + if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0)) { + return MA_FALSE; + } + riceParamParts0 &= riceParamMask; + riceParamParts0 |= (zeroCountParts0 << riceParam); + riceParamParts0 = (riceParamParts0 >> 1) ^ t[riceParamParts0 & 0x01]; + pDecodedSamples[0] = riceParamParts0 + ma_dr_flac__calculate_prediction_32(order, shift, coefficients, pDecodedSamples); + i += 1; + pDecodedSamples += 1; + } + return MA_TRUE; +} +static ma_bool32 ma_dr_flac__decode_samples_with_residual__rice__sse41_64(ma_dr_flac_bs* bs, ma_uint32 count, ma_uint8 riceParam, ma_uint32 order, ma_int32 shift, const ma_int32* coefficients, ma_int32* pSamplesOut) +{ + int i; + ma_uint32 riceParamMask; + ma_int32* pDecodedSamples = pSamplesOut; + ma_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3); + ma_uint32 zeroCountParts0 = 0; + ma_uint32 zeroCountParts1 = 0; + ma_uint32 zeroCountParts2 = 0; + ma_uint32 zeroCountParts3 = 0; + ma_uint32 riceParamParts0 = 0; + ma_uint32 riceParamParts1 = 0; + ma_uint32 riceParamParts2 = 0; + ma_uint32 riceParamParts3 = 0; + __m128i coefficients128_0; + __m128i coefficients128_4; + __m128i coefficients128_8; + __m128i samples128_0; + __m128i samples128_4; + __m128i samples128_8; + __m128i prediction128; + __m128i riceParamMask128; + const ma_uint32 t[2] = {0x00000000, 0xFFFFFFFF}; + MA_DR_FLAC_ASSERT(order <= 12); + riceParamMask = (ma_uint32)~((~0UL) << riceParam); + riceParamMask128 = _mm_set1_epi32(riceParamMask); + prediction128 = _mm_setzero_si128(); + coefficients128_0 = _mm_setzero_si128(); + coefficients128_4 = _mm_setzero_si128(); + coefficients128_8 = _mm_setzero_si128(); + samples128_0 = _mm_setzero_si128(); + samples128_4 = _mm_setzero_si128(); + samples128_8 = _mm_setzero_si128(); +#if 1 + { + int runningOrder = order; + if (runningOrder >= 4) { + coefficients128_0 = _mm_loadu_si128((const __m128i*)(coefficients + 0)); + samples128_0 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 4)); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: coefficients128_0 = _mm_set_epi32(0, coefficients[2], coefficients[1], coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], pSamplesOut[-2], pSamplesOut[-3], 0); break; + case 2: coefficients128_0 = _mm_set_epi32(0, 0, coefficients[1], coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], pSamplesOut[-2], 0, 0); break; + case 1: coefficients128_0 = _mm_set_epi32(0, 0, 0, coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], 0, 0, 0); break; + } + runningOrder = 0; + } + if (runningOrder >= 4) { + coefficients128_4 = _mm_loadu_si128((const __m128i*)(coefficients + 4)); + samples128_4 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 8)); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: coefficients128_4 = _mm_set_epi32(0, coefficients[6], coefficients[5], coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], pSamplesOut[-6], pSamplesOut[-7], 0); break; + case 2: coefficients128_4 = _mm_set_epi32(0, 0, coefficients[5], coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], pSamplesOut[-6], 0, 0); break; + case 1: coefficients128_4 = _mm_set_epi32(0, 0, 0, coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], 0, 0, 0); break; + } + runningOrder = 0; + } + if (runningOrder == 4) { + coefficients128_8 = _mm_loadu_si128((const __m128i*)(coefficients + 8)); + samples128_8 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 12)); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: coefficients128_8 = _mm_set_epi32(0, coefficients[10], coefficients[9], coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], pSamplesOut[-10], pSamplesOut[-11], 0); break; + case 2: coefficients128_8 = _mm_set_epi32(0, 0, coefficients[9], coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], pSamplesOut[-10], 0, 0); break; + case 1: coefficients128_8 = _mm_set_epi32(0, 0, 0, coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], 0, 0, 0); break; + } + runningOrder = 0; + } + coefficients128_0 = _mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(0, 1, 2, 3)); + coefficients128_4 = _mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(0, 1, 2, 3)); + coefficients128_8 = _mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(0, 1, 2, 3)); + } +#else + switch (order) + { + case 12: ((ma_int32*)&coefficients128_8)[0] = coefficients[11]; ((ma_int32*)&samples128_8)[0] = pDecodedSamples[-12]; + case 11: ((ma_int32*)&coefficients128_8)[1] = coefficients[10]; ((ma_int32*)&samples128_8)[1] = pDecodedSamples[-11]; + case 10: ((ma_int32*)&coefficients128_8)[2] = coefficients[ 9]; ((ma_int32*)&samples128_8)[2] = pDecodedSamples[-10]; + case 9: ((ma_int32*)&coefficients128_8)[3] = coefficients[ 8]; ((ma_int32*)&samples128_8)[3] = pDecodedSamples[- 9]; + case 8: ((ma_int32*)&coefficients128_4)[0] = coefficients[ 7]; ((ma_int32*)&samples128_4)[0] = pDecodedSamples[- 8]; + case 7: ((ma_int32*)&coefficients128_4)[1] = coefficients[ 6]; ((ma_int32*)&samples128_4)[1] = pDecodedSamples[- 7]; + case 6: ((ma_int32*)&coefficients128_4)[2] = coefficients[ 5]; ((ma_int32*)&samples128_4)[2] = pDecodedSamples[- 6]; + case 5: ((ma_int32*)&coefficients128_4)[3] = coefficients[ 4]; ((ma_int32*)&samples128_4)[3] = pDecodedSamples[- 5]; + case 4: ((ma_int32*)&coefficients128_0)[0] = coefficients[ 3]; ((ma_int32*)&samples128_0)[0] = pDecodedSamples[- 4]; + case 3: ((ma_int32*)&coefficients128_0)[1] = coefficients[ 2]; ((ma_int32*)&samples128_0)[1] = pDecodedSamples[- 3]; + case 2: ((ma_int32*)&coefficients128_0)[2] = coefficients[ 1]; ((ma_int32*)&samples128_0)[2] = pDecodedSamples[- 2]; + case 1: ((ma_int32*)&coefficients128_0)[3] = coefficients[ 0]; ((ma_int32*)&samples128_0)[3] = pDecodedSamples[- 1]; + } +#endif + while (pDecodedSamples < pDecodedSamplesEnd) { + __m128i zeroCountPart128; + __m128i riceParamPart128; + if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0) || + !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts1, &riceParamParts1) || + !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts2, &riceParamParts2) || + !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts3, &riceParamParts3)) { + return MA_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_add_epi32(ma_dr_flac__mm_not_si128(_mm_and_si128(riceParamPart128, _mm_set1_epi32(1))), _mm_set1_epi32(1))); + for (i = 0; i < 4; i += 1) { + prediction128 = _mm_xor_si128(prediction128, prediction128); + switch (order) + { + case 12: + case 11: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(1, 1, 0, 0)), _mm_shuffle_epi32(samples128_8, _MM_SHUFFLE(1, 1, 0, 0)))); + case 10: + case 9: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(3, 3, 2, 2)), _mm_shuffle_epi32(samples128_8, _MM_SHUFFLE(3, 3, 2, 2)))); + case 8: + case 7: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(1, 1, 0, 0)), _mm_shuffle_epi32(samples128_4, _MM_SHUFFLE(1, 1, 0, 0)))); + case 6: + case 5: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(3, 3, 2, 2)), _mm_shuffle_epi32(samples128_4, _MM_SHUFFLE(3, 3, 2, 2)))); + case 4: + case 3: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(1, 1, 0, 0)), _mm_shuffle_epi32(samples128_0, _MM_SHUFFLE(1, 1, 0, 0)))); + case 2: + case 1: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(3, 3, 2, 2)), _mm_shuffle_epi32(samples128_0, _MM_SHUFFLE(3, 3, 2, 2)))); + } + prediction128 = ma_dr_flac__mm_hadd_epi64(prediction128); + prediction128 = ma_dr_flac__mm_srai_epi64(prediction128, shift); + prediction128 = _mm_add_epi32(riceParamPart128, prediction128); + samples128_8 = _mm_alignr_epi8(samples128_4, samples128_8, 4); + samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4); + samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4); + riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4); + } + _mm_storeu_si128((__m128i*)pDecodedSamples, samples128_0); + pDecodedSamples += 4; + } + i = (count & ~3); + while (i < (int)count) { + if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0)) { + return MA_FALSE; + } + riceParamParts0 &= riceParamMask; + riceParamParts0 |= (zeroCountParts0 << riceParam); + riceParamParts0 = (riceParamParts0 >> 1) ^ t[riceParamParts0 & 0x01]; + pDecodedSamples[0] = riceParamParts0 + ma_dr_flac__calculate_prediction_64(order, shift, coefficients, pDecodedSamples); + i += 1; + pDecodedSamples += 1; + } + return MA_TRUE; +} +static ma_bool32 ma_dr_flac__decode_samples_with_residual__rice__sse41(ma_dr_flac_bs* bs, ma_uint32 bitsPerSample, ma_uint32 count, ma_uint8 riceParam, ma_uint32 lpcOrder, ma_int32 lpcShift, ma_uint32 lpcPrecision, const ma_int32* coefficients, ma_int32* pSamplesOut) +{ + MA_DR_FLAC_ASSERT(bs != NULL); + MA_DR_FLAC_ASSERT(pSamplesOut != NULL); + if (lpcOrder > 0 && lpcOrder <= 12) { + if (ma_dr_flac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) { + return ma_dr_flac__decode_samples_with_residual__rice__sse41_64(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut); + } else { + return ma_dr_flac__decode_samples_with_residual__rice__sse41_32(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut); + } + } else { + return ma_dr_flac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut); + } +} +#endif +#if defined(MA_DR_FLAC_SUPPORT_NEON) +static MA_INLINE void ma_dr_flac__vst2q_s32(ma_int32* p, int32x4x2_t x) +{ + vst1q_s32(p+0, x.val[0]); + vst1q_s32(p+4, x.val[1]); +} +static MA_INLINE void ma_dr_flac__vst2q_u32(ma_uint32* p, uint32x4x2_t x) +{ + vst1q_u32(p+0, x.val[0]); + vst1q_u32(p+4, x.val[1]); +} +static MA_INLINE void ma_dr_flac__vst2q_f32(float* p, float32x4x2_t x) +{ + vst1q_f32(p+0, x.val[0]); + vst1q_f32(p+4, x.val[1]); +} +static MA_INLINE void ma_dr_flac__vst2q_s16(ma_int16* p, int16x4x2_t x) +{ + vst1q_s16(p, vcombine_s16(x.val[0], x.val[1])); +} +static MA_INLINE void ma_dr_flac__vst2q_u16(ma_uint16* p, uint16x4x2_t x) +{ + vst1q_u16(p, vcombine_u16(x.val[0], x.val[1])); +} +static MA_INLINE int32x4_t ma_dr_flac__vdupq_n_s32x4(ma_int32 x3, ma_int32 x2, ma_int32 x1, ma_int32 x0) +{ + ma_int32 x[4]; + x[3] = x3; + x[2] = x2; + x[1] = x1; + x[0] = x0; + return vld1q_s32(x); +} +static MA_INLINE int32x4_t ma_dr_flac__valignrq_s32_1(int32x4_t a, int32x4_t b) +{ + return vextq_s32(b, a, 1); +} +static MA_INLINE uint32x4_t ma_dr_flac__valignrq_u32_1(uint32x4_t a, uint32x4_t b) +{ + return vextq_u32(b, a, 1); +} +static MA_INLINE int32x2_t ma_dr_flac__vhaddq_s32(int32x4_t x) +{ + int32x2_t r = vadd_s32(vget_high_s32(x), vget_low_s32(x)); + return vpadd_s32(r, r); +} +static MA_INLINE int64x1_t ma_dr_flac__vhaddq_s64(int64x2_t x) +{ + return vadd_s64(vget_high_s64(x), vget_low_s64(x)); +} +static MA_INLINE int32x4_t ma_dr_flac__vrevq_s32(int32x4_t x) +{ + return vrev64q_s32(vcombine_s32(vget_high_s32(x), vget_low_s32(x))); +} +static MA_INLINE int32x4_t ma_dr_flac__vnotq_s32(int32x4_t x) +{ + return veorq_s32(x, vdupq_n_s32(0xFFFFFFFF)); +} +static MA_INLINE uint32x4_t ma_dr_flac__vnotq_u32(uint32x4_t x) +{ + return veorq_u32(x, vdupq_n_u32(0xFFFFFFFF)); +} +static ma_bool32 ma_dr_flac__decode_samples_with_residual__rice__neon_32(ma_dr_flac_bs* bs, ma_uint32 count, ma_uint8 riceParam, ma_uint32 order, ma_int32 shift, const ma_int32* coefficients, ma_int32* pSamplesOut) +{ + int i; + ma_uint32 riceParamMask; + ma_int32* pDecodedSamples = pSamplesOut; + ma_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3); + ma_uint32 zeroCountParts[4]; + ma_uint32 riceParamParts[4]; + int32x4_t coefficients128_0; + int32x4_t coefficients128_4; + int32x4_t coefficients128_8; + int32x4_t samples128_0; + int32x4_t samples128_4; + int32x4_t samples128_8; + uint32x4_t riceParamMask128; + int32x4_t riceParam128; + int32x2_t shift64; + uint32x4_t one128; + const ma_uint32 t[2] = {0x00000000, 0xFFFFFFFF}; + riceParamMask = (ma_uint32)~((~0UL) << riceParam); + riceParamMask128 = vdupq_n_u32(riceParamMask); + riceParam128 = vdupq_n_s32(riceParam); + shift64 = vdup_n_s32(-shift); + one128 = vdupq_n_u32(1); + { + int runningOrder = order; + ma_int32 tempC[4] = {0, 0, 0, 0}; + ma_int32 tempS[4] = {0, 0, 0, 0}; + if (runningOrder >= 4) { + coefficients128_0 = vld1q_s32(coefficients + 0); + samples128_0 = vld1q_s32(pSamplesOut - 4); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: tempC[2] = coefficients[2]; tempS[1] = pSamplesOut[-3]; + case 2: tempC[1] = coefficients[1]; tempS[2] = pSamplesOut[-2]; + case 1: tempC[0] = coefficients[0]; tempS[3] = pSamplesOut[-1]; + } + coefficients128_0 = vld1q_s32(tempC); + samples128_0 = vld1q_s32(tempS); + runningOrder = 0; + } + if (runningOrder >= 4) { + coefficients128_4 = vld1q_s32(coefficients + 4); + samples128_4 = vld1q_s32(pSamplesOut - 8); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: tempC[2] = coefficients[6]; tempS[1] = pSamplesOut[-7]; + case 2: tempC[1] = coefficients[5]; tempS[2] = pSamplesOut[-6]; + case 1: tempC[0] = coefficients[4]; tempS[3] = pSamplesOut[-5]; + } + coefficients128_4 = vld1q_s32(tempC); + samples128_4 = vld1q_s32(tempS); + runningOrder = 0; + } + if (runningOrder == 4) { + coefficients128_8 = vld1q_s32(coefficients + 8); + samples128_8 = vld1q_s32(pSamplesOut - 12); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: tempC[2] = coefficients[10]; tempS[1] = pSamplesOut[-11]; + case 2: tempC[1] = coefficients[ 9]; tempS[2] = pSamplesOut[-10]; + case 1: tempC[0] = coefficients[ 8]; tempS[3] = pSamplesOut[- 9]; + } + coefficients128_8 = vld1q_s32(tempC); + samples128_8 = vld1q_s32(tempS); + runningOrder = 0; + } + coefficients128_0 = ma_dr_flac__vrevq_s32(coefficients128_0); + coefficients128_4 = ma_dr_flac__vrevq_s32(coefficients128_4); + coefficients128_8 = ma_dr_flac__vrevq_s32(coefficients128_8); + } + while (pDecodedSamples < pDecodedSamplesEnd) { + int32x4_t prediction128; + int32x2_t prediction64; + uint32x4_t zeroCountPart128; + uint32x4_t riceParamPart128; + if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0]) || + !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[1], &riceParamParts[1]) || + !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[2], &riceParamParts[2]) || + !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[3], &riceParamParts[3])) { + return MA_FALSE; + } + zeroCountPart128 = vld1q_u32(zeroCountParts); + riceParamPart128 = vld1q_u32(riceParamParts); + riceParamPart128 = vandq_u32(riceParamPart128, riceParamMask128); + riceParamPart128 = vorrq_u32(riceParamPart128, vshlq_u32(zeroCountPart128, riceParam128)); + riceParamPart128 = veorq_u32(vshrq_n_u32(riceParamPart128, 1), vaddq_u32(ma_dr_flac__vnotq_u32(vandq_u32(riceParamPart128, one128)), one128)); + if (order <= 4) { + for (i = 0; i < 4; i += 1) { + prediction128 = vmulq_s32(coefficients128_0, samples128_0); + prediction64 = ma_dr_flac__vhaddq_s32(prediction128); + prediction64 = vshl_s32(prediction64, shift64); + prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128))); + samples128_0 = ma_dr_flac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0); + riceParamPart128 = ma_dr_flac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128); + } + } else if (order <= 8) { + for (i = 0; i < 4; i += 1) { + prediction128 = vmulq_s32(coefficients128_4, samples128_4); + prediction128 = vmlaq_s32(prediction128, coefficients128_0, samples128_0); + prediction64 = ma_dr_flac__vhaddq_s32(prediction128); + prediction64 = vshl_s32(prediction64, shift64); + prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128))); + samples128_4 = ma_dr_flac__valignrq_s32_1(samples128_0, samples128_4); + samples128_0 = ma_dr_flac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0); + riceParamPart128 = ma_dr_flac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128); + } + } else { + for (i = 0; i < 4; i += 1) { + prediction128 = vmulq_s32(coefficients128_8, samples128_8); + prediction128 = vmlaq_s32(prediction128, coefficients128_4, samples128_4); + prediction128 = vmlaq_s32(prediction128, coefficients128_0, samples128_0); + prediction64 = ma_dr_flac__vhaddq_s32(prediction128); + prediction64 = vshl_s32(prediction64, shift64); + prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128))); + samples128_8 = ma_dr_flac__valignrq_s32_1(samples128_4, samples128_8); + samples128_4 = ma_dr_flac__valignrq_s32_1(samples128_0, samples128_4); + samples128_0 = ma_dr_flac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0); + riceParamPart128 = ma_dr_flac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128); + } + } + vst1q_s32(pDecodedSamples, samples128_0); + pDecodedSamples += 4; + } + i = (count & ~3); + while (i < (int)count) { + if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0])) { + return MA_FALSE; + } + riceParamParts[0] &= riceParamMask; + riceParamParts[0] |= (zeroCountParts[0] << riceParam); + riceParamParts[0] = (riceParamParts[0] >> 1) ^ t[riceParamParts[0] & 0x01]; + pDecodedSamples[0] = riceParamParts[0] + ma_dr_flac__calculate_prediction_32(order, shift, coefficients, pDecodedSamples); + i += 1; + pDecodedSamples += 1; + } + return MA_TRUE; +} +static ma_bool32 ma_dr_flac__decode_samples_with_residual__rice__neon_64(ma_dr_flac_bs* bs, ma_uint32 count, ma_uint8 riceParam, ma_uint32 order, ma_int32 shift, const ma_int32* coefficients, ma_int32* pSamplesOut) +{ + int i; + ma_uint32 riceParamMask; + ma_int32* pDecodedSamples = pSamplesOut; + ma_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3); + ma_uint32 zeroCountParts[4]; + ma_uint32 riceParamParts[4]; + int32x4_t coefficients128_0; + int32x4_t coefficients128_4; + int32x4_t coefficients128_8; + int32x4_t samples128_0; + int32x4_t samples128_4; + int32x4_t samples128_8; + uint32x4_t riceParamMask128; + int32x4_t riceParam128; + int64x1_t shift64; + uint32x4_t one128; + int64x2_t prediction128 = { 0 }; + uint32x4_t zeroCountPart128; + uint32x4_t riceParamPart128; + const ma_uint32 t[2] = {0x00000000, 0xFFFFFFFF}; + riceParamMask = (ma_uint32)~((~0UL) << riceParam); + riceParamMask128 = vdupq_n_u32(riceParamMask); + riceParam128 = vdupq_n_s32(riceParam); + shift64 = vdup_n_s64(-shift); + one128 = vdupq_n_u32(1); + { + int runningOrder = order; + ma_int32 tempC[4] = {0, 0, 0, 0}; + ma_int32 tempS[4] = {0, 0, 0, 0}; + if (runningOrder >= 4) { + coefficients128_0 = vld1q_s32(coefficients + 0); + samples128_0 = vld1q_s32(pSamplesOut - 4); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: tempC[2] = coefficients[2]; tempS[1] = pSamplesOut[-3]; + case 2: tempC[1] = coefficients[1]; tempS[2] = pSamplesOut[-2]; + case 1: tempC[0] = coefficients[0]; tempS[3] = pSamplesOut[-1]; + } + coefficients128_0 = vld1q_s32(tempC); + samples128_0 = vld1q_s32(tempS); + runningOrder = 0; + } + if (runningOrder >= 4) { + coefficients128_4 = vld1q_s32(coefficients + 4); + samples128_4 = vld1q_s32(pSamplesOut - 8); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: tempC[2] = coefficients[6]; tempS[1] = pSamplesOut[-7]; + case 2: tempC[1] = coefficients[5]; tempS[2] = pSamplesOut[-6]; + case 1: tempC[0] = coefficients[4]; tempS[3] = pSamplesOut[-5]; + } + coefficients128_4 = vld1q_s32(tempC); + samples128_4 = vld1q_s32(tempS); + runningOrder = 0; + } + if (runningOrder == 4) { + coefficients128_8 = vld1q_s32(coefficients + 8); + samples128_8 = vld1q_s32(pSamplesOut - 12); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: tempC[2] = coefficients[10]; tempS[1] = pSamplesOut[-11]; + case 2: tempC[1] = coefficients[ 9]; tempS[2] = pSamplesOut[-10]; + case 1: tempC[0] = coefficients[ 8]; tempS[3] = pSamplesOut[- 9]; + } + coefficients128_8 = vld1q_s32(tempC); + samples128_8 = vld1q_s32(tempS); + runningOrder = 0; + } + coefficients128_0 = ma_dr_flac__vrevq_s32(coefficients128_0); + coefficients128_4 = ma_dr_flac__vrevq_s32(coefficients128_4); + coefficients128_8 = ma_dr_flac__vrevq_s32(coefficients128_8); + } + while (pDecodedSamples < pDecodedSamplesEnd) { + if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0]) || + !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[1], &riceParamParts[1]) || + !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[2], &riceParamParts[2]) || + !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[3], &riceParamParts[3])) { + return MA_FALSE; + } + zeroCountPart128 = vld1q_u32(zeroCountParts); + riceParamPart128 = vld1q_u32(riceParamParts); + riceParamPart128 = vandq_u32(riceParamPart128, riceParamMask128); + riceParamPart128 = vorrq_u32(riceParamPart128, vshlq_u32(zeroCountPart128, riceParam128)); + riceParamPart128 = veorq_u32(vshrq_n_u32(riceParamPart128, 1), vaddq_u32(ma_dr_flac__vnotq_u32(vandq_u32(riceParamPart128, one128)), one128)); + for (i = 0; i < 4; i += 1) { + int64x1_t prediction64; + prediction128 = veorq_s64(prediction128, prediction128); + switch (order) + { + case 12: + case 11: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_8), vget_low_s32(samples128_8))); + case 10: + case 9: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_8), vget_high_s32(samples128_8))); + case 8: + case 7: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_4), vget_low_s32(samples128_4))); + case 6: + case 5: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_4), vget_high_s32(samples128_4))); + case 4: + case 3: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_0), vget_low_s32(samples128_0))); + case 2: + case 1: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_0), vget_high_s32(samples128_0))); + } + prediction64 = ma_dr_flac__vhaddq_s64(prediction128); + prediction64 = vshl_s64(prediction64, shift64); + prediction64 = vadd_s64(prediction64, vdup_n_s64(vgetq_lane_u32(riceParamPart128, 0))); + samples128_8 = ma_dr_flac__valignrq_s32_1(samples128_4, samples128_8); + samples128_4 = ma_dr_flac__valignrq_s32_1(samples128_0, samples128_4); + samples128_0 = ma_dr_flac__valignrq_s32_1(vcombine_s32(vreinterpret_s32_s64(prediction64), vdup_n_s32(0)), samples128_0); + riceParamPart128 = ma_dr_flac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128); + } + vst1q_s32(pDecodedSamples, samples128_0); + pDecodedSamples += 4; + } + i = (count & ~3); + while (i < (int)count) { + if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0])) { + return MA_FALSE; + } + riceParamParts[0] &= riceParamMask; + riceParamParts[0] |= (zeroCountParts[0] << riceParam); + riceParamParts[0] = (riceParamParts[0] >> 1) ^ t[riceParamParts[0] & 0x01]; + pDecodedSamples[0] = riceParamParts[0] + ma_dr_flac__calculate_prediction_64(order, shift, coefficients, pDecodedSamples); + i += 1; + pDecodedSamples += 1; + } + return MA_TRUE; +} +static ma_bool32 ma_dr_flac__decode_samples_with_residual__rice__neon(ma_dr_flac_bs* bs, ma_uint32 bitsPerSample, ma_uint32 count, ma_uint8 riceParam, ma_uint32 lpcOrder, ma_int32 lpcShift, ma_uint32 lpcPrecision, const ma_int32* coefficients, ma_int32* pSamplesOut) +{ + MA_DR_FLAC_ASSERT(bs != NULL); + MA_DR_FLAC_ASSERT(pSamplesOut != NULL); + if (lpcOrder > 0 && lpcOrder <= 12) { + if (ma_dr_flac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) { + return ma_dr_flac__decode_samples_with_residual__rice__neon_64(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut); + } else { + return ma_dr_flac__decode_samples_with_residual__rice__neon_32(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut); + } + } else { + return ma_dr_flac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut); + } +} +#endif +static ma_bool32 ma_dr_flac__decode_samples_with_residual__rice(ma_dr_flac_bs* bs, ma_uint32 bitsPerSample, ma_uint32 count, ma_uint8 riceParam, ma_uint32 lpcOrder, ma_int32 lpcShift, ma_uint32 lpcPrecision, const ma_int32* coefficients, ma_int32* pSamplesOut) +{ +#if defined(MA_DR_FLAC_SUPPORT_SSE41) + if (ma_dr_flac__gIsSSE41Supported) { + return ma_dr_flac__decode_samples_with_residual__rice__sse41(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut); + } else +#elif defined(MA_DR_FLAC_SUPPORT_NEON) + if (ma_dr_flac__gIsNEONSupported) { + return ma_dr_flac__decode_samples_with_residual__rice__neon(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut); + } else +#endif + { + #if 0 + return ma_dr_flac__decode_samples_with_residual__rice__reference(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut); + #else + return ma_dr_flac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut); + #endif + } +} +static ma_bool32 ma_dr_flac__read_and_seek_residual__rice(ma_dr_flac_bs* bs, ma_uint32 count, ma_uint8 riceParam) +{ + ma_uint32 i; + MA_DR_FLAC_ASSERT(bs != NULL); + for (i = 0; i < count; ++i) { + if (!ma_dr_flac__seek_rice_parts(bs, riceParam)) { + return MA_FALSE; + } + } + return MA_TRUE; +} +#if defined(__clang__) +__attribute__((no_sanitize("signed-integer-overflow"))) +#endif +static ma_bool32 ma_dr_flac__decode_samples_with_residual__unencoded(ma_dr_flac_bs* bs, ma_uint32 bitsPerSample, ma_uint32 count, ma_uint8 unencodedBitsPerSample, ma_uint32 lpcOrder, ma_int32 lpcShift, ma_uint32 lpcPrecision, const ma_int32* coefficients, ma_int32* pSamplesOut) +{ + ma_uint32 i; + MA_DR_FLAC_ASSERT(bs != NULL); + MA_DR_FLAC_ASSERT(unencodedBitsPerSample <= 31); + MA_DR_FLAC_ASSERT(pSamplesOut != NULL); + for (i = 0; i < count; ++i) { + if (unencodedBitsPerSample > 0) { + if (!ma_dr_flac__read_int32(bs, unencodedBitsPerSample, pSamplesOut + i)) { + return MA_FALSE; + } + } else { + pSamplesOut[i] = 0; + } + if (ma_dr_flac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) { + pSamplesOut[i] += ma_dr_flac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + i); + } else { + pSamplesOut[i] += ma_dr_flac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + i); + } + } + return MA_TRUE; +} +static ma_bool32 ma_dr_flac__decode_samples_with_residual(ma_dr_flac_bs* bs, ma_uint32 bitsPerSample, ma_uint32 blockSize, ma_uint32 lpcOrder, ma_int32 lpcShift, ma_uint32 lpcPrecision, const ma_int32* coefficients, ma_int32* pDecodedSamples) +{ + ma_uint8 residualMethod; + ma_uint8 partitionOrder; + ma_uint32 samplesInPartition; + ma_uint32 partitionsRemaining; + MA_DR_FLAC_ASSERT(bs != NULL); + MA_DR_FLAC_ASSERT(blockSize != 0); + MA_DR_FLAC_ASSERT(pDecodedSamples != NULL); + if (!ma_dr_flac__read_uint8(bs, 2, &residualMethod)) { + return MA_FALSE; + } + if (residualMethod != MA_DR_FLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != MA_DR_FLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) { + return MA_FALSE; + } + pDecodedSamples += lpcOrder; + if (!ma_dr_flac__read_uint8(bs, 4, &partitionOrder)) { + return MA_FALSE; + } + if (partitionOrder > 8) { + return MA_FALSE; + } + if ((blockSize / (1 << partitionOrder)) < lpcOrder) { + return MA_FALSE; + } + samplesInPartition = (blockSize / (1 << partitionOrder)) - lpcOrder; + partitionsRemaining = (1 << partitionOrder); + for (;;) { + ma_uint8 riceParam = 0; + if (residualMethod == MA_DR_FLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) { + if (!ma_dr_flac__read_uint8(bs, 4, &riceParam)) { + return MA_FALSE; + } + if (riceParam == 15) { + riceParam = 0xFF; + } + } else if (residualMethod == MA_DR_FLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) { + if (!ma_dr_flac__read_uint8(bs, 5, &riceParam)) { + return MA_FALSE; + } + if (riceParam == 31) { + riceParam = 0xFF; + } + } + if (riceParam != 0xFF) { + if (!ma_dr_flac__decode_samples_with_residual__rice(bs, bitsPerSample, samplesInPartition, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) { + return MA_FALSE; + } + } else { + ma_uint8 unencodedBitsPerSample = 0; + if (!ma_dr_flac__read_uint8(bs, 5, &unencodedBitsPerSample)) { + return MA_FALSE; + } + if (!ma_dr_flac__decode_samples_with_residual__unencoded(bs, bitsPerSample, samplesInPartition, unencodedBitsPerSample, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) { + return MA_FALSE; + } + } + pDecodedSamples += samplesInPartition; + if (partitionsRemaining == 1) { + break; + } + partitionsRemaining -= 1; + if (partitionOrder != 0) { + samplesInPartition = blockSize / (1 << partitionOrder); + } + } + return MA_TRUE; +} +static ma_bool32 ma_dr_flac__read_and_seek_residual(ma_dr_flac_bs* bs, ma_uint32 blockSize, ma_uint32 order) +{ + ma_uint8 residualMethod; + ma_uint8 partitionOrder; + ma_uint32 samplesInPartition; + ma_uint32 partitionsRemaining; + MA_DR_FLAC_ASSERT(bs != NULL); + MA_DR_FLAC_ASSERT(blockSize != 0); + if (!ma_dr_flac__read_uint8(bs, 2, &residualMethod)) { + return MA_FALSE; + } + if (residualMethod != MA_DR_FLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != MA_DR_FLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) { + return MA_FALSE; + } + if (!ma_dr_flac__read_uint8(bs, 4, &partitionOrder)) { + return MA_FALSE; + } + if (partitionOrder > 8) { + return MA_FALSE; + } + if ((blockSize / (1 << partitionOrder)) <= order) { + return MA_FALSE; + } + samplesInPartition = (blockSize / (1 << partitionOrder)) - order; + partitionsRemaining = (1 << partitionOrder); + for (;;) + { + ma_uint8 riceParam = 0; + if (residualMethod == MA_DR_FLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) { + if (!ma_dr_flac__read_uint8(bs, 4, &riceParam)) { + return MA_FALSE; + } + if (riceParam == 15) { + riceParam = 0xFF; + } + } else if (residualMethod == MA_DR_FLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) { + if (!ma_dr_flac__read_uint8(bs, 5, &riceParam)) { + return MA_FALSE; + } + if (riceParam == 31) { + riceParam = 0xFF; + } + } + if (riceParam != 0xFF) { + if (!ma_dr_flac__read_and_seek_residual__rice(bs, samplesInPartition, riceParam)) { + return MA_FALSE; + } + } else { + ma_uint8 unencodedBitsPerSample = 0; + if (!ma_dr_flac__read_uint8(bs, 5, &unencodedBitsPerSample)) { + return MA_FALSE; + } + if (!ma_dr_flac__seek_bits(bs, unencodedBitsPerSample * samplesInPartition)) { + return MA_FALSE; + } + } + if (partitionsRemaining == 1) { + break; + } + partitionsRemaining -= 1; + samplesInPartition = blockSize / (1 << partitionOrder); + } + return MA_TRUE; +} +static ma_bool32 ma_dr_flac__decode_samples__constant(ma_dr_flac_bs* bs, ma_uint32 blockSize, ma_uint32 subframeBitsPerSample, ma_int32* pDecodedSamples) +{ + ma_uint32 i; + ma_int32 sample; + if (!ma_dr_flac__read_int32(bs, subframeBitsPerSample, &sample)) { + return MA_FALSE; + } + for (i = 0; i < blockSize; ++i) { + pDecodedSamples[i] = sample; + } + return MA_TRUE; +} +static ma_bool32 ma_dr_flac__decode_samples__verbatim(ma_dr_flac_bs* bs, ma_uint32 blockSize, ma_uint32 subframeBitsPerSample, ma_int32* pDecodedSamples) +{ + ma_uint32 i; + for (i = 0; i < blockSize; ++i) { + ma_int32 sample; + if (!ma_dr_flac__read_int32(bs, subframeBitsPerSample, &sample)) { + return MA_FALSE; + } + pDecodedSamples[i] = sample; + } + return MA_TRUE; +} +static ma_bool32 ma_dr_flac__decode_samples__fixed(ma_dr_flac_bs* bs, ma_uint32 blockSize, ma_uint32 subframeBitsPerSample, ma_uint8 lpcOrder, ma_int32* pDecodedSamples) +{ + ma_uint32 i; + static ma_int32 lpcCoefficientsTable[5][4] = { + {0, 0, 0, 0}, + {1, 0, 0, 0}, + {2, -1, 0, 0}, + {3, -3, 1, 0}, + {4, -6, 4, -1} + }; + for (i = 0; i < lpcOrder; ++i) { + ma_int32 sample; + if (!ma_dr_flac__read_int32(bs, subframeBitsPerSample, &sample)) { + return MA_FALSE; + } + pDecodedSamples[i] = sample; + } + if (!ma_dr_flac__decode_samples_with_residual(bs, subframeBitsPerSample, blockSize, lpcOrder, 0, 4, lpcCoefficientsTable[lpcOrder], pDecodedSamples)) { + return MA_FALSE; + } + return MA_TRUE; +} +static ma_bool32 ma_dr_flac__decode_samples__lpc(ma_dr_flac_bs* bs, ma_uint32 blockSize, ma_uint32 bitsPerSample, ma_uint8 lpcOrder, ma_int32* pDecodedSamples) +{ + ma_uint8 i; + ma_uint8 lpcPrecision; + ma_int8 lpcShift; + ma_int32 coefficients[32]; + for (i = 0; i < lpcOrder; ++i) { + ma_int32 sample; + if (!ma_dr_flac__read_int32(bs, bitsPerSample, &sample)) { + return MA_FALSE; + } + pDecodedSamples[i] = sample; + } + if (!ma_dr_flac__read_uint8(bs, 4, &lpcPrecision)) { + return MA_FALSE; + } + if (lpcPrecision == 15) { + return MA_FALSE; + } + lpcPrecision += 1; + if (!ma_dr_flac__read_int8(bs, 5, &lpcShift)) { + return MA_FALSE; + } + if (lpcShift < 0) { + return MA_FALSE; + } + MA_DR_FLAC_ZERO_MEMORY(coefficients, sizeof(coefficients)); + for (i = 0; i < lpcOrder; ++i) { + if (!ma_dr_flac__read_int32(bs, lpcPrecision, coefficients + i)) { + return MA_FALSE; + } + } + if (!ma_dr_flac__decode_samples_with_residual(bs, bitsPerSample, blockSize, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) { + return MA_FALSE; + } + return MA_TRUE; +} +static ma_bool32 ma_dr_flac__read_next_flac_frame_header(ma_dr_flac_bs* bs, ma_uint8 streaminfoBitsPerSample, ma_dr_flac_frame_header* header) +{ + const ma_uint32 sampleRateTable[12] = {0, 88200, 176400, 192000, 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000}; + const ma_uint8 bitsPerSampleTable[8] = {0, 8, 12, (ma_uint8)-1, 16, 20, 24, (ma_uint8)-1}; + MA_DR_FLAC_ASSERT(bs != NULL); + MA_DR_FLAC_ASSERT(header != NULL); + for (;;) { + ma_uint8 crc8 = 0xCE; + ma_uint8 reserved = 0; + ma_uint8 blockingStrategy = 0; + ma_uint8 blockSize = 0; + ma_uint8 sampleRate = 0; + ma_uint8 channelAssignment = 0; + ma_uint8 bitsPerSample = 0; + ma_bool32 isVariableBlockSize; + if (!ma_dr_flac__find_and_seek_to_next_sync_code(bs)) { + return MA_FALSE; + } + if (!ma_dr_flac__read_uint8(bs, 1, &reserved)) { + return MA_FALSE; + } + if (reserved == 1) { + continue; + } + crc8 = ma_dr_flac_crc8(crc8, reserved, 1); + if (!ma_dr_flac__read_uint8(bs, 1, &blockingStrategy)) { + return MA_FALSE; + } + crc8 = ma_dr_flac_crc8(crc8, blockingStrategy, 1); + if (!ma_dr_flac__read_uint8(bs, 4, &blockSize)) { + return MA_FALSE; + } + if (blockSize == 0) { + continue; + } + crc8 = ma_dr_flac_crc8(crc8, blockSize, 4); + if (!ma_dr_flac__read_uint8(bs, 4, &sampleRate)) { + return MA_FALSE; + } + crc8 = ma_dr_flac_crc8(crc8, sampleRate, 4); + if (!ma_dr_flac__read_uint8(bs, 4, &channelAssignment)) { + return MA_FALSE; + } + if (channelAssignment > 10) { + continue; + } + crc8 = ma_dr_flac_crc8(crc8, channelAssignment, 4); + if (!ma_dr_flac__read_uint8(bs, 3, &bitsPerSample)) { + return MA_FALSE; + } + if (bitsPerSample == 3 || bitsPerSample == 7) { + continue; + } + crc8 = ma_dr_flac_crc8(crc8, bitsPerSample, 3); + if (!ma_dr_flac__read_uint8(bs, 1, &reserved)) { + return MA_FALSE; + } + if (reserved == 1) { + continue; + } + crc8 = ma_dr_flac_crc8(crc8, reserved, 1); + isVariableBlockSize = blockingStrategy == 1; + if (isVariableBlockSize) { + ma_uint64 pcmFrameNumber; + ma_result result = ma_dr_flac__read_utf8_coded_number(bs, &pcmFrameNumber, &crc8); + if (result != MA_SUCCESS) { + if (result == MA_AT_END) { + return MA_FALSE; + } else { + continue; + } + } + header->flacFrameNumber = 0; + header->pcmFrameNumber = pcmFrameNumber; + } else { + ma_uint64 flacFrameNumber = 0; + ma_result result = ma_dr_flac__read_utf8_coded_number(bs, &flacFrameNumber, &crc8); + if (result != MA_SUCCESS) { + if (result == MA_AT_END) { + return MA_FALSE; + } else { + continue; + } + } + header->flacFrameNumber = (ma_uint32)flacFrameNumber; + header->pcmFrameNumber = 0; + } + MA_DR_FLAC_ASSERT(blockSize > 0); + if (blockSize == 1) { + header->blockSizeInPCMFrames = 192; + } else if (blockSize <= 5) { + MA_DR_FLAC_ASSERT(blockSize >= 2); + header->blockSizeInPCMFrames = 576 * (1 << (blockSize - 2)); + } else if (blockSize == 6) { + if (!ma_dr_flac__read_uint16(bs, 8, &header->blockSizeInPCMFrames)) { + return MA_FALSE; + } + crc8 = ma_dr_flac_crc8(crc8, header->blockSizeInPCMFrames, 8); + header->blockSizeInPCMFrames += 1; + } else if (blockSize == 7) { + if (!ma_dr_flac__read_uint16(bs, 16, &header->blockSizeInPCMFrames)) { + return MA_FALSE; + } + crc8 = ma_dr_flac_crc8(crc8, header->blockSizeInPCMFrames, 16); + if (header->blockSizeInPCMFrames == 0xFFFF) { + return MA_FALSE; + } + header->blockSizeInPCMFrames += 1; + } else { + MA_DR_FLAC_ASSERT(blockSize >= 8); + header->blockSizeInPCMFrames = 256 * (1 << (blockSize - 8)); + } + if (sampleRate <= 11) { + header->sampleRate = sampleRateTable[sampleRate]; + } else if (sampleRate == 12) { + if (!ma_dr_flac__read_uint32(bs, 8, &header->sampleRate)) { + return MA_FALSE; + } + crc8 = ma_dr_flac_crc8(crc8, header->sampleRate, 8); + header->sampleRate *= 1000; + } else if (sampleRate == 13) { + if (!ma_dr_flac__read_uint32(bs, 16, &header->sampleRate)) { + return MA_FALSE; + } + crc8 = ma_dr_flac_crc8(crc8, header->sampleRate, 16); + } else if (sampleRate == 14) { + if (!ma_dr_flac__read_uint32(bs, 16, &header->sampleRate)) { + return MA_FALSE; + } + crc8 = ma_dr_flac_crc8(crc8, header->sampleRate, 16); + header->sampleRate *= 10; + } else { + continue; + } + header->channelAssignment = channelAssignment; + header->bitsPerSample = bitsPerSampleTable[bitsPerSample]; + if (header->bitsPerSample == 0) { + header->bitsPerSample = streaminfoBitsPerSample; + } + if (header->bitsPerSample != streaminfoBitsPerSample) { + return MA_FALSE; + } + if (!ma_dr_flac__read_uint8(bs, 8, &header->crc8)) { + return MA_FALSE; + } +#ifndef MA_DR_FLAC_NO_CRC + if (header->crc8 != crc8) { + continue; + } +#endif + return MA_TRUE; + } +} +static ma_bool32 ma_dr_flac__read_subframe_header(ma_dr_flac_bs* bs, ma_dr_flac_subframe* pSubframe) +{ + ma_uint8 header; + int type; + if (!ma_dr_flac__read_uint8(bs, 8, &header)) { + return MA_FALSE; + } + if ((header & 0x80) != 0) { + return MA_FALSE; + } + type = (header & 0x7E) >> 1; + if (type == 0) { + pSubframe->subframeType = MA_DR_FLAC_SUBFRAME_CONSTANT; + } else if (type == 1) { + pSubframe->subframeType = MA_DR_FLAC_SUBFRAME_VERBATIM; + } else { + if ((type & 0x20) != 0) { + pSubframe->subframeType = MA_DR_FLAC_SUBFRAME_LPC; + pSubframe->lpcOrder = (ma_uint8)(type & 0x1F) + 1; + } else if ((type & 0x08) != 0) { + pSubframe->subframeType = MA_DR_FLAC_SUBFRAME_FIXED; + pSubframe->lpcOrder = (ma_uint8)(type & 0x07); + if (pSubframe->lpcOrder > 4) { + pSubframe->subframeType = MA_DR_FLAC_SUBFRAME_RESERVED; + pSubframe->lpcOrder = 0; + } + } else { + pSubframe->subframeType = MA_DR_FLAC_SUBFRAME_RESERVED; + } + } + if (pSubframe->subframeType == MA_DR_FLAC_SUBFRAME_RESERVED) { + return MA_FALSE; + } + pSubframe->wastedBitsPerSample = 0; + if ((header & 0x01) == 1) { + unsigned int wastedBitsPerSample; + if (!ma_dr_flac__seek_past_next_set_bit(bs, &wastedBitsPerSample)) { + return MA_FALSE; + } + pSubframe->wastedBitsPerSample = (ma_uint8)wastedBitsPerSample + 1; + } + return MA_TRUE; +} +static ma_bool32 ma_dr_flac__decode_subframe(ma_dr_flac_bs* bs, ma_dr_flac_frame* frame, int subframeIndex, ma_int32* pDecodedSamplesOut) +{ + ma_dr_flac_subframe* pSubframe; + ma_uint32 subframeBitsPerSample; + MA_DR_FLAC_ASSERT(bs != NULL); + MA_DR_FLAC_ASSERT(frame != NULL); + pSubframe = frame->subframes + subframeIndex; + if (!ma_dr_flac__read_subframe_header(bs, pSubframe)) { + return MA_FALSE; + } + subframeBitsPerSample = frame->header.bitsPerSample; + if ((frame->header.channelAssignment == MA_DR_FLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == MA_DR_FLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) { + subframeBitsPerSample += 1; + } else if (frame->header.channelAssignment == MA_DR_FLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) { + subframeBitsPerSample += 1; + } + if (subframeBitsPerSample > 32) { + return MA_FALSE; + } + if (pSubframe->wastedBitsPerSample >= subframeBitsPerSample) { + return MA_FALSE; + } + subframeBitsPerSample -= pSubframe->wastedBitsPerSample; + pSubframe->pSamplesS32 = pDecodedSamplesOut; + switch (pSubframe->subframeType) + { + case MA_DR_FLAC_SUBFRAME_CONSTANT: + { + ma_dr_flac__decode_samples__constant(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->pSamplesS32); + } break; + case MA_DR_FLAC_SUBFRAME_VERBATIM: + { + ma_dr_flac__decode_samples__verbatim(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->pSamplesS32); + } break; + case MA_DR_FLAC_SUBFRAME_FIXED: + { + ma_dr_flac__decode_samples__fixed(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->lpcOrder, pSubframe->pSamplesS32); + } break; + case MA_DR_FLAC_SUBFRAME_LPC: + { + ma_dr_flac__decode_samples__lpc(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->lpcOrder, pSubframe->pSamplesS32); + } break; + default: return MA_FALSE; + } + return MA_TRUE; +} +static ma_bool32 ma_dr_flac__seek_subframe(ma_dr_flac_bs* bs, ma_dr_flac_frame* frame, int subframeIndex) +{ + ma_dr_flac_subframe* pSubframe; + ma_uint32 subframeBitsPerSample; + MA_DR_FLAC_ASSERT(bs != NULL); + MA_DR_FLAC_ASSERT(frame != NULL); + pSubframe = frame->subframes + subframeIndex; + if (!ma_dr_flac__read_subframe_header(bs, pSubframe)) { + return MA_FALSE; + } + subframeBitsPerSample = frame->header.bitsPerSample; + if ((frame->header.channelAssignment == MA_DR_FLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == MA_DR_FLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) { + subframeBitsPerSample += 1; + } else if (frame->header.channelAssignment == MA_DR_FLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) { + subframeBitsPerSample += 1; + } + if (pSubframe->wastedBitsPerSample >= subframeBitsPerSample) { + return MA_FALSE; + } + subframeBitsPerSample -= pSubframe->wastedBitsPerSample; + pSubframe->pSamplesS32 = NULL; + switch (pSubframe->subframeType) + { + case MA_DR_FLAC_SUBFRAME_CONSTANT: + { + if (!ma_dr_flac__seek_bits(bs, subframeBitsPerSample)) { + return MA_FALSE; + } + } break; + case MA_DR_FLAC_SUBFRAME_VERBATIM: + { + unsigned int bitsToSeek = frame->header.blockSizeInPCMFrames * subframeBitsPerSample; + if (!ma_dr_flac__seek_bits(bs, bitsToSeek)) { + return MA_FALSE; + } + } break; + case MA_DR_FLAC_SUBFRAME_FIXED: + { + unsigned int bitsToSeek = pSubframe->lpcOrder * subframeBitsPerSample; + if (!ma_dr_flac__seek_bits(bs, bitsToSeek)) { + return MA_FALSE; + } + if (!ma_dr_flac__read_and_seek_residual(bs, frame->header.blockSizeInPCMFrames, pSubframe->lpcOrder)) { + return MA_FALSE; + } + } break; + case MA_DR_FLAC_SUBFRAME_LPC: + { + ma_uint8 lpcPrecision; + unsigned int bitsToSeek = pSubframe->lpcOrder * subframeBitsPerSample; + if (!ma_dr_flac__seek_bits(bs, bitsToSeek)) { + return MA_FALSE; + } + if (!ma_dr_flac__read_uint8(bs, 4, &lpcPrecision)) { + return MA_FALSE; + } + if (lpcPrecision == 15) { + return MA_FALSE; + } + lpcPrecision += 1; + bitsToSeek = (pSubframe->lpcOrder * lpcPrecision) + 5; + if (!ma_dr_flac__seek_bits(bs, bitsToSeek)) { + return MA_FALSE; + } + if (!ma_dr_flac__read_and_seek_residual(bs, frame->header.blockSizeInPCMFrames, pSubframe->lpcOrder)) { + return MA_FALSE; + } + } break; + default: return MA_FALSE; + } + return MA_TRUE; +} +static MA_INLINE ma_uint8 ma_dr_flac__get_channel_count_from_channel_assignment(ma_int8 channelAssignment) +{ + ma_uint8 lookup[] = {1, 2, 3, 4, 5, 6, 7, 8, 2, 2, 2}; + MA_DR_FLAC_ASSERT(channelAssignment <= 10); + return lookup[channelAssignment]; +} +static ma_result ma_dr_flac__decode_flac_frame(ma_dr_flac* pFlac) +{ + int channelCount; + int i; + ma_uint8 paddingSizeInBits; + ma_uint16 desiredCRC16; +#ifndef MA_DR_FLAC_NO_CRC + ma_uint16 actualCRC16; +#endif + MA_DR_FLAC_ZERO_MEMORY(pFlac->currentFLACFrame.subframes, sizeof(pFlac->currentFLACFrame.subframes)); + if (pFlac->currentFLACFrame.header.blockSizeInPCMFrames > pFlac->maxBlockSizeInPCMFrames) { + return MA_ERROR; + } + channelCount = ma_dr_flac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment); + if (channelCount != (int)pFlac->channels) { + return MA_ERROR; + } + for (i = 0; i < channelCount; ++i) { + if (!ma_dr_flac__decode_subframe(&pFlac->bs, &pFlac->currentFLACFrame, i, pFlac->pDecodedSamples + (pFlac->currentFLACFrame.header.blockSizeInPCMFrames * i))) { + return MA_ERROR; + } + } + paddingSizeInBits = (ma_uint8)(MA_DR_FLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7); + if (paddingSizeInBits > 0) { + ma_uint8 padding = 0; + if (!ma_dr_flac__read_uint8(&pFlac->bs, paddingSizeInBits, &padding)) { + return MA_AT_END; + } + } +#ifndef MA_DR_FLAC_NO_CRC + actualCRC16 = ma_dr_flac__flush_crc16(&pFlac->bs); +#endif + if (!ma_dr_flac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) { + return MA_AT_END; + } +#ifndef MA_DR_FLAC_NO_CRC + if (actualCRC16 != desiredCRC16) { + return MA_CRC_MISMATCH; + } +#endif + pFlac->currentFLACFrame.pcmFramesRemaining = pFlac->currentFLACFrame.header.blockSizeInPCMFrames; + return MA_SUCCESS; +} +static ma_result ma_dr_flac__seek_flac_frame(ma_dr_flac* pFlac) +{ + int channelCount; + int i; + ma_uint16 desiredCRC16; +#ifndef MA_DR_FLAC_NO_CRC + ma_uint16 actualCRC16; +#endif + channelCount = ma_dr_flac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment); + for (i = 0; i < channelCount; ++i) { + if (!ma_dr_flac__seek_subframe(&pFlac->bs, &pFlac->currentFLACFrame, i)) { + return MA_ERROR; + } + } + if (!ma_dr_flac__seek_bits(&pFlac->bs, MA_DR_FLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7)) { + return MA_ERROR; + } +#ifndef MA_DR_FLAC_NO_CRC + actualCRC16 = ma_dr_flac__flush_crc16(&pFlac->bs); +#endif + if (!ma_dr_flac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) { + return MA_AT_END; + } +#ifndef MA_DR_FLAC_NO_CRC + if (actualCRC16 != desiredCRC16) { + return MA_CRC_MISMATCH; + } +#endif + return MA_SUCCESS; +} +static ma_bool32 ma_dr_flac__read_and_decode_next_flac_frame(ma_dr_flac* pFlac) +{ + MA_DR_FLAC_ASSERT(pFlac != NULL); + for (;;) { + ma_result result; + if (!ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + return MA_FALSE; + } + result = ma_dr_flac__decode_flac_frame(pFlac); + if (result != MA_SUCCESS) { + if (result == MA_CRC_MISMATCH) { + continue; + } else { + return MA_FALSE; + } + } + return MA_TRUE; + } +} +static void ma_dr_flac__get_pcm_frame_range_of_current_flac_frame(ma_dr_flac* pFlac, ma_uint64* pFirstPCMFrame, ma_uint64* pLastPCMFrame) +{ + ma_uint64 firstPCMFrame; + ma_uint64 lastPCMFrame; + MA_DR_FLAC_ASSERT(pFlac != NULL); + firstPCMFrame = pFlac->currentFLACFrame.header.pcmFrameNumber; + if (firstPCMFrame == 0) { + firstPCMFrame = ((ma_uint64)pFlac->currentFLACFrame.header.flacFrameNumber) * pFlac->maxBlockSizeInPCMFrames; + } + lastPCMFrame = firstPCMFrame + pFlac->currentFLACFrame.header.blockSizeInPCMFrames; + if (lastPCMFrame > 0) { + lastPCMFrame -= 1; + } + if (pFirstPCMFrame) { + *pFirstPCMFrame = firstPCMFrame; + } + if (pLastPCMFrame) { + *pLastPCMFrame = lastPCMFrame; + } +} +static ma_bool32 ma_dr_flac__seek_to_first_frame(ma_dr_flac* pFlac) +{ + ma_bool32 result; + MA_DR_FLAC_ASSERT(pFlac != NULL); + result = ma_dr_flac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes); + MA_DR_FLAC_ZERO_MEMORY(&pFlac->currentFLACFrame, sizeof(pFlac->currentFLACFrame)); + pFlac->currentPCMFrame = 0; + return result; +} +static MA_INLINE ma_result ma_dr_flac__seek_to_next_flac_frame(ma_dr_flac* pFlac) +{ + MA_DR_FLAC_ASSERT(pFlac != NULL); + return ma_dr_flac__seek_flac_frame(pFlac); +} +static ma_uint64 ma_dr_flac__seek_forward_by_pcm_frames(ma_dr_flac* pFlac, ma_uint64 pcmFramesToSeek) +{ + ma_uint64 pcmFramesRead = 0; + while (pcmFramesToSeek > 0) { + if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) { + if (!ma_dr_flac__read_and_decode_next_flac_frame(pFlac)) { + break; + } + } else { + if (pFlac->currentFLACFrame.pcmFramesRemaining > pcmFramesToSeek) { + pcmFramesRead += pcmFramesToSeek; + pFlac->currentFLACFrame.pcmFramesRemaining -= (ma_uint32)pcmFramesToSeek; + pcmFramesToSeek = 0; + } else { + pcmFramesRead += pFlac->currentFLACFrame.pcmFramesRemaining; + pcmFramesToSeek -= pFlac->currentFLACFrame.pcmFramesRemaining; + pFlac->currentFLACFrame.pcmFramesRemaining = 0; + } + } + } + pFlac->currentPCMFrame += pcmFramesRead; + return pcmFramesRead; +} +static ma_bool32 ma_dr_flac__seek_to_pcm_frame__brute_force(ma_dr_flac* pFlac, ma_uint64 pcmFrameIndex) +{ + ma_bool32 isMidFrame = MA_FALSE; + ma_uint64 runningPCMFrameCount; + MA_DR_FLAC_ASSERT(pFlac != NULL); + if (pcmFrameIndex >= pFlac->currentPCMFrame) { + runningPCMFrameCount = pFlac->currentPCMFrame; + if (pFlac->currentPCMFrame == 0 && pFlac->currentFLACFrame.pcmFramesRemaining == 0) { + if (!ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + return MA_FALSE; + } + } else { + isMidFrame = MA_TRUE; + } + } else { + runningPCMFrameCount = 0; + if (!ma_dr_flac__seek_to_first_frame(pFlac)) { + return MA_FALSE; + } + if (!ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + return MA_FALSE; + } + } + for (;;) { + ma_uint64 pcmFrameCountInThisFLACFrame; + ma_uint64 firstPCMFrameInFLACFrame = 0; + ma_uint64 lastPCMFrameInFLACFrame = 0; + ma_dr_flac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame); + pcmFrameCountInThisFLACFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1; + if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFLACFrame)) { + ma_uint64 pcmFramesToDecode = pcmFrameIndex - runningPCMFrameCount; + if (!isMidFrame) { + ma_result result = ma_dr_flac__decode_flac_frame(pFlac); + if (result == MA_SUCCESS) { + return ma_dr_flac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode; + } else { + if (result == MA_CRC_MISMATCH) { + goto next_iteration; + } else { + return MA_FALSE; + } + } + } else { + return ma_dr_flac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode; + } + } else { + if (!isMidFrame) { + ma_result result = ma_dr_flac__seek_to_next_flac_frame(pFlac); + if (result == MA_SUCCESS) { + runningPCMFrameCount += pcmFrameCountInThisFLACFrame; + } else { + if (result == MA_CRC_MISMATCH) { + goto next_iteration; + } else { + return MA_FALSE; + } + } + } else { + runningPCMFrameCount += pFlac->currentFLACFrame.pcmFramesRemaining; + pFlac->currentFLACFrame.pcmFramesRemaining = 0; + isMidFrame = MA_FALSE; + } + if (pcmFrameIndex == pFlac->totalPCMFrameCount && runningPCMFrameCount == pFlac->totalPCMFrameCount) { + return MA_TRUE; + } + } + next_iteration: + if (!ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + return MA_FALSE; + } + } +} +#if !defined(MA_DR_FLAC_NO_CRC) +#define MA_DR_FLAC_BINARY_SEARCH_APPROX_COMPRESSION_RATIO 0.6f +static ma_bool32 ma_dr_flac__seek_to_approximate_flac_frame_to_byte(ma_dr_flac* pFlac, ma_uint64 targetByte, ma_uint64 rangeLo, ma_uint64 rangeHi, ma_uint64* pLastSuccessfulSeekOffset) +{ + MA_DR_FLAC_ASSERT(pFlac != NULL); + MA_DR_FLAC_ASSERT(pLastSuccessfulSeekOffset != NULL); + MA_DR_FLAC_ASSERT(targetByte >= rangeLo); + MA_DR_FLAC_ASSERT(targetByte <= rangeHi); + *pLastSuccessfulSeekOffset = pFlac->firstFLACFramePosInBytes; + for (;;) { + ma_uint64 lastTargetByte = targetByte; + if (!ma_dr_flac__seek_to_byte(&pFlac->bs, targetByte)) { + if (targetByte == 0) { + ma_dr_flac__seek_to_first_frame(pFlac); + return MA_FALSE; + } + targetByte = rangeLo + ((rangeHi - rangeLo)/2); + rangeHi = targetByte; + } else { + MA_DR_FLAC_ZERO_MEMORY(&pFlac->currentFLACFrame, sizeof(pFlac->currentFLACFrame)); +#if 1 + if (!ma_dr_flac__read_and_decode_next_flac_frame(pFlac)) { + targetByte = rangeLo + ((rangeHi - rangeLo)/2); + rangeHi = targetByte; + } else { + break; + } +#else + if (!ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + targetByte = rangeLo + ((rangeHi - rangeLo)/2); + rangeHi = targetByte; + } else { + break; + } +#endif + } + if(targetByte == lastTargetByte) { + return MA_FALSE; + } + } + ma_dr_flac__get_pcm_frame_range_of_current_flac_frame(pFlac, &pFlac->currentPCMFrame, NULL); + MA_DR_FLAC_ASSERT(targetByte <= rangeHi); + *pLastSuccessfulSeekOffset = targetByte; + return MA_TRUE; +} +static ma_bool32 ma_dr_flac__decode_flac_frame_and_seek_forward_by_pcm_frames(ma_dr_flac* pFlac, ma_uint64 offset) +{ +#if 0 + if (ma_dr_flac__decode_flac_frame(pFlac) != MA_SUCCESS) { + if (ma_dr_flac__read_and_decode_next_flac_frame(pFlac) == MA_FALSE) { + return MA_FALSE; + } + } +#endif + return ma_dr_flac__seek_forward_by_pcm_frames(pFlac, offset) == offset; +} +static ma_bool32 ma_dr_flac__seek_to_pcm_frame__binary_search_internal(ma_dr_flac* pFlac, ma_uint64 pcmFrameIndex, ma_uint64 byteRangeLo, ma_uint64 byteRangeHi) +{ + ma_uint64 targetByte; + ma_uint64 pcmRangeLo = pFlac->totalPCMFrameCount; + ma_uint64 pcmRangeHi = 0; + ma_uint64 lastSuccessfulSeekOffset = (ma_uint64)-1; + ma_uint64 closestSeekOffsetBeforeTargetPCMFrame = byteRangeLo; + ma_uint32 seekForwardThreshold = (pFlac->maxBlockSizeInPCMFrames != 0) ? pFlac->maxBlockSizeInPCMFrames*2 : 4096; + targetByte = byteRangeLo + (ma_uint64)(((ma_int64)((pcmFrameIndex - pFlac->currentPCMFrame) * pFlac->channels * pFlac->bitsPerSample)/8.0f) * MA_DR_FLAC_BINARY_SEARCH_APPROX_COMPRESSION_RATIO); + if (targetByte > byteRangeHi) { + targetByte = byteRangeHi; + } + for (;;) { + if (ma_dr_flac__seek_to_approximate_flac_frame_to_byte(pFlac, targetByte, byteRangeLo, byteRangeHi, &lastSuccessfulSeekOffset)) { + ma_uint64 newPCMRangeLo; + ma_uint64 newPCMRangeHi; + ma_dr_flac__get_pcm_frame_range_of_current_flac_frame(pFlac, &newPCMRangeLo, &newPCMRangeHi); + if (pcmRangeLo == newPCMRangeLo) { + if (!ma_dr_flac__seek_to_approximate_flac_frame_to_byte(pFlac, closestSeekOffsetBeforeTargetPCMFrame, closestSeekOffsetBeforeTargetPCMFrame, byteRangeHi, &lastSuccessfulSeekOffset)) { + break; + } + if (ma_dr_flac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame)) { + return MA_TRUE; + } else { + break; + } + } + pcmRangeLo = newPCMRangeLo; + pcmRangeHi = newPCMRangeHi; + if (pcmRangeLo <= pcmFrameIndex && pcmRangeHi >= pcmFrameIndex) { + if (ma_dr_flac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame) ) { + return MA_TRUE; + } else { + break; + } + } else { + const float approxCompressionRatio = (ma_int64)(lastSuccessfulSeekOffset - pFlac->firstFLACFramePosInBytes) / ((ma_int64)(pcmRangeLo * pFlac->channels * pFlac->bitsPerSample)/8.0f); + if (pcmRangeLo > pcmFrameIndex) { + byteRangeHi = lastSuccessfulSeekOffset; + if (byteRangeLo > byteRangeHi) { + byteRangeLo = byteRangeHi; + } + targetByte = byteRangeLo + ((byteRangeHi - byteRangeLo) / 2); + if (targetByte < byteRangeLo) { + targetByte = byteRangeLo; + } + } else { + if ((pcmFrameIndex - pcmRangeLo) < seekForwardThreshold) { + if (ma_dr_flac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame)) { + return MA_TRUE; + } else { + break; + } + } else { + byteRangeLo = lastSuccessfulSeekOffset; + if (byteRangeHi < byteRangeLo) { + byteRangeHi = byteRangeLo; + } + targetByte = lastSuccessfulSeekOffset + (ma_uint64)(((ma_int64)((pcmFrameIndex-pcmRangeLo) * pFlac->channels * pFlac->bitsPerSample)/8.0f) * approxCompressionRatio); + if (targetByte > byteRangeHi) { + targetByte = byteRangeHi; + } + if (closestSeekOffsetBeforeTargetPCMFrame < lastSuccessfulSeekOffset) { + closestSeekOffsetBeforeTargetPCMFrame = lastSuccessfulSeekOffset; + } + } + } + } + } else { + break; + } + } + ma_dr_flac__seek_to_first_frame(pFlac); + return MA_FALSE; +} +static ma_bool32 ma_dr_flac__seek_to_pcm_frame__binary_search(ma_dr_flac* pFlac, ma_uint64 pcmFrameIndex) +{ + ma_uint64 byteRangeLo; + ma_uint64 byteRangeHi; + ma_uint32 seekForwardThreshold = (pFlac->maxBlockSizeInPCMFrames != 0) ? pFlac->maxBlockSizeInPCMFrames*2 : 4096; + if (ma_dr_flac__seek_to_first_frame(pFlac) == MA_FALSE) { + return MA_FALSE; + } + if (pcmFrameIndex < seekForwardThreshold) { + return ma_dr_flac__seek_forward_by_pcm_frames(pFlac, pcmFrameIndex) == pcmFrameIndex; + } + byteRangeLo = pFlac->firstFLACFramePosInBytes; + byteRangeHi = pFlac->firstFLACFramePosInBytes + (ma_uint64)((ma_int64)(pFlac->totalPCMFrameCount * pFlac->channels * pFlac->bitsPerSample)/8.0f); + return ma_dr_flac__seek_to_pcm_frame__binary_search_internal(pFlac, pcmFrameIndex, byteRangeLo, byteRangeHi); +} +#endif +static ma_bool32 ma_dr_flac__seek_to_pcm_frame__seek_table(ma_dr_flac* pFlac, ma_uint64 pcmFrameIndex) +{ + ma_uint32 iClosestSeekpoint = 0; + ma_bool32 isMidFrame = MA_FALSE; + ma_uint64 runningPCMFrameCount; + ma_uint32 iSeekpoint; + MA_DR_FLAC_ASSERT(pFlac != NULL); + if (pFlac->pSeekpoints == NULL || pFlac->seekpointCount == 0) { + return MA_FALSE; + } + if (pFlac->pSeekpoints[0].firstPCMFrame > pcmFrameIndex) { + return MA_FALSE; + } + for (iSeekpoint = 0; iSeekpoint < pFlac->seekpointCount; ++iSeekpoint) { + if (pFlac->pSeekpoints[iSeekpoint].firstPCMFrame >= pcmFrameIndex) { + break; + } + iClosestSeekpoint = iSeekpoint; + } + if (pFlac->pSeekpoints[iClosestSeekpoint].pcmFrameCount == 0 || pFlac->pSeekpoints[iClosestSeekpoint].pcmFrameCount > pFlac->maxBlockSizeInPCMFrames) { + return MA_FALSE; + } + if (pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame > pFlac->totalPCMFrameCount && pFlac->totalPCMFrameCount > 0) { + return MA_FALSE; + } +#if !defined(MA_DR_FLAC_NO_CRC) + if (pFlac->totalPCMFrameCount > 0) { + ma_uint64 byteRangeLo; + ma_uint64 byteRangeHi; + byteRangeHi = pFlac->firstFLACFramePosInBytes + (ma_uint64)((ma_int64)(pFlac->totalPCMFrameCount * pFlac->channels * pFlac->bitsPerSample)/8.0f); + byteRangeLo = pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset; + if (iClosestSeekpoint < pFlac->seekpointCount-1) { + ma_uint32 iNextSeekpoint = iClosestSeekpoint + 1; + if (pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset >= pFlac->pSeekpoints[iNextSeekpoint].flacFrameOffset || pFlac->pSeekpoints[iNextSeekpoint].pcmFrameCount == 0) { + return MA_FALSE; + } + if (pFlac->pSeekpoints[iNextSeekpoint].firstPCMFrame != (((ma_uint64)0xFFFFFFFF << 32) | 0xFFFFFFFF)) { + byteRangeHi = pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iNextSeekpoint].flacFrameOffset - 1; + } + } + if (ma_dr_flac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset)) { + if (ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + ma_dr_flac__get_pcm_frame_range_of_current_flac_frame(pFlac, &pFlac->currentPCMFrame, NULL); + if (ma_dr_flac__seek_to_pcm_frame__binary_search_internal(pFlac, pcmFrameIndex, byteRangeLo, byteRangeHi)) { + return MA_TRUE; + } + } + } + } +#endif + if (pcmFrameIndex >= pFlac->currentPCMFrame && pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame <= pFlac->currentPCMFrame) { + runningPCMFrameCount = pFlac->currentPCMFrame; + if (pFlac->currentPCMFrame == 0 && pFlac->currentFLACFrame.pcmFramesRemaining == 0) { + if (!ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + return MA_FALSE; + } + } else { + isMidFrame = MA_TRUE; + } + } else { + runningPCMFrameCount = pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame; + if (!ma_dr_flac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset)) { + return MA_FALSE; + } + if (!ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + return MA_FALSE; + } + } + for (;;) { + ma_uint64 pcmFrameCountInThisFLACFrame; + ma_uint64 firstPCMFrameInFLACFrame = 0; + ma_uint64 lastPCMFrameInFLACFrame = 0; + ma_dr_flac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame); + pcmFrameCountInThisFLACFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1; + if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFLACFrame)) { + ma_uint64 pcmFramesToDecode = pcmFrameIndex - runningPCMFrameCount; + if (!isMidFrame) { + ma_result result = ma_dr_flac__decode_flac_frame(pFlac); + if (result == MA_SUCCESS) { + return ma_dr_flac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode; + } else { + if (result == MA_CRC_MISMATCH) { + goto next_iteration; + } else { + return MA_FALSE; + } + } + } else { + return ma_dr_flac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode; + } + } else { + if (!isMidFrame) { + ma_result result = ma_dr_flac__seek_to_next_flac_frame(pFlac); + if (result == MA_SUCCESS) { + runningPCMFrameCount += pcmFrameCountInThisFLACFrame; + } else { + if (result == MA_CRC_MISMATCH) { + goto next_iteration; + } else { + return MA_FALSE; + } + } + } else { + runningPCMFrameCount += pFlac->currentFLACFrame.pcmFramesRemaining; + pFlac->currentFLACFrame.pcmFramesRemaining = 0; + isMidFrame = MA_FALSE; + } + if (pcmFrameIndex == pFlac->totalPCMFrameCount && runningPCMFrameCount == pFlac->totalPCMFrameCount) { + return MA_TRUE; + } + } + next_iteration: + if (!ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + return MA_FALSE; + } + } +} +#ifndef MA_DR_FLAC_NO_OGG +typedef struct +{ + ma_uint8 capturePattern[4]; + ma_uint8 structureVersion; + ma_uint8 headerType; + ma_uint64 granulePosition; + ma_uint32 serialNumber; + ma_uint32 sequenceNumber; + ma_uint32 checksum; + ma_uint8 segmentCount; + ma_uint8 segmentTable[255]; +} ma_dr_flac_ogg_page_header; +#endif +typedef struct +{ + ma_dr_flac_read_proc onRead; + ma_dr_flac_seek_proc onSeek; + ma_dr_flac_meta_proc onMeta; + ma_dr_flac_container container; + void* pUserData; + void* pUserDataMD; + ma_uint32 sampleRate; + ma_uint8 channels; + ma_uint8 bitsPerSample; + ma_uint64 totalPCMFrameCount; + ma_uint16 maxBlockSizeInPCMFrames; + ma_uint64 runningFilePos; + ma_bool32 hasStreamInfoBlock; + ma_bool32 hasMetadataBlocks; + ma_dr_flac_bs bs; + ma_dr_flac_frame_header firstFrameHeader; +#ifndef MA_DR_FLAC_NO_OGG + ma_uint32 oggSerial; + ma_uint64 oggFirstBytePos; + ma_dr_flac_ogg_page_header oggBosHeader; +#endif +} ma_dr_flac_init_info; +static MA_INLINE void ma_dr_flac__decode_block_header(ma_uint32 blockHeader, ma_uint8* isLastBlock, ma_uint8* blockType, ma_uint32* blockSize) +{ + blockHeader = ma_dr_flac__be2host_32(blockHeader); + *isLastBlock = (ma_uint8)((blockHeader & 0x80000000UL) >> 31); + *blockType = (ma_uint8)((blockHeader & 0x7F000000UL) >> 24); + *blockSize = (blockHeader & 0x00FFFFFFUL); +} +static MA_INLINE ma_bool32 ma_dr_flac__read_and_decode_block_header(ma_dr_flac_read_proc onRead, void* pUserData, ma_uint8* isLastBlock, ma_uint8* blockType, ma_uint32* blockSize) +{ + ma_uint32 blockHeader; + *blockSize = 0; + if (onRead(pUserData, &blockHeader, 4) != 4) { + return MA_FALSE; + } + ma_dr_flac__decode_block_header(blockHeader, isLastBlock, blockType, blockSize); + return MA_TRUE; +} +static ma_bool32 ma_dr_flac__read_streaminfo(ma_dr_flac_read_proc onRead, void* pUserData, ma_dr_flac_streaminfo* pStreamInfo) +{ + ma_uint32 blockSizes; + ma_uint64 frameSizes = 0; + ma_uint64 importantProps; + ma_uint8 md5[16]; + if (onRead(pUserData, &blockSizes, 4) != 4) { + return MA_FALSE; + } + if (onRead(pUserData, &frameSizes, 6) != 6) { + return MA_FALSE; + } + if (onRead(pUserData, &importantProps, 8) != 8) { + return MA_FALSE; + } + if (onRead(pUserData, md5, sizeof(md5)) != sizeof(md5)) { + return MA_FALSE; + } + blockSizes = ma_dr_flac__be2host_32(blockSizes); + frameSizes = ma_dr_flac__be2host_64(frameSizes); + importantProps = ma_dr_flac__be2host_64(importantProps); + pStreamInfo->minBlockSizeInPCMFrames = (ma_uint16)((blockSizes & 0xFFFF0000) >> 16); + pStreamInfo->maxBlockSizeInPCMFrames = (ma_uint16) (blockSizes & 0x0000FFFF); + pStreamInfo->minFrameSizeInPCMFrames = (ma_uint32)((frameSizes & (((ma_uint64)0x00FFFFFF << 16) << 24)) >> 40); + pStreamInfo->maxFrameSizeInPCMFrames = (ma_uint32)((frameSizes & (((ma_uint64)0x00FFFFFF << 16) << 0)) >> 16); + pStreamInfo->sampleRate = (ma_uint32)((importantProps & (((ma_uint64)0x000FFFFF << 16) << 28)) >> 44); + pStreamInfo->channels = (ma_uint8 )((importantProps & (((ma_uint64)0x0000000E << 16) << 24)) >> 41) + 1; + pStreamInfo->bitsPerSample = (ma_uint8 )((importantProps & (((ma_uint64)0x0000001F << 16) << 20)) >> 36) + 1; + pStreamInfo->totalPCMFrameCount = ((importantProps & ((((ma_uint64)0x0000000F << 16) << 16) | 0xFFFFFFFF))); + MA_DR_FLAC_COPY_MEMORY(pStreamInfo->md5, md5, sizeof(md5)); + return MA_TRUE; +} +static void* ma_dr_flac__malloc_default(size_t sz, void* pUserData) +{ + (void)pUserData; + return MA_DR_FLAC_MALLOC(sz); +} +static void* ma_dr_flac__realloc_default(void* p, size_t sz, void* pUserData) +{ + (void)pUserData; + return MA_DR_FLAC_REALLOC(p, sz); +} +static void ma_dr_flac__free_default(void* p, void* pUserData) +{ + (void)pUserData; + MA_DR_FLAC_FREE(p); +} +static void* ma_dr_flac__malloc_from_callbacks(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pAllocationCallbacks == NULL) { + return NULL; + } + if (pAllocationCallbacks->onMalloc != NULL) { + return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData); + } + if (pAllocationCallbacks->onRealloc != NULL) { + return pAllocationCallbacks->onRealloc(NULL, sz, pAllocationCallbacks->pUserData); + } + return NULL; +} +static void* ma_dr_flac__realloc_from_callbacks(void* p, size_t szNew, size_t szOld, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pAllocationCallbacks == NULL) { + return NULL; + } + if (pAllocationCallbacks->onRealloc != NULL) { + return pAllocationCallbacks->onRealloc(p, szNew, pAllocationCallbacks->pUserData); + } + if (pAllocationCallbacks->onMalloc != NULL && pAllocationCallbacks->onFree != NULL) { + void* p2; + p2 = pAllocationCallbacks->onMalloc(szNew, pAllocationCallbacks->pUserData); + if (p2 == NULL) { + return NULL; + } + if (p != NULL) { + MA_DR_FLAC_COPY_MEMORY(p2, p, szOld); + pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData); + } + return p2; + } + return NULL; +} +static void ma_dr_flac__free_from_callbacks(void* p, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (p == NULL || pAllocationCallbacks == NULL) { + return; + } + if (pAllocationCallbacks->onFree != NULL) { + pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData); + } +} +static ma_bool32 ma_dr_flac__read_and_decode_metadata(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_meta_proc onMeta, void* pUserData, void* pUserDataMD, ma_uint64* pFirstFramePos, ma_uint64* pSeektablePos, ma_uint32* pSeekpointCount, ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_uint64 runningFilePos = 42; + ma_uint64 seektablePos = 0; + ma_uint32 seektableSize = 0; + for (;;) { + ma_dr_flac_metadata metadata; + ma_uint8 isLastBlock = 0; + ma_uint8 blockType = 0; + ma_uint32 blockSize; + if (ma_dr_flac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize) == MA_FALSE) { + return MA_FALSE; + } + runningFilePos += 4; + metadata.type = blockType; + metadata.pRawData = NULL; + metadata.rawDataSize = 0; + switch (blockType) + { + case MA_DR_FLAC_METADATA_BLOCK_TYPE_APPLICATION: + { + if (blockSize < 4) { + return MA_FALSE; + } + if (onMeta) { + void* pRawData = ma_dr_flac__malloc_from_callbacks(blockSize, pAllocationCallbacks); + if (pRawData == NULL) { + return MA_FALSE; + } + if (onRead(pUserData, pRawData, blockSize) != blockSize) { + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + return MA_FALSE; + } + metadata.pRawData = pRawData; + metadata.rawDataSize = blockSize; + metadata.data.application.id = ma_dr_flac__be2host_32(*(ma_uint32*)pRawData); + metadata.data.application.pData = (const void*)((ma_uint8*)pRawData + sizeof(ma_uint32)); + metadata.data.application.dataSize = blockSize - sizeof(ma_uint32); + onMeta(pUserDataMD, &metadata); + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + } + } break; + case MA_DR_FLAC_METADATA_BLOCK_TYPE_SEEKTABLE: + { + seektablePos = runningFilePos; + seektableSize = blockSize; + if (onMeta) { + ma_uint32 seekpointCount; + ma_uint32 iSeekpoint; + void* pRawData; + seekpointCount = blockSize/MA_DR_FLAC_SEEKPOINT_SIZE_IN_BYTES; + pRawData = ma_dr_flac__malloc_from_callbacks(seekpointCount * sizeof(ma_dr_flac_seekpoint), pAllocationCallbacks); + if (pRawData == NULL) { + return MA_FALSE; + } + for (iSeekpoint = 0; iSeekpoint < seekpointCount; ++iSeekpoint) { + ma_dr_flac_seekpoint* pSeekpoint = (ma_dr_flac_seekpoint*)pRawData + iSeekpoint; + if (onRead(pUserData, pSeekpoint, MA_DR_FLAC_SEEKPOINT_SIZE_IN_BYTES) != MA_DR_FLAC_SEEKPOINT_SIZE_IN_BYTES) { + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + return MA_FALSE; + } + pSeekpoint->firstPCMFrame = ma_dr_flac__be2host_64(pSeekpoint->firstPCMFrame); + pSeekpoint->flacFrameOffset = ma_dr_flac__be2host_64(pSeekpoint->flacFrameOffset); + pSeekpoint->pcmFrameCount = ma_dr_flac__be2host_16(pSeekpoint->pcmFrameCount); + } + metadata.pRawData = pRawData; + metadata.rawDataSize = blockSize; + metadata.data.seektable.seekpointCount = seekpointCount; + metadata.data.seektable.pSeekpoints = (const ma_dr_flac_seekpoint*)pRawData; + onMeta(pUserDataMD, &metadata); + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + } + } break; + case MA_DR_FLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT: + { + if (blockSize < 8) { + return MA_FALSE; + } + if (onMeta) { + void* pRawData; + const char* pRunningData; + const char* pRunningDataEnd; + ma_uint32 i; + pRawData = ma_dr_flac__malloc_from_callbacks(blockSize, pAllocationCallbacks); + if (pRawData == NULL) { + return MA_FALSE; + } + if (onRead(pUserData, pRawData, blockSize) != blockSize) { + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + return MA_FALSE; + } + metadata.pRawData = pRawData; + metadata.rawDataSize = blockSize; + pRunningData = (const char*)pRawData; + pRunningDataEnd = (const char*)pRawData + blockSize; + metadata.data.vorbis_comment.vendorLength = ma_dr_flac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4; + if ((pRunningDataEnd - pRunningData) - 4 < (ma_int64)metadata.data.vorbis_comment.vendorLength) { + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + return MA_FALSE; + } + metadata.data.vorbis_comment.vendor = pRunningData; pRunningData += metadata.data.vorbis_comment.vendorLength; + metadata.data.vorbis_comment.commentCount = ma_dr_flac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4; + if ((pRunningDataEnd - pRunningData) / sizeof(ma_uint32) < metadata.data.vorbis_comment.commentCount) { + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + return MA_FALSE; + } + metadata.data.vorbis_comment.pComments = pRunningData; + for (i = 0; i < metadata.data.vorbis_comment.commentCount; ++i) { + ma_uint32 commentLength; + if (pRunningDataEnd - pRunningData < 4) { + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + return MA_FALSE; + } + commentLength = ma_dr_flac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4; + if (pRunningDataEnd - pRunningData < (ma_int64)commentLength) { + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + return MA_FALSE; + } + pRunningData += commentLength; + } + onMeta(pUserDataMD, &metadata); + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + } + } break; + case MA_DR_FLAC_METADATA_BLOCK_TYPE_CUESHEET: + { + if (blockSize < 396) { + return MA_FALSE; + } + if (onMeta) { + void* pRawData; + const char* pRunningData; + const char* pRunningDataEnd; + size_t bufferSize; + ma_uint8 iTrack; + ma_uint8 iIndex; + void* pTrackData; + pRawData = ma_dr_flac__malloc_from_callbacks(blockSize, pAllocationCallbacks); + if (pRawData == NULL) { + return MA_FALSE; + } + if (onRead(pUserData, pRawData, blockSize) != blockSize) { + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + return MA_FALSE; + } + metadata.pRawData = pRawData; + metadata.rawDataSize = blockSize; + pRunningData = (const char*)pRawData; + pRunningDataEnd = (const char*)pRawData + blockSize; + MA_DR_FLAC_COPY_MEMORY(metadata.data.cuesheet.catalog, pRunningData, 128); pRunningData += 128; + metadata.data.cuesheet.leadInSampleCount = ma_dr_flac__be2host_64(*(const ma_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 = NULL; + { + const char* pRunningDataSaved = pRunningData; + bufferSize = metadata.data.cuesheet.trackCount * MA_DR_FLAC_CUESHEET_TRACK_SIZE_IN_BYTES; + for (iTrack = 0; iTrack < metadata.data.cuesheet.trackCount; ++iTrack) { + ma_uint8 indexCount; + ma_uint32 indexPointSize; + if (pRunningDataEnd - pRunningData < MA_DR_FLAC_CUESHEET_TRACK_SIZE_IN_BYTES) { + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + return MA_FALSE; + } + pRunningData += 35; + indexCount = pRunningData[0]; + pRunningData += 1; + bufferSize += indexCount * sizeof(ma_dr_flac_cuesheet_track_index); + indexPointSize = indexCount * MA_DR_FLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES; + if (pRunningDataEnd - pRunningData < (ma_int64)indexPointSize) { + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + return MA_FALSE; + } + pRunningData += indexPointSize; + } + pRunningData = pRunningDataSaved; + } + { + char* pRunningTrackData; + pTrackData = ma_dr_flac__malloc_from_callbacks(bufferSize, pAllocationCallbacks); + if (pTrackData == NULL) { + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + return MA_FALSE; + } + pRunningTrackData = (char*)pTrackData; + for (iTrack = 0; iTrack < metadata.data.cuesheet.trackCount; ++iTrack) { + ma_uint8 indexCount; + MA_DR_FLAC_COPY_MEMORY(pRunningTrackData, pRunningData, MA_DR_FLAC_CUESHEET_TRACK_SIZE_IN_BYTES); + pRunningData += MA_DR_FLAC_CUESHEET_TRACK_SIZE_IN_BYTES-1; + pRunningTrackData += MA_DR_FLAC_CUESHEET_TRACK_SIZE_IN_BYTES-1; + indexCount = pRunningData[0]; + pRunningData += 1; + pRunningTrackData += 1; + for (iIndex = 0; iIndex < indexCount; ++iIndex) { + ma_dr_flac_cuesheet_track_index* pTrackIndex = (ma_dr_flac_cuesheet_track_index*)pRunningTrackData; + MA_DR_FLAC_COPY_MEMORY(pRunningTrackData, pRunningData, MA_DR_FLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES); + pRunningData += MA_DR_FLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES; + pRunningTrackData += sizeof(ma_dr_flac_cuesheet_track_index); + pTrackIndex->offset = ma_dr_flac__be2host_64(pTrackIndex->offset); + } + } + metadata.data.cuesheet.pTrackData = pTrackData; + } + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + pRawData = NULL; + onMeta(pUserDataMD, &metadata); + ma_dr_flac__free_from_callbacks(pTrackData, pAllocationCallbacks); + pTrackData = NULL; + } + } break; + case MA_DR_FLAC_METADATA_BLOCK_TYPE_PICTURE: + { + if (blockSize < 32) { + return MA_FALSE; + } + if (onMeta) { + void* pRawData; + const char* pRunningData; + const char* pRunningDataEnd; + pRawData = ma_dr_flac__malloc_from_callbacks(blockSize, pAllocationCallbacks); + if (pRawData == NULL) { + return MA_FALSE; + } + if (onRead(pUserData, pRawData, blockSize) != blockSize) { + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + return MA_FALSE; + } + metadata.pRawData = pRawData; + metadata.rawDataSize = blockSize; + pRunningData = (const char*)pRawData; + pRunningDataEnd = (const char*)pRawData + blockSize; + metadata.data.picture.type = ma_dr_flac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4; + metadata.data.picture.mimeLength = ma_dr_flac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4; + if ((pRunningDataEnd - pRunningData) - 24 < (ma_int64)metadata.data.picture.mimeLength) { + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + return MA_FALSE; + } + metadata.data.picture.mime = pRunningData; pRunningData += metadata.data.picture.mimeLength; + metadata.data.picture.descriptionLength = ma_dr_flac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4; + if ((pRunningDataEnd - pRunningData) - 20 < (ma_int64)metadata.data.picture.descriptionLength) { + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + return MA_FALSE; + } + metadata.data.picture.description = pRunningData; pRunningData += metadata.data.picture.descriptionLength; + metadata.data.picture.width = ma_dr_flac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4; + metadata.data.picture.height = ma_dr_flac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4; + metadata.data.picture.colorDepth = ma_dr_flac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4; + metadata.data.picture.indexColorCount = ma_dr_flac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4; + metadata.data.picture.pictureDataSize = ma_dr_flac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4; + metadata.data.picture.pPictureData = (const ma_uint8*)pRunningData; + if (pRunningDataEnd - pRunningData < (ma_int64)metadata.data.picture.pictureDataSize) { + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + return MA_FALSE; + } + onMeta(pUserDataMD, &metadata); + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + } + } break; + case MA_DR_FLAC_METADATA_BLOCK_TYPE_PADDING: + { + if (onMeta) { + metadata.data.padding.unused = 0; + if (!onSeek(pUserData, blockSize, ma_dr_flac_seek_origin_current)) { + isLastBlock = MA_TRUE; + } else { + onMeta(pUserDataMD, &metadata); + } + } + } break; + case MA_DR_FLAC_METADATA_BLOCK_TYPE_INVALID: + { + if (onMeta) { + if (!onSeek(pUserData, blockSize, ma_dr_flac_seek_origin_current)) { + isLastBlock = MA_TRUE; + } + } + } break; + default: + { + if (onMeta) { + void* pRawData = ma_dr_flac__malloc_from_callbacks(blockSize, pAllocationCallbacks); + if (pRawData == NULL) { + return MA_FALSE; + } + if (onRead(pUserData, pRawData, blockSize) != blockSize) { + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + return MA_FALSE; + } + metadata.pRawData = pRawData; + metadata.rawDataSize = blockSize; + onMeta(pUserDataMD, &metadata); + ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks); + } + } break; + } + if (onMeta == NULL && blockSize > 0) { + if (!onSeek(pUserData, blockSize, ma_dr_flac_seek_origin_current)) { + isLastBlock = MA_TRUE; + } + } + runningFilePos += blockSize; + if (isLastBlock) { + break; + } + } + *pSeektablePos = seektablePos; + *pSeekpointCount = seektableSize / MA_DR_FLAC_SEEKPOINT_SIZE_IN_BYTES; + *pFirstFramePos = runningFilePos; + return MA_TRUE; +} +static ma_bool32 ma_dr_flac__init_private__native(ma_dr_flac_init_info* pInit, ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_meta_proc onMeta, void* pUserData, void* pUserDataMD, ma_bool32 relaxed) +{ + ma_uint8 isLastBlock; + ma_uint8 blockType; + ma_uint32 blockSize; + (void)onSeek; + pInit->container = ma_dr_flac_container_native; + if (!ma_dr_flac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) { + return MA_FALSE; + } + if (blockType != MA_DR_FLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) { + if (!relaxed) { + return MA_FALSE; + } else { + pInit->hasStreamInfoBlock = MA_FALSE; + pInit->hasMetadataBlocks = MA_FALSE; + if (!ma_dr_flac__read_next_flac_frame_header(&pInit->bs, 0, &pInit->firstFrameHeader)) { + return MA_FALSE; + } + if (pInit->firstFrameHeader.bitsPerSample == 0) { + return MA_FALSE; + } + pInit->sampleRate = pInit->firstFrameHeader.sampleRate; + pInit->channels = ma_dr_flac__get_channel_count_from_channel_assignment(pInit->firstFrameHeader.channelAssignment); + pInit->bitsPerSample = pInit->firstFrameHeader.bitsPerSample; + pInit->maxBlockSizeInPCMFrames = 65535; + return MA_TRUE; + } + } else { + ma_dr_flac_streaminfo streaminfo; + if (!ma_dr_flac__read_streaminfo(onRead, pUserData, &streaminfo)) { + return MA_FALSE; + } + pInit->hasStreamInfoBlock = MA_TRUE; + pInit->sampleRate = streaminfo.sampleRate; + pInit->channels = streaminfo.channels; + pInit->bitsPerSample = streaminfo.bitsPerSample; + pInit->totalPCMFrameCount = streaminfo.totalPCMFrameCount; + pInit->maxBlockSizeInPCMFrames = streaminfo.maxBlockSizeInPCMFrames; + pInit->hasMetadataBlocks = !isLastBlock; + if (onMeta) { + ma_dr_flac_metadata metadata; + metadata.type = MA_DR_FLAC_METADATA_BLOCK_TYPE_STREAMINFO; + metadata.pRawData = NULL; + metadata.rawDataSize = 0; + metadata.data.streaminfo = streaminfo; + onMeta(pUserDataMD, &metadata); + } + return MA_TRUE; + } +} +#ifndef MA_DR_FLAC_NO_OGG +#define MA_DR_FLAC_OGG_MAX_PAGE_SIZE 65307 +#define MA_DR_FLAC_OGG_CAPTURE_PATTERN_CRC32 1605413199 +typedef enum +{ + ma_dr_flac_ogg_recover_on_crc_mismatch, + ma_dr_flac_ogg_fail_on_crc_mismatch +} ma_dr_flac_ogg_crc_mismatch_recovery; +#ifndef MA_DR_FLAC_NO_CRC +static ma_uint32 ma_dr_flac__crc32_table[] = { + 0x00000000L, 0x04C11DB7L, 0x09823B6EL, 0x0D4326D9L, + 0x130476DCL, 0x17C56B6BL, 0x1A864DB2L, 0x1E475005L, + 0x2608EDB8L, 0x22C9F00FL, 0x2F8AD6D6L, 0x2B4BCB61L, + 0x350C9B64L, 0x31CD86D3L, 0x3C8EA00AL, 0x384FBDBDL, + 0x4C11DB70L, 0x48D0C6C7L, 0x4593E01EL, 0x4152FDA9L, + 0x5F15ADACL, 0x5BD4B01BL, 0x569796C2L, 0x52568B75L, + 0x6A1936C8L, 0x6ED82B7FL, 0x639B0DA6L, 0x675A1011L, + 0x791D4014L, 0x7DDC5DA3L, 0x709F7B7AL, 0x745E66CDL, + 0x9823B6E0L, 0x9CE2AB57L, 0x91A18D8EL, 0x95609039L, + 0x8B27C03CL, 0x8FE6DD8BL, 0x82A5FB52L, 0x8664E6E5L, + 0xBE2B5B58L, 0xBAEA46EFL, 0xB7A96036L, 0xB3687D81L, + 0xAD2F2D84L, 0xA9EE3033L, 0xA4AD16EAL, 0xA06C0B5DL, + 0xD4326D90L, 0xD0F37027L, 0xDDB056FEL, 0xD9714B49L, + 0xC7361B4CL, 0xC3F706FBL, 0xCEB42022L, 0xCA753D95L, + 0xF23A8028L, 0xF6FB9D9FL, 0xFBB8BB46L, 0xFF79A6F1L, + 0xE13EF6F4L, 0xE5FFEB43L, 0xE8BCCD9AL, 0xEC7DD02DL, + 0x34867077L, 0x30476DC0L, 0x3D044B19L, 0x39C556AEL, + 0x278206ABL, 0x23431B1CL, 0x2E003DC5L, 0x2AC12072L, + 0x128E9DCFL, 0x164F8078L, 0x1B0CA6A1L, 0x1FCDBB16L, + 0x018AEB13L, 0x054BF6A4L, 0x0808D07DL, 0x0CC9CDCAL, + 0x7897AB07L, 0x7C56B6B0L, 0x71159069L, 0x75D48DDEL, + 0x6B93DDDBL, 0x6F52C06CL, 0x6211E6B5L, 0x66D0FB02L, + 0x5E9F46BFL, 0x5A5E5B08L, 0x571D7DD1L, 0x53DC6066L, + 0x4D9B3063L, 0x495A2DD4L, 0x44190B0DL, 0x40D816BAL, + 0xACA5C697L, 0xA864DB20L, 0xA527FDF9L, 0xA1E6E04EL, + 0xBFA1B04BL, 0xBB60ADFCL, 0xB6238B25L, 0xB2E29692L, + 0x8AAD2B2FL, 0x8E6C3698L, 0x832F1041L, 0x87EE0DF6L, + 0x99A95DF3L, 0x9D684044L, 0x902B669DL, 0x94EA7B2AL, + 0xE0B41DE7L, 0xE4750050L, 0xE9362689L, 0xEDF73B3EL, + 0xF3B06B3BL, 0xF771768CL, 0xFA325055L, 0xFEF34DE2L, + 0xC6BCF05FL, 0xC27DEDE8L, 0xCF3ECB31L, 0xCBFFD686L, + 0xD5B88683L, 0xD1799B34L, 0xDC3ABDEDL, 0xD8FBA05AL, + 0x690CE0EEL, 0x6DCDFD59L, 0x608EDB80L, 0x644FC637L, + 0x7A089632L, 0x7EC98B85L, 0x738AAD5CL, 0x774BB0EBL, + 0x4F040D56L, 0x4BC510E1L, 0x46863638L, 0x42472B8FL, + 0x5C007B8AL, 0x58C1663DL, 0x558240E4L, 0x51435D53L, + 0x251D3B9EL, 0x21DC2629L, 0x2C9F00F0L, 0x285E1D47L, + 0x36194D42L, 0x32D850F5L, 0x3F9B762CL, 0x3B5A6B9BL, + 0x0315D626L, 0x07D4CB91L, 0x0A97ED48L, 0x0E56F0FFL, + 0x1011A0FAL, 0x14D0BD4DL, 0x19939B94L, 0x1D528623L, + 0xF12F560EL, 0xF5EE4BB9L, 0xF8AD6D60L, 0xFC6C70D7L, + 0xE22B20D2L, 0xE6EA3D65L, 0xEBA91BBCL, 0xEF68060BL, + 0xD727BBB6L, 0xD3E6A601L, 0xDEA580D8L, 0xDA649D6FL, + 0xC423CD6AL, 0xC0E2D0DDL, 0xCDA1F604L, 0xC960EBB3L, + 0xBD3E8D7EL, 0xB9FF90C9L, 0xB4BCB610L, 0xB07DABA7L, + 0xAE3AFBA2L, 0xAAFBE615L, 0xA7B8C0CCL, 0xA379DD7BL, + 0x9B3660C6L, 0x9FF77D71L, 0x92B45BA8L, 0x9675461FL, + 0x8832161AL, 0x8CF30BADL, 0x81B02D74L, 0x857130C3L, + 0x5D8A9099L, 0x594B8D2EL, 0x5408ABF7L, 0x50C9B640L, + 0x4E8EE645L, 0x4A4FFBF2L, 0x470CDD2BL, 0x43CDC09CL, + 0x7B827D21L, 0x7F436096L, 0x7200464FL, 0x76C15BF8L, + 0x68860BFDL, 0x6C47164AL, 0x61043093L, 0x65C52D24L, + 0x119B4BE9L, 0x155A565EL, 0x18197087L, 0x1CD86D30L, + 0x029F3D35L, 0x065E2082L, 0x0B1D065BL, 0x0FDC1BECL, + 0x3793A651L, 0x3352BBE6L, 0x3E119D3FL, 0x3AD08088L, + 0x2497D08DL, 0x2056CD3AL, 0x2D15EBE3L, 0x29D4F654L, + 0xC5A92679L, 0xC1683BCEL, 0xCC2B1D17L, 0xC8EA00A0L, + 0xD6AD50A5L, 0xD26C4D12L, 0xDF2F6BCBL, 0xDBEE767CL, + 0xE3A1CBC1L, 0xE760D676L, 0xEA23F0AFL, 0xEEE2ED18L, + 0xF0A5BD1DL, 0xF464A0AAL, 0xF9278673L, 0xFDE69BC4L, + 0x89B8FD09L, 0x8D79E0BEL, 0x803AC667L, 0x84FBDBD0L, + 0x9ABC8BD5L, 0x9E7D9662L, 0x933EB0BBL, 0x97FFAD0CL, + 0xAFB010B1L, 0xAB710D06L, 0xA6322BDFL, 0xA2F33668L, + 0xBCB4666DL, 0xB8757BDAL, 0xB5365D03L, 0xB1F740B4L +}; +#endif +static MA_INLINE ma_uint32 ma_dr_flac_crc32_byte(ma_uint32 crc32, ma_uint8 data) +{ +#ifndef MA_DR_FLAC_NO_CRC + return (crc32 << 8) ^ ma_dr_flac__crc32_table[(ma_uint8)((crc32 >> 24) & 0xFF) ^ data]; +#else + (void)data; + return crc32; +#endif +} +#if 0 +static MA_INLINE ma_uint32 ma_dr_flac_crc32_uint32(ma_uint32 crc32, ma_uint32 data) +{ + crc32 = ma_dr_flac_crc32_byte(crc32, (ma_uint8)((data >> 24) & 0xFF)); + crc32 = ma_dr_flac_crc32_byte(crc32, (ma_uint8)((data >> 16) & 0xFF)); + crc32 = ma_dr_flac_crc32_byte(crc32, (ma_uint8)((data >> 8) & 0xFF)); + crc32 = ma_dr_flac_crc32_byte(crc32, (ma_uint8)((data >> 0) & 0xFF)); + return crc32; +} +static MA_INLINE ma_uint32 ma_dr_flac_crc32_uint64(ma_uint32 crc32, ma_uint64 data) +{ + crc32 = ma_dr_flac_crc32_uint32(crc32, (ma_uint32)((data >> 32) & 0xFFFFFFFF)); + crc32 = ma_dr_flac_crc32_uint32(crc32, (ma_uint32)((data >> 0) & 0xFFFFFFFF)); + return crc32; +} +#endif +static MA_INLINE ma_uint32 ma_dr_flac_crc32_buffer(ma_uint32 crc32, ma_uint8* pData, ma_uint32 dataSize) +{ + ma_uint32 i; + for (i = 0; i < dataSize; ++i) { + crc32 = ma_dr_flac_crc32_byte(crc32, pData[i]); + } + return crc32; +} +static MA_INLINE ma_bool32 ma_dr_flac_ogg__is_capture_pattern(ma_uint8 pattern[4]) +{ + return pattern[0] == 'O' && pattern[1] == 'g' && pattern[2] == 'g' && pattern[3] == 'S'; +} +static MA_INLINE ma_uint32 ma_dr_flac_ogg__get_page_header_size(ma_dr_flac_ogg_page_header* pHeader) +{ + return 27 + pHeader->segmentCount; +} +static MA_INLINE ma_uint32 ma_dr_flac_ogg__get_page_body_size(ma_dr_flac_ogg_page_header* pHeader) +{ + ma_uint32 pageBodySize = 0; + int i; + for (i = 0; i < pHeader->segmentCount; ++i) { + pageBodySize += pHeader->segmentTable[i]; + } + return pageBodySize; +} +static ma_result ma_dr_flac_ogg__read_page_header_after_capture_pattern(ma_dr_flac_read_proc onRead, void* pUserData, ma_dr_flac_ogg_page_header* pHeader, ma_uint32* pBytesRead, ma_uint32* pCRC32) +{ + ma_uint8 data[23]; + ma_uint32 i; + MA_DR_FLAC_ASSERT(*pCRC32 == MA_DR_FLAC_OGG_CAPTURE_PATTERN_CRC32); + if (onRead(pUserData, data, 23) != 23) { + return MA_AT_END; + } + *pBytesRead += 23; + pHeader->capturePattern[0] = 'O'; + pHeader->capturePattern[1] = 'g'; + pHeader->capturePattern[2] = 'g'; + pHeader->capturePattern[3] = 'S'; + pHeader->structureVersion = data[0]; + pHeader->headerType = data[1]; + MA_DR_FLAC_COPY_MEMORY(&pHeader->granulePosition, &data[ 2], 8); + MA_DR_FLAC_COPY_MEMORY(&pHeader->serialNumber, &data[10], 4); + MA_DR_FLAC_COPY_MEMORY(&pHeader->sequenceNumber, &data[14], 4); + MA_DR_FLAC_COPY_MEMORY(&pHeader->checksum, &data[18], 4); + pHeader->segmentCount = data[22]; + data[18] = 0; + data[19] = 0; + data[20] = 0; + data[21] = 0; + for (i = 0; i < 23; ++i) { + *pCRC32 = ma_dr_flac_crc32_byte(*pCRC32, data[i]); + } + if (onRead(pUserData, pHeader->segmentTable, pHeader->segmentCount) != pHeader->segmentCount) { + return MA_AT_END; + } + *pBytesRead += pHeader->segmentCount; + for (i = 0; i < pHeader->segmentCount; ++i) { + *pCRC32 = ma_dr_flac_crc32_byte(*pCRC32, pHeader->segmentTable[i]); + } + return MA_SUCCESS; +} +static ma_result ma_dr_flac_ogg__read_page_header(ma_dr_flac_read_proc onRead, void* pUserData, ma_dr_flac_ogg_page_header* pHeader, ma_uint32* pBytesRead, ma_uint32* pCRC32) +{ + ma_uint8 id[4]; + *pBytesRead = 0; + if (onRead(pUserData, id, 4) != 4) { + return MA_AT_END; + } + *pBytesRead += 4; + for (;;) { + if (ma_dr_flac_ogg__is_capture_pattern(id)) { + ma_result result; + *pCRC32 = MA_DR_FLAC_OGG_CAPTURE_PATTERN_CRC32; + result = ma_dr_flac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, pHeader, pBytesRead, pCRC32); + if (result == MA_SUCCESS) { + return MA_SUCCESS; + } else { + if (result == MA_CRC_MISMATCH) { + continue; + } else { + return result; + } + } + } else { + id[0] = id[1]; + id[1] = id[2]; + id[2] = id[3]; + if (onRead(pUserData, &id[3], 1) != 1) { + return MA_AT_END; + } + *pBytesRead += 1; + } + } +} +typedef struct +{ + ma_dr_flac_read_proc onRead; + ma_dr_flac_seek_proc onSeek; + void* pUserData; + ma_uint64 currentBytePos; + ma_uint64 firstBytePos; + ma_uint32 serialNumber; + ma_dr_flac_ogg_page_header bosPageHeader; + ma_dr_flac_ogg_page_header currentPageHeader; + ma_uint32 bytesRemainingInPage; + ma_uint32 pageDataSize; + ma_uint8 pageData[MA_DR_FLAC_OGG_MAX_PAGE_SIZE]; +} ma_dr_flac_oggbs; +static size_t ma_dr_flac_oggbs__read_physical(ma_dr_flac_oggbs* oggbs, void* bufferOut, size_t bytesToRead) +{ + size_t bytesActuallyRead = oggbs->onRead(oggbs->pUserData, bufferOut, bytesToRead); + oggbs->currentBytePos += bytesActuallyRead; + return bytesActuallyRead; +} +static ma_bool32 ma_dr_flac_oggbs__seek_physical(ma_dr_flac_oggbs* oggbs, ma_uint64 offset, ma_dr_flac_seek_origin origin) +{ + if (origin == ma_dr_flac_seek_origin_start) { + if (offset <= 0x7FFFFFFF) { + if (!oggbs->onSeek(oggbs->pUserData, (int)offset, ma_dr_flac_seek_origin_start)) { + return MA_FALSE; + } + oggbs->currentBytePos = offset; + return MA_TRUE; + } else { + if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, ma_dr_flac_seek_origin_start)) { + return MA_FALSE; + } + oggbs->currentBytePos = offset; + return ma_dr_flac_oggbs__seek_physical(oggbs, offset - 0x7FFFFFFF, ma_dr_flac_seek_origin_current); + } + } else { + while (offset > 0x7FFFFFFF) { + if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, ma_dr_flac_seek_origin_current)) { + return MA_FALSE; + } + oggbs->currentBytePos += 0x7FFFFFFF; + offset -= 0x7FFFFFFF; + } + if (!oggbs->onSeek(oggbs->pUserData, (int)offset, ma_dr_flac_seek_origin_current)) { + return MA_FALSE; + } + oggbs->currentBytePos += offset; + return MA_TRUE; + } +} +static ma_bool32 ma_dr_flac_oggbs__goto_next_page(ma_dr_flac_oggbs* oggbs, ma_dr_flac_ogg_crc_mismatch_recovery recoveryMethod) +{ + ma_dr_flac_ogg_page_header header; + for (;;) { + ma_uint32 crc32 = 0; + ma_uint32 bytesRead; + ma_uint32 pageBodySize; +#ifndef MA_DR_FLAC_NO_CRC + ma_uint32 actualCRC32; +#endif + if (ma_dr_flac_ogg__read_page_header(oggbs->onRead, oggbs->pUserData, &header, &bytesRead, &crc32) != MA_SUCCESS) { + return MA_FALSE; + } + oggbs->currentBytePos += bytesRead; + pageBodySize = ma_dr_flac_ogg__get_page_body_size(&header); + if (pageBodySize > MA_DR_FLAC_OGG_MAX_PAGE_SIZE) { + continue; + } + if (header.serialNumber != oggbs->serialNumber) { + if (pageBodySize > 0 && !ma_dr_flac_oggbs__seek_physical(oggbs, pageBodySize, ma_dr_flac_seek_origin_current)) { + return MA_FALSE; + } + continue; + } + if (ma_dr_flac_oggbs__read_physical(oggbs, oggbs->pageData, pageBodySize) != pageBodySize) { + return MA_FALSE; + } + oggbs->pageDataSize = pageBodySize; +#ifndef MA_DR_FLAC_NO_CRC + actualCRC32 = ma_dr_flac_crc32_buffer(crc32, oggbs->pageData, oggbs->pageDataSize); + if (actualCRC32 != header.checksum) { + if (recoveryMethod == ma_dr_flac_ogg_recover_on_crc_mismatch) { + continue; + } else { + ma_dr_flac_oggbs__goto_next_page(oggbs, ma_dr_flac_ogg_recover_on_crc_mismatch); + return MA_FALSE; + } + } +#else + (void)recoveryMethod; +#endif + oggbs->currentPageHeader = header; + oggbs->bytesRemainingInPage = pageBodySize; + return MA_TRUE; + } +} +#if 0 +static ma_uint8 ma_dr_flac_oggbs__get_current_segment_index(ma_dr_flac_oggbs* oggbs, ma_uint8* pBytesRemainingInSeg) +{ + ma_uint32 bytesConsumedInPage = ma_dr_flac_ogg__get_page_body_size(&oggbs->currentPageHeader) - oggbs->bytesRemainingInPage; + ma_uint8 iSeg = 0; + ma_uint32 iByte = 0; + while (iByte < bytesConsumedInPage) { + ma_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg]; + if (iByte + segmentSize > bytesConsumedInPage) { + break; + } else { + iSeg += 1; + iByte += segmentSize; + } + } + *pBytesRemainingInSeg = oggbs->currentPageHeader.segmentTable[iSeg] - (ma_uint8)(bytesConsumedInPage - iByte); + return iSeg; +} +static ma_bool32 ma_dr_flac_oggbs__seek_to_next_packet(ma_dr_flac_oggbs* oggbs) +{ + for (;;) { + ma_bool32 atEndOfPage = MA_FALSE; + ma_uint8 bytesRemainingInSeg; + ma_uint8 iFirstSeg = ma_dr_flac_oggbs__get_current_segment_index(oggbs, &bytesRemainingInSeg); + ma_uint32 bytesToEndOfPacketOrPage = bytesRemainingInSeg; + for (ma_uint8 iSeg = iFirstSeg; iSeg < oggbs->currentPageHeader.segmentCount; ++iSeg) { + ma_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg]; + if (segmentSize < 255) { + if (iSeg == oggbs->currentPageHeader.segmentCount-1) { + atEndOfPage = MA_TRUE; + } + break; + } + bytesToEndOfPacketOrPage += segmentSize; + } + ma_dr_flac_oggbs__seek_physical(oggbs, bytesToEndOfPacketOrPage, ma_dr_flac_seek_origin_current); + oggbs->bytesRemainingInPage -= bytesToEndOfPacketOrPage; + if (atEndOfPage) { + if (!ma_dr_flac_oggbs__goto_next_page(oggbs)) { + return MA_FALSE; + } + if ((oggbs->currentPageHeader.headerType & 0x01) == 0) { + return MA_TRUE; + } + } else { + return MA_TRUE; + } + } +} +static ma_bool32 ma_dr_flac_oggbs__seek_to_next_frame(ma_dr_flac_oggbs* oggbs) +{ + return ma_dr_flac_oggbs__seek_to_next_packet(oggbs); +} +#endif +static size_t ma_dr_flac__on_read_ogg(void* pUserData, void* bufferOut, size_t bytesToRead) +{ + ma_dr_flac_oggbs* oggbs = (ma_dr_flac_oggbs*)pUserData; + ma_uint8* pRunningBufferOut = (ma_uint8*)bufferOut; + size_t bytesRead = 0; + MA_DR_FLAC_ASSERT(oggbs != NULL); + MA_DR_FLAC_ASSERT(pRunningBufferOut != NULL); + while (bytesRead < bytesToRead) { + size_t bytesRemainingToRead = bytesToRead - bytesRead; + if (oggbs->bytesRemainingInPage >= bytesRemainingToRead) { + MA_DR_FLAC_COPY_MEMORY(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), bytesRemainingToRead); + bytesRead += bytesRemainingToRead; + oggbs->bytesRemainingInPage -= (ma_uint32)bytesRemainingToRead; + break; + } + if (oggbs->bytesRemainingInPage > 0) { + MA_DR_FLAC_COPY_MEMORY(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), oggbs->bytesRemainingInPage); + bytesRead += oggbs->bytesRemainingInPage; + pRunningBufferOut += oggbs->bytesRemainingInPage; + oggbs->bytesRemainingInPage = 0; + } + MA_DR_FLAC_ASSERT(bytesRemainingToRead > 0); + if (!ma_dr_flac_oggbs__goto_next_page(oggbs, ma_dr_flac_ogg_recover_on_crc_mismatch)) { + break; + } + } + return bytesRead; +} +static ma_bool32 ma_dr_flac__on_seek_ogg(void* pUserData, int offset, ma_dr_flac_seek_origin origin) +{ + ma_dr_flac_oggbs* oggbs = (ma_dr_flac_oggbs*)pUserData; + int bytesSeeked = 0; + MA_DR_FLAC_ASSERT(oggbs != NULL); + MA_DR_FLAC_ASSERT(offset >= 0); + if (origin == ma_dr_flac_seek_origin_start) { + if (!ma_dr_flac_oggbs__seek_physical(oggbs, (int)oggbs->firstBytePos, ma_dr_flac_seek_origin_start)) { + return MA_FALSE; + } + if (!ma_dr_flac_oggbs__goto_next_page(oggbs, ma_dr_flac_ogg_fail_on_crc_mismatch)) { + return MA_FALSE; + } + return ma_dr_flac__on_seek_ogg(pUserData, offset, ma_dr_flac_seek_origin_current); + } + MA_DR_FLAC_ASSERT(origin == ma_dr_flac_seek_origin_current); + while (bytesSeeked < offset) { + int bytesRemainingToSeek = offset - bytesSeeked; + MA_DR_FLAC_ASSERT(bytesRemainingToSeek >= 0); + if (oggbs->bytesRemainingInPage >= (size_t)bytesRemainingToSeek) { + bytesSeeked += bytesRemainingToSeek; + (void)bytesSeeked; + oggbs->bytesRemainingInPage -= bytesRemainingToSeek; + break; + } + if (oggbs->bytesRemainingInPage > 0) { + bytesSeeked += (int)oggbs->bytesRemainingInPage; + oggbs->bytesRemainingInPage = 0; + } + MA_DR_FLAC_ASSERT(bytesRemainingToSeek > 0); + if (!ma_dr_flac_oggbs__goto_next_page(oggbs, ma_dr_flac_ogg_fail_on_crc_mismatch)) { + return MA_FALSE; + } + } + return MA_TRUE; +} +static ma_bool32 ma_dr_flac_ogg__seek_to_pcm_frame(ma_dr_flac* pFlac, ma_uint64 pcmFrameIndex) +{ + ma_dr_flac_oggbs* oggbs = (ma_dr_flac_oggbs*)pFlac->_oggbs; + ma_uint64 originalBytePos; + ma_uint64 runningGranulePosition; + ma_uint64 runningFrameBytePos; + ma_uint64 runningPCMFrameCount; + MA_DR_FLAC_ASSERT(oggbs != NULL); + originalBytePos = oggbs->currentBytePos; + if (!ma_dr_flac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes)) { + return MA_FALSE; + } + oggbs->bytesRemainingInPage = 0; + runningGranulePosition = 0; + for (;;) { + if (!ma_dr_flac_oggbs__goto_next_page(oggbs, ma_dr_flac_ogg_recover_on_crc_mismatch)) { + ma_dr_flac_oggbs__seek_physical(oggbs, originalBytePos, ma_dr_flac_seek_origin_start); + return MA_FALSE; + } + runningFrameBytePos = oggbs->currentBytePos - ma_dr_flac_ogg__get_page_header_size(&oggbs->currentPageHeader) - oggbs->pageDataSize; + if (oggbs->currentPageHeader.granulePosition >= pcmFrameIndex) { + break; + } + if ((oggbs->currentPageHeader.headerType & 0x01) == 0) { + if (oggbs->currentPageHeader.segmentTable[0] >= 2) { + ma_uint8 firstBytesInPage[2]; + firstBytesInPage[0] = oggbs->pageData[0]; + firstBytesInPage[1] = oggbs->pageData[1]; + if ((firstBytesInPage[0] == 0xFF) && (firstBytesInPage[1] & 0xFC) == 0xF8) { + runningGranulePosition = oggbs->currentPageHeader.granulePosition; + } + continue; + } + } + } + if (!ma_dr_flac_oggbs__seek_physical(oggbs, runningFrameBytePos, ma_dr_flac_seek_origin_start)) { + return MA_FALSE; + } + if (!ma_dr_flac_oggbs__goto_next_page(oggbs, ma_dr_flac_ogg_recover_on_crc_mismatch)) { + return MA_FALSE; + } + runningPCMFrameCount = runningGranulePosition; + for (;;) { + ma_uint64 firstPCMFrameInFLACFrame = 0; + ma_uint64 lastPCMFrameInFLACFrame = 0; + ma_uint64 pcmFrameCountInThisFrame; + if (!ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + return MA_FALSE; + } + ma_dr_flac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame); + pcmFrameCountInThisFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1; + if (pcmFrameIndex == pFlac->totalPCMFrameCount && (runningPCMFrameCount + pcmFrameCountInThisFrame) == pFlac->totalPCMFrameCount) { + ma_result result = ma_dr_flac__decode_flac_frame(pFlac); + if (result == MA_SUCCESS) { + pFlac->currentPCMFrame = pcmFrameIndex; + pFlac->currentFLACFrame.pcmFramesRemaining = 0; + return MA_TRUE; + } else { + return MA_FALSE; + } + } + if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFrame)) { + ma_result result = ma_dr_flac__decode_flac_frame(pFlac); + if (result == MA_SUCCESS) { + ma_uint64 pcmFramesToDecode = (size_t)(pcmFrameIndex - runningPCMFrameCount); + if (pcmFramesToDecode == 0) { + return MA_TRUE; + } + pFlac->currentPCMFrame = runningPCMFrameCount; + return ma_dr_flac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode; + } else { + if (result == MA_CRC_MISMATCH) { + continue; + } else { + return MA_FALSE; + } + } + } else { + ma_result result = ma_dr_flac__seek_to_next_flac_frame(pFlac); + if (result == MA_SUCCESS) { + runningPCMFrameCount += pcmFrameCountInThisFrame; + } else { + if (result == MA_CRC_MISMATCH) { + continue; + } else { + return MA_FALSE; + } + } + } + } +} +static ma_bool32 ma_dr_flac__init_private__ogg(ma_dr_flac_init_info* pInit, ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_meta_proc onMeta, void* pUserData, void* pUserDataMD, ma_bool32 relaxed) +{ + ma_dr_flac_ogg_page_header header; + ma_uint32 crc32 = MA_DR_FLAC_OGG_CAPTURE_PATTERN_CRC32; + ma_uint32 bytesRead = 0; + (void)relaxed; + pInit->container = ma_dr_flac_container_ogg; + pInit->oggFirstBytePos = 0; + if (ma_dr_flac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, &header, &bytesRead, &crc32) != MA_SUCCESS) { + return MA_FALSE; + } + pInit->runningFilePos += bytesRead; + for (;;) { + int pageBodySize; + if ((header.headerType & 0x02) == 0) { + return MA_FALSE; + } + pageBodySize = ma_dr_flac_ogg__get_page_body_size(&header); + if (pageBodySize == 51) { + ma_uint32 bytesRemainingInPage = pageBodySize; + ma_uint8 packetType; + if (onRead(pUserData, &packetType, 1) != 1) { + return MA_FALSE; + } + bytesRemainingInPage -= 1; + if (packetType == 0x7F) { + ma_uint8 sig[4]; + if (onRead(pUserData, sig, 4) != 4) { + return MA_FALSE; + } + bytesRemainingInPage -= 4; + if (sig[0] == 'F' && sig[1] == 'L' && sig[2] == 'A' && sig[3] == 'C') { + ma_uint8 mappingVersion[2]; + if (onRead(pUserData, mappingVersion, 2) != 2) { + return MA_FALSE; + } + if (mappingVersion[0] != 1) { + return MA_FALSE; + } + if (!onSeek(pUserData, 2, ma_dr_flac_seek_origin_current)) { + return MA_FALSE; + } + if (onRead(pUserData, sig, 4) != 4) { + return MA_FALSE; + } + if (sig[0] == 'f' && sig[1] == 'L' && sig[2] == 'a' && sig[3] == 'C') { + ma_dr_flac_streaminfo streaminfo; + ma_uint8 isLastBlock; + ma_uint8 blockType; + ma_uint32 blockSize; + if (!ma_dr_flac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) { + return MA_FALSE; + } + if (blockType != MA_DR_FLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) { + return MA_FALSE; + } + if (ma_dr_flac__read_streaminfo(onRead, pUserData, &streaminfo)) { + pInit->hasStreamInfoBlock = MA_TRUE; + pInit->sampleRate = streaminfo.sampleRate; + pInit->channels = streaminfo.channels; + pInit->bitsPerSample = streaminfo.bitsPerSample; + pInit->totalPCMFrameCount = streaminfo.totalPCMFrameCount; + pInit->maxBlockSizeInPCMFrames = streaminfo.maxBlockSizeInPCMFrames; + pInit->hasMetadataBlocks = !isLastBlock; + if (onMeta) { + ma_dr_flac_metadata metadata; + metadata.type = MA_DR_FLAC_METADATA_BLOCK_TYPE_STREAMINFO; + metadata.pRawData = NULL; + metadata.rawDataSize = 0; + metadata.data.streaminfo = streaminfo; + onMeta(pUserDataMD, &metadata); + } + pInit->runningFilePos += pageBodySize; + pInit->oggFirstBytePos = pInit->runningFilePos - 79; + pInit->oggSerial = header.serialNumber; + pInit->oggBosHeader = header; + break; + } else { + return MA_FALSE; + } + } else { + return MA_FALSE; + } + } else { + if (!onSeek(pUserData, bytesRemainingInPage, ma_dr_flac_seek_origin_current)) { + return MA_FALSE; + } + } + } else { + if (!onSeek(pUserData, bytesRemainingInPage, ma_dr_flac_seek_origin_current)) { + return MA_FALSE; + } + } + } else { + if (!onSeek(pUserData, pageBodySize, ma_dr_flac_seek_origin_current)) { + return MA_FALSE; + } + } + pInit->runningFilePos += pageBodySize; + if (ma_dr_flac_ogg__read_page_header(onRead, pUserData, &header, &bytesRead, &crc32) != MA_SUCCESS) { + return MA_FALSE; + } + pInit->runningFilePos += bytesRead; + } + pInit->hasMetadataBlocks = MA_TRUE; + return MA_TRUE; +} +#endif +static ma_bool32 ma_dr_flac__init_private(ma_dr_flac_init_info* pInit, ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_meta_proc onMeta, ma_dr_flac_container container, void* pUserData, void* pUserDataMD) +{ + ma_bool32 relaxed; + ma_uint8 id[4]; + if (pInit == NULL || onRead == NULL || onSeek == NULL) { + return MA_FALSE; + } + MA_DR_FLAC_ZERO_MEMORY(pInit, sizeof(*pInit)); + pInit->onRead = onRead; + pInit->onSeek = onSeek; + pInit->onMeta = onMeta; + pInit->container = container; + pInit->pUserData = pUserData; + pInit->pUserDataMD = pUserDataMD; + pInit->bs.onRead = onRead; + pInit->bs.onSeek = onSeek; + pInit->bs.pUserData = pUserData; + ma_dr_flac__reset_cache(&pInit->bs); + relaxed = container != ma_dr_flac_container_unknown; + for (;;) { + if (onRead(pUserData, id, 4) != 4) { + return MA_FALSE; + } + pInit->runningFilePos += 4; + if (id[0] == 'I' && id[1] == 'D' && id[2] == '3') { + ma_uint8 header[6]; + ma_uint8 flags; + ma_uint32 headerSize; + if (onRead(pUserData, header, 6) != 6) { + return MA_FALSE; + } + pInit->runningFilePos += 6; + flags = header[1]; + MA_DR_FLAC_COPY_MEMORY(&headerSize, header+2, 4); + headerSize = ma_dr_flac__unsynchsafe_32(ma_dr_flac__be2host_32(headerSize)); + if (flags & 0x10) { + headerSize += 10; + } + if (!onSeek(pUserData, headerSize, ma_dr_flac_seek_origin_current)) { + return MA_FALSE; + } + pInit->runningFilePos += headerSize; + } else { + break; + } + } + if (id[0] == 'f' && id[1] == 'L' && id[2] == 'a' && id[3] == 'C') { + return ma_dr_flac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed); + } +#ifndef MA_DR_FLAC_NO_OGG + if (id[0] == 'O' && id[1] == 'g' && id[2] == 'g' && id[3] == 'S') { + return ma_dr_flac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed); + } +#endif + if (relaxed) { + if (container == ma_dr_flac_container_native) { + return ma_dr_flac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed); + } +#ifndef MA_DR_FLAC_NO_OGG + if (container == ma_dr_flac_container_ogg) { + return ma_dr_flac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed); + } +#endif + } + return MA_FALSE; +} +static void ma_dr_flac__init_from_info(ma_dr_flac* pFlac, const ma_dr_flac_init_info* pInit) +{ + MA_DR_FLAC_ASSERT(pFlac != NULL); + MA_DR_FLAC_ASSERT(pInit != NULL); + MA_DR_FLAC_ZERO_MEMORY(pFlac, sizeof(*pFlac)); + pFlac->bs = pInit->bs; + pFlac->onMeta = pInit->onMeta; + pFlac->pUserDataMD = pInit->pUserDataMD; + pFlac->maxBlockSizeInPCMFrames = pInit->maxBlockSizeInPCMFrames; + pFlac->sampleRate = pInit->sampleRate; + pFlac->channels = (ma_uint8)pInit->channels; + pFlac->bitsPerSample = (ma_uint8)pInit->bitsPerSample; + pFlac->totalPCMFrameCount = pInit->totalPCMFrameCount; + pFlac->container = pInit->container; +} +static ma_dr_flac* ma_dr_flac_open_with_metadata_private(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_meta_proc onMeta, ma_dr_flac_container container, void* pUserData, void* pUserDataMD, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_flac_init_info init; + ma_uint32 allocationSize; + ma_uint32 wholeSIMDVectorCountPerChannel; + ma_uint32 decodedSamplesAllocationSize; +#ifndef MA_DR_FLAC_NO_OGG + ma_dr_flac_oggbs* pOggbs = NULL; +#endif + ma_uint64 firstFramePos; + ma_uint64 seektablePos; + ma_uint32 seekpointCount; + ma_allocation_callbacks allocationCallbacks; + ma_dr_flac* pFlac; + ma_dr_flac__init_cpu_caps(); + if (!ma_dr_flac__init_private(&init, onRead, onSeek, onMeta, container, pUserData, pUserDataMD)) { + return NULL; + } + if (pAllocationCallbacks != NULL) { + allocationCallbacks = *pAllocationCallbacks; + if (allocationCallbacks.onFree == NULL || (allocationCallbacks.onMalloc == NULL && allocationCallbacks.onRealloc == NULL)) { + return NULL; + } + } else { + allocationCallbacks.pUserData = NULL; + allocationCallbacks.onMalloc = ma_dr_flac__malloc_default; + allocationCallbacks.onRealloc = ma_dr_flac__realloc_default; + allocationCallbacks.onFree = ma_dr_flac__free_default; + } + allocationSize = sizeof(ma_dr_flac); + if ((init.maxBlockSizeInPCMFrames % (MA_DR_FLAC_MAX_SIMD_VECTOR_SIZE / sizeof(ma_int32))) == 0) { + wholeSIMDVectorCountPerChannel = (init.maxBlockSizeInPCMFrames / (MA_DR_FLAC_MAX_SIMD_VECTOR_SIZE / sizeof(ma_int32))); + } else { + wholeSIMDVectorCountPerChannel = (init.maxBlockSizeInPCMFrames / (MA_DR_FLAC_MAX_SIMD_VECTOR_SIZE / sizeof(ma_int32))) + 1; + } + decodedSamplesAllocationSize = wholeSIMDVectorCountPerChannel * MA_DR_FLAC_MAX_SIMD_VECTOR_SIZE * init.channels; + allocationSize += decodedSamplesAllocationSize; + allocationSize += MA_DR_FLAC_MAX_SIMD_VECTOR_SIZE; +#ifndef MA_DR_FLAC_NO_OGG + if (init.container == ma_dr_flac_container_ogg) { + allocationSize += sizeof(ma_dr_flac_oggbs); + pOggbs = (ma_dr_flac_oggbs*)ma_dr_flac__malloc_from_callbacks(sizeof(*pOggbs), &allocationCallbacks); + if (pOggbs == NULL) { + return NULL; + } + MA_DR_FLAC_ZERO_MEMORY(pOggbs, sizeof(*pOggbs)); + pOggbs->onRead = onRead; + pOggbs->onSeek = onSeek; + pOggbs->pUserData = pUserData; + pOggbs->currentBytePos = init.oggFirstBytePos; + pOggbs->firstBytePos = init.oggFirstBytePos; + pOggbs->serialNumber = init.oggSerial; + pOggbs->bosPageHeader = init.oggBosHeader; + pOggbs->bytesRemainingInPage = 0; + } +#endif + firstFramePos = 42; + seektablePos = 0; + seekpointCount = 0; + if (init.hasMetadataBlocks) { + ma_dr_flac_read_proc onReadOverride = onRead; + ma_dr_flac_seek_proc onSeekOverride = onSeek; + void* pUserDataOverride = pUserData; +#ifndef MA_DR_FLAC_NO_OGG + if (init.container == ma_dr_flac_container_ogg) { + onReadOverride = ma_dr_flac__on_read_ogg; + onSeekOverride = ma_dr_flac__on_seek_ogg; + pUserDataOverride = (void*)pOggbs; + } +#endif + if (!ma_dr_flac__read_and_decode_metadata(onReadOverride, onSeekOverride, onMeta, pUserDataOverride, pUserDataMD, &firstFramePos, &seektablePos, &seekpointCount, &allocationCallbacks)) { + #ifndef MA_DR_FLAC_NO_OGG + ma_dr_flac__free_from_callbacks(pOggbs, &allocationCallbacks); + #endif + return NULL; + } + allocationSize += seekpointCount * sizeof(ma_dr_flac_seekpoint); + } + pFlac = (ma_dr_flac*)ma_dr_flac__malloc_from_callbacks(allocationSize, &allocationCallbacks); + if (pFlac == NULL) { + #ifndef MA_DR_FLAC_NO_OGG + ma_dr_flac__free_from_callbacks(pOggbs, &allocationCallbacks); + #endif + return NULL; + } + ma_dr_flac__init_from_info(pFlac, &init); + pFlac->allocationCallbacks = allocationCallbacks; + pFlac->pDecodedSamples = (ma_int32*)ma_dr_flac_align((size_t)pFlac->pExtraData, MA_DR_FLAC_MAX_SIMD_VECTOR_SIZE); +#ifndef MA_DR_FLAC_NO_OGG + if (init.container == ma_dr_flac_container_ogg) { + ma_dr_flac_oggbs* pInternalOggbs = (ma_dr_flac_oggbs*)((ma_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize + (seekpointCount * sizeof(ma_dr_flac_seekpoint))); + MA_DR_FLAC_COPY_MEMORY(pInternalOggbs, pOggbs, sizeof(*pOggbs)); + ma_dr_flac__free_from_callbacks(pOggbs, &allocationCallbacks); + pOggbs = NULL; + pFlac->bs.onRead = ma_dr_flac__on_read_ogg; + pFlac->bs.onSeek = ma_dr_flac__on_seek_ogg; + pFlac->bs.pUserData = (void*)pInternalOggbs; + pFlac->_oggbs = (void*)pInternalOggbs; + } +#endif + pFlac->firstFLACFramePosInBytes = firstFramePos; +#ifndef MA_DR_FLAC_NO_OGG + if (init.container == ma_dr_flac_container_ogg) + { + pFlac->pSeekpoints = NULL; + pFlac->seekpointCount = 0; + } + else +#endif + { + if (seektablePos != 0) { + pFlac->seekpointCount = seekpointCount; + pFlac->pSeekpoints = (ma_dr_flac_seekpoint*)((ma_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize); + MA_DR_FLAC_ASSERT(pFlac->bs.onSeek != NULL); + MA_DR_FLAC_ASSERT(pFlac->bs.onRead != NULL); + if (pFlac->bs.onSeek(pFlac->bs.pUserData, (int)seektablePos, ma_dr_flac_seek_origin_start)) { + ma_uint32 iSeekpoint; + for (iSeekpoint = 0; iSeekpoint < seekpointCount; iSeekpoint += 1) { + if (pFlac->bs.onRead(pFlac->bs.pUserData, pFlac->pSeekpoints + iSeekpoint, MA_DR_FLAC_SEEKPOINT_SIZE_IN_BYTES) == MA_DR_FLAC_SEEKPOINT_SIZE_IN_BYTES) { + pFlac->pSeekpoints[iSeekpoint].firstPCMFrame = ma_dr_flac__be2host_64(pFlac->pSeekpoints[iSeekpoint].firstPCMFrame); + pFlac->pSeekpoints[iSeekpoint].flacFrameOffset = ma_dr_flac__be2host_64(pFlac->pSeekpoints[iSeekpoint].flacFrameOffset); + pFlac->pSeekpoints[iSeekpoint].pcmFrameCount = ma_dr_flac__be2host_16(pFlac->pSeekpoints[iSeekpoint].pcmFrameCount); + } else { + pFlac->pSeekpoints = NULL; + pFlac->seekpointCount = 0; + break; + } + } + if (!pFlac->bs.onSeek(pFlac->bs.pUserData, (int)pFlac->firstFLACFramePosInBytes, ma_dr_flac_seek_origin_start)) { + ma_dr_flac__free_from_callbacks(pFlac, &allocationCallbacks); + return NULL; + } + } else { + pFlac->pSeekpoints = NULL; + pFlac->seekpointCount = 0; + } + } + } + if (!init.hasStreamInfoBlock) { + pFlac->currentFLACFrame.header = init.firstFrameHeader; + for (;;) { + ma_result result = ma_dr_flac__decode_flac_frame(pFlac); + if (result == MA_SUCCESS) { + break; + } else { + if (result == MA_CRC_MISMATCH) { + if (!ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + ma_dr_flac__free_from_callbacks(pFlac, &allocationCallbacks); + return NULL; + } + continue; + } else { + ma_dr_flac__free_from_callbacks(pFlac, &allocationCallbacks); + return NULL; + } + } + } + } + return pFlac; +} +#ifndef MA_DR_FLAC_NO_STDIO +#include +#ifndef MA_DR_FLAC_NO_WCHAR +#include +#endif +static size_t ma_dr_flac__on_read_stdio(void* pUserData, void* bufferOut, size_t bytesToRead) +{ + return fread(bufferOut, 1, bytesToRead, (FILE*)pUserData); +} +static ma_bool32 ma_dr_flac__on_seek_stdio(void* pUserData, int offset, ma_dr_flac_seek_origin origin) +{ + MA_DR_FLAC_ASSERT(offset >= 0); + return fseek((FILE*)pUserData, offset, (origin == ma_dr_flac_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0; +} +MA_API ma_dr_flac* ma_dr_flac_open_file(const char* pFileName, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_flac* pFlac; + FILE* pFile; + if (ma_fopen(&pFile, pFileName, "rb") != MA_SUCCESS) { + return NULL; + } + pFlac = ma_dr_flac_open(ma_dr_flac__on_read_stdio, ma_dr_flac__on_seek_stdio, (void*)pFile, pAllocationCallbacks); + if (pFlac == NULL) { + fclose(pFile); + return NULL; + } + return pFlac; +} +#ifndef MA_DR_FLAC_NO_WCHAR +MA_API ma_dr_flac* ma_dr_flac_open_file_w(const wchar_t* pFileName, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_flac* pFlac; + FILE* pFile; + if (ma_wfopen(&pFile, pFileName, L"rb", pAllocationCallbacks) != MA_SUCCESS) { + return NULL; + } + pFlac = ma_dr_flac_open(ma_dr_flac__on_read_stdio, ma_dr_flac__on_seek_stdio, (void*)pFile, pAllocationCallbacks); + if (pFlac == NULL) { + fclose(pFile); + return NULL; + } + return pFlac; +} +#endif +MA_API ma_dr_flac* ma_dr_flac_open_file_with_metadata(const char* pFileName, ma_dr_flac_meta_proc onMeta, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_flac* pFlac; + FILE* pFile; + if (ma_fopen(&pFile, pFileName, "rb") != MA_SUCCESS) { + return NULL; + } + pFlac = ma_dr_flac_open_with_metadata_private(ma_dr_flac__on_read_stdio, ma_dr_flac__on_seek_stdio, onMeta, ma_dr_flac_container_unknown, (void*)pFile, pUserData, pAllocationCallbacks); + if (pFlac == NULL) { + fclose(pFile); + return pFlac; + } + return pFlac; +} +#ifndef MA_DR_FLAC_NO_WCHAR +MA_API ma_dr_flac* ma_dr_flac_open_file_with_metadata_w(const wchar_t* pFileName, ma_dr_flac_meta_proc onMeta, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_flac* pFlac; + FILE* pFile; + if (ma_wfopen(&pFile, pFileName, L"rb", pAllocationCallbacks) != MA_SUCCESS) { + return NULL; + } + pFlac = ma_dr_flac_open_with_metadata_private(ma_dr_flac__on_read_stdio, ma_dr_flac__on_seek_stdio, onMeta, ma_dr_flac_container_unknown, (void*)pFile, pUserData, pAllocationCallbacks); + if (pFlac == NULL) { + fclose(pFile); + return pFlac; + } + return pFlac; +} +#endif +#endif +static size_t ma_dr_flac__on_read_memory(void* pUserData, void* bufferOut, size_t bytesToRead) +{ + ma_dr_flac__memory_stream* memoryStream = (ma_dr_flac__memory_stream*)pUserData; + size_t bytesRemaining; + MA_DR_FLAC_ASSERT(memoryStream != NULL); + MA_DR_FLAC_ASSERT(memoryStream->dataSize >= memoryStream->currentReadPos); + bytesRemaining = memoryStream->dataSize - memoryStream->currentReadPos; + if (bytesToRead > bytesRemaining) { + bytesToRead = bytesRemaining; + } + if (bytesToRead > 0) { + MA_DR_FLAC_COPY_MEMORY(bufferOut, memoryStream->data + memoryStream->currentReadPos, bytesToRead); + memoryStream->currentReadPos += bytesToRead; + } + return bytesToRead; +} +static ma_bool32 ma_dr_flac__on_seek_memory(void* pUserData, int offset, ma_dr_flac_seek_origin origin) +{ + ma_dr_flac__memory_stream* memoryStream = (ma_dr_flac__memory_stream*)pUserData; + MA_DR_FLAC_ASSERT(memoryStream != NULL); + MA_DR_FLAC_ASSERT(offset >= 0); + if (offset > (ma_int64)memoryStream->dataSize) { + return MA_FALSE; + } + if (origin == ma_dr_flac_seek_origin_current) { + if (memoryStream->currentReadPos + offset <= memoryStream->dataSize) { + memoryStream->currentReadPos += offset; + } else { + return MA_FALSE; + } + } else { + if ((ma_uint32)offset <= memoryStream->dataSize) { + memoryStream->currentReadPos = offset; + } else { + return MA_FALSE; + } + } + return MA_TRUE; +} +MA_API ma_dr_flac* ma_dr_flac_open_memory(const void* pData, size_t dataSize, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_flac__memory_stream memoryStream; + ma_dr_flac* pFlac; + memoryStream.data = (const ma_uint8*)pData; + memoryStream.dataSize = dataSize; + memoryStream.currentReadPos = 0; + pFlac = ma_dr_flac_open(ma_dr_flac__on_read_memory, ma_dr_flac__on_seek_memory, &memoryStream, pAllocationCallbacks); + if (pFlac == NULL) { + return NULL; + } + pFlac->memoryStream = memoryStream; +#ifndef MA_DR_FLAC_NO_OGG + if (pFlac->container == ma_dr_flac_container_ogg) + { + ma_dr_flac_oggbs* oggbs = (ma_dr_flac_oggbs*)pFlac->_oggbs; + oggbs->pUserData = &pFlac->memoryStream; + } + else +#endif + { + pFlac->bs.pUserData = &pFlac->memoryStream; + } + return pFlac; +} +MA_API ma_dr_flac* ma_dr_flac_open_memory_with_metadata(const void* pData, size_t dataSize, ma_dr_flac_meta_proc onMeta, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_flac__memory_stream memoryStream; + ma_dr_flac* pFlac; + memoryStream.data = (const ma_uint8*)pData; + memoryStream.dataSize = dataSize; + memoryStream.currentReadPos = 0; + pFlac = ma_dr_flac_open_with_metadata_private(ma_dr_flac__on_read_memory, ma_dr_flac__on_seek_memory, onMeta, ma_dr_flac_container_unknown, &memoryStream, pUserData, pAllocationCallbacks); + if (pFlac == NULL) { + return NULL; + } + pFlac->memoryStream = memoryStream; +#ifndef MA_DR_FLAC_NO_OGG + if (pFlac->container == ma_dr_flac_container_ogg) + { + ma_dr_flac_oggbs* oggbs = (ma_dr_flac_oggbs*)pFlac->_oggbs; + oggbs->pUserData = &pFlac->memoryStream; + } + else +#endif + { + pFlac->bs.pUserData = &pFlac->memoryStream; + } + return pFlac; +} +MA_API ma_dr_flac* ma_dr_flac_open(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks) +{ + return ma_dr_flac_open_with_metadata_private(onRead, onSeek, NULL, ma_dr_flac_container_unknown, pUserData, pUserData, pAllocationCallbacks); +} +MA_API ma_dr_flac* ma_dr_flac_open_relaxed(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_container container, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks) +{ + return ma_dr_flac_open_with_metadata_private(onRead, onSeek, NULL, container, pUserData, pUserData, pAllocationCallbacks); +} +MA_API ma_dr_flac* ma_dr_flac_open_with_metadata(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_meta_proc onMeta, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks) +{ + return ma_dr_flac_open_with_metadata_private(onRead, onSeek, onMeta, ma_dr_flac_container_unknown, pUserData, pUserData, pAllocationCallbacks); +} +MA_API ma_dr_flac* ma_dr_flac_open_with_metadata_relaxed(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_meta_proc onMeta, ma_dr_flac_container container, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks) +{ + return ma_dr_flac_open_with_metadata_private(onRead, onSeek, onMeta, container, pUserData, pUserData, pAllocationCallbacks); +} +MA_API void ma_dr_flac_close(ma_dr_flac* pFlac) +{ + if (pFlac == NULL) { + return; + } +#ifndef MA_DR_FLAC_NO_STDIO + if (pFlac->bs.onRead == ma_dr_flac__on_read_stdio) { + fclose((FILE*)pFlac->bs.pUserData); + } +#ifndef MA_DR_FLAC_NO_OGG + if (pFlac->container == ma_dr_flac_container_ogg) { + ma_dr_flac_oggbs* oggbs = (ma_dr_flac_oggbs*)pFlac->_oggbs; + MA_DR_FLAC_ASSERT(pFlac->bs.onRead == ma_dr_flac__on_read_ogg); + if (oggbs->onRead == ma_dr_flac__on_read_stdio) { + fclose((FILE*)oggbs->pUserData); + } + } +#endif +#endif + ma_dr_flac__free_from_callbacks(pFlac, &pFlac->allocationCallbacks); +} +#if 0 +static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_left_side__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples) +{ + ma_uint64 i; + for (i = 0; i < frameCount; ++i) { + ma_uint32 left = (ma_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + ma_uint32 side = (ma_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + ma_uint32 right = left - side; + pOutputSamples[i*2+0] = (ma_int32)left; + pOutputSamples[i*2+1] = (ma_int32)right; + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_left_side__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + for (i = 0; i < frameCount4; ++i) { + ma_uint32 left0 = pInputSamples0U32[i*4+0] << shift0; + ma_uint32 left1 = pInputSamples0U32[i*4+1] << shift0; + ma_uint32 left2 = pInputSamples0U32[i*4+2] << shift0; + ma_uint32 left3 = pInputSamples0U32[i*4+3] << shift0; + ma_uint32 side0 = pInputSamples1U32[i*4+0] << shift1; + ma_uint32 side1 = pInputSamples1U32[i*4+1] << shift1; + ma_uint32 side2 = pInputSamples1U32[i*4+2] << shift1; + ma_uint32 side3 = pInputSamples1U32[i*4+3] << shift1; + ma_uint32 right0 = left0 - side0; + ma_uint32 right1 = left1 - side1; + ma_uint32 right2 = left2 - side2; + ma_uint32 right3 = left3 - side3; + pOutputSamples[i*8+0] = (ma_int32)left0; + pOutputSamples[i*8+1] = (ma_int32)right0; + pOutputSamples[i*8+2] = (ma_int32)left1; + pOutputSamples[i*8+3] = (ma_int32)right1; + pOutputSamples[i*8+4] = (ma_int32)left2; + pOutputSamples[i*8+5] = (ma_int32)right2; + pOutputSamples[i*8+6] = (ma_int32)left3; + pOutputSamples[i*8+7] = (ma_int32)right3; + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 left = pInputSamples0U32[i] << shift0; + ma_uint32 side = pInputSamples1U32[i] << shift1; + ma_uint32 right = left - side; + pOutputSamples[i*2+0] = (ma_int32)left; + pOutputSamples[i*2+1] = (ma_int32)right; + } +} +#if defined(MA_DR_FLAC_SUPPORT_SSE2) +static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_left_side__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24); + for (i = 0; i < frameCount4; ++i) { + __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0); + __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1); + __m128i right = _mm_sub_epi32(left, side); + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right)); + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 left = pInputSamples0U32[i] << shift0; + ma_uint32 side = pInputSamples1U32[i] << shift1; + ma_uint32 right = left - side; + pOutputSamples[i*2+0] = (ma_int32)left; + pOutputSamples[i*2+1] = (ma_int32)right; + } +} +#endif +#if defined(MA_DR_FLAC_SUPPORT_NEON) +static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_left_side__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + int32x4_t shift0_4; + int32x4_t shift1_4; + MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24); + shift0_4 = vdupq_n_s32(shift0); + shift1_4 = vdupq_n_s32(shift1); + for (i = 0; i < frameCount4; ++i) { + uint32x4_t left; + uint32x4_t side; + uint32x4_t right; + left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4); + side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4); + right = vsubq_u32(left, side); + ma_dr_flac__vst2q_u32((ma_uint32*)pOutputSamples + i*8, vzipq_u32(left, right)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 left = pInputSamples0U32[i] << shift0; + ma_uint32 side = pInputSamples1U32[i] << shift1; + ma_uint32 right = left - side; + pOutputSamples[i*2+0] = (ma_int32)left; + pOutputSamples[i*2+1] = (ma_int32)right; + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_left_side(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples) +{ +#if defined(MA_DR_FLAC_SUPPORT_SSE2) + if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_s32__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(MA_DR_FLAC_SUPPORT_NEON) + if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_s32__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { +#if 0 + ma_dr_flac_read_pcm_frames_s32__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + ma_dr_flac_read_pcm_frames_s32__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} +#if 0 +static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_right_side__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples) +{ + ma_uint64 i; + for (i = 0; i < frameCount; ++i) { + ma_uint32 side = (ma_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + ma_uint32 right = (ma_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + ma_uint32 left = right + side; + pOutputSamples[i*2+0] = (ma_int32)left; + pOutputSamples[i*2+1] = (ma_int32)right; + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_right_side__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + for (i = 0; i < frameCount4; ++i) { + ma_uint32 side0 = pInputSamples0U32[i*4+0] << shift0; + ma_uint32 side1 = pInputSamples0U32[i*4+1] << shift0; + ma_uint32 side2 = pInputSamples0U32[i*4+2] << shift0; + ma_uint32 side3 = pInputSamples0U32[i*4+3] << shift0; + ma_uint32 right0 = pInputSamples1U32[i*4+0] << shift1; + ma_uint32 right1 = pInputSamples1U32[i*4+1] << shift1; + ma_uint32 right2 = pInputSamples1U32[i*4+2] << shift1; + ma_uint32 right3 = pInputSamples1U32[i*4+3] << shift1; + ma_uint32 left0 = right0 + side0; + ma_uint32 left1 = right1 + side1; + ma_uint32 left2 = right2 + side2; + ma_uint32 left3 = right3 + side3; + pOutputSamples[i*8+0] = (ma_int32)left0; + pOutputSamples[i*8+1] = (ma_int32)right0; + pOutputSamples[i*8+2] = (ma_int32)left1; + pOutputSamples[i*8+3] = (ma_int32)right1; + pOutputSamples[i*8+4] = (ma_int32)left2; + pOutputSamples[i*8+5] = (ma_int32)right2; + pOutputSamples[i*8+6] = (ma_int32)left3; + pOutputSamples[i*8+7] = (ma_int32)right3; + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 side = pInputSamples0U32[i] << shift0; + ma_uint32 right = pInputSamples1U32[i] << shift1; + ma_uint32 left = right + side; + pOutputSamples[i*2+0] = (ma_int32)left; + pOutputSamples[i*2+1] = (ma_int32)right; + } +} +#if defined(MA_DR_FLAC_SUPPORT_SSE2) +static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_right_side__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24); + for (i = 0; i < frameCount4; ++i) { + __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0); + __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1); + __m128i left = _mm_add_epi32(right, side); + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right)); + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 side = pInputSamples0U32[i] << shift0; + ma_uint32 right = pInputSamples1U32[i] << shift1; + ma_uint32 left = right + side; + pOutputSamples[i*2+0] = (ma_int32)left; + pOutputSamples[i*2+1] = (ma_int32)right; + } +} +#endif +#if defined(MA_DR_FLAC_SUPPORT_NEON) +static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_right_side__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + int32x4_t shift0_4; + int32x4_t shift1_4; + MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24); + shift0_4 = vdupq_n_s32(shift0); + shift1_4 = vdupq_n_s32(shift1); + for (i = 0; i < frameCount4; ++i) { + uint32x4_t side; + uint32x4_t right; + uint32x4_t left; + side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4); + right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4); + left = vaddq_u32(right, side); + ma_dr_flac__vst2q_u32((ma_uint32*)pOutputSamples + i*8, vzipq_u32(left, right)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 side = pInputSamples0U32[i] << shift0; + ma_uint32 right = pInputSamples1U32[i] << shift1; + ma_uint32 left = right + side; + pOutputSamples[i*2+0] = (ma_int32)left; + pOutputSamples[i*2+1] = (ma_int32)right; + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_right_side(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples) +{ +#if defined(MA_DR_FLAC_SUPPORT_SSE2) + if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_s32__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(MA_DR_FLAC_SUPPORT_NEON) + if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_s32__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { +#if 0 + ma_dr_flac_read_pcm_frames_s32__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + ma_dr_flac_read_pcm_frames_s32__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} +#if 0 +static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_mid_side__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples) +{ + for (ma_uint64 i = 0; i < frameCount; ++i) { + ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid = (mid << 1) | (side & 0x01); + pOutputSamples[i*2+0] = (ma_int32)((ma_uint32)((ma_int32)(mid + side) >> 1) << unusedBitsPerSample); + pOutputSamples[i*2+1] = (ma_int32)((ma_uint32)((ma_int32)(mid - side) >> 1) << unusedBitsPerSample); + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_mid_side__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_int32 shift = unusedBitsPerSample; + if (shift > 0) { + shift -= 1; + for (i = 0; i < frameCount4; ++i) { + ma_uint32 temp0L; + ma_uint32 temp1L; + ma_uint32 temp2L; + ma_uint32 temp3L; + ma_uint32 temp0R; + ma_uint32 temp1R; + ma_uint32 temp2R; + ma_uint32 temp3R; + ma_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + ma_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + ma_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + ma_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid0 = (mid0 << 1) | (side0 & 0x01); + mid1 = (mid1 << 1) | (side1 & 0x01); + mid2 = (mid2 << 1) | (side2 & 0x01); + mid3 = (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] = (ma_int32)temp0L; + pOutputSamples[i*8+1] = (ma_int32)temp0R; + pOutputSamples[i*8+2] = (ma_int32)temp1L; + pOutputSamples[i*8+3] = (ma_int32)temp1R; + pOutputSamples[i*8+4] = (ma_int32)temp2L; + pOutputSamples[i*8+5] = (ma_int32)temp2R; + pOutputSamples[i*8+6] = (ma_int32)temp3L; + pOutputSamples[i*8+7] = (ma_int32)temp3R; + } + } else { + for (i = 0; i < frameCount4; ++i) { + ma_uint32 temp0L; + ma_uint32 temp1L; + ma_uint32 temp2L; + ma_uint32 temp3L; + ma_uint32 temp0R; + ma_uint32 temp1R; + ma_uint32 temp2R; + ma_uint32 temp3R; + ma_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + ma_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + ma_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + ma_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid0 = (mid0 << 1) | (side0 & 0x01); + mid1 = (mid1 << 1) | (side1 & 0x01); + mid2 = (mid2 << 1) | (side2 & 0x01); + mid3 = (mid3 << 1) | (side3 & 0x01); + temp0L = (ma_uint32)((ma_int32)(mid0 + side0) >> 1); + temp1L = (ma_uint32)((ma_int32)(mid1 + side1) >> 1); + temp2L = (ma_uint32)((ma_int32)(mid2 + side2) >> 1); + temp3L = (ma_uint32)((ma_int32)(mid3 + side3) >> 1); + temp0R = (ma_uint32)((ma_int32)(mid0 - side0) >> 1); + temp1R = (ma_uint32)((ma_int32)(mid1 - side1) >> 1); + temp2R = (ma_uint32)((ma_int32)(mid2 - side2) >> 1); + temp3R = (ma_uint32)((ma_int32)(mid3 - side3) >> 1); + pOutputSamples[i*8+0] = (ma_int32)temp0L; + pOutputSamples[i*8+1] = (ma_int32)temp0R; + pOutputSamples[i*8+2] = (ma_int32)temp1L; + pOutputSamples[i*8+3] = (ma_int32)temp1R; + pOutputSamples[i*8+4] = (ma_int32)temp2L; + pOutputSamples[i*8+5] = (ma_int32)temp2R; + pOutputSamples[i*8+6] = (ma_int32)temp3L; + pOutputSamples[i*8+7] = (ma_int32)temp3R; + } + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid = (mid << 1) | (side & 0x01); + pOutputSamples[i*2+0] = (ma_int32)((ma_uint32)((ma_int32)(mid + side) >> 1) << unusedBitsPerSample); + pOutputSamples[i*2+1] = (ma_int32)((ma_uint32)((ma_int32)(mid - side) >> 1) << unusedBitsPerSample); + } +} +#if defined(MA_DR_FLAC_SUPPORT_SSE2) +static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_mid_side__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_int32 shift = unusedBitsPerSample; + MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24); + if (shift == 0) { + for (i = 0; i < frameCount4; ++i) { + __m128i mid; + __m128i side; + __m128i left; + __m128i right; + mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01))); + left = _mm_srai_epi32(_mm_add_epi32(mid, side), 1); + right = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1); + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right)); + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid = (mid << 1) | (side & 0x01); + pOutputSamples[i*2+0] = (ma_int32)(mid + side) >> 1; + pOutputSamples[i*2+1] = (ma_int32)(mid - side) >> 1; + } + } else { + shift -= 1; + for (i = 0; i < frameCount4; ++i) { + __m128i mid; + __m128i side; + __m128i left; + __m128i right; + mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01))); + left = _mm_slli_epi32(_mm_add_epi32(mid, side), shift); + right = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift); + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right)); + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid = (mid << 1) | (side & 0x01); + pOutputSamples[i*2+0] = (ma_int32)((mid + side) << shift); + pOutputSamples[i*2+1] = (ma_int32)((mid - side) << shift); + } + } +} +#endif +#if defined(MA_DR_FLAC_SUPPORT_NEON) +static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_mid_side__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_int32 shift = unusedBitsPerSample; + int32x4_t wbpsShift0_4; + int32x4_t wbpsShift1_4; + uint32x4_t one4; + MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24); + wbpsShift0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + wbpsShift1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + one4 = vdupq_n_u32(1); + if (shift == 0) { + for (i = 0; i < frameCount4; ++i) { + uint32x4_t mid; + uint32x4_t side; + int32x4_t left; + int32x4_t right; + mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4); + side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4); + mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, one4)); + left = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1); + right = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1); + ma_dr_flac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid = (mid << 1) | (side & 0x01); + pOutputSamples[i*2+0] = (ma_int32)(mid + side) >> 1; + pOutputSamples[i*2+1] = (ma_int32)(mid - side) >> 1; + } + } else { + int32x4_t shift4; + shift -= 1; + shift4 = vdupq_n_s32(shift); + for (i = 0; i < frameCount4; ++i) { + uint32x4_t mid; + uint32x4_t side; + int32x4_t left; + int32x4_t right; + mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4); + side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4); + mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, one4)); + left = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4)); + right = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4)); + ma_dr_flac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid = (mid << 1) | (side & 0x01); + pOutputSamples[i*2+0] = (ma_int32)((mid + side) << shift); + pOutputSamples[i*2+1] = (ma_int32)((mid - side) << shift); + } + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_mid_side(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples) +{ +#if defined(MA_DR_FLAC_SUPPORT_SSE2) + if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_s32__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(MA_DR_FLAC_SUPPORT_NEON) + if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_s32__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { +#if 0 + ma_dr_flac_read_pcm_frames_s32__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + ma_dr_flac_read_pcm_frames_s32__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} +#if 0 +static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_independent_stereo__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples) +{ + for (ma_uint64 i = 0; i < frameCount; ++i) { + pOutputSamples[i*2+0] = (ma_int32)((ma_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)); + pOutputSamples[i*2+1] = (ma_int32)((ma_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)); + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_independent_stereo__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + for (i = 0; i < frameCount4; ++i) { + ma_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0; + ma_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0; + ma_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0; + ma_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0; + ma_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1; + ma_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1; + ma_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1; + ma_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1; + pOutputSamples[i*8+0] = (ma_int32)tempL0; + pOutputSamples[i*8+1] = (ma_int32)tempR0; + pOutputSamples[i*8+2] = (ma_int32)tempL1; + pOutputSamples[i*8+3] = (ma_int32)tempR1; + pOutputSamples[i*8+4] = (ma_int32)tempL2; + pOutputSamples[i*8+5] = (ma_int32)tempR2; + pOutputSamples[i*8+6] = (ma_int32)tempL3; + pOutputSamples[i*8+7] = (ma_int32)tempR3; + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + pOutputSamples[i*2+0] = (ma_int32)(pInputSamples0U32[i] << shift0); + pOutputSamples[i*2+1] = (ma_int32)(pInputSamples1U32[i] << shift1); + } +} +#if defined(MA_DR_FLAC_SUPPORT_SSE2) +static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_independent_stereo__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + for (i = 0; i < frameCount4; ++i) { + __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0); + __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1); + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right)); + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + pOutputSamples[i*2+0] = (ma_int32)(pInputSamples0U32[i] << shift0); + pOutputSamples[i*2+1] = (ma_int32)(pInputSamples1U32[i] << shift1); + } +} +#endif +#if defined(MA_DR_FLAC_SUPPORT_NEON) +static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_independent_stereo__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + int32x4_t shift4_0 = vdupq_n_s32(shift0); + int32x4_t shift4_1 = vdupq_n_s32(shift1); + for (i = 0; i < frameCount4; ++i) { + int32x4_t left; + int32x4_t right; + left = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift4_0)); + right = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift4_1)); + ma_dr_flac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + pOutputSamples[i*2+0] = (ma_int32)(pInputSamples0U32[i] << shift0); + pOutputSamples[i*2+1] = (ma_int32)(pInputSamples1U32[i] << shift1); + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_independent_stereo(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples) +{ +#if defined(MA_DR_FLAC_SUPPORT_SSE2) + if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_s32__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(MA_DR_FLAC_SUPPORT_NEON) + if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_s32__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { +#if 0 + ma_dr_flac_read_pcm_frames_s32__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + ma_dr_flac_read_pcm_frames_s32__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} +MA_API ma_uint64 ma_dr_flac_read_pcm_frames_s32(ma_dr_flac* pFlac, ma_uint64 framesToRead, ma_int32* pBufferOut) +{ + ma_uint64 framesRead; + ma_uint32 unusedBitsPerSample; + if (pFlac == NULL || framesToRead == 0) { + return 0; + } + if (pBufferOut == NULL) { + return ma_dr_flac__seek_forward_by_pcm_frames(pFlac, framesToRead); + } + MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 32); + unusedBitsPerSample = 32 - pFlac->bitsPerSample; + framesRead = 0; + while (framesToRead > 0) { + if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) { + if (!ma_dr_flac__read_and_decode_next_flac_frame(pFlac)) { + break; + } + } else { + unsigned int channelCount = ma_dr_flac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment); + ma_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining; + ma_uint64 frameCountThisIteration = framesToRead; + if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) { + frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining; + } + if (channelCount == 2) { + const ma_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame; + const ma_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame; + switch (pFlac->currentFLACFrame.header.channelAssignment) + { + case MA_DR_FLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE: + { + ma_dr_flac_read_pcm_frames_s32__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + case MA_DR_FLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE: + { + ma_dr_flac_read_pcm_frames_s32__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + case MA_DR_FLAC_CHANNEL_ASSIGNMENT_MID_SIDE: + { + ma_dr_flac_read_pcm_frames_s32__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + case MA_DR_FLAC_CHANNEL_ASSIGNMENT_INDEPENDENT: + default: + { + ma_dr_flac_read_pcm_frames_s32__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + } + } else { + ma_uint64 i; + for (i = 0; i < frameCountThisIteration; ++i) { + unsigned int j; + for (j = 0; j < channelCount; ++j) { + pBufferOut[(i*channelCount)+j] = (ma_int32)((ma_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample)); + } + } + } + framesRead += frameCountThisIteration; + pBufferOut += frameCountThisIteration * channelCount; + framesToRead -= frameCountThisIteration; + pFlac->currentPCMFrame += frameCountThisIteration; + pFlac->currentFLACFrame.pcmFramesRemaining -= (ma_uint32)frameCountThisIteration; + } + } + return framesRead; +} +#if 0 +static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_left_side__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples) +{ + ma_uint64 i; + for (i = 0; i < frameCount; ++i) { + ma_uint32 left = (ma_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + ma_uint32 side = (ma_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + ma_uint32 right = left - side; + left >>= 16; + right >>= 16; + pOutputSamples[i*2+0] = (ma_int16)left; + pOutputSamples[i*2+1] = (ma_int16)right; + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_left_side__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + for (i = 0; i < frameCount4; ++i) { + ma_uint32 left0 = pInputSamples0U32[i*4+0] << shift0; + ma_uint32 left1 = pInputSamples0U32[i*4+1] << shift0; + ma_uint32 left2 = pInputSamples0U32[i*4+2] << shift0; + ma_uint32 left3 = pInputSamples0U32[i*4+3] << shift0; + ma_uint32 side0 = pInputSamples1U32[i*4+0] << shift1; + ma_uint32 side1 = pInputSamples1U32[i*4+1] << shift1; + ma_uint32 side2 = pInputSamples1U32[i*4+2] << shift1; + ma_uint32 side3 = pInputSamples1U32[i*4+3] << shift1; + ma_uint32 right0 = left0 - side0; + ma_uint32 right1 = left1 - side1; + ma_uint32 right2 = left2 - side2; + ma_uint32 right3 = left3 - side3; + left0 >>= 16; + left1 >>= 16; + left2 >>= 16; + left3 >>= 16; + right0 >>= 16; + right1 >>= 16; + right2 >>= 16; + right3 >>= 16; + pOutputSamples[i*8+0] = (ma_int16)left0; + pOutputSamples[i*8+1] = (ma_int16)right0; + pOutputSamples[i*8+2] = (ma_int16)left1; + pOutputSamples[i*8+3] = (ma_int16)right1; + pOutputSamples[i*8+4] = (ma_int16)left2; + pOutputSamples[i*8+5] = (ma_int16)right2; + pOutputSamples[i*8+6] = (ma_int16)left3; + pOutputSamples[i*8+7] = (ma_int16)right3; + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 left = pInputSamples0U32[i] << shift0; + ma_uint32 side = pInputSamples1U32[i] << shift1; + ma_uint32 right = left - side; + left >>= 16; + right >>= 16; + pOutputSamples[i*2+0] = (ma_int16)left; + pOutputSamples[i*2+1] = (ma_int16)right; + } +} +#if defined(MA_DR_FLAC_SUPPORT_SSE2) +static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_left_side__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24); + for (i = 0; i < frameCount4; ++i) { + __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0); + __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1); + __m128i right = _mm_sub_epi32(left, side); + left = _mm_srai_epi32(left, 16); + right = _mm_srai_epi32(right, 16); + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), ma_dr_flac__mm_packs_interleaved_epi32(left, right)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 left = pInputSamples0U32[i] << shift0; + ma_uint32 side = pInputSamples1U32[i] << shift1; + ma_uint32 right = left - side; + left >>= 16; + right >>= 16; + pOutputSamples[i*2+0] = (ma_int16)left; + pOutputSamples[i*2+1] = (ma_int16)right; + } +} +#endif +#if defined(MA_DR_FLAC_SUPPORT_NEON) +static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_left_side__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + int32x4_t shift0_4; + int32x4_t shift1_4; + MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24); + shift0_4 = vdupq_n_s32(shift0); + shift1_4 = vdupq_n_s32(shift1); + for (i = 0; i < frameCount4; ++i) { + uint32x4_t left; + uint32x4_t side; + uint32x4_t right; + left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4); + side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4); + right = vsubq_u32(left, side); + left = vshrq_n_u32(left, 16); + right = vshrq_n_u32(right, 16); + ma_dr_flac__vst2q_u16((ma_uint16*)pOutputSamples + i*8, vzip_u16(vmovn_u32(left), vmovn_u32(right))); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 left = pInputSamples0U32[i] << shift0; + ma_uint32 side = pInputSamples1U32[i] << shift1; + ma_uint32 right = left - side; + left >>= 16; + right >>= 16; + pOutputSamples[i*2+0] = (ma_int16)left; + pOutputSamples[i*2+1] = (ma_int16)right; + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_left_side(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples) +{ +#if defined(MA_DR_FLAC_SUPPORT_SSE2) + if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_s16__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(MA_DR_FLAC_SUPPORT_NEON) + if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_s16__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { +#if 0 + ma_dr_flac_read_pcm_frames_s16__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + ma_dr_flac_read_pcm_frames_s16__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} +#if 0 +static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_right_side__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples) +{ + ma_uint64 i; + for (i = 0; i < frameCount; ++i) { + ma_uint32 side = (ma_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + ma_uint32 right = (ma_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + ma_uint32 left = right + side; + left >>= 16; + right >>= 16; + pOutputSamples[i*2+0] = (ma_int16)left; + pOutputSamples[i*2+1] = (ma_int16)right; + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_right_side__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + for (i = 0; i < frameCount4; ++i) { + ma_uint32 side0 = pInputSamples0U32[i*4+0] << shift0; + ma_uint32 side1 = pInputSamples0U32[i*4+1] << shift0; + ma_uint32 side2 = pInputSamples0U32[i*4+2] << shift0; + ma_uint32 side3 = pInputSamples0U32[i*4+3] << shift0; + ma_uint32 right0 = pInputSamples1U32[i*4+0] << shift1; + ma_uint32 right1 = pInputSamples1U32[i*4+1] << shift1; + ma_uint32 right2 = pInputSamples1U32[i*4+2] << shift1; + ma_uint32 right3 = pInputSamples1U32[i*4+3] << shift1; + ma_uint32 left0 = right0 + side0; + ma_uint32 left1 = right1 + side1; + ma_uint32 left2 = right2 + side2; + ma_uint32 left3 = right3 + side3; + left0 >>= 16; + left1 >>= 16; + left2 >>= 16; + left3 >>= 16; + right0 >>= 16; + right1 >>= 16; + right2 >>= 16; + right3 >>= 16; + pOutputSamples[i*8+0] = (ma_int16)left0; + pOutputSamples[i*8+1] = (ma_int16)right0; + pOutputSamples[i*8+2] = (ma_int16)left1; + pOutputSamples[i*8+3] = (ma_int16)right1; + pOutputSamples[i*8+4] = (ma_int16)left2; + pOutputSamples[i*8+5] = (ma_int16)right2; + pOutputSamples[i*8+6] = (ma_int16)left3; + pOutputSamples[i*8+7] = (ma_int16)right3; + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 side = pInputSamples0U32[i] << shift0; + ma_uint32 right = pInputSamples1U32[i] << shift1; + ma_uint32 left = right + side; + left >>= 16; + right >>= 16; + pOutputSamples[i*2+0] = (ma_int16)left; + pOutputSamples[i*2+1] = (ma_int16)right; + } +} +#if defined(MA_DR_FLAC_SUPPORT_SSE2) +static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_right_side__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24); + for (i = 0; i < frameCount4; ++i) { + __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0); + __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1); + __m128i left = _mm_add_epi32(right, side); + left = _mm_srai_epi32(left, 16); + right = _mm_srai_epi32(right, 16); + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), ma_dr_flac__mm_packs_interleaved_epi32(left, right)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 side = pInputSamples0U32[i] << shift0; + ma_uint32 right = pInputSamples1U32[i] << shift1; + ma_uint32 left = right + side; + left >>= 16; + right >>= 16; + pOutputSamples[i*2+0] = (ma_int16)left; + pOutputSamples[i*2+1] = (ma_int16)right; + } +} +#endif +#if defined(MA_DR_FLAC_SUPPORT_NEON) +static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_right_side__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + int32x4_t shift0_4; + int32x4_t shift1_4; + MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24); + shift0_4 = vdupq_n_s32(shift0); + shift1_4 = vdupq_n_s32(shift1); + for (i = 0; i < frameCount4; ++i) { + uint32x4_t side; + uint32x4_t right; + uint32x4_t left; + side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4); + right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4); + left = vaddq_u32(right, side); + left = vshrq_n_u32(left, 16); + right = vshrq_n_u32(right, 16); + ma_dr_flac__vst2q_u16((ma_uint16*)pOutputSamples + i*8, vzip_u16(vmovn_u32(left), vmovn_u32(right))); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 side = pInputSamples0U32[i] << shift0; + ma_uint32 right = pInputSamples1U32[i] << shift1; + ma_uint32 left = right + side; + left >>= 16; + right >>= 16; + pOutputSamples[i*2+0] = (ma_int16)left; + pOutputSamples[i*2+1] = (ma_int16)right; + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_right_side(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples) +{ +#if defined(MA_DR_FLAC_SUPPORT_SSE2) + if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_s16__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(MA_DR_FLAC_SUPPORT_NEON) + if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_s16__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { +#if 0 + ma_dr_flac_read_pcm_frames_s16__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + ma_dr_flac_read_pcm_frames_s16__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} +#if 0 +static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_mid_side__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples) +{ + for (ma_uint64 i = 0; i < frameCount; ++i) { + ma_uint32 mid = (ma_uint32)pInputSamples0[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side = (ma_uint32)pInputSamples1[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid = (mid << 1) | (side & 0x01); + pOutputSamples[i*2+0] = (ma_int16)(((ma_uint32)((ma_int32)(mid + side) >> 1) << unusedBitsPerSample) >> 16); + pOutputSamples[i*2+1] = (ma_int16)(((ma_uint32)((ma_int32)(mid - side) >> 1) << unusedBitsPerSample) >> 16); + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_mid_side__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift = unusedBitsPerSample; + if (shift > 0) { + shift -= 1; + for (i = 0; i < frameCount4; ++i) { + ma_uint32 temp0L; + ma_uint32 temp1L; + ma_uint32 temp2L; + ma_uint32 temp3L; + ma_uint32 temp0R; + ma_uint32 temp1R; + ma_uint32 temp2R; + ma_uint32 temp3R; + ma_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + ma_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + ma_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + ma_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid0 = (mid0 << 1) | (side0 & 0x01); + mid1 = (mid1 << 1) | (side1 & 0x01); + mid2 = (mid2 << 1) | (side2 & 0x01); + mid3 = (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; + temp0L >>= 16; + temp1L >>= 16; + temp2L >>= 16; + temp3L >>= 16; + temp0R >>= 16; + temp1R >>= 16; + temp2R >>= 16; + temp3R >>= 16; + pOutputSamples[i*8+0] = (ma_int16)temp0L; + pOutputSamples[i*8+1] = (ma_int16)temp0R; + pOutputSamples[i*8+2] = (ma_int16)temp1L; + pOutputSamples[i*8+3] = (ma_int16)temp1R; + pOutputSamples[i*8+4] = (ma_int16)temp2L; + pOutputSamples[i*8+5] = (ma_int16)temp2R; + pOutputSamples[i*8+6] = (ma_int16)temp3L; + pOutputSamples[i*8+7] = (ma_int16)temp3R; + } + } else { + for (i = 0; i < frameCount4; ++i) { + ma_uint32 temp0L; + ma_uint32 temp1L; + ma_uint32 temp2L; + ma_uint32 temp3L; + ma_uint32 temp0R; + ma_uint32 temp1R; + ma_uint32 temp2R; + ma_uint32 temp3R; + ma_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + ma_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + ma_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + ma_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid0 = (mid0 << 1) | (side0 & 0x01); + mid1 = (mid1 << 1) | (side1 & 0x01); + mid2 = (mid2 << 1) | (side2 & 0x01); + mid3 = (mid3 << 1) | (side3 & 0x01); + temp0L = ((ma_int32)(mid0 + side0) >> 1); + temp1L = ((ma_int32)(mid1 + side1) >> 1); + temp2L = ((ma_int32)(mid2 + side2) >> 1); + temp3L = ((ma_int32)(mid3 + side3) >> 1); + temp0R = ((ma_int32)(mid0 - side0) >> 1); + temp1R = ((ma_int32)(mid1 - side1) >> 1); + temp2R = ((ma_int32)(mid2 - side2) >> 1); + temp3R = ((ma_int32)(mid3 - side3) >> 1); + temp0L >>= 16; + temp1L >>= 16; + temp2L >>= 16; + temp3L >>= 16; + temp0R >>= 16; + temp1R >>= 16; + temp2R >>= 16; + temp3R >>= 16; + pOutputSamples[i*8+0] = (ma_int16)temp0L; + pOutputSamples[i*8+1] = (ma_int16)temp0R; + pOutputSamples[i*8+2] = (ma_int16)temp1L; + pOutputSamples[i*8+3] = (ma_int16)temp1R; + pOutputSamples[i*8+4] = (ma_int16)temp2L; + pOutputSamples[i*8+5] = (ma_int16)temp2R; + pOutputSamples[i*8+6] = (ma_int16)temp3L; + pOutputSamples[i*8+7] = (ma_int16)temp3R; + } + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid = (mid << 1) | (side & 0x01); + pOutputSamples[i*2+0] = (ma_int16)(((ma_uint32)((ma_int32)(mid + side) >> 1) << unusedBitsPerSample) >> 16); + pOutputSamples[i*2+1] = (ma_int16)(((ma_uint32)((ma_int32)(mid - side) >> 1) << unusedBitsPerSample) >> 16); + } +} +#if defined(MA_DR_FLAC_SUPPORT_SSE2) +static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_mid_side__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift = unusedBitsPerSample; + MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24); + if (shift == 0) { + for (i = 0; i < frameCount4; ++i) { + __m128i mid; + __m128i side; + __m128i left; + __m128i right; + mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01))); + left = _mm_srai_epi32(_mm_add_epi32(mid, side), 1); + right = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1); + left = _mm_srai_epi32(left, 16); + right = _mm_srai_epi32(right, 16); + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), ma_dr_flac__mm_packs_interleaved_epi32(left, right)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid = (mid << 1) | (side & 0x01); + pOutputSamples[i*2+0] = (ma_int16)(((ma_int32)(mid + side) >> 1) >> 16); + pOutputSamples[i*2+1] = (ma_int16)(((ma_int32)(mid - side) >> 1) >> 16); + } + } else { + shift -= 1; + for (i = 0; i < frameCount4; ++i) { + __m128i mid; + __m128i side; + __m128i left; + __m128i right; + mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01))); + left = _mm_slli_epi32(_mm_add_epi32(mid, side), shift); + right = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift); + left = _mm_srai_epi32(left, 16); + right = _mm_srai_epi32(right, 16); + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), ma_dr_flac__mm_packs_interleaved_epi32(left, right)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid = (mid << 1) | (side & 0x01); + pOutputSamples[i*2+0] = (ma_int16)(((mid + side) << shift) >> 16); + pOutputSamples[i*2+1] = (ma_int16)(((mid - side) << shift) >> 16); + } + } +} +#endif +#if defined(MA_DR_FLAC_SUPPORT_NEON) +static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_mid_side__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift = unusedBitsPerSample; + int32x4_t wbpsShift0_4; + int32x4_t wbpsShift1_4; + MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24); + wbpsShift0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + wbpsShift1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + if (shift == 0) { + for (i = 0; i < frameCount4; ++i) { + uint32x4_t mid; + uint32x4_t side; + int32x4_t left; + int32x4_t right; + mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4); + side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4); + mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1))); + left = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1); + right = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1); + left = vshrq_n_s32(left, 16); + right = vshrq_n_s32(right, 16); + ma_dr_flac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right))); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid = (mid << 1) | (side & 0x01); + pOutputSamples[i*2+0] = (ma_int16)(((ma_int32)(mid + side) >> 1) >> 16); + pOutputSamples[i*2+1] = (ma_int16)(((ma_int32)(mid - side) >> 1) >> 16); + } + } else { + int32x4_t shift4; + shift -= 1; + shift4 = vdupq_n_s32(shift); + for (i = 0; i < frameCount4; ++i) { + uint32x4_t mid; + uint32x4_t side; + int32x4_t left; + int32x4_t right; + mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4); + side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4); + mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1))); + left = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4)); + right = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4)); + left = vshrq_n_s32(left, 16); + right = vshrq_n_s32(right, 16); + ma_dr_flac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right))); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid = (mid << 1) | (side & 0x01); + pOutputSamples[i*2+0] = (ma_int16)(((mid + side) << shift) >> 16); + pOutputSamples[i*2+1] = (ma_int16)(((mid - side) << shift) >> 16); + } + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_mid_side(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples) +{ +#if defined(MA_DR_FLAC_SUPPORT_SSE2) + if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_s16__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(MA_DR_FLAC_SUPPORT_NEON) + if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_s16__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { +#if 0 + ma_dr_flac_read_pcm_frames_s16__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + ma_dr_flac_read_pcm_frames_s16__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} +#if 0 +static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_independent_stereo__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples) +{ + for (ma_uint64 i = 0; i < frameCount; ++i) { + pOutputSamples[i*2+0] = (ma_int16)((ma_int32)((ma_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)) >> 16); + pOutputSamples[i*2+1] = (ma_int16)((ma_int32)((ma_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)) >> 16); + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_independent_stereo__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + for (i = 0; i < frameCount4; ++i) { + ma_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0; + ma_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0; + ma_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0; + ma_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0; + ma_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1; + ma_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1; + ma_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1; + ma_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1; + tempL0 >>= 16; + tempL1 >>= 16; + tempL2 >>= 16; + tempL3 >>= 16; + tempR0 >>= 16; + tempR1 >>= 16; + tempR2 >>= 16; + tempR3 >>= 16; + pOutputSamples[i*8+0] = (ma_int16)tempL0; + pOutputSamples[i*8+1] = (ma_int16)tempR0; + pOutputSamples[i*8+2] = (ma_int16)tempL1; + pOutputSamples[i*8+3] = (ma_int16)tempR1; + pOutputSamples[i*8+4] = (ma_int16)tempL2; + pOutputSamples[i*8+5] = (ma_int16)tempR2; + pOutputSamples[i*8+6] = (ma_int16)tempL3; + pOutputSamples[i*8+7] = (ma_int16)tempR3; + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + pOutputSamples[i*2+0] = (ma_int16)((pInputSamples0U32[i] << shift0) >> 16); + pOutputSamples[i*2+1] = (ma_int16)((pInputSamples1U32[i] << shift1) >> 16); + } +} +#if defined(MA_DR_FLAC_SUPPORT_SSE2) +static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_independent_stereo__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + for (i = 0; i < frameCount4; ++i) { + __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0); + __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1); + left = _mm_srai_epi32(left, 16); + right = _mm_srai_epi32(right, 16); + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), ma_dr_flac__mm_packs_interleaved_epi32(left, right)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + pOutputSamples[i*2+0] = (ma_int16)((pInputSamples0U32[i] << shift0) >> 16); + pOutputSamples[i*2+1] = (ma_int16)((pInputSamples1U32[i] << shift1) >> 16); + } +} +#endif +#if defined(MA_DR_FLAC_SUPPORT_NEON) +static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_independent_stereo__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + int32x4_t shift0_4 = vdupq_n_s32(shift0); + int32x4_t shift1_4 = vdupq_n_s32(shift1); + for (i = 0; i < frameCount4; ++i) { + int32x4_t left; + int32x4_t right; + left = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4)); + right = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4)); + left = vshrq_n_s32(left, 16); + right = vshrq_n_s32(right, 16); + ma_dr_flac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right))); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + pOutputSamples[i*2+0] = (ma_int16)((pInputSamples0U32[i] << shift0) >> 16); + pOutputSamples[i*2+1] = (ma_int16)((pInputSamples1U32[i] << shift1) >> 16); + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_independent_stereo(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples) +{ +#if defined(MA_DR_FLAC_SUPPORT_SSE2) + if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_s16__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(MA_DR_FLAC_SUPPORT_NEON) + if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_s16__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { +#if 0 + ma_dr_flac_read_pcm_frames_s16__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + ma_dr_flac_read_pcm_frames_s16__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} +MA_API ma_uint64 ma_dr_flac_read_pcm_frames_s16(ma_dr_flac* pFlac, ma_uint64 framesToRead, ma_int16* pBufferOut) +{ + ma_uint64 framesRead; + ma_uint32 unusedBitsPerSample; + if (pFlac == NULL || framesToRead == 0) { + return 0; + } + if (pBufferOut == NULL) { + return ma_dr_flac__seek_forward_by_pcm_frames(pFlac, framesToRead); + } + MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 32); + unusedBitsPerSample = 32 - pFlac->bitsPerSample; + framesRead = 0; + while (framesToRead > 0) { + if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) { + if (!ma_dr_flac__read_and_decode_next_flac_frame(pFlac)) { + break; + } + } else { + unsigned int channelCount = ma_dr_flac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment); + ma_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining; + ma_uint64 frameCountThisIteration = framesToRead; + if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) { + frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining; + } + if (channelCount == 2) { + const ma_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame; + const ma_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame; + switch (pFlac->currentFLACFrame.header.channelAssignment) + { + case MA_DR_FLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE: + { + ma_dr_flac_read_pcm_frames_s16__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + case MA_DR_FLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE: + { + ma_dr_flac_read_pcm_frames_s16__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + case MA_DR_FLAC_CHANNEL_ASSIGNMENT_MID_SIDE: + { + ma_dr_flac_read_pcm_frames_s16__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + case MA_DR_FLAC_CHANNEL_ASSIGNMENT_INDEPENDENT: + default: + { + ma_dr_flac_read_pcm_frames_s16__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + } + } else { + ma_uint64 i; + for (i = 0; i < frameCountThisIteration; ++i) { + unsigned int j; + for (j = 0; j < channelCount; ++j) { + ma_int32 sampleS32 = (ma_int32)((ma_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample)); + pBufferOut[(i*channelCount)+j] = (ma_int16)(sampleS32 >> 16); + } + } + } + framesRead += frameCountThisIteration; + pBufferOut += frameCountThisIteration * channelCount; + framesToRead -= frameCountThisIteration; + pFlac->currentPCMFrame += frameCountThisIteration; + pFlac->currentFLACFrame.pcmFramesRemaining -= (ma_uint32)frameCountThisIteration; + } + } + return framesRead; +} +#if 0 +static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_left_side__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples) +{ + ma_uint64 i; + for (i = 0; i < frameCount; ++i) { + ma_uint32 left = (ma_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + ma_uint32 side = (ma_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + ma_uint32 right = left - side; + pOutputSamples[i*2+0] = (float)((ma_int32)left / 2147483648.0); + pOutputSamples[i*2+1] = (float)((ma_int32)right / 2147483648.0); + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_left_side__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + float factor = 1 / 2147483648.0; + for (i = 0; i < frameCount4; ++i) { + ma_uint32 left0 = pInputSamples0U32[i*4+0] << shift0; + ma_uint32 left1 = pInputSamples0U32[i*4+1] << shift0; + ma_uint32 left2 = pInputSamples0U32[i*4+2] << shift0; + ma_uint32 left3 = pInputSamples0U32[i*4+3] << shift0; + ma_uint32 side0 = pInputSamples1U32[i*4+0] << shift1; + ma_uint32 side1 = pInputSamples1U32[i*4+1] << shift1; + ma_uint32 side2 = pInputSamples1U32[i*4+2] << shift1; + ma_uint32 side3 = pInputSamples1U32[i*4+3] << shift1; + ma_uint32 right0 = left0 - side0; + ma_uint32 right1 = left1 - side1; + ma_uint32 right2 = left2 - side2; + ma_uint32 right3 = left3 - side3; + pOutputSamples[i*8+0] = (ma_int32)left0 * factor; + pOutputSamples[i*8+1] = (ma_int32)right0 * factor; + pOutputSamples[i*8+2] = (ma_int32)left1 * factor; + pOutputSamples[i*8+3] = (ma_int32)right1 * factor; + pOutputSamples[i*8+4] = (ma_int32)left2 * factor; + pOutputSamples[i*8+5] = (ma_int32)right2 * factor; + pOutputSamples[i*8+6] = (ma_int32)left3 * factor; + pOutputSamples[i*8+7] = (ma_int32)right3 * factor; + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 left = pInputSamples0U32[i] << shift0; + ma_uint32 side = pInputSamples1U32[i] << shift1; + ma_uint32 right = left - side; + pOutputSamples[i*2+0] = (ma_int32)left * factor; + pOutputSamples[i*2+1] = (ma_int32)right * factor; + } +} +#if defined(MA_DR_FLAC_SUPPORT_SSE2) +static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_left_side__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8; + ma_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8; + __m128 factor; + MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24); + factor = _mm_set1_ps(1.0f / 8388608.0f); + for (i = 0; i < frameCount4; ++i) { + __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0); + __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), 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); + _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf)); + _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 left = pInputSamples0U32[i] << shift0; + ma_uint32 side = pInputSamples1U32[i] << shift1; + ma_uint32 right = left - side; + pOutputSamples[i*2+0] = (ma_int32)left / 8388608.0f; + pOutputSamples[i*2+1] = (ma_int32)right / 8388608.0f; + } +} +#endif +#if defined(MA_DR_FLAC_SUPPORT_NEON) +static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_left_side__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8; + ma_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8; + float32x4_t factor4; + int32x4_t shift0_4; + int32x4_t shift1_4; + MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24); + factor4 = vdupq_n_f32(1.0f / 8388608.0f); + shift0_4 = vdupq_n_s32(shift0); + shift1_4 = vdupq_n_s32(shift1); + for (i = 0; i < frameCount4; ++i) { + uint32x4_t left; + uint32x4_t side; + uint32x4_t right; + float32x4_t leftf; + float32x4_t rightf; + left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4); + side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4); + right = vsubq_u32(left, side); + leftf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(left)), factor4); + rightf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(right)), factor4); + ma_dr_flac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 left = pInputSamples0U32[i] << shift0; + ma_uint32 side = pInputSamples1U32[i] << shift1; + ma_uint32 right = left - side; + pOutputSamples[i*2+0] = (ma_int32)left / 8388608.0f; + pOutputSamples[i*2+1] = (ma_int32)right / 8388608.0f; + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_left_side(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples) +{ +#if defined(MA_DR_FLAC_SUPPORT_SSE2) + if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_f32__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(MA_DR_FLAC_SUPPORT_NEON) + if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_f32__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { +#if 0 + ma_dr_flac_read_pcm_frames_f32__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + ma_dr_flac_read_pcm_frames_f32__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} +#if 0 +static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_right_side__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples) +{ + ma_uint64 i; + for (i = 0; i < frameCount; ++i) { + ma_uint32 side = (ma_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + ma_uint32 right = (ma_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + ma_uint32 left = right + side; + pOutputSamples[i*2+0] = (float)((ma_int32)left / 2147483648.0); + pOutputSamples[i*2+1] = (float)((ma_int32)right / 2147483648.0); + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_right_side__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + float factor = 1 / 2147483648.0; + for (i = 0; i < frameCount4; ++i) { + ma_uint32 side0 = pInputSamples0U32[i*4+0] << shift0; + ma_uint32 side1 = pInputSamples0U32[i*4+1] << shift0; + ma_uint32 side2 = pInputSamples0U32[i*4+2] << shift0; + ma_uint32 side3 = pInputSamples0U32[i*4+3] << shift0; + ma_uint32 right0 = pInputSamples1U32[i*4+0] << shift1; + ma_uint32 right1 = pInputSamples1U32[i*4+1] << shift1; + ma_uint32 right2 = pInputSamples1U32[i*4+2] << shift1; + ma_uint32 right3 = pInputSamples1U32[i*4+3] << shift1; + ma_uint32 left0 = right0 + side0; + ma_uint32 left1 = right1 + side1; + ma_uint32 left2 = right2 + side2; + ma_uint32 left3 = right3 + side3; + pOutputSamples[i*8+0] = (ma_int32)left0 * factor; + pOutputSamples[i*8+1] = (ma_int32)right0 * factor; + pOutputSamples[i*8+2] = (ma_int32)left1 * factor; + pOutputSamples[i*8+3] = (ma_int32)right1 * factor; + pOutputSamples[i*8+4] = (ma_int32)left2 * factor; + pOutputSamples[i*8+5] = (ma_int32)right2 * factor; + pOutputSamples[i*8+6] = (ma_int32)left3 * factor; + pOutputSamples[i*8+7] = (ma_int32)right3 * factor; + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 side = pInputSamples0U32[i] << shift0; + ma_uint32 right = pInputSamples1U32[i] << shift1; + ma_uint32 left = right + side; + pOutputSamples[i*2+0] = (ma_int32)left * factor; + pOutputSamples[i*2+1] = (ma_int32)right * factor; + } +} +#if defined(MA_DR_FLAC_SUPPORT_SSE2) +static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_right_side__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8; + ma_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8; + __m128 factor; + MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24); + factor = _mm_set1_ps(1.0f / 8388608.0f); + for (i = 0; i < frameCount4; ++i) { + __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0); + __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), 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); + _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf)); + _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 side = pInputSamples0U32[i] << shift0; + ma_uint32 right = pInputSamples1U32[i] << shift1; + ma_uint32 left = right + side; + pOutputSamples[i*2+0] = (ma_int32)left / 8388608.0f; + pOutputSamples[i*2+1] = (ma_int32)right / 8388608.0f; + } +} +#endif +#if defined(MA_DR_FLAC_SUPPORT_NEON) +static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_right_side__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8; + ma_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8; + float32x4_t factor4; + int32x4_t shift0_4; + int32x4_t shift1_4; + MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24); + factor4 = vdupq_n_f32(1.0f / 8388608.0f); + shift0_4 = vdupq_n_s32(shift0); + shift1_4 = vdupq_n_s32(shift1); + for (i = 0; i < frameCount4; ++i) { + uint32x4_t side; + uint32x4_t right; + uint32x4_t left; + float32x4_t leftf; + float32x4_t rightf; + side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4); + right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4); + left = vaddq_u32(right, side); + leftf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(left)), factor4); + rightf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(right)), factor4); + ma_dr_flac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 side = pInputSamples0U32[i] << shift0; + ma_uint32 right = pInputSamples1U32[i] << shift1; + ma_uint32 left = right + side; + pOutputSamples[i*2+0] = (ma_int32)left / 8388608.0f; + pOutputSamples[i*2+1] = (ma_int32)right / 8388608.0f; + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_right_side(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples) +{ +#if defined(MA_DR_FLAC_SUPPORT_SSE2) + if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_f32__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(MA_DR_FLAC_SUPPORT_NEON) + if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_f32__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { +#if 0 + ma_dr_flac_read_pcm_frames_f32__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + ma_dr_flac_read_pcm_frames_f32__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} +#if 0 +static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_mid_side__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples) +{ + for (ma_uint64 i = 0; i < frameCount; ++i) { + ma_uint32 mid = (ma_uint32)pInputSamples0[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side = (ma_uint32)pInputSamples1[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid = (mid << 1) | (side & 0x01); + pOutputSamples[i*2+0] = (float)((((ma_int32)(mid + side) >> 1) << (unusedBitsPerSample)) / 2147483648.0); + pOutputSamples[i*2+1] = (float)((((ma_int32)(mid - side) >> 1) << (unusedBitsPerSample)) / 2147483648.0); + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_mid_side__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift = unusedBitsPerSample; + float factor = 1 / 2147483648.0; + if (shift > 0) { + shift -= 1; + for (i = 0; i < frameCount4; ++i) { + ma_uint32 temp0L; + ma_uint32 temp1L; + ma_uint32 temp2L; + ma_uint32 temp3L; + ma_uint32 temp0R; + ma_uint32 temp1R; + ma_uint32 temp2R; + ma_uint32 temp3R; + ma_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + ma_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + ma_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + ma_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid0 = (mid0 << 1) | (side0 & 0x01); + mid1 = (mid1 << 1) | (side1 & 0x01); + mid2 = (mid2 << 1) | (side2 & 0x01); + mid3 = (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] = (ma_int32)temp0L * factor; + pOutputSamples[i*8+1] = (ma_int32)temp0R * factor; + pOutputSamples[i*8+2] = (ma_int32)temp1L * factor; + pOutputSamples[i*8+3] = (ma_int32)temp1R * factor; + pOutputSamples[i*8+4] = (ma_int32)temp2L * factor; + pOutputSamples[i*8+5] = (ma_int32)temp2R * factor; + pOutputSamples[i*8+6] = (ma_int32)temp3L * factor; + pOutputSamples[i*8+7] = (ma_int32)temp3R * factor; + } + } else { + for (i = 0; i < frameCount4; ++i) { + ma_uint32 temp0L; + ma_uint32 temp1L; + ma_uint32 temp2L; + ma_uint32 temp3L; + ma_uint32 temp0R; + ma_uint32 temp1R; + ma_uint32 temp2R; + ma_uint32 temp3R; + ma_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + ma_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + ma_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + ma_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid0 = (mid0 << 1) | (side0 & 0x01); + mid1 = (mid1 << 1) | (side1 & 0x01); + mid2 = (mid2 << 1) | (side2 & 0x01); + mid3 = (mid3 << 1) | (side3 & 0x01); + temp0L = (ma_uint32)((ma_int32)(mid0 + side0) >> 1); + temp1L = (ma_uint32)((ma_int32)(mid1 + side1) >> 1); + temp2L = (ma_uint32)((ma_int32)(mid2 + side2) >> 1); + temp3L = (ma_uint32)((ma_int32)(mid3 + side3) >> 1); + temp0R = (ma_uint32)((ma_int32)(mid0 - side0) >> 1); + temp1R = (ma_uint32)((ma_int32)(mid1 - side1) >> 1); + temp2R = (ma_uint32)((ma_int32)(mid2 - side2) >> 1); + temp3R = (ma_uint32)((ma_int32)(mid3 - side3) >> 1); + pOutputSamples[i*8+0] = (ma_int32)temp0L * factor; + pOutputSamples[i*8+1] = (ma_int32)temp0R * factor; + pOutputSamples[i*8+2] = (ma_int32)temp1L * factor; + pOutputSamples[i*8+3] = (ma_int32)temp1R * factor; + pOutputSamples[i*8+4] = (ma_int32)temp2L * factor; + pOutputSamples[i*8+5] = (ma_int32)temp2R * factor; + pOutputSamples[i*8+6] = (ma_int32)temp3L * factor; + pOutputSamples[i*8+7] = (ma_int32)temp3R * factor; + } + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid = (mid << 1) | (side & 0x01); + pOutputSamples[i*2+0] = (ma_int32)((ma_uint32)((ma_int32)(mid + side) >> 1) << unusedBitsPerSample) * factor; + pOutputSamples[i*2+1] = (ma_int32)((ma_uint32)((ma_int32)(mid - side) >> 1) << unusedBitsPerSample) * factor; + } +} +#if defined(MA_DR_FLAC_SUPPORT_SSE2) +static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_mid_side__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift = unusedBitsPerSample - 8; + float factor; + __m128 factor128; + MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24); + factor = 1.0f / 8388608.0f; + factor128 = _mm_set1_ps(factor); + if (shift == 0) { + for (i = 0; i < frameCount4; ++i) { + __m128i mid; + __m128i side; + __m128i tempL; + __m128i tempR; + __m128 leftf; + __m128 rightf; + mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01))); + tempL = _mm_srai_epi32(_mm_add_epi32(mid, side), 1); + tempR = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1); + leftf = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128); + rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128); + _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf)); + _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid = (mid << 1) | (side & 0x01); + pOutputSamples[i*2+0] = ((ma_int32)(mid + side) >> 1) * factor; + pOutputSamples[i*2+1] = ((ma_int32)(mid - side) >> 1) * factor; + } + } else { + shift -= 1; + for (i = 0; i < frameCount4; ++i) { + __m128i mid; + __m128i side; + __m128i tempL; + __m128i tempR; + __m128 leftf; + __m128 rightf; + mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.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_add_epi32(mid, side), shift); + tempR = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift); + leftf = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128); + rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128); + _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf)); + _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid = (mid << 1) | (side & 0x01); + pOutputSamples[i*2+0] = (ma_int32)((mid + side) << shift) * factor; + pOutputSamples[i*2+1] = (ma_int32)((mid - side) << shift) * factor; + } + } +} +#endif +#if defined(MA_DR_FLAC_SUPPORT_NEON) +static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_mid_side__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift = unusedBitsPerSample - 8; + float factor; + float32x4_t factor4; + int32x4_t shift4; + int32x4_t wbps0_4; + int32x4_t wbps1_4; + MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24); + factor = 1.0f / 8388608.0f; + factor4 = vdupq_n_f32(factor); + wbps0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + wbps1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + if (shift == 0) { + for (i = 0; i < frameCount4; ++i) { + int32x4_t lefti; + int32x4_t righti; + float32x4_t leftf; + float32x4_t rightf; + uint32x4_t mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbps0_4); + uint32x4_t side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbps1_4); + mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1))); + lefti = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1); + righti = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1); + leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4); + rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4); + ma_dr_flac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid = (mid << 1) | (side & 0x01); + pOutputSamples[i*2+0] = ((ma_int32)(mid + side) >> 1) * factor; + pOutputSamples[i*2+1] = ((ma_int32)(mid - side) >> 1) * factor; + } + } else { + shift -= 1; + shift4 = vdupq_n_s32(shift); + for (i = 0; i < frameCount4; ++i) { + uint32x4_t mid; + uint32x4_t side; + int32x4_t lefti; + int32x4_t righti; + float32x4_t leftf; + float32x4_t rightf; + mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbps0_4); + side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbps1_4); + mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1))); + lefti = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4)); + righti = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4)); + leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4); + rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4); + ma_dr_flac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + mid = (mid << 1) | (side & 0x01); + pOutputSamples[i*2+0] = (ma_int32)((mid + side) << shift) * factor; + pOutputSamples[i*2+1] = (ma_int32)((mid - side) << shift) * factor; + } + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_mid_side(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples) +{ +#if defined(MA_DR_FLAC_SUPPORT_SSE2) + if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_f32__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(MA_DR_FLAC_SUPPORT_NEON) + if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_f32__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { +#if 0 + ma_dr_flac_read_pcm_frames_f32__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + ma_dr_flac_read_pcm_frames_f32__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} +#if 0 +static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_independent_stereo__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples) +{ + for (ma_uint64 i = 0; i < frameCount; ++i) { + pOutputSamples[i*2+0] = (float)((ma_int32)((ma_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)) / 2147483648.0); + pOutputSamples[i*2+1] = (float)((ma_int32)((ma_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)) / 2147483648.0); + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_independent_stereo__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + float factor = 1 / 2147483648.0; + for (i = 0; i < frameCount4; ++i) { + ma_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0; + ma_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0; + ma_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0; + ma_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0; + ma_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1; + ma_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1; + ma_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1; + ma_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1; + pOutputSamples[i*8+0] = (ma_int32)tempL0 * factor; + pOutputSamples[i*8+1] = (ma_int32)tempR0 * factor; + pOutputSamples[i*8+2] = (ma_int32)tempL1 * factor; + pOutputSamples[i*8+3] = (ma_int32)tempR1 * factor; + pOutputSamples[i*8+4] = (ma_int32)tempL2 * factor; + pOutputSamples[i*8+5] = (ma_int32)tempR2 * factor; + pOutputSamples[i*8+6] = (ma_int32)tempL3 * factor; + pOutputSamples[i*8+7] = (ma_int32)tempR3 * factor; + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + pOutputSamples[i*2+0] = (ma_int32)(pInputSamples0U32[i] << shift0) * factor; + pOutputSamples[i*2+1] = (ma_int32)(pInputSamples1U32[i] << shift1) * factor; + } +} +#if defined(MA_DR_FLAC_SUPPORT_SSE2) +static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_independent_stereo__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8; + ma_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8; + float factor = 1.0f / 8388608.0f; + __m128 factor128 = _mm_set1_ps(factor); + for (i = 0; i < frameCount4; ++i) { + __m128i lefti; + __m128i righti; + __m128 leftf; + __m128 rightf; + lefti = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0); + righti = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1); + leftf = _mm_mul_ps(_mm_cvtepi32_ps(lefti), factor128); + rightf = _mm_mul_ps(_mm_cvtepi32_ps(righti), factor128); + _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf)); + _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + pOutputSamples[i*2+0] = (ma_int32)(pInputSamples0U32[i] << shift0) * factor; + pOutputSamples[i*2+1] = (ma_int32)(pInputSamples1U32[i] << shift1) * factor; + } +} +#endif +#if defined(MA_DR_FLAC_SUPPORT_NEON) +static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_independent_stereo__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples) +{ + ma_uint64 i; + ma_uint64 frameCount4 = frameCount >> 2; + const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0; + const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1; + ma_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8; + ma_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8; + float factor = 1.0f / 8388608.0f; + float32x4_t factor4 = vdupq_n_f32(factor); + int32x4_t shift0_4 = vdupq_n_s32(shift0); + int32x4_t shift1_4 = vdupq_n_s32(shift1); + for (i = 0; i < frameCount4; ++i) { + int32x4_t lefti; + int32x4_t righti; + float32x4_t leftf; + float32x4_t rightf; + lefti = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4)); + righti = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4)); + leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4); + rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4); + ma_dr_flac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf)); + } + for (i = (frameCount4 << 2); i < frameCount; ++i) { + pOutputSamples[i*2+0] = (ma_int32)(pInputSamples0U32[i] << shift0) * factor; + pOutputSamples[i*2+1] = (ma_int32)(pInputSamples1U32[i] << shift1) * factor; + } +} +#endif +static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_independent_stereo(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples) +{ +#if defined(MA_DR_FLAC_SUPPORT_SSE2) + if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_f32__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(MA_DR_FLAC_SUPPORT_NEON) + if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + ma_dr_flac_read_pcm_frames_f32__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { +#if 0 + ma_dr_flac_read_pcm_frames_f32__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + ma_dr_flac_read_pcm_frames_f32__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} +MA_API ma_uint64 ma_dr_flac_read_pcm_frames_f32(ma_dr_flac* pFlac, ma_uint64 framesToRead, float* pBufferOut) +{ + ma_uint64 framesRead; + ma_uint32 unusedBitsPerSample; + if (pFlac == NULL || framesToRead == 0) { + return 0; + } + if (pBufferOut == NULL) { + return ma_dr_flac__seek_forward_by_pcm_frames(pFlac, framesToRead); + } + MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 32); + unusedBitsPerSample = 32 - pFlac->bitsPerSample; + framesRead = 0; + while (framesToRead > 0) { + if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) { + if (!ma_dr_flac__read_and_decode_next_flac_frame(pFlac)) { + break; + } + } else { + unsigned int channelCount = ma_dr_flac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment); + ma_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining; + ma_uint64 frameCountThisIteration = framesToRead; + if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) { + frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining; + } + if (channelCount == 2) { + const ma_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame; + const ma_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame; + switch (pFlac->currentFLACFrame.header.channelAssignment) + { + case MA_DR_FLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE: + { + ma_dr_flac_read_pcm_frames_f32__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + case MA_DR_FLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE: + { + ma_dr_flac_read_pcm_frames_f32__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + case MA_DR_FLAC_CHANNEL_ASSIGNMENT_MID_SIDE: + { + ma_dr_flac_read_pcm_frames_f32__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + case MA_DR_FLAC_CHANNEL_ASSIGNMENT_INDEPENDENT: + default: + { + ma_dr_flac_read_pcm_frames_f32__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + } + } else { + ma_uint64 i; + for (i = 0; i < frameCountThisIteration; ++i) { + unsigned int j; + for (j = 0; j < channelCount; ++j) { + ma_int32 sampleS32 = (ma_int32)((ma_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample)); + pBufferOut[(i*channelCount)+j] = (float)(sampleS32 / 2147483648.0); + } + } + } + framesRead += frameCountThisIteration; + pBufferOut += frameCountThisIteration * channelCount; + framesToRead -= frameCountThisIteration; + pFlac->currentPCMFrame += frameCountThisIteration; + pFlac->currentFLACFrame.pcmFramesRemaining -= (unsigned int)frameCountThisIteration; + } + } + return framesRead; +} +MA_API ma_bool32 ma_dr_flac_seek_to_pcm_frame(ma_dr_flac* pFlac, ma_uint64 pcmFrameIndex) +{ + if (pFlac == NULL) { + return MA_FALSE; + } + if (pFlac->currentPCMFrame == pcmFrameIndex) { + return MA_TRUE; + } + if (pFlac->firstFLACFramePosInBytes == 0) { + return MA_FALSE; + } + if (pcmFrameIndex == 0) { + pFlac->currentPCMFrame = 0; + return ma_dr_flac__seek_to_first_frame(pFlac); + } else { + ma_bool32 wasSuccessful = MA_FALSE; + ma_uint64 originalPCMFrame = pFlac->currentPCMFrame; + if (pcmFrameIndex > pFlac->totalPCMFrameCount) { + pcmFrameIndex = pFlac->totalPCMFrameCount; + } + if (pcmFrameIndex > pFlac->currentPCMFrame) { + ma_uint32 offset = (ma_uint32)(pcmFrameIndex - pFlac->currentPCMFrame); + if (pFlac->currentFLACFrame.pcmFramesRemaining > offset) { + pFlac->currentFLACFrame.pcmFramesRemaining -= offset; + pFlac->currentPCMFrame = pcmFrameIndex; + return MA_TRUE; + } + } else { + ma_uint32 offsetAbs = (ma_uint32)(pFlac->currentPCMFrame - pcmFrameIndex); + ma_uint32 currentFLACFramePCMFrameCount = pFlac->currentFLACFrame.header.blockSizeInPCMFrames; + ma_uint32 currentFLACFramePCMFramesConsumed = currentFLACFramePCMFrameCount - pFlac->currentFLACFrame.pcmFramesRemaining; + if (currentFLACFramePCMFramesConsumed > offsetAbs) { + pFlac->currentFLACFrame.pcmFramesRemaining += offsetAbs; + pFlac->currentPCMFrame = pcmFrameIndex; + return MA_TRUE; + } + } +#ifndef MA_DR_FLAC_NO_OGG + if (pFlac->container == ma_dr_flac_container_ogg) + { + wasSuccessful = ma_dr_flac_ogg__seek_to_pcm_frame(pFlac, pcmFrameIndex); + } + else +#endif + { + if (!pFlac->_noSeekTableSeek) { + wasSuccessful = ma_dr_flac__seek_to_pcm_frame__seek_table(pFlac, pcmFrameIndex); + } +#if !defined(MA_DR_FLAC_NO_CRC) + if (!wasSuccessful && !pFlac->_noBinarySearchSeek && pFlac->totalPCMFrameCount > 0) { + wasSuccessful = ma_dr_flac__seek_to_pcm_frame__binary_search(pFlac, pcmFrameIndex); + } +#endif + if (!wasSuccessful && !pFlac->_noBruteForceSeek) { + wasSuccessful = ma_dr_flac__seek_to_pcm_frame__brute_force(pFlac, pcmFrameIndex); + } + } + if (wasSuccessful) { + pFlac->currentPCMFrame = pcmFrameIndex; + } else { + if (ma_dr_flac_seek_to_pcm_frame(pFlac, originalPCMFrame) == MA_FALSE) { + ma_dr_flac_seek_to_pcm_frame(pFlac, 0); + } + } + return wasSuccessful; + } +} +#define MA_DR_FLAC_DEFINE_FULL_READ_AND_CLOSE(extension, type) \ +static type* ma_dr_flac__full_read_and_close_ ## extension (ma_dr_flac* pFlac, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalPCMFrameCountOut)\ +{ \ + type* pSampleData = NULL; \ + ma_uint64 totalPCMFrameCount; \ + \ + MA_DR_FLAC_ASSERT(pFlac != NULL); \ + \ + totalPCMFrameCount = pFlac->totalPCMFrameCount; \ + \ + if (totalPCMFrameCount == 0) { \ + type buffer[4096]; \ + ma_uint64 pcmFramesRead; \ + size_t sampleDataBufferSize = sizeof(buffer); \ + \ + pSampleData = (type*)ma_dr_flac__malloc_from_callbacks(sampleDataBufferSize, &pFlac->allocationCallbacks); \ + if (pSampleData == NULL) { \ + goto on_error; \ + } \ + \ + while ((pcmFramesRead = (ma_uint64)ma_dr_flac_read_pcm_frames_##extension(pFlac, sizeof(buffer)/sizeof(buffer[0])/pFlac->channels, buffer)) > 0) { \ + if (((totalPCMFrameCount + pcmFramesRead) * pFlac->channels * sizeof(type)) > sampleDataBufferSize) { \ + type* pNewSampleData; \ + size_t newSampleDataBufferSize; \ + \ + newSampleDataBufferSize = sampleDataBufferSize * 2; \ + pNewSampleData = (type*)ma_dr_flac__realloc_from_callbacks(pSampleData, newSampleDataBufferSize, sampleDataBufferSize, &pFlac->allocationCallbacks); \ + if (pNewSampleData == NULL) { \ + ma_dr_flac__free_from_callbacks(pSampleData, &pFlac->allocationCallbacks); \ + goto on_error; \ + } \ + \ + sampleDataBufferSize = newSampleDataBufferSize; \ + pSampleData = pNewSampleData; \ + } \ + \ + MA_DR_FLAC_COPY_MEMORY(pSampleData + (totalPCMFrameCount*pFlac->channels), buffer, (size_t)(pcmFramesRead*pFlac->channels*sizeof(type))); \ + totalPCMFrameCount += pcmFramesRead; \ + } \ + \ + \ + MA_DR_FLAC_ZERO_MEMORY(pSampleData + (totalPCMFrameCount*pFlac->channels), (size_t)(sampleDataBufferSize - totalPCMFrameCount*pFlac->channels*sizeof(type))); \ + } else { \ + ma_uint64 dataSize = totalPCMFrameCount*pFlac->channels*sizeof(type); \ + if (dataSize > (ma_uint64)MA_SIZE_MAX) { \ + goto on_error; \ + } \ + \ + pSampleData = (type*)ma_dr_flac__malloc_from_callbacks((size_t)dataSize, &pFlac->allocationCallbacks); \ + if (pSampleData == NULL) { \ + goto on_error; \ + } \ + \ + totalPCMFrameCount = ma_dr_flac_read_pcm_frames_##extension(pFlac, pFlac->totalPCMFrameCount, pSampleData); \ + } \ + \ + if (sampleRateOut) *sampleRateOut = pFlac->sampleRate; \ + if (channelsOut) *channelsOut = pFlac->channels; \ + if (totalPCMFrameCountOut) *totalPCMFrameCountOut = totalPCMFrameCount; \ + \ + ma_dr_flac_close(pFlac); \ + return pSampleData; \ + \ +on_error: \ + ma_dr_flac_close(pFlac); \ + return NULL; \ +} +MA_DR_FLAC_DEFINE_FULL_READ_AND_CLOSE(s32, ma_int32) +MA_DR_FLAC_DEFINE_FULL_READ_AND_CLOSE(s16, ma_int16) +MA_DR_FLAC_DEFINE_FULL_READ_AND_CLOSE(f32, float) +MA_API ma_int32* ma_dr_flac_open_and_read_pcm_frames_s32(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalPCMFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_flac* pFlac; + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalPCMFrameCountOut) { + *totalPCMFrameCountOut = 0; + } + pFlac = ma_dr_flac_open(onRead, onSeek, pUserData, pAllocationCallbacks); + if (pFlac == NULL) { + return NULL; + } + return ma_dr_flac__full_read_and_close_s32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut); +} +MA_API ma_int16* ma_dr_flac_open_and_read_pcm_frames_s16(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalPCMFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_flac* pFlac; + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalPCMFrameCountOut) { + *totalPCMFrameCountOut = 0; + } + pFlac = ma_dr_flac_open(onRead, onSeek, pUserData, pAllocationCallbacks); + if (pFlac == NULL) { + return NULL; + } + return ma_dr_flac__full_read_and_close_s16(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut); +} +MA_API float* ma_dr_flac_open_and_read_pcm_frames_f32(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalPCMFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_flac* pFlac; + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalPCMFrameCountOut) { + *totalPCMFrameCountOut = 0; + } + pFlac = ma_dr_flac_open(onRead, onSeek, pUserData, pAllocationCallbacks); + if (pFlac == NULL) { + return NULL; + } + return ma_dr_flac__full_read_and_close_f32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut); +} +#ifndef MA_DR_FLAC_NO_STDIO +MA_API ma_int32* ma_dr_flac_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_flac* pFlac; + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalPCMFrameCount) { + *totalPCMFrameCount = 0; + } + pFlac = ma_dr_flac_open_file(filename, pAllocationCallbacks); + if (pFlac == NULL) { + return NULL; + } + return ma_dr_flac__full_read_and_close_s32(pFlac, channels, sampleRate, totalPCMFrameCount); +} +MA_API ma_int16* ma_dr_flac_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_flac* pFlac; + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalPCMFrameCount) { + *totalPCMFrameCount = 0; + } + pFlac = ma_dr_flac_open_file(filename, pAllocationCallbacks); + if (pFlac == NULL) { + return NULL; + } + return ma_dr_flac__full_read_and_close_s16(pFlac, channels, sampleRate, totalPCMFrameCount); +} +MA_API float* ma_dr_flac_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_flac* pFlac; + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalPCMFrameCount) { + *totalPCMFrameCount = 0; + } + pFlac = ma_dr_flac_open_file(filename, pAllocationCallbacks); + if (pFlac == NULL) { + return NULL; + } + return ma_dr_flac__full_read_and_close_f32(pFlac, channels, sampleRate, totalPCMFrameCount); +} +#endif +MA_API ma_int32* ma_dr_flac_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_flac* pFlac; + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalPCMFrameCount) { + *totalPCMFrameCount = 0; + } + pFlac = ma_dr_flac_open_memory(data, dataSize, pAllocationCallbacks); + if (pFlac == NULL) { + return NULL; + } + return ma_dr_flac__full_read_and_close_s32(pFlac, channels, sampleRate, totalPCMFrameCount); +} +MA_API ma_int16* ma_dr_flac_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_flac* pFlac; + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalPCMFrameCount) { + *totalPCMFrameCount = 0; + } + pFlac = ma_dr_flac_open_memory(data, dataSize, pAllocationCallbacks); + if (pFlac == NULL) { + return NULL; + } + return ma_dr_flac__full_read_and_close_s16(pFlac, channels, sampleRate, totalPCMFrameCount); +} +MA_API float* ma_dr_flac_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_flac* pFlac; + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalPCMFrameCount) { + *totalPCMFrameCount = 0; + } + pFlac = ma_dr_flac_open_memory(data, dataSize, pAllocationCallbacks); + if (pFlac == NULL) { + return NULL; + } + return ma_dr_flac__full_read_and_close_f32(pFlac, channels, sampleRate, totalPCMFrameCount); +} +MA_API void ma_dr_flac_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pAllocationCallbacks != NULL) { + ma_dr_flac__free_from_callbacks(p, pAllocationCallbacks); + } else { + ma_dr_flac__free_default(p, NULL); + } +} +MA_API void ma_dr_flac_init_vorbis_comment_iterator(ma_dr_flac_vorbis_comment_iterator* pIter, ma_uint32 commentCount, const void* pComments) +{ + if (pIter == NULL) { + return; + } + pIter->countRemaining = commentCount; + pIter->pRunningData = (const char*)pComments; +} +MA_API const char* ma_dr_flac_next_vorbis_comment(ma_dr_flac_vorbis_comment_iterator* pIter, ma_uint32* pCommentLengthOut) +{ + ma_int32 length; + const char* pComment; + if (pCommentLengthOut) { + *pCommentLengthOut = 0; + } + if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) { + return NULL; + } + length = ma_dr_flac__le2host_32_ptr_unaligned(pIter->pRunningData); + pIter->pRunningData += 4; + pComment = pIter->pRunningData; + pIter->pRunningData += length; + pIter->countRemaining -= 1; + if (pCommentLengthOut) { + *pCommentLengthOut = length; + } + return pComment; +} +MA_API void ma_dr_flac_init_cuesheet_track_iterator(ma_dr_flac_cuesheet_track_iterator* pIter, ma_uint32 trackCount, const void* pTrackData) +{ + if (pIter == NULL) { + return; + } + pIter->countRemaining = trackCount; + pIter->pRunningData = (const char*)pTrackData; +} +MA_API ma_bool32 ma_dr_flac_next_cuesheet_track(ma_dr_flac_cuesheet_track_iterator* pIter, ma_dr_flac_cuesheet_track* pCuesheetTrack) +{ + ma_dr_flac_cuesheet_track cuesheetTrack; + const char* pRunningData; + ma_uint64 offsetHi; + ma_uint64 offsetLo; + if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) { + return MA_FALSE; + } + pRunningData = pIter->pRunningData; + offsetHi = ma_dr_flac__be2host_32(*(const ma_uint32*)pRunningData); pRunningData += 4; + offsetLo = ma_dr_flac__be2host_32(*(const ma_uint32*)pRunningData); pRunningData += 4; + cuesheetTrack.offset = offsetLo | (offsetHi << 32); + cuesheetTrack.trackNumber = pRunningData[0]; pRunningData += 1; + MA_DR_FLAC_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 ma_dr_flac_cuesheet_track_index*)pRunningData; pRunningData += cuesheetTrack.indexCount * sizeof(ma_dr_flac_cuesheet_track_index); + pIter->pRunningData = pRunningData; + pIter->countRemaining -= 1; + if (pCuesheetTrack) { + *pCuesheetTrack = cuesheetTrack; + } + return MA_TRUE; +} +#if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))) + #pragma GCC diagnostic pop +#endif +#endif +/* dr_flac_c end */ +#endif /* MA_DR_FLAC_IMPLEMENTATION */ +#endif /* MA_NO_FLAC */ + +#if !defined(MA_NO_MP3) && !defined(MA_NO_DECODING) +#if !defined(MA_DR_MP3_IMPLEMENTATION) && !defined(MA_DR_MP3_IMPLEMENTATION) /* For backwards compatibility. Will be removed in version 0.11 for cleanliness. */ +/* dr_mp3_c begin */ +#ifndef ma_dr_mp3_c +#define ma_dr_mp3_c +#include +#include +#include +MA_API void ma_dr_mp3_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision) +{ + if (pMajor) { + *pMajor = MA_DR_MP3_VERSION_MAJOR; + } + if (pMinor) { + *pMinor = MA_DR_MP3_VERSION_MINOR; + } + if (pRevision) { + *pRevision = MA_DR_MP3_VERSION_REVISION; + } +} +MA_API const char* ma_dr_mp3_version_string(void) +{ + return MA_DR_MP3_VERSION_STRING; +} +#if defined(__TINYC__) +#define MA_DR_MP3_NO_SIMD +#endif +#define MA_DR_MP3_OFFSET_PTR(p, offset) ((void*)((ma_uint8*)(p) + (offset))) +#define MA_DR_MP3_MAX_FREE_FORMAT_FRAME_SIZE 2304 +#ifndef MA_DR_MP3_MAX_FRAME_SYNC_MATCHES +#define MA_DR_MP3_MAX_FRAME_SYNC_MATCHES 10 +#endif +#define MA_DR_MP3_MAX_L3_FRAME_PAYLOAD_BYTES MA_DR_MP3_MAX_FREE_FORMAT_FRAME_SIZE +#define MA_DR_MP3_MAX_BITRESERVOIR_BYTES 511 +#define MA_DR_MP3_SHORT_BLOCK_TYPE 2 +#define MA_DR_MP3_STOP_BLOCK_TYPE 3 +#define MA_DR_MP3_MODE_MONO 3 +#define MA_DR_MP3_MODE_JOINT_STEREO 1 +#define MA_DR_MP3_HDR_SIZE 4 +#define MA_DR_MP3_HDR_IS_MONO(h) (((h[3]) & 0xC0) == 0xC0) +#define MA_DR_MP3_HDR_IS_MS_STEREO(h) (((h[3]) & 0xE0) == 0x60) +#define MA_DR_MP3_HDR_IS_FREE_FORMAT(h) (((h[2]) & 0xF0) == 0) +#define MA_DR_MP3_HDR_IS_CRC(h) (!((h[1]) & 1)) +#define MA_DR_MP3_HDR_TEST_PADDING(h) ((h[2]) & 0x2) +#define MA_DR_MP3_HDR_TEST_MPEG1(h) ((h[1]) & 0x8) +#define MA_DR_MP3_HDR_TEST_NOT_MPEG25(h) ((h[1]) & 0x10) +#define MA_DR_MP3_HDR_TEST_I_STEREO(h) ((h[3]) & 0x10) +#define MA_DR_MP3_HDR_TEST_MS_STEREO(h) ((h[3]) & 0x20) +#define MA_DR_MP3_HDR_GET_STEREO_MODE(h) (((h[3]) >> 6) & 3) +#define MA_DR_MP3_HDR_GET_STEREO_MODE_EXT(h) (((h[3]) >> 4) & 3) +#define MA_DR_MP3_HDR_GET_LAYER(h) (((h[1]) >> 1) & 3) +#define MA_DR_MP3_HDR_GET_BITRATE(h) ((h[2]) >> 4) +#define MA_DR_MP3_HDR_GET_SAMPLE_RATE(h) (((h[2]) >> 2) & 3) +#define MA_DR_MP3_HDR_GET_MY_SAMPLE_RATE(h) (MA_DR_MP3_HDR_GET_SAMPLE_RATE(h) + (((h[1] >> 3) & 1) + ((h[1] >> 4) & 1))*3) +#define MA_DR_MP3_HDR_IS_FRAME_576(h) ((h[1] & 14) == 2) +#define MA_DR_MP3_HDR_IS_LAYER_1(h) ((h[1] & 6) == 6) +#define MA_DR_MP3_BITS_DEQUANTIZER_OUT -1 +#define MA_DR_MP3_MAX_SCF (255 + MA_DR_MP3_BITS_DEQUANTIZER_OUT*4 - 210) +#define MA_DR_MP3_MAX_SCFI ((MA_DR_MP3_MAX_SCF + 3) & ~3) +#define MA_DR_MP3_MIN(a, b) ((a) > (b) ? (b) : (a)) +#define MA_DR_MP3_MAX(a, b) ((a) < (b) ? (b) : (a)) +#if !defined(MA_DR_MP3_NO_SIMD) +#if !defined(MA_DR_MP3_ONLY_SIMD) && (defined(_M_X64) || defined(__x86_64__) || defined(__aarch64__) || defined(_M_ARM64)) +#define MA_DR_MP3_ONLY_SIMD +#endif +#if ((defined(_MSC_VER) && _MSC_VER >= 1400) && defined(_M_X64)) || ((defined(__i386) || defined(_M_IX86) || defined(__i386__) || defined(__x86_64__)) && ((defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__))) +#if defined(_MSC_VER) +#include +#endif +#include +#define MA_DR_MP3_HAVE_SSE 1 +#define MA_DR_MP3_HAVE_SIMD 1 +#define MA_DR_MP3_VSTORE _mm_storeu_ps +#define MA_DR_MP3_VLD _mm_loadu_ps +#define MA_DR_MP3_VSET _mm_set1_ps +#define MA_DR_MP3_VADD _mm_add_ps +#define MA_DR_MP3_VSUB _mm_sub_ps +#define MA_DR_MP3_VMUL _mm_mul_ps +#define MA_DR_MP3_VMAC(a, x, y) _mm_add_ps(a, _mm_mul_ps(x, y)) +#define MA_DR_MP3_VMSB(a, x, y) _mm_sub_ps(a, _mm_mul_ps(x, y)) +#define MA_DR_MP3_VMUL_S(x, s) _mm_mul_ps(x, _mm_set1_ps(s)) +#define MA_DR_MP3_VREV(x) _mm_shuffle_ps(x, x, _MM_SHUFFLE(0, 1, 2, 3)) +typedef __m128 ma_dr_mp3_f4; +#if defined(_MSC_VER) || defined(MA_DR_MP3_ONLY_SIMD) +#define ma_dr_mp3_cpuid __cpuid +#else +static __inline__ __attribute__((always_inline)) void ma_dr_mp3_cpuid(int CPUInfo[], const int InfoType) +{ +#if defined(__PIC__) + __asm__ __volatile__( +#if defined(__x86_64__) + "push %%rbx\n" + "cpuid\n" + "xchgl %%ebx, %1\n" + "pop %%rbx\n" +#else + "xchgl %%ebx, %1\n" + "cpuid\n" + "xchgl %%ebx, %1\n" +#endif + : "=a" (CPUInfo[0]), "=r" (CPUInfo[1]), "=c" (CPUInfo[2]), "=d" (CPUInfo[3]) + : "a" (InfoType)); +#else + __asm__ __volatile__( + "cpuid" + : "=a" (CPUInfo[0]), "=b" (CPUInfo[1]), "=c" (CPUInfo[2]), "=d" (CPUInfo[3]) + : "a" (InfoType)); +#endif +} +#endif +static int ma_dr_mp3_have_simd(void) +{ +#ifdef MA_DR_MP3_ONLY_SIMD + return 1; +#else + static int g_have_simd; + int CPUInfo[4]; +#ifdef MINIMP3_TEST + static int g_counter; + if (g_counter++ > 100) + return 0; +#endif + if (g_have_simd) + goto end; + ma_dr_mp3_cpuid(CPUInfo, 0); + if (CPUInfo[0] > 0) + { + ma_dr_mp3_cpuid(CPUInfo, 1); + g_have_simd = (CPUInfo[3] & (1 << 26)) + 1; + return g_have_simd - 1; + } +end: + return g_have_simd - 1; +#endif +} +#elif defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64) +#include +#define MA_DR_MP3_HAVE_SSE 0 +#define MA_DR_MP3_HAVE_SIMD 1 +#define MA_DR_MP3_VSTORE vst1q_f32 +#define MA_DR_MP3_VLD vld1q_f32 +#define MA_DR_MP3_VSET vmovq_n_f32 +#define MA_DR_MP3_VADD vaddq_f32 +#define MA_DR_MP3_VSUB vsubq_f32 +#define MA_DR_MP3_VMUL vmulq_f32 +#define MA_DR_MP3_VMAC(a, x, y) vmlaq_f32(a, x, y) +#define MA_DR_MP3_VMSB(a, x, y) vmlsq_f32(a, x, y) +#define MA_DR_MP3_VMUL_S(x, s) vmulq_f32(x, vmovq_n_f32(s)) +#define MA_DR_MP3_VREV(x) vcombine_f32(vget_high_f32(vrev64q_f32(x)), vget_low_f32(vrev64q_f32(x))) +typedef float32x4_t ma_dr_mp3_f4; +static int ma_dr_mp3_have_simd(void) +{ + return 1; +} +#else +#define MA_DR_MP3_HAVE_SSE 0 +#define MA_DR_MP3_HAVE_SIMD 0 +#ifdef MA_DR_MP3_ONLY_SIMD +#error MA_DR_MP3_ONLY_SIMD used, but SSE/NEON not enabled +#endif +#endif +#else +#define MA_DR_MP3_HAVE_SIMD 0 +#endif +#if defined(__ARM_ARCH) && (__ARM_ARCH >= 6) && !defined(__aarch64__) && !defined(_M_ARM64) && !defined(__ARM_ARCH_6M__) +#define MA_DR_MP3_HAVE_ARMV6 1 +static __inline__ __attribute__((always_inline)) ma_int32 ma_dr_mp3_clip_int16_arm(ma_int32 a) +{ + ma_int32 x = 0; + __asm__ ("ssat %0, #16, %1" : "=r"(x) : "r"(a)); + return x; +} +#else +#define MA_DR_MP3_HAVE_ARMV6 0 +#endif +#ifndef MA_DR_MP3_ASSERT +#include +#define MA_DR_MP3_ASSERT(expression) assert(expression) +#endif +#ifndef MA_DR_MP3_COPY_MEMORY +#define MA_DR_MP3_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz)) +#endif +#ifndef MA_DR_MP3_MOVE_MEMORY +#define MA_DR_MP3_MOVE_MEMORY(dst, src, sz) memmove((dst), (src), (sz)) +#endif +#ifndef MA_DR_MP3_ZERO_MEMORY +#define MA_DR_MP3_ZERO_MEMORY(p, sz) memset((p), 0, (sz)) +#endif +#define MA_DR_MP3_ZERO_OBJECT(p) MA_DR_MP3_ZERO_MEMORY((p), sizeof(*(p))) +#ifndef MA_DR_MP3_MALLOC +#define MA_DR_MP3_MALLOC(sz) malloc((sz)) +#endif +#ifndef MA_DR_MP3_REALLOC +#define MA_DR_MP3_REALLOC(p, sz) realloc((p), (sz)) +#endif +#ifndef MA_DR_MP3_FREE +#define MA_DR_MP3_FREE(p) free((p)) +#endif +typedef struct +{ + const ma_uint8 *buf; + int pos, limit; +} ma_dr_mp3_bs; +typedef struct +{ + float scf[3*64]; + ma_uint8 total_bands, stereo_bands, bitalloc[64], scfcod[64]; +} ma_dr_mp3_L12_scale_info; +typedef struct +{ + ma_uint8 tab_offset, code_tab_width, band_count; +} ma_dr_mp3_L12_subband_alloc; +typedef struct +{ + const ma_uint8 *sfbtab; + ma_uint16 part_23_length, big_values, scalefac_compress; + ma_uint8 global_gain, block_type, mixed_block_flag, n_long_sfb, n_short_sfb; + ma_uint8 table_select[3], region_count[3], subblock_gain[3]; + ma_uint8 preflag, scalefac_scale, count1_table, scfsi; +} ma_dr_mp3_L3_gr_info; +typedef struct +{ + ma_dr_mp3_bs bs; + ma_uint8 maindata[MA_DR_MP3_MAX_BITRESERVOIR_BYTES + MA_DR_MP3_MAX_L3_FRAME_PAYLOAD_BYTES]; + ma_dr_mp3_L3_gr_info gr_info[4]; + float grbuf[2][576], scf[40], syn[18 + 15][2*32]; + ma_uint8 ist_pos[2][39]; +} ma_dr_mp3dec_scratch; +static void ma_dr_mp3_bs_init(ma_dr_mp3_bs *bs, const ma_uint8 *data, int bytes) +{ + bs->buf = data; + bs->pos = 0; + bs->limit = bytes*8; +} +static ma_uint32 ma_dr_mp3_bs_get_bits(ma_dr_mp3_bs *bs, int n) +{ + ma_uint32 next, cache = 0, s = bs->pos & 7; + int shl = n + s; + const ma_uint8 *p = bs->buf + (bs->pos >> 3); + if ((bs->pos += n) > bs->limit) + return 0; + next = *p++ & (255 >> s); + while ((shl -= 8) > 0) + { + cache |= next << shl; + next = *p++; + } + return cache | (next >> -shl); +} +static int ma_dr_mp3_hdr_valid(const ma_uint8 *h) +{ + return h[0] == 0xff && + ((h[1] & 0xF0) == 0xf0 || (h[1] & 0xFE) == 0xe2) && + (MA_DR_MP3_HDR_GET_LAYER(h) != 0) && + (MA_DR_MP3_HDR_GET_BITRATE(h) != 15) && + (MA_DR_MP3_HDR_GET_SAMPLE_RATE(h) != 3); +} +static int ma_dr_mp3_hdr_compare(const ma_uint8 *h1, const ma_uint8 *h2) +{ + return ma_dr_mp3_hdr_valid(h2) && + ((h1[1] ^ h2[1]) & 0xFE) == 0 && + ((h1[2] ^ h2[2]) & 0x0C) == 0 && + !(MA_DR_MP3_HDR_IS_FREE_FORMAT(h1) ^ MA_DR_MP3_HDR_IS_FREE_FORMAT(h2)); +} +static unsigned ma_dr_mp3_hdr_bitrate_kbps(const ma_uint8 *h) +{ + static const ma_uint8 halfrate[2][3][15] = { + { { 0,4,8,12,16,20,24,28,32,40,48,56,64,72,80 }, { 0,4,8,12,16,20,24,28,32,40,48,56,64,72,80 }, { 0,16,24,28,32,40,48,56,64,72,80,88,96,112,128 } }, + { { 0,16,20,24,28,32,40,48,56,64,80,96,112,128,160 }, { 0,16,24,28,32,40,48,56,64,80,96,112,128,160,192 }, { 0,16,32,48,64,80,96,112,128,144,160,176,192,208,224 } }, + }; + return 2*halfrate[!!MA_DR_MP3_HDR_TEST_MPEG1(h)][MA_DR_MP3_HDR_GET_LAYER(h) - 1][MA_DR_MP3_HDR_GET_BITRATE(h)]; +} +static unsigned ma_dr_mp3_hdr_sample_rate_hz(const ma_uint8 *h) +{ + static const unsigned g_hz[3] = { 44100, 48000, 32000 }; + return g_hz[MA_DR_MP3_HDR_GET_SAMPLE_RATE(h)] >> (int)!MA_DR_MP3_HDR_TEST_MPEG1(h) >> (int)!MA_DR_MP3_HDR_TEST_NOT_MPEG25(h); +} +static unsigned ma_dr_mp3_hdr_frame_samples(const ma_uint8 *h) +{ + return MA_DR_MP3_HDR_IS_LAYER_1(h) ? 384 : (1152 >> (int)MA_DR_MP3_HDR_IS_FRAME_576(h)); +} +static int ma_dr_mp3_hdr_frame_bytes(const ma_uint8 *h, int free_format_size) +{ + int frame_bytes = ma_dr_mp3_hdr_frame_samples(h)*ma_dr_mp3_hdr_bitrate_kbps(h)*125/ma_dr_mp3_hdr_sample_rate_hz(h); + if (MA_DR_MP3_HDR_IS_LAYER_1(h)) + { + frame_bytes &= ~3; + } + return frame_bytes ? frame_bytes : free_format_size; +} +static int ma_dr_mp3_hdr_padding(const ma_uint8 *h) +{ + return MA_DR_MP3_HDR_TEST_PADDING(h) ? (MA_DR_MP3_HDR_IS_LAYER_1(h) ? 4 : 1) : 0; +} +#ifndef MA_DR_MP3_ONLY_MP3 +static const ma_dr_mp3_L12_subband_alloc *ma_dr_mp3_L12_subband_alloc_table(const ma_uint8 *hdr, ma_dr_mp3_L12_scale_info *sci) +{ + const ma_dr_mp3_L12_subband_alloc *alloc; + int mode = MA_DR_MP3_HDR_GET_STEREO_MODE(hdr); + int nbands, stereo_bands = (mode == MA_DR_MP3_MODE_MONO) ? 0 : (mode == MA_DR_MP3_MODE_JOINT_STEREO) ? (MA_DR_MP3_HDR_GET_STEREO_MODE_EXT(hdr) << 2) + 4 : 32; + if (MA_DR_MP3_HDR_IS_LAYER_1(hdr)) + { + static const ma_dr_mp3_L12_subband_alloc g_alloc_L1[] = { { 76, 4, 32 } }; + alloc = g_alloc_L1; + nbands = 32; + } else if (!MA_DR_MP3_HDR_TEST_MPEG1(hdr)) + { + static const ma_dr_mp3_L12_subband_alloc g_alloc_L2M2[] = { { 60, 4, 4 }, { 44, 3, 7 }, { 44, 2, 19 } }; + alloc = g_alloc_L2M2; + nbands = 30; + } else + { + static const ma_dr_mp3_L12_subband_alloc g_alloc_L2M1[] = { { 0, 4, 3 }, { 16, 4, 8 }, { 32, 3, 12 }, { 40, 2, 7 } }; + int sample_rate_idx = MA_DR_MP3_HDR_GET_SAMPLE_RATE(hdr); + unsigned kbps = ma_dr_mp3_hdr_bitrate_kbps(hdr) >> (int)(mode != MA_DR_MP3_MODE_MONO); + if (!kbps) + { + kbps = 192; + } + alloc = g_alloc_L2M1; + nbands = 27; + if (kbps < 56) + { + static const ma_dr_mp3_L12_subband_alloc g_alloc_L2M1_lowrate[] = { { 44, 4, 2 }, { 44, 3, 10 } }; + alloc = g_alloc_L2M1_lowrate; + nbands = sample_rate_idx == 2 ? 12 : 8; + } else if (kbps >= 96 && sample_rate_idx != 1) + { + nbands = 30; + } + } + sci->total_bands = (ma_uint8)nbands; + sci->stereo_bands = (ma_uint8)MA_DR_MP3_MIN(stereo_bands, nbands); + return alloc; +} +static void ma_dr_mp3_L12_read_scalefactors(ma_dr_mp3_bs *bs, ma_uint8 *pba, ma_uint8 *scfcod, int bands, float *scf) +{ + static const float g_deq_L12[18*3] = { +#define MA_DR_MP3_DQ(x) 9.53674316e-07f/x, 7.56931807e-07f/x, 6.00777173e-07f/x + MA_DR_MP3_DQ(3),MA_DR_MP3_DQ(7),MA_DR_MP3_DQ(15),MA_DR_MP3_DQ(31),MA_DR_MP3_DQ(63),MA_DR_MP3_DQ(127),MA_DR_MP3_DQ(255),MA_DR_MP3_DQ(511),MA_DR_MP3_DQ(1023),MA_DR_MP3_DQ(2047),MA_DR_MP3_DQ(4095),MA_DR_MP3_DQ(8191),MA_DR_MP3_DQ(16383),MA_DR_MP3_DQ(32767),MA_DR_MP3_DQ(65535),MA_DR_MP3_DQ(3),MA_DR_MP3_DQ(5),MA_DR_MP3_DQ(9) + }; + int i, m; + for (i = 0; i < bands; i++) + { + float s = 0; + int ba = *pba++; + int mask = ba ? 4 + ((19 >> scfcod[i]) & 3) : 0; + for (m = 4; m; m >>= 1) + { + if (mask & m) + { + int b = ma_dr_mp3_bs_get_bits(bs, 6); + s = g_deq_L12[ba*3 - 6 + b % 3]*(int)(1 << 21 >> b/3); + } + *scf++ = s; + } + } +} +static void ma_dr_mp3_L12_read_scale_info(const ma_uint8 *hdr, ma_dr_mp3_bs *bs, ma_dr_mp3_L12_scale_info *sci) +{ + static const ma_uint8 g_bitalloc_code_tab[] = { + 0,17, 3, 4, 5,6,7, 8,9,10,11,12,13,14,15,16, + 0,17,18, 3,19,4,5, 6,7, 8, 9,10,11,12,13,16, + 0,17,18, 3,19,4,5,16, + 0,17,18,16, + 0,17,18,19, 4,5,6, 7,8, 9,10,11,12,13,14,15, + 0,17,18, 3,19,4,5, 6,7, 8, 9,10,11,12,13,14, + 0, 2, 3, 4, 5,6,7, 8,9,10,11,12,13,14,15,16 + }; + const ma_dr_mp3_L12_subband_alloc *subband_alloc = ma_dr_mp3_L12_subband_alloc_table(hdr, sci); + int i, k = 0, ba_bits = 0; + const ma_uint8 *ba_code_tab = g_bitalloc_code_tab; + for (i = 0; i < sci->total_bands; i++) + { + ma_uint8 ba; + if (i == k) + { + k += subband_alloc->band_count; + ba_bits = subband_alloc->code_tab_width; + ba_code_tab = g_bitalloc_code_tab + subband_alloc->tab_offset; + subband_alloc++; + } + ba = ba_code_tab[ma_dr_mp3_bs_get_bits(bs, ba_bits)]; + sci->bitalloc[2*i] = ba; + if (i < sci->stereo_bands) + { + ba = ba_code_tab[ma_dr_mp3_bs_get_bits(bs, ba_bits)]; + } + sci->bitalloc[2*i + 1] = sci->stereo_bands ? ba : 0; + } + for (i = 0; i < 2*sci->total_bands; i++) + { + sci->scfcod[i] = (ma_uint8)(sci->bitalloc[i] ? MA_DR_MP3_HDR_IS_LAYER_1(hdr) ? 2 : ma_dr_mp3_bs_get_bits(bs, 2) : 6); + } + ma_dr_mp3_L12_read_scalefactors(bs, sci->bitalloc, sci->scfcod, sci->total_bands*2, sci->scf); + for (i = sci->stereo_bands; i < sci->total_bands; i++) + { + sci->bitalloc[2*i + 1] = 0; + } +} +static int ma_dr_mp3_L12_dequantize_granule(float *grbuf, ma_dr_mp3_bs *bs, ma_dr_mp3_L12_scale_info *sci, int group_size) +{ + int i, j, k, choff = 576; + for (j = 0; j < 4; j++) + { + float *dst = grbuf + group_size*j; + for (i = 0; i < 2*sci->total_bands; i++) + { + int ba = sci->bitalloc[i]; + if (ba != 0) + { + if (ba < 17) + { + int half = (1 << (ba - 1)) - 1; + for (k = 0; k < group_size; k++) + { + dst[k] = (float)((int)ma_dr_mp3_bs_get_bits(bs, ba) - half); + } + } else + { + unsigned mod = (2 << (ba - 17)) + 1; + unsigned code = ma_dr_mp3_bs_get_bits(bs, mod + 2 - (mod >> 3)); + for (k = 0; k < group_size; k++, code /= mod) + { + dst[k] = (float)((int)(code % mod - mod/2)); + } + } + } + dst += choff; + choff = 18 - choff; + } + } + return group_size*4; +} +static void ma_dr_mp3_L12_apply_scf_384(ma_dr_mp3_L12_scale_info *sci, const float *scf, float *dst) +{ + int i, k; + MA_DR_MP3_COPY_MEMORY(dst + 576 + sci->stereo_bands*18, dst + sci->stereo_bands*18, (sci->total_bands - sci->stereo_bands)*18*sizeof(float)); + for (i = 0; i < sci->total_bands; i++, dst += 18, scf += 6) + { + for (k = 0; k < 12; k++) + { + dst[k + 0] *= scf[0]; + dst[k + 576] *= scf[3]; + } + } +} +#endif +static int ma_dr_mp3_L3_read_side_info(ma_dr_mp3_bs *bs, ma_dr_mp3_L3_gr_info *gr, const ma_uint8 *hdr) +{ + static const ma_uint8 g_scf_long[8][23] = { + { 6,6,6,6,6,6,8,10,12,14,16,20,24,28,32,38,46,52,60,68,58,54,0 }, + { 12,12,12,12,12,12,16,20,24,28,32,40,48,56,64,76,90,2,2,2,2,2,0 }, + { 6,6,6,6,6,6,8,10,12,14,16,20,24,28,32,38,46,52,60,68,58,54,0 }, + { 6,6,6,6,6,6,8,10,12,14,16,18,22,26,32,38,46,54,62,70,76,36,0 }, + { 6,6,6,6,6,6,8,10,12,14,16,20,24,28,32,38,46,52,60,68,58,54,0 }, + { 4,4,4,4,4,4,6,6,8,8,10,12,16,20,24,28,34,42,50,54,76,158,0 }, + { 4,4,4,4,4,4,6,6,6,8,10,12,16,18,22,28,34,40,46,54,54,192,0 }, + { 4,4,4,4,4,4,6,6,8,10,12,16,20,24,30,38,46,56,68,84,102,26,0 } + }; + static const ma_uint8 g_scf_short[8][40] = { + { 4,4,4,4,4,4,4,4,4,6,6,6,8,8,8,10,10,10,12,12,12,14,14,14,18,18,18,24,24,24,30,30,30,40,40,40,18,18,18,0 }, + { 8,8,8,8,8,8,8,8,8,12,12,12,16,16,16,20,20,20,24,24,24,28,28,28,36,36,36,2,2,2,2,2,2,2,2,2,26,26,26,0 }, + { 4,4,4,4,4,4,4,4,4,6,6,6,6,6,6,8,8,8,10,10,10,14,14,14,18,18,18,26,26,26,32,32,32,42,42,42,18,18,18,0 }, + { 4,4,4,4,4,4,4,4,4,6,6,6,8,8,8,10,10,10,12,12,12,14,14,14,18,18,18,24,24,24,32,32,32,44,44,44,12,12,12,0 }, + { 4,4,4,4,4,4,4,4,4,6,6,6,8,8,8,10,10,10,12,12,12,14,14,14,18,18,18,24,24,24,30,30,30,40,40,40,18,18,18,0 }, + { 4,4,4,4,4,4,4,4,4,4,4,4,6,6,6,8,8,8,10,10,10,12,12,12,14,14,14,18,18,18,22,22,22,30,30,30,56,56,56,0 }, + { 4,4,4,4,4,4,4,4,4,4,4,4,6,6,6,6,6,6,10,10,10,12,12,12,14,14,14,16,16,16,20,20,20,26,26,26,66,66,66,0 }, + { 4,4,4,4,4,4,4,4,4,4,4,4,6,6,6,8,8,8,12,12,12,16,16,16,20,20,20,26,26,26,34,34,34,42,42,42,12,12,12,0 } + }; + static const ma_uint8 g_scf_mixed[8][40] = { + { 6,6,6,6,6,6,6,6,6,8,8,8,10,10,10,12,12,12,14,14,14,18,18,18,24,24,24,30,30,30,40,40,40,18,18,18,0 }, + { 12,12,12,4,4,4,8,8,8,12,12,12,16,16,16,20,20,20,24,24,24,28,28,28,36,36,36,2,2,2,2,2,2,2,2,2,26,26,26,0 }, + { 6,6,6,6,6,6,6,6,6,6,6,6,8,8,8,10,10,10,14,14,14,18,18,18,26,26,26,32,32,32,42,42,42,18,18,18,0 }, + { 6,6,6,6,6,6,6,6,6,8,8,8,10,10,10,12,12,12,14,14,14,18,18,18,24,24,24,32,32,32,44,44,44,12,12,12,0 }, + { 6,6,6,6,6,6,6,6,6,8,8,8,10,10,10,12,12,12,14,14,14,18,18,18,24,24,24,30,30,30,40,40,40,18,18,18,0 }, + { 4,4,4,4,4,4,6,6,4,4,4,6,6,6,8,8,8,10,10,10,12,12,12,14,14,14,18,18,18,22,22,22,30,30,30,56,56,56,0 }, + { 4,4,4,4,4,4,6,6,4,4,4,6,6,6,6,6,6,10,10,10,12,12,12,14,14,14,16,16,16,20,20,20,26,26,26,66,66,66,0 }, + { 4,4,4,4,4,4,6,6,4,4,4,6,6,6,8,8,8,12,12,12,16,16,16,20,20,20,26,26,26,34,34,34,42,42,42,12,12,12,0 } + }; + unsigned tables, scfsi = 0; + int main_data_begin, part_23_sum = 0; + int gr_count = MA_DR_MP3_HDR_IS_MONO(hdr) ? 1 : 2; + int sr_idx = MA_DR_MP3_HDR_GET_MY_SAMPLE_RATE(hdr); sr_idx -= (sr_idx != 0); + if (MA_DR_MP3_HDR_TEST_MPEG1(hdr)) + { + gr_count *= 2; + main_data_begin = ma_dr_mp3_bs_get_bits(bs, 9); + scfsi = ma_dr_mp3_bs_get_bits(bs, 7 + gr_count); + } else + { + main_data_begin = ma_dr_mp3_bs_get_bits(bs, 8 + gr_count) >> gr_count; + } + do + { + if (MA_DR_MP3_HDR_IS_MONO(hdr)) + { + scfsi <<= 4; + } + gr->part_23_length = (ma_uint16)ma_dr_mp3_bs_get_bits(bs, 12); + part_23_sum += gr->part_23_length; + gr->big_values = (ma_uint16)ma_dr_mp3_bs_get_bits(bs, 9); + if (gr->big_values > 288) + { + return -1; + } + gr->global_gain = (ma_uint8)ma_dr_mp3_bs_get_bits(bs, 8); + gr->scalefac_compress = (ma_uint16)ma_dr_mp3_bs_get_bits(bs, MA_DR_MP3_HDR_TEST_MPEG1(hdr) ? 4 : 9); + gr->sfbtab = g_scf_long[sr_idx]; + gr->n_long_sfb = 22; + gr->n_short_sfb = 0; + if (ma_dr_mp3_bs_get_bits(bs, 1)) + { + gr->block_type = (ma_uint8)ma_dr_mp3_bs_get_bits(bs, 2); + if (!gr->block_type) + { + return -1; + } + gr->mixed_block_flag = (ma_uint8)ma_dr_mp3_bs_get_bits(bs, 1); + gr->region_count[0] = 7; + gr->region_count[1] = 255; + if (gr->block_type == MA_DR_MP3_SHORT_BLOCK_TYPE) + { + scfsi &= 0x0F0F; + if (!gr->mixed_block_flag) + { + gr->region_count[0] = 8; + gr->sfbtab = g_scf_short[sr_idx]; + gr->n_long_sfb = 0; + gr->n_short_sfb = 39; + } else + { + gr->sfbtab = g_scf_mixed[sr_idx]; + gr->n_long_sfb = MA_DR_MP3_HDR_TEST_MPEG1(hdr) ? 8 : 6; + gr->n_short_sfb = 30; + } + } + tables = ma_dr_mp3_bs_get_bits(bs, 10); + tables <<= 5; + gr->subblock_gain[0] = (ma_uint8)ma_dr_mp3_bs_get_bits(bs, 3); + gr->subblock_gain[1] = (ma_uint8)ma_dr_mp3_bs_get_bits(bs, 3); + gr->subblock_gain[2] = (ma_uint8)ma_dr_mp3_bs_get_bits(bs, 3); + } else + { + gr->block_type = 0; + gr->mixed_block_flag = 0; + tables = ma_dr_mp3_bs_get_bits(bs, 15); + gr->region_count[0] = (ma_uint8)ma_dr_mp3_bs_get_bits(bs, 4); + gr->region_count[1] = (ma_uint8)ma_dr_mp3_bs_get_bits(bs, 3); + gr->region_count[2] = 255; + } + gr->table_select[0] = (ma_uint8)(tables >> 10); + gr->table_select[1] = (ma_uint8)((tables >> 5) & 31); + gr->table_select[2] = (ma_uint8)((tables) & 31); + gr->preflag = (ma_uint8)(MA_DR_MP3_HDR_TEST_MPEG1(hdr) ? ma_dr_mp3_bs_get_bits(bs, 1) : (gr->scalefac_compress >= 500)); + gr->scalefac_scale = (ma_uint8)ma_dr_mp3_bs_get_bits(bs, 1); + gr->count1_table = (ma_uint8)ma_dr_mp3_bs_get_bits(bs, 1); + gr->scfsi = (ma_uint8)((scfsi >> 12) & 15); + scfsi <<= 4; + gr++; + } while(--gr_count); + if (part_23_sum + bs->pos > bs->limit + main_data_begin*8) + { + return -1; + } + return main_data_begin; +} +static void ma_dr_mp3_L3_read_scalefactors(ma_uint8 *scf, ma_uint8 *ist_pos, const ma_uint8 *scf_size, const ma_uint8 *scf_count, ma_dr_mp3_bs *bitbuf, int scfsi) +{ + int i, k; + for (i = 0; i < 4 && scf_count[i]; i++, scfsi *= 2) + { + int cnt = scf_count[i]; + if (scfsi & 8) + { + MA_DR_MP3_COPY_MEMORY(scf, ist_pos, cnt); + } else + { + int bits = scf_size[i]; + if (!bits) + { + MA_DR_MP3_ZERO_MEMORY(scf, cnt); + MA_DR_MP3_ZERO_MEMORY(ist_pos, cnt); + } else + { + int max_scf = (scfsi < 0) ? (1 << bits) - 1 : -1; + for (k = 0; k < cnt; k++) + { + int s = ma_dr_mp3_bs_get_bits(bitbuf, bits); + ist_pos[k] = (ma_uint8)(s == max_scf ? -1 : s); + scf[k] = (ma_uint8)s; + } + } + } + ist_pos += cnt; + scf += cnt; + } + scf[0] = scf[1] = scf[2] = 0; +} +static float ma_dr_mp3_L3_ldexp_q2(float y, int exp_q2) +{ + static const float g_expfrac[4] = { 9.31322575e-10f,7.83145814e-10f,6.58544508e-10f,5.53767716e-10f }; + int e; + do + { + e = MA_DR_MP3_MIN(30*4, exp_q2); + y *= g_expfrac[e & 3]*(1 << 30 >> (e >> 2)); + } while ((exp_q2 -= e) > 0); + return y; +} +static void ma_dr_mp3_L3_decode_scalefactors(const ma_uint8 *hdr, ma_uint8 *ist_pos, ma_dr_mp3_bs *bs, const ma_dr_mp3_L3_gr_info *gr, float *scf, int ch) +{ + static const ma_uint8 g_scf_partitions[3][28] = { + { 6,5,5, 5,6,5,5,5,6,5, 7,3,11,10,0,0, 7, 7, 7,0, 6, 6,6,3, 8, 8,5,0 }, + { 8,9,6,12,6,9,9,9,6,9,12,6,15,18,0,0, 6,15,12,0, 6,12,9,6, 6,18,9,0 }, + { 9,9,6,12,9,9,9,9,9,9,12,6,18,18,0,0,12,12,12,0,12, 9,9,6,15,12,9,0 } + }; + const ma_uint8 *scf_partition = g_scf_partitions[!!gr->n_short_sfb + !gr->n_long_sfb]; + ma_uint8 scf_size[4], iscf[40]; + int i, scf_shift = gr->scalefac_scale + 1, gain_exp, scfsi = gr->scfsi; + float gain; + if (MA_DR_MP3_HDR_TEST_MPEG1(hdr)) + { + static const ma_uint8 g_scfc_decode[16] = { 0,1,2,3, 12,5,6,7, 9,10,11,13, 14,15,18,19 }; + int part = g_scfc_decode[gr->scalefac_compress]; + scf_size[1] = scf_size[0] = (ma_uint8)(part >> 2); + scf_size[3] = scf_size[2] = (ma_uint8)(part & 3); + } else + { + static const ma_uint8 g_mod[6*4] = { 5,5,4,4,5,5,4,1,4,3,1,1,5,6,6,1,4,4,4,1,4,3,1,1 }; + int k, modprod, sfc, ist = MA_DR_MP3_HDR_TEST_I_STEREO(hdr) && ch; + sfc = gr->scalefac_compress >> ist; + for (k = ist*3*4; sfc >= 0; sfc -= modprod, k += 4) + { + for (modprod = 1, i = 3; i >= 0; i--) + { + scf_size[i] = (ma_uint8)(sfc / modprod % g_mod[k + i]); + modprod *= g_mod[k + i]; + } + } + scf_partition += k; + scfsi = -16; + } + ma_dr_mp3_L3_read_scalefactors(iscf, ist_pos, scf_size, scf_partition, bs, scfsi); + if (gr->n_short_sfb) + { + int sh = 3 - scf_shift; + for (i = 0; i < gr->n_short_sfb; i += 3) + { + iscf[gr->n_long_sfb + i + 0] = (ma_uint8)(iscf[gr->n_long_sfb + i + 0] + (gr->subblock_gain[0] << sh)); + iscf[gr->n_long_sfb + i + 1] = (ma_uint8)(iscf[gr->n_long_sfb + i + 1] + (gr->subblock_gain[1] << sh)); + iscf[gr->n_long_sfb + i + 2] = (ma_uint8)(iscf[gr->n_long_sfb + i + 2] + (gr->subblock_gain[2] << sh)); + } + } else if (gr->preflag) + { + static const ma_uint8 g_preamp[10] = { 1,1,1,1,2,2,3,3,3,2 }; + for (i = 0; i < 10; i++) + { + iscf[11 + i] = (ma_uint8)(iscf[11 + i] + g_preamp[i]); + } + } + gain_exp = gr->global_gain + MA_DR_MP3_BITS_DEQUANTIZER_OUT*4 - 210 - (MA_DR_MP3_HDR_IS_MS_STEREO(hdr) ? 2 : 0); + gain = ma_dr_mp3_L3_ldexp_q2(1 << (MA_DR_MP3_MAX_SCFI/4), MA_DR_MP3_MAX_SCFI - gain_exp); + for (i = 0; i < (int)(gr->n_long_sfb + gr->n_short_sfb); i++) + { + scf[i] = ma_dr_mp3_L3_ldexp_q2(gain, iscf[i] << scf_shift); + } +} +static const float g_ma_dr_mp3_pow43[129 + 16] = { + 0,-1,-2.519842f,-4.326749f,-6.349604f,-8.549880f,-10.902724f,-13.390518f,-16.000000f,-18.720754f,-21.544347f,-24.463781f,-27.473142f,-30.567351f,-33.741992f,-36.993181f, + 0,1,2.519842f,4.326749f,6.349604f,8.549880f,10.902724f,13.390518f,16.000000f,18.720754f,21.544347f,24.463781f,27.473142f,30.567351f,33.741992f,36.993181f,40.317474f,43.711787f,47.173345f,50.699631f,54.288352f,57.937408f,61.644865f,65.408941f,69.227979f,73.100443f,77.024898f,81.000000f,85.024491f,89.097188f,93.216975f,97.382800f,101.593667f,105.848633f,110.146801f,114.487321f,118.869381f,123.292209f,127.755065f,132.257246f,136.798076f,141.376907f,145.993119f,150.646117f,155.335327f,160.060199f,164.820202f,169.614826f,174.443577f,179.305980f,184.201575f,189.129918f,194.090580f,199.083145f,204.107210f,209.162385f,214.248292f,219.364564f,224.510845f,229.686789f,234.892058f,240.126328f,245.389280f,250.680604f,256.000000f,261.347174f,266.721841f,272.123723f,277.552547f,283.008049f,288.489971f,293.998060f,299.532071f,305.091761f,310.676898f,316.287249f,321.922592f,327.582707f,333.267377f,338.976394f,344.709550f,350.466646f,356.247482f,362.051866f,367.879608f,373.730522f,379.604427f,385.501143f,391.420496f,397.362314f,403.326427f,409.312672f,415.320884f,421.350905f,427.402579f,433.475750f,439.570269f,445.685987f,451.822757f,457.980436f,464.158883f,470.357960f,476.577530f,482.817459f,489.077615f,495.357868f,501.658090f,507.978156f,514.317941f,520.677324f,527.056184f,533.454404f,539.871867f,546.308458f,552.764065f,559.238575f,565.731879f,572.243870f,578.774440f,585.323483f,591.890898f,598.476581f,605.080431f,611.702349f,618.342238f,625.000000f,631.675540f,638.368763f,645.079578f +}; +static float ma_dr_mp3_L3_pow_43(int x) +{ + float frac; + int sign, mult = 256; + if (x < 129) + { + return g_ma_dr_mp3_pow43[16 + x]; + } + if (x < 1024) + { + mult = 16; + x <<= 3; + } + sign = 2*x & 64; + frac = (float)((x & 63) - sign) / ((x & ~63) + sign); + return g_ma_dr_mp3_pow43[16 + ((x + sign) >> 6)]*(1.f + frac*((4.f/3) + frac*(2.f/9)))*mult; +} +static void ma_dr_mp3_L3_huffman(float *dst, ma_dr_mp3_bs *bs, const ma_dr_mp3_L3_gr_info *gr_info, const float *scf, int layer3gr_limit) +{ + static const ma_int16 tabs[] = { 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, + 785,785,785,785,784,784,784,784,513,513,513,513,513,513,513,513,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256, + -255,1313,1298,1282,785,785,785,785,784,784,784,784,769,769,769,769,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,290,288, + -255,1313,1298,1282,769,769,769,769,529,529,529,529,529,529,529,529,528,528,528,528,528,528,528,528,512,512,512,512,512,512,512,512,290,288, + -253,-318,-351,-367,785,785,785,785,784,784,784,784,769,769,769,769,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,819,818,547,547,275,275,275,275,561,560,515,546,289,274,288,258, + -254,-287,1329,1299,1314,1312,1057,1057,1042,1042,1026,1026,784,784,784,784,529,529,529,529,529,529,529,529,769,769,769,769,768,768,768,768,563,560,306,306,291,259, + -252,-413,-477,-542,1298,-575,1041,1041,784,784,784,784,769,769,769,769,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,-383,-399,1107,1092,1106,1061,849,849,789,789,1104,1091,773,773,1076,1075,341,340,325,309,834,804,577,577,532,532,516,516,832,818,803,816,561,561,531,531,515,546,289,289,288,258, + -252,-429,-493,-559,1057,1057,1042,1042,529,529,529,529,529,529,529,529,784,784,784,784,769,769,769,769,512,512,512,512,512,512,512,512,-382,1077,-415,1106,1061,1104,849,849,789,789,1091,1076,1029,1075,834,834,597,581,340,340,339,324,804,833,532,532,832,772,818,803,817,787,816,771,290,290,290,290,288,258, + -253,-349,-414,-447,-463,1329,1299,-479,1314,1312,1057,1057,1042,1042,1026,1026,785,785,785,785,784,784,784,784,769,769,769,769,768,768,768,768,-319,851,821,-335,836,850,805,849,341,340,325,336,533,533,579,579,564,564,773,832,578,548,563,516,321,276,306,291,304,259, + -251,-572,-733,-830,-863,-879,1041,1041,784,784,784,784,769,769,769,769,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,-511,-527,-543,1396,1351,1381,1366,1395,1335,1380,-559,1334,1138,1138,1063,1063,1350,1392,1031,1031,1062,1062,1364,1363,1120,1120,1333,1348,881,881,881,881,375,374,359,373,343,358,341,325,791,791,1123,1122,-703,1105,1045,-719,865,865,790,790,774,774,1104,1029,338,293,323,308,-799,-815,833,788,772,818,803,816,322,292,307,320,561,531,515,546,289,274,288,258, + -251,-525,-605,-685,-765,-831,-846,1298,1057,1057,1312,1282,785,785,785,785,784,784,784,784,769,769,769,769,512,512,512,512,512,512,512,512,1399,1398,1383,1367,1382,1396,1351,-511,1381,1366,1139,1139,1079,1079,1124,1124,1364,1349,1363,1333,882,882,882,882,807,807,807,807,1094,1094,1136,1136,373,341,535,535,881,775,867,822,774,-591,324,338,-671,849,550,550,866,864,609,609,293,336,534,534,789,835,773,-751,834,804,308,307,833,788,832,772,562,562,547,547,305,275,560,515,290,290, + -252,-397,-477,-557,-622,-653,-719,-735,-750,1329,1299,1314,1057,1057,1042,1042,1312,1282,1024,1024,785,785,785,785,784,784,784,784,769,769,769,769,-383,1127,1141,1111,1126,1140,1095,1110,869,869,883,883,1079,1109,882,882,375,374,807,868,838,881,791,-463,867,822,368,263,852,837,836,-543,610,610,550,550,352,336,534,534,865,774,851,821,850,805,593,533,579,564,773,832,578,578,548,548,577,577,307,276,306,291,516,560,259,259, + -250,-2107,-2507,-2764,-2909,-2974,-3007,-3023,1041,1041,1040,1040,769,769,769,769,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,-767,-1052,-1213,-1277,-1358,-1405,-1469,-1535,-1550,-1582,-1614,-1647,-1662,-1694,-1726,-1759,-1774,-1807,-1822,-1854,-1886,1565,-1919,-1935,-1951,-1967,1731,1730,1580,1717,-1983,1729,1564,-1999,1548,-2015,-2031,1715,1595,-2047,1714,-2063,1610,-2079,1609,-2095,1323,1323,1457,1457,1307,1307,1712,1547,1641,1700,1699,1594,1685,1625,1442,1442,1322,1322,-780,-973,-910,1279,1278,1277,1262,1276,1261,1275,1215,1260,1229,-959,974,974,989,989,-943,735,478,478,495,463,506,414,-1039,1003,958,1017,927,942,987,957,431,476,1272,1167,1228,-1183,1256,-1199,895,895,941,941,1242,1227,1212,1135,1014,1014,490,489,503,487,910,1013,985,925,863,894,970,955,1012,847,-1343,831,755,755,984,909,428,366,754,559,-1391,752,486,457,924,997,698,698,983,893,740,740,908,877,739,739,667,667,953,938,497,287,271,271,683,606,590,712,726,574,302,302,738,736,481,286,526,725,605,711,636,724,696,651,589,681,666,710,364,467,573,695,466,466,301,465,379,379,709,604,665,679,316,316,634,633,436,436,464,269,424,394,452,332,438,363,347,408,393,448,331,422,362,407,392,421,346,406,391,376,375,359,1441,1306,-2367,1290,-2383,1337,-2399,-2415,1426,1321,-2431,1411,1336,-2447,-2463,-2479,1169,1169,1049,1049,1424,1289,1412,1352,1319,-2495,1154,1154,1064,1064,1153,1153,416,390,360,404,403,389,344,374,373,343,358,372,327,357,342,311,356,326,1395,1394,1137,1137,1047,1047,1365,1392,1287,1379,1334,1364,1349,1378,1318,1363,792,792,792,792,1152,1152,1032,1032,1121,1121,1046,1046,1120,1120,1030,1030,-2895,1106,1061,1104,849,849,789,789,1091,1076,1029,1090,1060,1075,833,833,309,324,532,532,832,772,818,803,561,561,531,560,515,546,289,274,288,258, + -250,-1179,-1579,-1836,-1996,-2124,-2253,-2333,-2413,-2477,-2542,-2574,-2607,-2622,-2655,1314,1313,1298,1312,1282,785,785,785,785,1040,1040,1025,1025,768,768,768,768,-766,-798,-830,-862,-895,-911,-927,-943,-959,-975,-991,-1007,-1023,-1039,-1055,-1070,1724,1647,-1103,-1119,1631,1767,1662,1738,1708,1723,-1135,1780,1615,1779,1599,1677,1646,1778,1583,-1151,1777,1567,1737,1692,1765,1722,1707,1630,1751,1661,1764,1614,1736,1676,1763,1750,1645,1598,1721,1691,1762,1706,1582,1761,1566,-1167,1749,1629,767,766,751,765,494,494,735,764,719,749,734,763,447,447,748,718,477,506,431,491,446,476,461,505,415,430,475,445,504,399,460,489,414,503,383,474,429,459,502,502,746,752,488,398,501,473,413,472,486,271,480,270,-1439,-1455,1357,-1471,-1487,-1503,1341,1325,-1519,1489,1463,1403,1309,-1535,1372,1448,1418,1476,1356,1462,1387,-1551,1475,1340,1447,1402,1386,-1567,1068,1068,1474,1461,455,380,468,440,395,425,410,454,364,467,466,464,453,269,409,448,268,432,1371,1473,1432,1417,1308,1460,1355,1446,1459,1431,1083,1083,1401,1416,1458,1445,1067,1067,1370,1457,1051,1051,1291,1430,1385,1444,1354,1415,1400,1443,1082,1082,1173,1113,1186,1066,1185,1050,-1967,1158,1128,1172,1097,1171,1081,-1983,1157,1112,416,266,375,400,1170,1142,1127,1065,793,793,1169,1033,1156,1096,1141,1111,1155,1080,1126,1140,898,898,808,808,897,897,792,792,1095,1152,1032,1125,1110,1139,1079,1124,882,807,838,881,853,791,-2319,867,368,263,822,852,837,866,806,865,-2399,851,352,262,534,534,821,836,594,594,549,549,593,593,533,533,848,773,579,579,564,578,548,563,276,276,577,576,306,291,516,560,305,305,275,259, + -251,-892,-2058,-2620,-2828,-2957,-3023,-3039,1041,1041,1040,1040,769,769,769,769,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,-511,-527,-543,-559,1530,-575,-591,1528,1527,1407,1526,1391,1023,1023,1023,1023,1525,1375,1268,1268,1103,1103,1087,1087,1039,1039,1523,-604,815,815,815,815,510,495,509,479,508,463,507,447,431,505,415,399,-734,-782,1262,-815,1259,1244,-831,1258,1228,-847,-863,1196,-879,1253,987,987,748,-767,493,493,462,477,414,414,686,669,478,446,461,445,474,429,487,458,412,471,1266,1264,1009,1009,799,799,-1019,-1276,-1452,-1581,-1677,-1757,-1821,-1886,-1933,-1997,1257,1257,1483,1468,1512,1422,1497,1406,1467,1496,1421,1510,1134,1134,1225,1225,1466,1451,1374,1405,1252,1252,1358,1480,1164,1164,1251,1251,1238,1238,1389,1465,-1407,1054,1101,-1423,1207,-1439,830,830,1248,1038,1237,1117,1223,1148,1236,1208,411,426,395,410,379,269,1193,1222,1132,1235,1221,1116,976,976,1192,1162,1177,1220,1131,1191,963,963,-1647,961,780,-1663,558,558,994,993,437,408,393,407,829,978,813,797,947,-1743,721,721,377,392,844,950,828,890,706,706,812,859,796,960,948,843,934,874,571,571,-1919,690,555,689,421,346,539,539,944,779,918,873,932,842,903,888,570,570,931,917,674,674,-2575,1562,-2591,1609,-2607,1654,1322,1322,1441,1441,1696,1546,1683,1593,1669,1624,1426,1426,1321,1321,1639,1680,1425,1425,1305,1305,1545,1668,1608,1623,1667,1592,1638,1666,1320,1320,1652,1607,1409,1409,1304,1304,1288,1288,1664,1637,1395,1395,1335,1335,1622,1636,1394,1394,1319,1319,1606,1621,1392,1392,1137,1137,1137,1137,345,390,360,375,404,373,1047,-2751,-2767,-2783,1062,1121,1046,-2799,1077,-2815,1106,1061,789,789,1105,1104,263,355,310,340,325,354,352,262,339,324,1091,1076,1029,1090,1060,1075,833,833,788,788,1088,1028,818,818,803,803,561,561,531,531,816,771,546,546,289,274,288,258, + -253,-317,-381,-446,-478,-509,1279,1279,-811,-1179,-1451,-1756,-1900,-2028,-2189,-2253,-2333,-2414,-2445,-2511,-2526,1313,1298,-2559,1041,1041,1040,1040,1025,1025,1024,1024,1022,1007,1021,991,1020,975,1019,959,687,687,1018,1017,671,671,655,655,1016,1015,639,639,758,758,623,623,757,607,756,591,755,575,754,559,543,543,1009,783,-575,-621,-685,-749,496,-590,750,749,734,748,974,989,1003,958,988,973,1002,942,987,957,972,1001,926,986,941,971,956,1000,910,985,925,999,894,970,-1071,-1087,-1102,1390,-1135,1436,1509,1451,1374,-1151,1405,1358,1480,1420,-1167,1507,1494,1389,1342,1465,1435,1450,1326,1505,1310,1493,1373,1479,1404,1492,1464,1419,428,443,472,397,736,526,464,464,486,457,442,471,484,482,1357,1449,1434,1478,1388,1491,1341,1490,1325,1489,1463,1403,1309,1477,1372,1448,1418,1433,1476,1356,1462,1387,-1439,1475,1340,1447,1402,1474,1324,1461,1371,1473,269,448,1432,1417,1308,1460,-1711,1459,-1727,1441,1099,1099,1446,1386,1431,1401,-1743,1289,1083,1083,1160,1160,1458,1445,1067,1067,1370,1457,1307,1430,1129,1129,1098,1098,268,432,267,416,266,400,-1887,1144,1187,1082,1173,1113,1186,1066,1050,1158,1128,1143,1172,1097,1171,1081,420,391,1157,1112,1170,1142,1127,1065,1169,1049,1156,1096,1141,1111,1155,1080,1126,1154,1064,1153,1140,1095,1048,-2159,1125,1110,1137,-2175,823,823,1139,1138,807,807,384,264,368,263,868,838,853,791,867,822,852,837,866,806,865,790,-2319,851,821,836,352,262,850,805,849,-2399,533,533,835,820,336,261,578,548,563,577,532,532,832,772,562,562,547,547,305,275,560,515,290,290,288,258 }; + static const ma_uint8 tab32[] = { 130,162,193,209,44,28,76,140,9,9,9,9,9,9,9,9,190,254,222,238,126,94,157,157,109,61,173,205}; + static const ma_uint8 tab33[] = { 252,236,220,204,188,172,156,140,124,108,92,76,60,44,28,12 }; + static const ma_int16 tabindex[2*16] = { 0,32,64,98,0,132,180,218,292,364,426,538,648,746,0,1126,1460,1460,1460,1460,1460,1460,1460,1460,1842,1842,1842,1842,1842,1842,1842,1842 }; + static const ma_uint8 g_linbits[] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,4,6,8,10,13,4,5,6,7,8,9,11,13 }; +#define MA_DR_MP3_PEEK_BITS(n) (bs_cache >> (32 - (n))) +#define MA_DR_MP3_FLUSH_BITS(n) { bs_cache <<= (n); bs_sh += (n); } +#define MA_DR_MP3_CHECK_BITS while (bs_sh >= 0) { bs_cache |= (ma_uint32)*bs_next_ptr++ << bs_sh; bs_sh -= 8; } +#define MA_DR_MP3_BSPOS ((bs_next_ptr - bs->buf)*8 - 24 + bs_sh) + float one = 0.0f; + int ireg = 0, big_val_cnt = gr_info->big_values; + const ma_uint8 *sfb = gr_info->sfbtab; + const ma_uint8 *bs_next_ptr = bs->buf + bs->pos/8; + ma_uint32 bs_cache = (((bs_next_ptr[0]*256u + bs_next_ptr[1])*256u + bs_next_ptr[2])*256u + bs_next_ptr[3]) << (bs->pos & 7); + int pairs_to_decode, np, bs_sh = (bs->pos & 7) - 8; + bs_next_ptr += 4; + while (big_val_cnt > 0) + { + int tab_num = gr_info->table_select[ireg]; + int sfb_cnt = gr_info->region_count[ireg++]; + const ma_int16 *codebook = tabs + tabindex[tab_num]; + int linbits = g_linbits[tab_num]; + if (linbits) + { + do + { + np = *sfb++ / 2; + pairs_to_decode = MA_DR_MP3_MIN(big_val_cnt, np); + one = *scf++; + do + { + int j, w = 5; + int leaf = codebook[MA_DR_MP3_PEEK_BITS(w)]; + while (leaf < 0) + { + MA_DR_MP3_FLUSH_BITS(w); + w = leaf & 7; + leaf = codebook[MA_DR_MP3_PEEK_BITS(w) - (leaf >> 3)]; + } + MA_DR_MP3_FLUSH_BITS(leaf >> 8); + for (j = 0; j < 2; j++, dst++, leaf >>= 4) + { + int lsb = leaf & 0x0F; + if (lsb == 15) + { + lsb += MA_DR_MP3_PEEK_BITS(linbits); + MA_DR_MP3_FLUSH_BITS(linbits); + MA_DR_MP3_CHECK_BITS; + *dst = one*ma_dr_mp3_L3_pow_43(lsb)*((ma_int32)bs_cache < 0 ? -1: 1); + } else + { + *dst = g_ma_dr_mp3_pow43[16 + lsb - 16*(bs_cache >> 31)]*one; + } + MA_DR_MP3_FLUSH_BITS(lsb ? 1 : 0); + } + MA_DR_MP3_CHECK_BITS; + } while (--pairs_to_decode); + } while ((big_val_cnt -= np) > 0 && --sfb_cnt >= 0); + } else + { + do + { + np = *sfb++ / 2; + pairs_to_decode = MA_DR_MP3_MIN(big_val_cnt, np); + one = *scf++; + do + { + int j, w = 5; + int leaf = codebook[MA_DR_MP3_PEEK_BITS(w)]; + while (leaf < 0) + { + MA_DR_MP3_FLUSH_BITS(w); + w = leaf & 7; + leaf = codebook[MA_DR_MP3_PEEK_BITS(w) - (leaf >> 3)]; + } + MA_DR_MP3_FLUSH_BITS(leaf >> 8); + for (j = 0; j < 2; j++, dst++, leaf >>= 4) + { + int lsb = leaf & 0x0F; + *dst = g_ma_dr_mp3_pow43[16 + lsb - 16*(bs_cache >> 31)]*one; + MA_DR_MP3_FLUSH_BITS(lsb ? 1 : 0); + } + MA_DR_MP3_CHECK_BITS; + } while (--pairs_to_decode); + } while ((big_val_cnt -= np) > 0 && --sfb_cnt >= 0); + } + } + for (np = 1 - big_val_cnt;; dst += 4) + { + const ma_uint8 *codebook_count1 = (gr_info->count1_table) ? tab33 : tab32; + int leaf = codebook_count1[MA_DR_MP3_PEEK_BITS(4)]; + if (!(leaf & 8)) + { + leaf = codebook_count1[(leaf >> 3) + (bs_cache << 4 >> (32 - (leaf & 3)))]; + } + MA_DR_MP3_FLUSH_BITS(leaf & 7); + if (MA_DR_MP3_BSPOS > layer3gr_limit) + { + break; + } +#define MA_DR_MP3_RELOAD_SCALEFACTOR if (!--np) { np = *sfb++/2; if (!np) break; one = *scf++; } +#define MA_DR_MP3_DEQ_COUNT1(s) if (leaf & (128 >> s)) { dst[s] = ((ma_int32)bs_cache < 0) ? -one : one; MA_DR_MP3_FLUSH_BITS(1) } + MA_DR_MP3_RELOAD_SCALEFACTOR; + MA_DR_MP3_DEQ_COUNT1(0); + MA_DR_MP3_DEQ_COUNT1(1); + MA_DR_MP3_RELOAD_SCALEFACTOR; + MA_DR_MP3_DEQ_COUNT1(2); + MA_DR_MP3_DEQ_COUNT1(3); + MA_DR_MP3_CHECK_BITS; + } + bs->pos = layer3gr_limit; +} +static void ma_dr_mp3_L3_midside_stereo(float *left, int n) +{ + int i = 0; + float *right = left + 576; +#if MA_DR_MP3_HAVE_SIMD + if (ma_dr_mp3_have_simd()) + { + for (; i < n - 3; i += 4) + { + ma_dr_mp3_f4 vl = MA_DR_MP3_VLD(left + i); + ma_dr_mp3_f4 vr = MA_DR_MP3_VLD(right + i); + MA_DR_MP3_VSTORE(left + i, MA_DR_MP3_VADD(vl, vr)); + MA_DR_MP3_VSTORE(right + i, MA_DR_MP3_VSUB(vl, vr)); + } +#ifdef __GNUC__ + if (__builtin_constant_p(n % 4 == 0) && n % 4 == 0) + return; +#endif + } +#endif + for (; i < n; i++) + { + float a = left[i]; + float b = right[i]; + left[i] = a + b; + right[i] = a - b; + } +} +static void ma_dr_mp3_L3_intensity_stereo_band(float *left, int n, float kl, float kr) +{ + int i; + for (i = 0; i < n; i++) + { + left[i + 576] = left[i]*kr; + left[i] = left[i]*kl; + } +} +static void ma_dr_mp3_L3_stereo_top_band(const float *right, const ma_uint8 *sfb, int nbands, int max_band[3]) +{ + int i, k; + max_band[0] = max_band[1] = max_band[2] = -1; + for (i = 0; i < nbands; i++) + { + for (k = 0; k < sfb[i]; k += 2) + { + if (right[k] != 0 || right[k + 1] != 0) + { + max_band[i % 3] = i; + break; + } + } + right += sfb[i]; + } +} +static void ma_dr_mp3_L3_stereo_process(float *left, const ma_uint8 *ist_pos, const ma_uint8 *sfb, const ma_uint8 *hdr, int max_band[3], int mpeg2_sh) +{ + static const float g_pan[7*2] = { 0,1,0.21132487f,0.78867513f,0.36602540f,0.63397460f,0.5f,0.5f,0.63397460f,0.36602540f,0.78867513f,0.21132487f,1,0 }; + unsigned i, max_pos = MA_DR_MP3_HDR_TEST_MPEG1(hdr) ? 7 : 64; + for (i = 0; sfb[i]; i++) + { + unsigned ipos = ist_pos[i]; + if ((int)i > max_band[i % 3] && ipos < max_pos) + { + float kl, kr, s = MA_DR_MP3_HDR_TEST_MS_STEREO(hdr) ? 1.41421356f : 1; + if (MA_DR_MP3_HDR_TEST_MPEG1(hdr)) + { + kl = g_pan[2*ipos]; + kr = g_pan[2*ipos + 1]; + } else + { + kl = 1; + kr = ma_dr_mp3_L3_ldexp_q2(1, (ipos + 1) >> 1 << mpeg2_sh); + if (ipos & 1) + { + kl = kr; + kr = 1; + } + } + ma_dr_mp3_L3_intensity_stereo_band(left, sfb[i], kl*s, kr*s); + } else if (MA_DR_MP3_HDR_TEST_MS_STEREO(hdr)) + { + ma_dr_mp3_L3_midside_stereo(left, sfb[i]); + } + left += sfb[i]; + } +} +static void ma_dr_mp3_L3_intensity_stereo(float *left, ma_uint8 *ist_pos, const ma_dr_mp3_L3_gr_info *gr, const ma_uint8 *hdr) +{ + int max_band[3], n_sfb = gr->n_long_sfb + gr->n_short_sfb; + int i, max_blocks = gr->n_short_sfb ? 3 : 1; + ma_dr_mp3_L3_stereo_top_band(left + 576, gr->sfbtab, n_sfb, max_band); + if (gr->n_long_sfb) + { + max_band[0] = max_band[1] = max_band[2] = MA_DR_MP3_MAX(MA_DR_MP3_MAX(max_band[0], max_band[1]), max_band[2]); + } + for (i = 0; i < max_blocks; i++) + { + int default_pos = MA_DR_MP3_HDR_TEST_MPEG1(hdr) ? 3 : 0; + int itop = n_sfb - max_blocks + i; + int prev = itop - max_blocks; + ist_pos[itop] = (ma_uint8)(max_band[i] >= prev ? default_pos : ist_pos[prev]); + } + ma_dr_mp3_L3_stereo_process(left, ist_pos, gr->sfbtab, hdr, max_band, gr[1].scalefac_compress & 1); +} +static void ma_dr_mp3_L3_reorder(float *grbuf, float *scratch, const ma_uint8 *sfb) +{ + int i, len; + float *src = grbuf, *dst = scratch; + for (;0 != (len = *sfb); sfb += 3, src += 2*len) + { + for (i = 0; i < len; i++, src++) + { + *dst++ = src[0*len]; + *dst++ = src[1*len]; + *dst++ = src[2*len]; + } + } + MA_DR_MP3_COPY_MEMORY(grbuf, scratch, (dst - scratch)*sizeof(float)); +} +static void ma_dr_mp3_L3_antialias(float *grbuf, int nbands) +{ + static const float g_aa[2][8] = { + {0.85749293f,0.88174200f,0.94962865f,0.98331459f,0.99551782f,0.99916056f,0.99989920f,0.99999316f}, + {0.51449576f,0.47173197f,0.31337745f,0.18191320f,0.09457419f,0.04096558f,0.01419856f,0.00369997f} + }; + for (; nbands > 0; nbands--, grbuf += 18) + { + int i = 0; +#if MA_DR_MP3_HAVE_SIMD + if (ma_dr_mp3_have_simd()) for (; i < 8; i += 4) + { + ma_dr_mp3_f4 vu = MA_DR_MP3_VLD(grbuf + 18 + i); + ma_dr_mp3_f4 vd = MA_DR_MP3_VLD(grbuf + 14 - i); + ma_dr_mp3_f4 vc0 = MA_DR_MP3_VLD(g_aa[0] + i); + ma_dr_mp3_f4 vc1 = MA_DR_MP3_VLD(g_aa[1] + i); + vd = MA_DR_MP3_VREV(vd); + MA_DR_MP3_VSTORE(grbuf + 18 + i, MA_DR_MP3_VSUB(MA_DR_MP3_VMUL(vu, vc0), MA_DR_MP3_VMUL(vd, vc1))); + vd = MA_DR_MP3_VADD(MA_DR_MP3_VMUL(vu, vc1), MA_DR_MP3_VMUL(vd, vc0)); + MA_DR_MP3_VSTORE(grbuf + 14 - i, MA_DR_MP3_VREV(vd)); + } +#endif +#ifndef MA_DR_MP3_ONLY_SIMD + for(; i < 8; i++) + { + float u = grbuf[18 + i]; + float d = grbuf[17 - i]; + grbuf[18 + i] = u*g_aa[0][i] - d*g_aa[1][i]; + grbuf[17 - i] = u*g_aa[1][i] + d*g_aa[0][i]; + } +#endif + } +} +static void ma_dr_mp3_L3_dct3_9(float *y) +{ + float s0, s1, s2, s3, s4, s5, s6, s7, s8, t0, t2, t4; + s0 = y[0]; s2 = y[2]; s4 = y[4]; s6 = y[6]; s8 = y[8]; + t0 = s0 + s6*0.5f; + s0 -= s6; + t4 = (s4 + s2)*0.93969262f; + t2 = (s8 + s2)*0.76604444f; + s6 = (s4 - s8)*0.17364818f; + s4 += s8 - s2; + s2 = s0 - s4*0.5f; + y[4] = s4 + s0; + s8 = t0 - t2 + s6; + s0 = t0 - t4 + t2; + s4 = t0 + t4 - s6; + s1 = y[1]; s3 = y[3]; s5 = y[5]; s7 = y[7]; + s3 *= 0.86602540f; + t0 = (s5 + s1)*0.98480775f; + t4 = (s5 - s7)*0.34202014f; + t2 = (s1 + s7)*0.64278761f; + s1 = (s1 - s5 - s7)*0.86602540f; + s5 = t0 - s3 - t2; + s7 = t4 - s3 - t0; + s3 = t4 + s3 - t2; + y[0] = s4 - s7; + y[1] = s2 + s1; + y[2] = s0 - s3; + y[3] = s8 + s5; + y[5] = s8 - s5; + y[6] = s0 + s3; + y[7] = s2 - s1; + y[8] = s4 + s7; +} +static void ma_dr_mp3_L3_imdct36(float *grbuf, float *overlap, const float *window, int nbands) +{ + int i, j; + static const float g_twid9[18] = { + 0.73727734f,0.79335334f,0.84339145f,0.88701083f,0.92387953f,0.95371695f,0.97629601f,0.99144486f,0.99904822f,0.67559021f,0.60876143f,0.53729961f,0.46174861f,0.38268343f,0.30070580f,0.21643961f,0.13052619f,0.04361938f + }; + for (j = 0; j < nbands; j++, grbuf += 18, overlap += 9) + { + float co[9], si[9]; + co[0] = -grbuf[0]; + si[0] = grbuf[17]; + for (i = 0; i < 4; i++) + { + si[8 - 2*i] = grbuf[4*i + 1] - grbuf[4*i + 2]; + co[1 + 2*i] = grbuf[4*i + 1] + grbuf[4*i + 2]; + si[7 - 2*i] = grbuf[4*i + 4] - grbuf[4*i + 3]; + co[2 + 2*i] = -(grbuf[4*i + 3] + grbuf[4*i + 4]); + } + ma_dr_mp3_L3_dct3_9(co); + ma_dr_mp3_L3_dct3_9(si); + si[1] = -si[1]; + si[3] = -si[3]; + si[5] = -si[5]; + si[7] = -si[7]; + i = 0; +#if MA_DR_MP3_HAVE_SIMD + if (ma_dr_mp3_have_simd()) for (; i < 8; i += 4) + { + ma_dr_mp3_f4 vovl = MA_DR_MP3_VLD(overlap + i); + ma_dr_mp3_f4 vc = MA_DR_MP3_VLD(co + i); + ma_dr_mp3_f4 vs = MA_DR_MP3_VLD(si + i); + ma_dr_mp3_f4 vr0 = MA_DR_MP3_VLD(g_twid9 + i); + ma_dr_mp3_f4 vr1 = MA_DR_MP3_VLD(g_twid9 + 9 + i); + ma_dr_mp3_f4 vw0 = MA_DR_MP3_VLD(window + i); + ma_dr_mp3_f4 vw1 = MA_DR_MP3_VLD(window + 9 + i); + ma_dr_mp3_f4 vsum = MA_DR_MP3_VADD(MA_DR_MP3_VMUL(vc, vr1), MA_DR_MP3_VMUL(vs, vr0)); + MA_DR_MP3_VSTORE(overlap + i, MA_DR_MP3_VSUB(MA_DR_MP3_VMUL(vc, vr0), MA_DR_MP3_VMUL(vs, vr1))); + MA_DR_MP3_VSTORE(grbuf + i, MA_DR_MP3_VSUB(MA_DR_MP3_VMUL(vovl, vw0), MA_DR_MP3_VMUL(vsum, vw1))); + vsum = MA_DR_MP3_VADD(MA_DR_MP3_VMUL(vovl, vw1), MA_DR_MP3_VMUL(vsum, vw0)); + MA_DR_MP3_VSTORE(grbuf + 14 - i, MA_DR_MP3_VREV(vsum)); + } +#endif + for (; i < 9; i++) + { + float ovl = overlap[i]; + float sum = co[i]*g_twid9[9 + i] + si[i]*g_twid9[0 + i]; + overlap[i] = co[i]*g_twid9[0 + i] - si[i]*g_twid9[9 + i]; + grbuf[i] = ovl*window[0 + i] - sum*window[9 + i]; + grbuf[17 - i] = ovl*window[9 + i] + sum*window[0 + i]; + } + } +} +static void ma_dr_mp3_L3_idct3(float x0, float x1, float x2, float *dst) +{ + float m1 = x1*0.86602540f; + float a1 = x0 - x2*0.5f; + dst[1] = x0 + x2; + dst[0] = a1 + m1; + dst[2] = a1 - m1; +} +static void ma_dr_mp3_L3_imdct12(float *x, float *dst, float *overlap) +{ + static const float g_twid3[6] = { 0.79335334f,0.92387953f,0.99144486f, 0.60876143f,0.38268343f,0.13052619f }; + float co[3], si[3]; + int i; + ma_dr_mp3_L3_idct3(-x[0], x[6] + x[3], x[12] + x[9], co); + ma_dr_mp3_L3_idct3(x[15], x[12] - x[9], x[6] - x[3], si); + si[1] = -si[1]; + for (i = 0; i < 3; i++) + { + float ovl = overlap[i]; + float sum = co[i]*g_twid3[3 + i] + si[i]*g_twid3[0 + i]; + overlap[i] = co[i]*g_twid3[0 + i] - si[i]*g_twid3[3 + i]; + dst[i] = ovl*g_twid3[2 - i] - sum*g_twid3[5 - i]; + dst[5 - i] = ovl*g_twid3[5 - i] + sum*g_twid3[2 - i]; + } +} +static void ma_dr_mp3_L3_imdct_short(float *grbuf, float *overlap, int nbands) +{ + for (;nbands > 0; nbands--, overlap += 9, grbuf += 18) + { + float tmp[18]; + MA_DR_MP3_COPY_MEMORY(tmp, grbuf, sizeof(tmp)); + MA_DR_MP3_COPY_MEMORY(grbuf, overlap, 6*sizeof(float)); + ma_dr_mp3_L3_imdct12(tmp, grbuf + 6, overlap + 6); + ma_dr_mp3_L3_imdct12(tmp + 1, grbuf + 12, overlap + 6); + ma_dr_mp3_L3_imdct12(tmp + 2, overlap, overlap + 6); + } +} +static void ma_dr_mp3_L3_change_sign(float *grbuf) +{ + int b, i; + for (b = 0, grbuf += 18; b < 32; b += 2, grbuf += 36) + for (i = 1; i < 18; i += 2) + grbuf[i] = -grbuf[i]; +} +static void ma_dr_mp3_L3_imdct_gr(float *grbuf, float *overlap, unsigned block_type, unsigned n_long_bands) +{ + static const float g_mdct_window[2][18] = { + { 0.99904822f,0.99144486f,0.97629601f,0.95371695f,0.92387953f,0.88701083f,0.84339145f,0.79335334f,0.73727734f,0.04361938f,0.13052619f,0.21643961f,0.30070580f,0.38268343f,0.46174861f,0.53729961f,0.60876143f,0.67559021f }, + { 1,1,1,1,1,1,0.99144486f,0.92387953f,0.79335334f,0,0,0,0,0,0,0.13052619f,0.38268343f,0.60876143f } + }; + if (n_long_bands) + { + ma_dr_mp3_L3_imdct36(grbuf, overlap, g_mdct_window[0], n_long_bands); + grbuf += 18*n_long_bands; + overlap += 9*n_long_bands; + } + if (block_type == MA_DR_MP3_SHORT_BLOCK_TYPE) + ma_dr_mp3_L3_imdct_short(grbuf, overlap, 32 - n_long_bands); + else + ma_dr_mp3_L3_imdct36(grbuf, overlap, g_mdct_window[block_type == MA_DR_MP3_STOP_BLOCK_TYPE], 32 - n_long_bands); +} +static void ma_dr_mp3_L3_save_reservoir(ma_dr_mp3dec *h, ma_dr_mp3dec_scratch *s) +{ + int pos = (s->bs.pos + 7)/8u; + int remains = s->bs.limit/8u - pos; + if (remains > MA_DR_MP3_MAX_BITRESERVOIR_BYTES) + { + pos += remains - MA_DR_MP3_MAX_BITRESERVOIR_BYTES; + remains = MA_DR_MP3_MAX_BITRESERVOIR_BYTES; + } + if (remains > 0) + { + MA_DR_MP3_MOVE_MEMORY(h->reserv_buf, s->maindata + pos, remains); + } + h->reserv = remains; +} +static int ma_dr_mp3_L3_restore_reservoir(ma_dr_mp3dec *h, ma_dr_mp3_bs *bs, ma_dr_mp3dec_scratch *s, int main_data_begin) +{ + int frame_bytes = (bs->limit - bs->pos)/8; + int bytes_have = MA_DR_MP3_MIN(h->reserv, main_data_begin); + MA_DR_MP3_COPY_MEMORY(s->maindata, h->reserv_buf + MA_DR_MP3_MAX(0, h->reserv - main_data_begin), MA_DR_MP3_MIN(h->reserv, main_data_begin)); + MA_DR_MP3_COPY_MEMORY(s->maindata + bytes_have, bs->buf + bs->pos/8, frame_bytes); + ma_dr_mp3_bs_init(&s->bs, s->maindata, bytes_have + frame_bytes); + return h->reserv >= main_data_begin; +} +static void ma_dr_mp3_L3_decode(ma_dr_mp3dec *h, ma_dr_mp3dec_scratch *s, ma_dr_mp3_L3_gr_info *gr_info, int nch) +{ + int ch; + for (ch = 0; ch < nch; ch++) + { + int layer3gr_limit = s->bs.pos + gr_info[ch].part_23_length; + ma_dr_mp3_L3_decode_scalefactors(h->header, s->ist_pos[ch], &s->bs, gr_info + ch, s->scf, ch); + ma_dr_mp3_L3_huffman(s->grbuf[ch], &s->bs, gr_info + ch, s->scf, layer3gr_limit); + } + if (MA_DR_MP3_HDR_TEST_I_STEREO(h->header)) + { + ma_dr_mp3_L3_intensity_stereo(s->grbuf[0], s->ist_pos[1], gr_info, h->header); + } else if (MA_DR_MP3_HDR_IS_MS_STEREO(h->header)) + { + ma_dr_mp3_L3_midside_stereo(s->grbuf[0], 576); + } + for (ch = 0; ch < nch; ch++, gr_info++) + { + int aa_bands = 31; + int n_long_bands = (gr_info->mixed_block_flag ? 2 : 0) << (int)(MA_DR_MP3_HDR_GET_MY_SAMPLE_RATE(h->header) == 2); + if (gr_info->n_short_sfb) + { + aa_bands = n_long_bands - 1; + ma_dr_mp3_L3_reorder(s->grbuf[ch] + n_long_bands*18, s->syn[0], gr_info->sfbtab + gr_info->n_long_sfb); + } + ma_dr_mp3_L3_antialias(s->grbuf[ch], aa_bands); + ma_dr_mp3_L3_imdct_gr(s->grbuf[ch], h->mdct_overlap[ch], gr_info->block_type, n_long_bands); + ma_dr_mp3_L3_change_sign(s->grbuf[ch]); + } +} +static void ma_dr_mp3d_DCT_II(float *grbuf, int n) +{ + static const float g_sec[24] = { + 10.19000816f,0.50060302f,0.50241929f,3.40760851f,0.50547093f,0.52249861f,2.05778098f,0.51544732f,0.56694406f,1.48416460f,0.53104258f,0.64682180f,1.16943991f,0.55310392f,0.78815460f,0.97256821f,0.58293498f,1.06067765f,0.83934963f,0.62250412f,1.72244716f,0.74453628f,0.67480832f,5.10114861f + }; + int i, k = 0; +#if MA_DR_MP3_HAVE_SIMD + if (ma_dr_mp3_have_simd()) for (; k < n; k += 4) + { + ma_dr_mp3_f4 t[4][8], *x; + float *y = grbuf + k; + for (x = t[0], i = 0; i < 8; i++, x++) + { + ma_dr_mp3_f4 x0 = MA_DR_MP3_VLD(&y[i*18]); + ma_dr_mp3_f4 x1 = MA_DR_MP3_VLD(&y[(15 - i)*18]); + ma_dr_mp3_f4 x2 = MA_DR_MP3_VLD(&y[(16 + i)*18]); + ma_dr_mp3_f4 x3 = MA_DR_MP3_VLD(&y[(31 - i)*18]); + ma_dr_mp3_f4 t0 = MA_DR_MP3_VADD(x0, x3); + ma_dr_mp3_f4 t1 = MA_DR_MP3_VADD(x1, x2); + ma_dr_mp3_f4 t2 = MA_DR_MP3_VMUL_S(MA_DR_MP3_VSUB(x1, x2), g_sec[3*i + 0]); + ma_dr_mp3_f4 t3 = MA_DR_MP3_VMUL_S(MA_DR_MP3_VSUB(x0, x3), g_sec[3*i + 1]); + x[0] = MA_DR_MP3_VADD(t0, t1); + x[8] = MA_DR_MP3_VMUL_S(MA_DR_MP3_VSUB(t0, t1), g_sec[3*i + 2]); + x[16] = MA_DR_MP3_VADD(t3, t2); + x[24] = MA_DR_MP3_VMUL_S(MA_DR_MP3_VSUB(t3, t2), g_sec[3*i + 2]); + } + for (x = t[0], i = 0; i < 4; i++, x += 8) + { + ma_dr_mp3_f4 x0 = x[0], x1 = x[1], x2 = x[2], x3 = x[3], x4 = x[4], x5 = x[5], x6 = x[6], x7 = x[7], xt; + xt = MA_DR_MP3_VSUB(x0, x7); x0 = MA_DR_MP3_VADD(x0, x7); + x7 = MA_DR_MP3_VSUB(x1, x6); x1 = MA_DR_MP3_VADD(x1, x6); + x6 = MA_DR_MP3_VSUB(x2, x5); x2 = MA_DR_MP3_VADD(x2, x5); + x5 = MA_DR_MP3_VSUB(x3, x4); x3 = MA_DR_MP3_VADD(x3, x4); + x4 = MA_DR_MP3_VSUB(x0, x3); x0 = MA_DR_MP3_VADD(x0, x3); + x3 = MA_DR_MP3_VSUB(x1, x2); x1 = MA_DR_MP3_VADD(x1, x2); + x[0] = MA_DR_MP3_VADD(x0, x1); + x[4] = MA_DR_MP3_VMUL_S(MA_DR_MP3_VSUB(x0, x1), 0.70710677f); + x5 = MA_DR_MP3_VADD(x5, x6); + x6 = MA_DR_MP3_VMUL_S(MA_DR_MP3_VADD(x6, x7), 0.70710677f); + x7 = MA_DR_MP3_VADD(x7, xt); + x3 = MA_DR_MP3_VMUL_S(MA_DR_MP3_VADD(x3, x4), 0.70710677f); + x5 = MA_DR_MP3_VSUB(x5, MA_DR_MP3_VMUL_S(x7, 0.198912367f)); + x7 = MA_DR_MP3_VADD(x7, MA_DR_MP3_VMUL_S(x5, 0.382683432f)); + x5 = MA_DR_MP3_VSUB(x5, MA_DR_MP3_VMUL_S(x7, 0.198912367f)); + x0 = MA_DR_MP3_VSUB(xt, x6); xt = MA_DR_MP3_VADD(xt, x6); + x[1] = MA_DR_MP3_VMUL_S(MA_DR_MP3_VADD(xt, x7), 0.50979561f); + x[2] = MA_DR_MP3_VMUL_S(MA_DR_MP3_VADD(x4, x3), 0.54119611f); + x[3] = MA_DR_MP3_VMUL_S(MA_DR_MP3_VSUB(x0, x5), 0.60134488f); + x[5] = MA_DR_MP3_VMUL_S(MA_DR_MP3_VADD(x0, x5), 0.89997619f); + x[6] = MA_DR_MP3_VMUL_S(MA_DR_MP3_VSUB(x4, x3), 1.30656302f); + x[7] = MA_DR_MP3_VMUL_S(MA_DR_MP3_VSUB(xt, x7), 2.56291556f); + } + if (k > n - 3) + { +#if MA_DR_MP3_HAVE_SSE +#define MA_DR_MP3_VSAVE2(i, v) _mm_storel_pi((__m64 *)(void*)&y[i*18], v) +#else +#define MA_DR_MP3_VSAVE2(i, v) vst1_f32((float32_t *)&y[(i)*18], vget_low_f32(v)) +#endif + for (i = 0; i < 7; i++, y += 4*18) + { + ma_dr_mp3_f4 s = MA_DR_MP3_VADD(t[3][i], t[3][i + 1]); + MA_DR_MP3_VSAVE2(0, t[0][i]); + MA_DR_MP3_VSAVE2(1, MA_DR_MP3_VADD(t[2][i], s)); + MA_DR_MP3_VSAVE2(2, MA_DR_MP3_VADD(t[1][i], t[1][i + 1])); + MA_DR_MP3_VSAVE2(3, MA_DR_MP3_VADD(t[2][1 + i], s)); + } + MA_DR_MP3_VSAVE2(0, t[0][7]); + MA_DR_MP3_VSAVE2(1, MA_DR_MP3_VADD(t[2][7], t[3][7])); + MA_DR_MP3_VSAVE2(2, t[1][7]); + MA_DR_MP3_VSAVE2(3, t[3][7]); + } else + { +#define MA_DR_MP3_VSAVE4(i, v) MA_DR_MP3_VSTORE(&y[(i)*18], v) + for (i = 0; i < 7; i++, y += 4*18) + { + ma_dr_mp3_f4 s = MA_DR_MP3_VADD(t[3][i], t[3][i + 1]); + MA_DR_MP3_VSAVE4(0, t[0][i]); + MA_DR_MP3_VSAVE4(1, MA_DR_MP3_VADD(t[2][i], s)); + MA_DR_MP3_VSAVE4(2, MA_DR_MP3_VADD(t[1][i], t[1][i + 1])); + MA_DR_MP3_VSAVE4(3, MA_DR_MP3_VADD(t[2][1 + i], s)); + } + MA_DR_MP3_VSAVE4(0, t[0][7]); + MA_DR_MP3_VSAVE4(1, MA_DR_MP3_VADD(t[2][7], t[3][7])); + MA_DR_MP3_VSAVE4(2, t[1][7]); + MA_DR_MP3_VSAVE4(3, t[3][7]); + } + } else +#endif +#ifdef MA_DR_MP3_ONLY_SIMD + {} +#else + for (; k < n; k++) + { + float t[4][8], *x, *y = grbuf + k; + for (x = t[0], i = 0; i < 8; i++, x++) + { + float x0 = y[i*18]; + float x1 = y[(15 - i)*18]; + float x2 = y[(16 + i)*18]; + float x3 = y[(31 - i)*18]; + float t0 = x0 + x3; + float t1 = x1 + x2; + float t2 = (x1 - x2)*g_sec[3*i + 0]; + float t3 = (x0 - x3)*g_sec[3*i + 1]; + x[0] = t0 + t1; + x[8] = (t0 - t1)*g_sec[3*i + 2]; + x[16] = t3 + t2; + x[24] = (t3 - t2)*g_sec[3*i + 2]; + } + for (x = t[0], i = 0; i < 4; i++, x += 8) + { + float x0 = x[0], x1 = x[1], x2 = x[2], x3 = x[3], x4 = x[4], x5 = x[5], x6 = x[6], x7 = x[7], xt; + xt = x0 - x7; x0 += x7; + x7 = x1 - x6; x1 += x6; + x6 = x2 - x5; x2 += x5; + x5 = x3 - x4; x3 += x4; + x4 = x0 - x3; x0 += x3; + x3 = x1 - x2; x1 += x2; + x[0] = x0 + x1; + x[4] = (x0 - x1)*0.70710677f; + x5 = x5 + x6; + x6 = (x6 + x7)*0.70710677f; + x7 = x7 + xt; + x3 = (x3 + x4)*0.70710677f; + x5 -= x7*0.198912367f; + x7 += x5*0.382683432f; + x5 -= x7*0.198912367f; + x0 = xt - x6; xt += x6; + x[1] = (xt + x7)*0.50979561f; + x[2] = (x4 + x3)*0.54119611f; + x[3] = (x0 - x5)*0.60134488f; + x[5] = (x0 + x5)*0.89997619f; + x[6] = (x4 - x3)*1.30656302f; + x[7] = (xt - x7)*2.56291556f; + } + for (i = 0; i < 7; i++, y += 4*18) + { + y[0*18] = t[0][i]; + y[1*18] = t[2][i] + t[3][i] + t[3][i + 1]; + y[2*18] = t[1][i] + t[1][i + 1]; + y[3*18] = t[2][i + 1] + t[3][i] + t[3][i + 1]; + } + y[0*18] = t[0][7]; + y[1*18] = t[2][7] + t[3][7]; + y[2*18] = t[1][7]; + y[3*18] = t[3][7]; + } +#endif +} +#ifndef MA_DR_MP3_FLOAT_OUTPUT +typedef ma_int16 ma_dr_mp3d_sample_t; +static ma_int16 ma_dr_mp3d_scale_pcm(float sample) +{ + ma_int16 s; +#if MA_DR_MP3_HAVE_ARMV6 + ma_int32 s32 = (ma_int32)(sample + .5f); + s32 -= (s32 < 0); + s = (ma_int16)ma_dr_mp3_clip_int16_arm(s32); +#else + if (sample >= 32766.5) return (ma_int16) 32767; + if (sample <= -32767.5) return (ma_int16)-32768; + s = (ma_int16)(sample + .5f); + s -= (s < 0); +#endif + return s; +} +#else +typedef float ma_dr_mp3d_sample_t; +static float ma_dr_mp3d_scale_pcm(float sample) +{ + return sample*(1.f/32768.f); +} +#endif +static void ma_dr_mp3d_synth_pair(ma_dr_mp3d_sample_t *pcm, int nch, const float *z) +{ + float a; + a = (z[14*64] - z[ 0]) * 29; + a += (z[ 1*64] + z[13*64]) * 213; + a += (z[12*64] - z[ 2*64]) * 459; + a += (z[ 3*64] + z[11*64]) * 2037; + a += (z[10*64] - z[ 4*64]) * 5153; + a += (z[ 5*64] + z[ 9*64]) * 6574; + a += (z[ 8*64] - z[ 6*64]) * 37489; + a += z[ 7*64] * 75038; + pcm[0] = ma_dr_mp3d_scale_pcm(a); + z += 2; + a = z[14*64] * 104; + a += z[12*64] * 1567; + a += z[10*64] * 9727; + a += z[ 8*64] * 64019; + a += z[ 6*64] * -9975; + a += z[ 4*64] * -45; + a += z[ 2*64] * 146; + a += z[ 0*64] * -5; + pcm[16*nch] = ma_dr_mp3d_scale_pcm(a); +} +static void ma_dr_mp3d_synth(float *xl, ma_dr_mp3d_sample_t *dstl, int nch, float *lins) +{ + int i; + float *xr = xl + 576*(nch - 1); + ma_dr_mp3d_sample_t *dstr = dstl + (nch - 1); + static const float g_win[] = { + -1,26,-31,208,218,401,-519,2063,2000,4788,-5517,7134,5959,35640,-39336,74992, + -1,24,-35,202,222,347,-581,2080,1952,4425,-5879,7640,5288,33791,-41176,74856, + -1,21,-38,196,225,294,-645,2087,1893,4063,-6237,8092,4561,31947,-43006,74630, + -1,19,-41,190,227,244,-711,2085,1822,3705,-6589,8492,3776,30112,-44821,74313, + -1,17,-45,183,228,197,-779,2075,1739,3351,-6935,8840,2935,28289,-46617,73908, + -1,16,-49,176,228,153,-848,2057,1644,3004,-7271,9139,2037,26482,-48390,73415, + -2,14,-53,169,227,111,-919,2032,1535,2663,-7597,9389,1082,24694,-50137,72835, + -2,13,-58,161,224,72,-991,2001,1414,2330,-7910,9592,70,22929,-51853,72169, + -2,11,-63,154,221,36,-1064,1962,1280,2006,-8209,9750,-998,21189,-53534,71420, + -2,10,-68,147,215,2,-1137,1919,1131,1692,-8491,9863,-2122,19478,-55178,70590, + -3,9,-73,139,208,-29,-1210,1870,970,1388,-8755,9935,-3300,17799,-56778,69679, + -3,8,-79,132,200,-57,-1283,1817,794,1095,-8998,9966,-4533,16155,-58333,68692, + -4,7,-85,125,189,-83,-1356,1759,605,814,-9219,9959,-5818,14548,-59838,67629, + -4,7,-91,117,177,-106,-1428,1698,402,545,-9416,9916,-7154,12980,-61289,66494, + -5,6,-97,111,163,-127,-1498,1634,185,288,-9585,9838,-8540,11455,-62684,65290 + }; + float *zlin = lins + 15*64; + const float *w = g_win; + zlin[4*15] = xl[18*16]; + zlin[4*15 + 1] = xr[18*16]; + zlin[4*15 + 2] = xl[0]; + zlin[4*15 + 3] = xr[0]; + zlin[4*31] = xl[1 + 18*16]; + zlin[4*31 + 1] = xr[1 + 18*16]; + zlin[4*31 + 2] = xl[1]; + zlin[4*31 + 3] = xr[1]; + ma_dr_mp3d_synth_pair(dstr, nch, lins + 4*15 + 1); + ma_dr_mp3d_synth_pair(dstr + 32*nch, nch, lins + 4*15 + 64 + 1); + ma_dr_mp3d_synth_pair(dstl, nch, lins + 4*15); + ma_dr_mp3d_synth_pair(dstl + 32*nch, nch, lins + 4*15 + 64); +#if MA_DR_MP3_HAVE_SIMD + if (ma_dr_mp3_have_simd()) for (i = 14; i >= 0; i--) + { +#define MA_DR_MP3_VLOAD(k) ma_dr_mp3_f4 w0 = MA_DR_MP3_VSET(*w++); ma_dr_mp3_f4 w1 = MA_DR_MP3_VSET(*w++); ma_dr_mp3_f4 vz = MA_DR_MP3_VLD(&zlin[4*i - 64*k]); ma_dr_mp3_f4 vy = MA_DR_MP3_VLD(&zlin[4*i - 64*(15 - k)]); +#define MA_DR_MP3_V0(k) { MA_DR_MP3_VLOAD(k) b = MA_DR_MP3_VADD(MA_DR_MP3_VMUL(vz, w1), MA_DR_MP3_VMUL(vy, w0)) ; a = MA_DR_MP3_VSUB(MA_DR_MP3_VMUL(vz, w0), MA_DR_MP3_VMUL(vy, w1)); } +#define MA_DR_MP3_V1(k) { MA_DR_MP3_VLOAD(k) b = MA_DR_MP3_VADD(b, MA_DR_MP3_VADD(MA_DR_MP3_VMUL(vz, w1), MA_DR_MP3_VMUL(vy, w0))); a = MA_DR_MP3_VADD(a, MA_DR_MP3_VSUB(MA_DR_MP3_VMUL(vz, w0), MA_DR_MP3_VMUL(vy, w1))); } +#define MA_DR_MP3_V2(k) { MA_DR_MP3_VLOAD(k) b = MA_DR_MP3_VADD(b, MA_DR_MP3_VADD(MA_DR_MP3_VMUL(vz, w1), MA_DR_MP3_VMUL(vy, w0))); a = MA_DR_MP3_VADD(a, MA_DR_MP3_VSUB(MA_DR_MP3_VMUL(vy, w1), MA_DR_MP3_VMUL(vz, w0))); } + ma_dr_mp3_f4 a, b; + zlin[4*i] = xl[18*(31 - i)]; + zlin[4*i + 1] = xr[18*(31 - i)]; + zlin[4*i + 2] = xl[1 + 18*(31 - i)]; + zlin[4*i + 3] = xr[1 + 18*(31 - i)]; + zlin[4*i + 64] = xl[1 + 18*(1 + i)]; + zlin[4*i + 64 + 1] = xr[1 + 18*(1 + i)]; + zlin[4*i - 64 + 2] = xl[18*(1 + i)]; + zlin[4*i - 64 + 3] = xr[18*(1 + i)]; + MA_DR_MP3_V0(0) MA_DR_MP3_V2(1) MA_DR_MP3_V1(2) MA_DR_MP3_V2(3) MA_DR_MP3_V1(4) MA_DR_MP3_V2(5) MA_DR_MP3_V1(6) MA_DR_MP3_V2(7) + { +#ifndef MA_DR_MP3_FLOAT_OUTPUT +#if MA_DR_MP3_HAVE_SSE + static const ma_dr_mp3_f4 g_max = { 32767.0f, 32767.0f, 32767.0f, 32767.0f }; + static const ma_dr_mp3_f4 g_min = { -32768.0f, -32768.0f, -32768.0f, -32768.0f }; + __m128i pcm8 = _mm_packs_epi32(_mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(a, g_max), g_min)), + _mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(b, g_max), g_min))); + dstr[(15 - i)*nch] = (ma_int16)_mm_extract_epi16(pcm8, 1); + dstr[(17 + i)*nch] = (ma_int16)_mm_extract_epi16(pcm8, 5); + dstl[(15 - i)*nch] = (ma_int16)_mm_extract_epi16(pcm8, 0); + dstl[(17 + i)*nch] = (ma_int16)_mm_extract_epi16(pcm8, 4); + dstr[(47 - i)*nch] = (ma_int16)_mm_extract_epi16(pcm8, 3); + dstr[(49 + i)*nch] = (ma_int16)_mm_extract_epi16(pcm8, 7); + dstl[(47 - i)*nch] = (ma_int16)_mm_extract_epi16(pcm8, 2); + dstl[(49 + i)*nch] = (ma_int16)_mm_extract_epi16(pcm8, 6); +#else + int16x4_t pcma, pcmb; + a = MA_DR_MP3_VADD(a, MA_DR_MP3_VSET(0.5f)); + b = MA_DR_MP3_VADD(b, MA_DR_MP3_VSET(0.5f)); + pcma = vqmovn_s32(vqaddq_s32(vcvtq_s32_f32(a), vreinterpretq_s32_u32(vcltq_f32(a, MA_DR_MP3_VSET(0))))); + pcmb = vqmovn_s32(vqaddq_s32(vcvtq_s32_f32(b), vreinterpretq_s32_u32(vcltq_f32(b, MA_DR_MP3_VSET(0))))); + vst1_lane_s16(dstr + (15 - i)*nch, pcma, 1); + vst1_lane_s16(dstr + (17 + i)*nch, pcmb, 1); + vst1_lane_s16(dstl + (15 - i)*nch, pcma, 0); + vst1_lane_s16(dstl + (17 + i)*nch, pcmb, 0); + vst1_lane_s16(dstr + (47 - i)*nch, pcma, 3); + vst1_lane_s16(dstr + (49 + i)*nch, pcmb, 3); + vst1_lane_s16(dstl + (47 - i)*nch, pcma, 2); + vst1_lane_s16(dstl + (49 + i)*nch, pcmb, 2); +#endif +#else + #if MA_DR_MP3_HAVE_SSE + static const ma_dr_mp3_f4 g_scale = { 1.0f/32768.0f, 1.0f/32768.0f, 1.0f/32768.0f, 1.0f/32768.0f }; + #else + const ma_dr_mp3_f4 g_scale = vdupq_n_f32(1.0f/32768.0f); + #endif + a = MA_DR_MP3_VMUL(a, g_scale); + b = MA_DR_MP3_VMUL(b, g_scale); +#if MA_DR_MP3_HAVE_SSE + _mm_store_ss(dstr + (15 - i)*nch, _mm_shuffle_ps(a, a, _MM_SHUFFLE(1, 1, 1, 1))); + _mm_store_ss(dstr + (17 + i)*nch, _mm_shuffle_ps(b, b, _MM_SHUFFLE(1, 1, 1, 1))); + _mm_store_ss(dstl + (15 - i)*nch, _mm_shuffle_ps(a, a, _MM_SHUFFLE(0, 0, 0, 0))); + _mm_store_ss(dstl + (17 + i)*nch, _mm_shuffle_ps(b, b, _MM_SHUFFLE(0, 0, 0, 0))); + _mm_store_ss(dstr + (47 - i)*nch, _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 3, 3, 3))); + _mm_store_ss(dstr + (49 + i)*nch, _mm_shuffle_ps(b, b, _MM_SHUFFLE(3, 3, 3, 3))); + _mm_store_ss(dstl + (47 - i)*nch, _mm_shuffle_ps(a, a, _MM_SHUFFLE(2, 2, 2, 2))); + _mm_store_ss(dstl + (49 + i)*nch, _mm_shuffle_ps(b, b, _MM_SHUFFLE(2, 2, 2, 2))); +#else + vst1q_lane_f32(dstr + (15 - i)*nch, a, 1); + vst1q_lane_f32(dstr + (17 + i)*nch, b, 1); + vst1q_lane_f32(dstl + (15 - i)*nch, a, 0); + vst1q_lane_f32(dstl + (17 + i)*nch, b, 0); + vst1q_lane_f32(dstr + (47 - i)*nch, a, 3); + vst1q_lane_f32(dstr + (49 + i)*nch, b, 3); + vst1q_lane_f32(dstl + (47 - i)*nch, a, 2); + vst1q_lane_f32(dstl + (49 + i)*nch, b, 2); +#endif +#endif + } + } else +#endif +#ifdef MA_DR_MP3_ONLY_SIMD + {} +#else + for (i = 14; i >= 0; i--) + { +#define MA_DR_MP3_LOAD(k) float w0 = *w++; float w1 = *w++; float *vz = &zlin[4*i - k*64]; float *vy = &zlin[4*i - (15 - k)*64]; +#define MA_DR_MP3_S0(k) { int j; MA_DR_MP3_LOAD(k); for (j = 0; j < 4; j++) b[j] = vz[j]*w1 + vy[j]*w0, a[j] = vz[j]*w0 - vy[j]*w1; } +#define MA_DR_MP3_S1(k) { int j; MA_DR_MP3_LOAD(k); for (j = 0; j < 4; j++) b[j] += vz[j]*w1 + vy[j]*w0, a[j] += vz[j]*w0 - vy[j]*w1; } +#define MA_DR_MP3_S2(k) { int j; MA_DR_MP3_LOAD(k); for (j = 0; j < 4; j++) b[j] += vz[j]*w1 + vy[j]*w0, a[j] += vy[j]*w1 - vz[j]*w0; } + float a[4], b[4]; + zlin[4*i] = xl[18*(31 - i)]; + zlin[4*i + 1] = xr[18*(31 - i)]; + zlin[4*i + 2] = xl[1 + 18*(31 - i)]; + zlin[4*i + 3] = xr[1 + 18*(31 - i)]; + zlin[4*(i + 16)] = xl[1 + 18*(1 + i)]; + zlin[4*(i + 16) + 1] = xr[1 + 18*(1 + i)]; + zlin[4*(i - 16) + 2] = xl[18*(1 + i)]; + zlin[4*(i - 16) + 3] = xr[18*(1 + i)]; + MA_DR_MP3_S0(0) MA_DR_MP3_S2(1) MA_DR_MP3_S1(2) MA_DR_MP3_S2(3) MA_DR_MP3_S1(4) MA_DR_MP3_S2(5) MA_DR_MP3_S1(6) MA_DR_MP3_S2(7) + dstr[(15 - i)*nch] = ma_dr_mp3d_scale_pcm(a[1]); + dstr[(17 + i)*nch] = ma_dr_mp3d_scale_pcm(b[1]); + dstl[(15 - i)*nch] = ma_dr_mp3d_scale_pcm(a[0]); + dstl[(17 + i)*nch] = ma_dr_mp3d_scale_pcm(b[0]); + dstr[(47 - i)*nch] = ma_dr_mp3d_scale_pcm(a[3]); + dstr[(49 + i)*nch] = ma_dr_mp3d_scale_pcm(b[3]); + dstl[(47 - i)*nch] = ma_dr_mp3d_scale_pcm(a[2]); + dstl[(49 + i)*nch] = ma_dr_mp3d_scale_pcm(b[2]); + } +#endif +} +static void ma_dr_mp3d_synth_granule(float *qmf_state, float *grbuf, int nbands, int nch, ma_dr_mp3d_sample_t *pcm, float *lins) +{ + int i; + for (i = 0; i < nch; i++) + { + ma_dr_mp3d_DCT_II(grbuf + 576*i, nbands); + } + MA_DR_MP3_COPY_MEMORY(lins, qmf_state, sizeof(float)*15*64); + for (i = 0; i < nbands; i += 2) + { + ma_dr_mp3d_synth(grbuf + i, pcm + 32*nch*i, nch, lins + i*64); + } +#ifndef MA_DR_MP3_NONSTANDARD_BUT_LOGICAL + if (nch == 1) + { + for (i = 0; i < 15*64; i += 2) + { + qmf_state[i] = lins[nbands*64 + i]; + } + } else +#endif + { + MA_DR_MP3_COPY_MEMORY(qmf_state, lins + nbands*64, sizeof(float)*15*64); + } +} +static int ma_dr_mp3d_match_frame(const ma_uint8 *hdr, int mp3_bytes, int frame_bytes) +{ + int i, nmatch; + for (i = 0, nmatch = 0; nmatch < MA_DR_MP3_MAX_FRAME_SYNC_MATCHES; nmatch++) + { + i += ma_dr_mp3_hdr_frame_bytes(hdr + i, frame_bytes) + ma_dr_mp3_hdr_padding(hdr + i); + if (i + MA_DR_MP3_HDR_SIZE > mp3_bytes) + return nmatch > 0; + if (!ma_dr_mp3_hdr_compare(hdr, hdr + i)) + return 0; + } + return 1; +} +static int ma_dr_mp3d_find_frame(const ma_uint8 *mp3, int mp3_bytes, int *free_format_bytes, int *ptr_frame_bytes) +{ + int i, k; + for (i = 0; i < mp3_bytes - MA_DR_MP3_HDR_SIZE; i++, mp3++) + { + if (ma_dr_mp3_hdr_valid(mp3)) + { + int frame_bytes = ma_dr_mp3_hdr_frame_bytes(mp3, *free_format_bytes); + int frame_and_padding = frame_bytes + ma_dr_mp3_hdr_padding(mp3); + for (k = MA_DR_MP3_HDR_SIZE; !frame_bytes && k < MA_DR_MP3_MAX_FREE_FORMAT_FRAME_SIZE && i + 2*k < mp3_bytes - MA_DR_MP3_HDR_SIZE; k++) + { + if (ma_dr_mp3_hdr_compare(mp3, mp3 + k)) + { + int fb = k - ma_dr_mp3_hdr_padding(mp3); + int nextfb = fb + ma_dr_mp3_hdr_padding(mp3 + k); + if (i + k + nextfb + MA_DR_MP3_HDR_SIZE > mp3_bytes || !ma_dr_mp3_hdr_compare(mp3, mp3 + k + nextfb)) + continue; + frame_and_padding = k; + frame_bytes = fb; + *free_format_bytes = fb; + } + } + if ((frame_bytes && i + frame_and_padding <= mp3_bytes && + ma_dr_mp3d_match_frame(mp3, mp3_bytes - i, frame_bytes)) || + (!i && frame_and_padding == mp3_bytes)) + { + *ptr_frame_bytes = frame_and_padding; + return i; + } + *free_format_bytes = 0; + } + } + *ptr_frame_bytes = 0; + return mp3_bytes; +} +MA_API void ma_dr_mp3dec_init(ma_dr_mp3dec *dec) +{ + dec->header[0] = 0; +} +MA_API int ma_dr_mp3dec_decode_frame(ma_dr_mp3dec *dec, const ma_uint8 *mp3, int mp3_bytes, void *pcm, ma_dr_mp3dec_frame_info *info) +{ + int i = 0, igr, frame_size = 0, success = 1; + const ma_uint8 *hdr; + ma_dr_mp3_bs bs_frame[1]; + ma_dr_mp3dec_scratch scratch; + if (mp3_bytes > 4 && dec->header[0] == 0xff && ma_dr_mp3_hdr_compare(dec->header, mp3)) + { + frame_size = ma_dr_mp3_hdr_frame_bytes(mp3, dec->free_format_bytes) + ma_dr_mp3_hdr_padding(mp3); + if (frame_size != mp3_bytes && (frame_size + MA_DR_MP3_HDR_SIZE > mp3_bytes || !ma_dr_mp3_hdr_compare(mp3, mp3 + frame_size))) + { + frame_size = 0; + } + } + if (!frame_size) + { + MA_DR_MP3_ZERO_MEMORY(dec, sizeof(ma_dr_mp3dec)); + i = ma_dr_mp3d_find_frame(mp3, mp3_bytes, &dec->free_format_bytes, &frame_size); + if (!frame_size || i + frame_size > mp3_bytes) + { + info->frame_bytes = i; + return 0; + } + } + hdr = mp3 + i; + MA_DR_MP3_COPY_MEMORY(dec->header, hdr, MA_DR_MP3_HDR_SIZE); + info->frame_bytes = i + frame_size; + info->channels = MA_DR_MP3_HDR_IS_MONO(hdr) ? 1 : 2; + info->hz = ma_dr_mp3_hdr_sample_rate_hz(hdr); + info->layer = 4 - MA_DR_MP3_HDR_GET_LAYER(hdr); + info->bitrate_kbps = ma_dr_mp3_hdr_bitrate_kbps(hdr); + ma_dr_mp3_bs_init(bs_frame, hdr + MA_DR_MP3_HDR_SIZE, frame_size - MA_DR_MP3_HDR_SIZE); + if (MA_DR_MP3_HDR_IS_CRC(hdr)) + { + ma_dr_mp3_bs_get_bits(bs_frame, 16); + } + if (info->layer == 3) + { + int main_data_begin = ma_dr_mp3_L3_read_side_info(bs_frame, scratch.gr_info, hdr); + if (main_data_begin < 0 || bs_frame->pos > bs_frame->limit) + { + ma_dr_mp3dec_init(dec); + return 0; + } + success = ma_dr_mp3_L3_restore_reservoir(dec, bs_frame, &scratch, main_data_begin); + if (success && pcm != NULL) + { + for (igr = 0; igr < (MA_DR_MP3_HDR_TEST_MPEG1(hdr) ? 2 : 1); igr++, pcm = MA_DR_MP3_OFFSET_PTR(pcm, sizeof(ma_dr_mp3d_sample_t)*576*info->channels)) + { + MA_DR_MP3_ZERO_MEMORY(scratch.grbuf[0], 576*2*sizeof(float)); + ma_dr_mp3_L3_decode(dec, &scratch, scratch.gr_info + igr*info->channels, info->channels); + ma_dr_mp3d_synth_granule(dec->qmf_state, scratch.grbuf[0], 18, info->channels, (ma_dr_mp3d_sample_t*)pcm, scratch.syn[0]); + } + } + ma_dr_mp3_L3_save_reservoir(dec, &scratch); + } else + { +#ifdef MA_DR_MP3_ONLY_MP3 + return 0; +#else + ma_dr_mp3_L12_scale_info sci[1]; + if (pcm == NULL) { + return ma_dr_mp3_hdr_frame_samples(hdr); + } + ma_dr_mp3_L12_read_scale_info(hdr, bs_frame, sci); + MA_DR_MP3_ZERO_MEMORY(scratch.grbuf[0], 576*2*sizeof(float)); + for (i = 0, igr = 0; igr < 3; igr++) + { + if (12 == (i += ma_dr_mp3_L12_dequantize_granule(scratch.grbuf[0] + i, bs_frame, sci, info->layer | 1))) + { + i = 0; + ma_dr_mp3_L12_apply_scf_384(sci, sci->scf + igr, scratch.grbuf[0]); + ma_dr_mp3d_synth_granule(dec->qmf_state, scratch.grbuf[0], 12, info->channels, (ma_dr_mp3d_sample_t*)pcm, scratch.syn[0]); + MA_DR_MP3_ZERO_MEMORY(scratch.grbuf[0], 576*2*sizeof(float)); + pcm = MA_DR_MP3_OFFSET_PTR(pcm, sizeof(ma_dr_mp3d_sample_t)*384*info->channels); + } + if (bs_frame->pos > bs_frame->limit) + { + ma_dr_mp3dec_init(dec); + return 0; + } + } +#endif + } + return success*ma_dr_mp3_hdr_frame_samples(dec->header); +} +MA_API void ma_dr_mp3dec_f32_to_s16(const float *in, ma_int16 *out, size_t num_samples) +{ + size_t i = 0; +#if MA_DR_MP3_HAVE_SIMD + size_t aligned_count = num_samples & ~7; + for(; i < aligned_count; i+=8) + { + ma_dr_mp3_f4 scale = MA_DR_MP3_VSET(32768.0f); + ma_dr_mp3_f4 a = MA_DR_MP3_VMUL(MA_DR_MP3_VLD(&in[i ]), scale); + ma_dr_mp3_f4 b = MA_DR_MP3_VMUL(MA_DR_MP3_VLD(&in[i+4]), scale); +#if MA_DR_MP3_HAVE_SSE + ma_dr_mp3_f4 s16max = MA_DR_MP3_VSET( 32767.0f); + ma_dr_mp3_f4 s16min = MA_DR_MP3_VSET(-32768.0f); + __m128i pcm8 = _mm_packs_epi32(_mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(a, s16max), s16min)), + _mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(b, s16max), s16min))); + out[i ] = (ma_int16)_mm_extract_epi16(pcm8, 0); + out[i+1] = (ma_int16)_mm_extract_epi16(pcm8, 1); + out[i+2] = (ma_int16)_mm_extract_epi16(pcm8, 2); + out[i+3] = (ma_int16)_mm_extract_epi16(pcm8, 3); + out[i+4] = (ma_int16)_mm_extract_epi16(pcm8, 4); + out[i+5] = (ma_int16)_mm_extract_epi16(pcm8, 5); + out[i+6] = (ma_int16)_mm_extract_epi16(pcm8, 6); + out[i+7] = (ma_int16)_mm_extract_epi16(pcm8, 7); +#else + int16x4_t pcma, pcmb; + a = MA_DR_MP3_VADD(a, MA_DR_MP3_VSET(0.5f)); + b = MA_DR_MP3_VADD(b, MA_DR_MP3_VSET(0.5f)); + pcma = vqmovn_s32(vqaddq_s32(vcvtq_s32_f32(a), vreinterpretq_s32_u32(vcltq_f32(a, MA_DR_MP3_VSET(0))))); + pcmb = vqmovn_s32(vqaddq_s32(vcvtq_s32_f32(b), vreinterpretq_s32_u32(vcltq_f32(b, MA_DR_MP3_VSET(0))))); + vst1_lane_s16(out+i , pcma, 0); + vst1_lane_s16(out+i+1, pcma, 1); + vst1_lane_s16(out+i+2, pcma, 2); + vst1_lane_s16(out+i+3, pcma, 3); + vst1_lane_s16(out+i+4, pcmb, 0); + vst1_lane_s16(out+i+5, pcmb, 1); + vst1_lane_s16(out+i+6, pcmb, 2); + vst1_lane_s16(out+i+7, pcmb, 3); +#endif + } +#endif + for(; i < num_samples; i++) + { + float sample = in[i] * 32768.0f; + if (sample >= 32766.5) + out[i] = (ma_int16) 32767; + else if (sample <= -32767.5) + out[i] = (ma_int16)-32768; + else + { + short s = (ma_int16)(sample + .5f); + s -= (s < 0); + out[i] = s; + } + } +} +#ifndef MA_DR_MP3_SEEK_LEADING_MP3_FRAMES +#define MA_DR_MP3_SEEK_LEADING_MP3_FRAMES 2 +#endif +#define MA_DR_MP3_MIN_DATA_CHUNK_SIZE 16384 +#ifndef MA_DR_MP3_DATA_CHUNK_SIZE +#define MA_DR_MP3_DATA_CHUNK_SIZE (MA_DR_MP3_MIN_DATA_CHUNK_SIZE*4) +#endif +#define MA_DR_MP3_COUNTOF(x) (sizeof(x) / sizeof(x[0])) +#define MA_DR_MP3_CLAMP(x, lo, hi) (MA_DR_MP3_MAX(lo, MA_DR_MP3_MIN(x, hi))) +#ifndef MA_DR_MP3_PI_D +#define MA_DR_MP3_PI_D 3.14159265358979323846264 +#endif +#define MA_DR_MP3_DEFAULT_RESAMPLER_LPF_ORDER 2 +static MA_INLINE float ma_dr_mp3_mix_f32(float x, float y, float a) +{ + return x*(1-a) + y*a; +} +static MA_INLINE float ma_dr_mp3_mix_f32_fast(float x, float y, float a) +{ + float r0 = (y - x); + float r1 = r0*a; + return x + r1; +} +static MA_INLINE ma_uint32 ma_dr_mp3_gcf_u32(ma_uint32 a, ma_uint32 b) +{ + for (;;) { + if (b == 0) { + break; + } else { + ma_uint32 t = a; + a = b; + b = t % a; + } + } + return a; +} +static void* ma_dr_mp3__malloc_default(size_t sz, void* pUserData) +{ + (void)pUserData; + return MA_DR_MP3_MALLOC(sz); +} +static void* ma_dr_mp3__realloc_default(void* p, size_t sz, void* pUserData) +{ + (void)pUserData; + return MA_DR_MP3_REALLOC(p, sz); +} +static void ma_dr_mp3__free_default(void* p, void* pUserData) +{ + (void)pUserData; + MA_DR_MP3_FREE(p); +} +static void* ma_dr_mp3__malloc_from_callbacks(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pAllocationCallbacks == NULL) { + return NULL; + } + if (pAllocationCallbacks->onMalloc != NULL) { + return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData); + } + if (pAllocationCallbacks->onRealloc != NULL) { + return pAllocationCallbacks->onRealloc(NULL, sz, pAllocationCallbacks->pUserData); + } + return NULL; +} +static void* ma_dr_mp3__realloc_from_callbacks(void* p, size_t szNew, size_t szOld, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pAllocationCallbacks == NULL) { + return NULL; + } + if (pAllocationCallbacks->onRealloc != NULL) { + return pAllocationCallbacks->onRealloc(p, szNew, pAllocationCallbacks->pUserData); + } + if (pAllocationCallbacks->onMalloc != NULL && pAllocationCallbacks->onFree != NULL) { + void* p2; + p2 = pAllocationCallbacks->onMalloc(szNew, pAllocationCallbacks->pUserData); + if (p2 == NULL) { + return NULL; + } + if (p != NULL) { + MA_DR_MP3_COPY_MEMORY(p2, p, szOld); + pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData); + } + return p2; + } + return NULL; +} +static void ma_dr_mp3__free_from_callbacks(void* p, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (p == NULL || pAllocationCallbacks == NULL) { + return; + } + if (pAllocationCallbacks->onFree != NULL) { + pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData); + } +} +static ma_allocation_callbacks ma_dr_mp3_copy_allocation_callbacks_or_defaults(const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pAllocationCallbacks != NULL) { + return *pAllocationCallbacks; + } else { + ma_allocation_callbacks allocationCallbacks; + allocationCallbacks.pUserData = NULL; + allocationCallbacks.onMalloc = ma_dr_mp3__malloc_default; + allocationCallbacks.onRealloc = ma_dr_mp3__realloc_default; + allocationCallbacks.onFree = ma_dr_mp3__free_default; + return allocationCallbacks; + } +} +static size_t ma_dr_mp3__on_read(ma_dr_mp3* pMP3, void* pBufferOut, size_t bytesToRead) +{ + size_t bytesRead = pMP3->onRead(pMP3->pUserData, pBufferOut, bytesToRead); + pMP3->streamCursor += bytesRead; + return bytesRead; +} +static ma_bool32 ma_dr_mp3__on_seek(ma_dr_mp3* pMP3, int offset, ma_dr_mp3_seek_origin origin) +{ + MA_DR_MP3_ASSERT(offset >= 0); + if (!pMP3->onSeek(pMP3->pUserData, offset, origin)) { + return MA_FALSE; + } + if (origin == ma_dr_mp3_seek_origin_start) { + pMP3->streamCursor = (ma_uint64)offset; + } else { + pMP3->streamCursor += offset; + } + return MA_TRUE; +} +static ma_bool32 ma_dr_mp3__on_seek_64(ma_dr_mp3* pMP3, ma_uint64 offset, ma_dr_mp3_seek_origin origin) +{ + if (offset <= 0x7FFFFFFF) { + return ma_dr_mp3__on_seek(pMP3, (int)offset, origin); + } + if (!ma_dr_mp3__on_seek(pMP3, 0x7FFFFFFF, ma_dr_mp3_seek_origin_start)) { + return MA_FALSE; + } + offset -= 0x7FFFFFFF; + while (offset > 0) { + if (offset <= 0x7FFFFFFF) { + if (!ma_dr_mp3__on_seek(pMP3, (int)offset, ma_dr_mp3_seek_origin_current)) { + return MA_FALSE; + } + offset = 0; + } else { + if (!ma_dr_mp3__on_seek(pMP3, 0x7FFFFFFF, ma_dr_mp3_seek_origin_current)) { + return MA_FALSE; + } + offset -= 0x7FFFFFFF; + } + } + return MA_TRUE; +} +static ma_uint32 ma_dr_mp3_decode_next_frame_ex__callbacks(ma_dr_mp3* pMP3, ma_dr_mp3d_sample_t* pPCMFrames) +{ + ma_uint32 pcmFramesRead = 0; + MA_DR_MP3_ASSERT(pMP3 != NULL); + MA_DR_MP3_ASSERT(pMP3->onRead != NULL); + if (pMP3->atEnd) { + return 0; + } + for (;;) { + ma_dr_mp3dec_frame_info info; + if (pMP3->dataSize < MA_DR_MP3_MIN_DATA_CHUNK_SIZE) { + size_t bytesRead; + if (pMP3->pData != NULL) { + MA_DR_MP3_MOVE_MEMORY(pMP3->pData, pMP3->pData + pMP3->dataConsumed, pMP3->dataSize); + } + pMP3->dataConsumed = 0; + if (pMP3->dataCapacity < MA_DR_MP3_DATA_CHUNK_SIZE) { + ma_uint8* pNewData; + size_t newDataCap; + newDataCap = MA_DR_MP3_DATA_CHUNK_SIZE; + pNewData = (ma_uint8*)ma_dr_mp3__realloc_from_callbacks(pMP3->pData, newDataCap, pMP3->dataCapacity, &pMP3->allocationCallbacks); + if (pNewData == NULL) { + return 0; + } + pMP3->pData = pNewData; + pMP3->dataCapacity = newDataCap; + } + bytesRead = ma_dr_mp3__on_read(pMP3, pMP3->pData + pMP3->dataSize, (pMP3->dataCapacity - pMP3->dataSize)); + if (bytesRead == 0) { + if (pMP3->dataSize == 0) { + pMP3->atEnd = MA_TRUE; + return 0; + } + } + pMP3->dataSize += bytesRead; + } + if (pMP3->dataSize > INT_MAX) { + pMP3->atEnd = MA_TRUE; + return 0; + } + MA_DR_MP3_ASSERT(pMP3->pData != NULL); + MA_DR_MP3_ASSERT(pMP3->dataCapacity > 0); + if (pMP3->pData == NULL) { + return 0; + } + pcmFramesRead = ma_dr_mp3dec_decode_frame(&pMP3->decoder, pMP3->pData + pMP3->dataConsumed, (int)pMP3->dataSize, pPCMFrames, &info); + if (info.frame_bytes > 0) { + pMP3->dataConsumed += (size_t)info.frame_bytes; + pMP3->dataSize -= (size_t)info.frame_bytes; + } + if (pcmFramesRead > 0) { + pcmFramesRead = ma_dr_mp3_hdr_frame_samples(pMP3->decoder.header); + pMP3->pcmFramesConsumedInMP3Frame = 0; + pMP3->pcmFramesRemainingInMP3Frame = pcmFramesRead; + pMP3->mp3FrameChannels = info.channels; + pMP3->mp3FrameSampleRate = info.hz; + break; + } else if (info.frame_bytes == 0) { + size_t bytesRead; + MA_DR_MP3_MOVE_MEMORY(pMP3->pData, pMP3->pData + pMP3->dataConsumed, pMP3->dataSize); + pMP3->dataConsumed = 0; + if (pMP3->dataCapacity == pMP3->dataSize) { + ma_uint8* pNewData; + size_t newDataCap; + newDataCap = pMP3->dataCapacity + MA_DR_MP3_DATA_CHUNK_SIZE; + pNewData = (ma_uint8*)ma_dr_mp3__realloc_from_callbacks(pMP3->pData, newDataCap, pMP3->dataCapacity, &pMP3->allocationCallbacks); + if (pNewData == NULL) { + return 0; + } + pMP3->pData = pNewData; + pMP3->dataCapacity = newDataCap; + } + bytesRead = ma_dr_mp3__on_read(pMP3, pMP3->pData + pMP3->dataSize, (pMP3->dataCapacity - pMP3->dataSize)); + if (bytesRead == 0) { + pMP3->atEnd = MA_TRUE; + return 0; + } + pMP3->dataSize += bytesRead; + } + }; + return pcmFramesRead; +} +static ma_uint32 ma_dr_mp3_decode_next_frame_ex__memory(ma_dr_mp3* pMP3, ma_dr_mp3d_sample_t* pPCMFrames) +{ + ma_uint32 pcmFramesRead = 0; + ma_dr_mp3dec_frame_info info; + MA_DR_MP3_ASSERT(pMP3 != NULL); + MA_DR_MP3_ASSERT(pMP3->memory.pData != NULL); + if (pMP3->atEnd) { + return 0; + } + for (;;) { + pcmFramesRead = ma_dr_mp3dec_decode_frame(&pMP3->decoder, pMP3->memory.pData + pMP3->memory.currentReadPos, (int)(pMP3->memory.dataSize - pMP3->memory.currentReadPos), pPCMFrames, &info); + if (pcmFramesRead > 0) { + pcmFramesRead = ma_dr_mp3_hdr_frame_samples(pMP3->decoder.header); + pMP3->pcmFramesConsumedInMP3Frame = 0; + pMP3->pcmFramesRemainingInMP3Frame = pcmFramesRead; + pMP3->mp3FrameChannels = info.channels; + pMP3->mp3FrameSampleRate = info.hz; + break; + } else if (info.frame_bytes > 0) { + pMP3->memory.currentReadPos += (size_t)info.frame_bytes; + } else { + break; + } + } + pMP3->memory.currentReadPos += (size_t)info.frame_bytes; + return pcmFramesRead; +} +static ma_uint32 ma_dr_mp3_decode_next_frame_ex(ma_dr_mp3* pMP3, ma_dr_mp3d_sample_t* pPCMFrames) +{ + if (pMP3->memory.pData != NULL && pMP3->memory.dataSize > 0) { + return ma_dr_mp3_decode_next_frame_ex__memory(pMP3, pPCMFrames); + } else { + return ma_dr_mp3_decode_next_frame_ex__callbacks(pMP3, pPCMFrames); + } +} +static ma_uint32 ma_dr_mp3_decode_next_frame(ma_dr_mp3* pMP3) +{ + MA_DR_MP3_ASSERT(pMP3 != NULL); + return ma_dr_mp3_decode_next_frame_ex(pMP3, (ma_dr_mp3d_sample_t*)pMP3->pcmFrames); +} +#if 0 +static ma_uint32 ma_dr_mp3_seek_next_frame(ma_dr_mp3* pMP3) +{ + ma_uint32 pcmFrameCount; + MA_DR_MP3_ASSERT(pMP3 != NULL); + pcmFrameCount = ma_dr_mp3_decode_next_frame_ex(pMP3, NULL); + if (pcmFrameCount == 0) { + return 0; + } + pMP3->currentPCMFrame += pcmFrameCount; + pMP3->pcmFramesConsumedInMP3Frame = pcmFrameCount; + pMP3->pcmFramesRemainingInMP3Frame = 0; + return pcmFrameCount; +} +#endif +static ma_bool32 ma_dr_mp3_init_internal(ma_dr_mp3* pMP3, ma_dr_mp3_read_proc onRead, ma_dr_mp3_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks) +{ + MA_DR_MP3_ASSERT(pMP3 != NULL); + MA_DR_MP3_ASSERT(onRead != NULL); + ma_dr_mp3dec_init(&pMP3->decoder); + pMP3->onRead = onRead; + pMP3->onSeek = onSeek; + pMP3->pUserData = pUserData; + pMP3->allocationCallbacks = ma_dr_mp3_copy_allocation_callbacks_or_defaults(pAllocationCallbacks); + if (pMP3->allocationCallbacks.onFree == NULL || (pMP3->allocationCallbacks.onMalloc == NULL && pMP3->allocationCallbacks.onRealloc == NULL)) { + return MA_FALSE; + } + if (ma_dr_mp3_decode_next_frame(pMP3) == 0) { + ma_dr_mp3__free_from_callbacks(pMP3->pData, &pMP3->allocationCallbacks); + return MA_FALSE; + } + pMP3->channels = pMP3->mp3FrameChannels; + pMP3->sampleRate = pMP3->mp3FrameSampleRate; + return MA_TRUE; +} +MA_API ma_bool32 ma_dr_mp3_init(ma_dr_mp3* pMP3, ma_dr_mp3_read_proc onRead, ma_dr_mp3_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pMP3 == NULL || onRead == NULL) { + return MA_FALSE; + } + MA_DR_MP3_ZERO_OBJECT(pMP3); + return ma_dr_mp3_init_internal(pMP3, onRead, onSeek, pUserData, pAllocationCallbacks); +} +static size_t ma_dr_mp3__on_read_memory(void* pUserData, void* pBufferOut, size_t bytesToRead) +{ + ma_dr_mp3* pMP3 = (ma_dr_mp3*)pUserData; + size_t bytesRemaining; + MA_DR_MP3_ASSERT(pMP3 != NULL); + MA_DR_MP3_ASSERT(pMP3->memory.dataSize >= pMP3->memory.currentReadPos); + bytesRemaining = pMP3->memory.dataSize - pMP3->memory.currentReadPos; + if (bytesToRead > bytesRemaining) { + bytesToRead = bytesRemaining; + } + if (bytesToRead > 0) { + MA_DR_MP3_COPY_MEMORY(pBufferOut, pMP3->memory.pData + pMP3->memory.currentReadPos, bytesToRead); + pMP3->memory.currentReadPos += bytesToRead; + } + return bytesToRead; +} +static ma_bool32 ma_dr_mp3__on_seek_memory(void* pUserData, int byteOffset, ma_dr_mp3_seek_origin origin) +{ + ma_dr_mp3* pMP3 = (ma_dr_mp3*)pUserData; + MA_DR_MP3_ASSERT(pMP3 != NULL); + if (origin == ma_dr_mp3_seek_origin_current) { + if (byteOffset > 0) { + if (pMP3->memory.currentReadPos + byteOffset > pMP3->memory.dataSize) { + byteOffset = (int)(pMP3->memory.dataSize - pMP3->memory.currentReadPos); + } + } else { + if (pMP3->memory.currentReadPos < (size_t)-byteOffset) { + byteOffset = -(int)pMP3->memory.currentReadPos; + } + } + pMP3->memory.currentReadPos += byteOffset; + } else { + if ((ma_uint32)byteOffset <= pMP3->memory.dataSize) { + pMP3->memory.currentReadPos = byteOffset; + } else { + pMP3->memory.currentReadPos = pMP3->memory.dataSize; + } + } + return MA_TRUE; +} +MA_API ma_bool32 ma_dr_mp3_init_memory(ma_dr_mp3* pMP3, const void* pData, size_t dataSize, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pMP3 == NULL) { + return MA_FALSE; + } + MA_DR_MP3_ZERO_OBJECT(pMP3); + if (pData == NULL || dataSize == 0) { + return MA_FALSE; + } + pMP3->memory.pData = (const ma_uint8*)pData; + pMP3->memory.dataSize = dataSize; + pMP3->memory.currentReadPos = 0; + return ma_dr_mp3_init_internal(pMP3, ma_dr_mp3__on_read_memory, ma_dr_mp3__on_seek_memory, pMP3, pAllocationCallbacks); +} +#ifndef MA_DR_MP3_NO_STDIO +#include +#include +static size_t ma_dr_mp3__on_read_stdio(void* pUserData, void* pBufferOut, size_t bytesToRead) +{ + return fread(pBufferOut, 1, bytesToRead, (FILE*)pUserData); +} +static ma_bool32 ma_dr_mp3__on_seek_stdio(void* pUserData, int offset, ma_dr_mp3_seek_origin origin) +{ + return fseek((FILE*)pUserData, offset, (origin == ma_dr_mp3_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0; +} +MA_API ma_bool32 ma_dr_mp3_init_file(ma_dr_mp3* pMP3, const char* pFilePath, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_bool32 result; + FILE* pFile; + if (ma_fopen(&pFile, pFilePath, "rb") != MA_SUCCESS) { + return MA_FALSE; + } + result = ma_dr_mp3_init(pMP3, ma_dr_mp3__on_read_stdio, ma_dr_mp3__on_seek_stdio, (void*)pFile, pAllocationCallbacks); + if (result != MA_TRUE) { + fclose(pFile); + return result; + } + return MA_TRUE; +} +MA_API ma_bool32 ma_dr_mp3_init_file_w(ma_dr_mp3* pMP3, const wchar_t* pFilePath, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_bool32 result; + FILE* pFile; + if (ma_wfopen(&pFile, pFilePath, L"rb", pAllocationCallbacks) != MA_SUCCESS) { + return MA_FALSE; + } + result = ma_dr_mp3_init(pMP3, ma_dr_mp3__on_read_stdio, ma_dr_mp3__on_seek_stdio, (void*)pFile, pAllocationCallbacks); + if (result != MA_TRUE) { + fclose(pFile); + return result; + } + return MA_TRUE; +} +#endif +MA_API void ma_dr_mp3_uninit(ma_dr_mp3* pMP3) +{ + if (pMP3 == NULL) { + return; + } +#ifndef MA_DR_MP3_NO_STDIO + if (pMP3->onRead == ma_dr_mp3__on_read_stdio) { + FILE* pFile = (FILE*)pMP3->pUserData; + if (pFile != NULL) { + fclose(pFile); + pMP3->pUserData = NULL; + } + } +#endif + ma_dr_mp3__free_from_callbacks(pMP3->pData, &pMP3->allocationCallbacks); +} +#if defined(MA_DR_MP3_FLOAT_OUTPUT) +static void ma_dr_mp3_f32_to_s16(ma_int16* dst, const float* src, ma_uint64 sampleCount) +{ + ma_uint64 i; + ma_uint64 i4; + ma_uint64 sampleCount4; + i = 0; + sampleCount4 = sampleCount >> 2; + for (i4 = 0; i4 < sampleCount4; i4 += 1) { + float x0 = src[i+0]; + float x1 = src[i+1]; + float x2 = src[i+2]; + float x3 = src[i+3]; + 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[i+0] = (ma_int16)x0; + dst[i+1] = (ma_int16)x1; + dst[i+2] = (ma_int16)x2; + dst[i+3] = (ma_int16)x3; + i += 4; + } + for (; i < sampleCount; i += 1) { + float x = src[i]; + x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); + x = x * 32767.0f; + dst[i] = (ma_int16)x; + } +} +#endif +#if !defined(MA_DR_MP3_FLOAT_OUTPUT) +static void ma_dr_mp3_s16_to_f32(float* dst, const ma_int16* src, ma_uint64 sampleCount) +{ + ma_uint64 i; + for (i = 0; i < sampleCount; i += 1) { + float x = (float)src[i]; + x = x * 0.000030517578125f; + dst[i] = x; + } +} +#endif +static ma_uint64 ma_dr_mp3_read_pcm_frames_raw(ma_dr_mp3* pMP3, ma_uint64 framesToRead, void* pBufferOut) +{ + ma_uint64 totalFramesRead = 0; + MA_DR_MP3_ASSERT(pMP3 != NULL); + MA_DR_MP3_ASSERT(pMP3->onRead != NULL); + while (framesToRead > 0) { + ma_uint32 framesToConsume = (ma_uint32)MA_DR_MP3_MIN(pMP3->pcmFramesRemainingInMP3Frame, framesToRead); + if (pBufferOut != NULL) { + #if defined(MA_DR_MP3_FLOAT_OUTPUT) + float* pFramesOutF32 = (float*)MA_DR_MP3_OFFSET_PTR(pBufferOut, sizeof(float) * totalFramesRead * pMP3->channels); + float* pFramesInF32 = (float*)MA_DR_MP3_OFFSET_PTR(&pMP3->pcmFrames[0], sizeof(float) * pMP3->pcmFramesConsumedInMP3Frame * pMP3->mp3FrameChannels); + MA_DR_MP3_COPY_MEMORY(pFramesOutF32, pFramesInF32, sizeof(float) * framesToConsume * pMP3->channels); + #else + ma_int16* pFramesOutS16 = (ma_int16*)MA_DR_MP3_OFFSET_PTR(pBufferOut, sizeof(ma_int16) * totalFramesRead * pMP3->channels); + ma_int16* pFramesInS16 = (ma_int16*)MA_DR_MP3_OFFSET_PTR(&pMP3->pcmFrames[0], sizeof(ma_int16) * pMP3->pcmFramesConsumedInMP3Frame * pMP3->mp3FrameChannels); + MA_DR_MP3_COPY_MEMORY(pFramesOutS16, pFramesInS16, sizeof(ma_int16) * framesToConsume * pMP3->channels); + #endif + } + pMP3->currentPCMFrame += framesToConsume; + pMP3->pcmFramesConsumedInMP3Frame += framesToConsume; + pMP3->pcmFramesRemainingInMP3Frame -= framesToConsume; + totalFramesRead += framesToConsume; + framesToRead -= framesToConsume; + if (framesToRead == 0) { + break; + } + MA_DR_MP3_ASSERT(pMP3->pcmFramesRemainingInMP3Frame == 0); + if (ma_dr_mp3_decode_next_frame(pMP3) == 0) { + break; + } + } + return totalFramesRead; +} +MA_API ma_uint64 ma_dr_mp3_read_pcm_frames_f32(ma_dr_mp3* pMP3, ma_uint64 framesToRead, float* pBufferOut) +{ + if (pMP3 == NULL || pMP3->onRead == NULL) { + return 0; + } +#if defined(MA_DR_MP3_FLOAT_OUTPUT) + return ma_dr_mp3_read_pcm_frames_raw(pMP3, framesToRead, pBufferOut); +#else + { + ma_int16 pTempS16[8192]; + ma_uint64 totalPCMFramesRead = 0; + while (totalPCMFramesRead < framesToRead) { + ma_uint64 framesJustRead; + ma_uint64 framesRemaining = framesToRead - totalPCMFramesRead; + ma_uint64 framesToReadNow = MA_DR_MP3_COUNTOF(pTempS16) / pMP3->channels; + if (framesToReadNow > framesRemaining) { + framesToReadNow = framesRemaining; + } + framesJustRead = ma_dr_mp3_read_pcm_frames_raw(pMP3, framesToReadNow, pTempS16); + if (framesJustRead == 0) { + break; + } + ma_dr_mp3_s16_to_f32((float*)MA_DR_MP3_OFFSET_PTR(pBufferOut, sizeof(float) * totalPCMFramesRead * pMP3->channels), pTempS16, framesJustRead * pMP3->channels); + totalPCMFramesRead += framesJustRead; + } + return totalPCMFramesRead; + } +#endif +} +MA_API ma_uint64 ma_dr_mp3_read_pcm_frames_s16(ma_dr_mp3* pMP3, ma_uint64 framesToRead, ma_int16* pBufferOut) +{ + if (pMP3 == NULL || pMP3->onRead == NULL) { + return 0; + } +#if !defined(MA_DR_MP3_FLOAT_OUTPUT) + return ma_dr_mp3_read_pcm_frames_raw(pMP3, framesToRead, pBufferOut); +#else + { + float pTempF32[4096]; + ma_uint64 totalPCMFramesRead = 0; + while (totalPCMFramesRead < framesToRead) { + ma_uint64 framesJustRead; + ma_uint64 framesRemaining = framesToRead - totalPCMFramesRead; + ma_uint64 framesToReadNow = MA_DR_MP3_COUNTOF(pTempF32) / pMP3->channels; + if (framesToReadNow > framesRemaining) { + framesToReadNow = framesRemaining; + } + framesJustRead = ma_dr_mp3_read_pcm_frames_raw(pMP3, framesToReadNow, pTempF32); + if (framesJustRead == 0) { + break; + } + ma_dr_mp3_f32_to_s16((ma_int16*)MA_DR_MP3_OFFSET_PTR(pBufferOut, sizeof(ma_int16) * totalPCMFramesRead * pMP3->channels), pTempF32, framesJustRead * pMP3->channels); + totalPCMFramesRead += framesJustRead; + } + return totalPCMFramesRead; + } +#endif +} +static void ma_dr_mp3_reset(ma_dr_mp3* pMP3) +{ + MA_DR_MP3_ASSERT(pMP3 != NULL); + pMP3->pcmFramesConsumedInMP3Frame = 0; + pMP3->pcmFramesRemainingInMP3Frame = 0; + pMP3->currentPCMFrame = 0; + pMP3->dataSize = 0; + pMP3->atEnd = MA_FALSE; + ma_dr_mp3dec_init(&pMP3->decoder); +} +static ma_bool32 ma_dr_mp3_seek_to_start_of_stream(ma_dr_mp3* pMP3) +{ + MA_DR_MP3_ASSERT(pMP3 != NULL); + MA_DR_MP3_ASSERT(pMP3->onSeek != NULL); + if (!ma_dr_mp3__on_seek(pMP3, 0, ma_dr_mp3_seek_origin_start)) { + return MA_FALSE; + } + ma_dr_mp3_reset(pMP3); + return MA_TRUE; +} +static ma_bool32 ma_dr_mp3_seek_forward_by_pcm_frames__brute_force(ma_dr_mp3* pMP3, ma_uint64 frameOffset) +{ + ma_uint64 framesRead; +#if defined(MA_DR_MP3_FLOAT_OUTPUT) + framesRead = ma_dr_mp3_read_pcm_frames_f32(pMP3, frameOffset, NULL); +#else + framesRead = ma_dr_mp3_read_pcm_frames_s16(pMP3, frameOffset, NULL); +#endif + if (framesRead != frameOffset) { + return MA_FALSE; + } + return MA_TRUE; +} +static ma_bool32 ma_dr_mp3_seek_to_pcm_frame__brute_force(ma_dr_mp3* pMP3, ma_uint64 frameIndex) +{ + MA_DR_MP3_ASSERT(pMP3 != NULL); + if (frameIndex == pMP3->currentPCMFrame) { + return MA_TRUE; + } + if (frameIndex < pMP3->currentPCMFrame) { + if (!ma_dr_mp3_seek_to_start_of_stream(pMP3)) { + return MA_FALSE; + } + } + MA_DR_MP3_ASSERT(frameIndex >= pMP3->currentPCMFrame); + return ma_dr_mp3_seek_forward_by_pcm_frames__brute_force(pMP3, (frameIndex - pMP3->currentPCMFrame)); +} +static ma_bool32 ma_dr_mp3_find_closest_seek_point(ma_dr_mp3* pMP3, ma_uint64 frameIndex, ma_uint32* pSeekPointIndex) +{ + ma_uint32 iSeekPoint; + MA_DR_MP3_ASSERT(pSeekPointIndex != NULL); + *pSeekPointIndex = 0; + if (frameIndex < pMP3->pSeekPoints[0].pcmFrameIndex) { + return MA_FALSE; + } + for (iSeekPoint = 0; iSeekPoint < pMP3->seekPointCount; ++iSeekPoint) { + if (pMP3->pSeekPoints[iSeekPoint].pcmFrameIndex > frameIndex) { + break; + } + *pSeekPointIndex = iSeekPoint; + } + return MA_TRUE; +} +static ma_bool32 ma_dr_mp3_seek_to_pcm_frame__seek_table(ma_dr_mp3* pMP3, ma_uint64 frameIndex) +{ + ma_dr_mp3_seek_point seekPoint; + ma_uint32 priorSeekPointIndex; + ma_uint16 iMP3Frame; + ma_uint64 leftoverFrames; + MA_DR_MP3_ASSERT(pMP3 != NULL); + MA_DR_MP3_ASSERT(pMP3->pSeekPoints != NULL); + MA_DR_MP3_ASSERT(pMP3->seekPointCount > 0); + if (ma_dr_mp3_find_closest_seek_point(pMP3, frameIndex, &priorSeekPointIndex)) { + seekPoint = pMP3->pSeekPoints[priorSeekPointIndex]; + } else { + seekPoint.seekPosInBytes = 0; + seekPoint.pcmFrameIndex = 0; + seekPoint.mp3FramesToDiscard = 0; + seekPoint.pcmFramesToDiscard = 0; + } + if (!ma_dr_mp3__on_seek_64(pMP3, seekPoint.seekPosInBytes, ma_dr_mp3_seek_origin_start)) { + return MA_FALSE; + } + ma_dr_mp3_reset(pMP3); + for (iMP3Frame = 0; iMP3Frame < seekPoint.mp3FramesToDiscard; ++iMP3Frame) { + ma_uint32 pcmFramesRead; + ma_dr_mp3d_sample_t* pPCMFrames; + pPCMFrames = NULL; + if (iMP3Frame == seekPoint.mp3FramesToDiscard-1) { + pPCMFrames = (ma_dr_mp3d_sample_t*)pMP3->pcmFrames; + } + pcmFramesRead = ma_dr_mp3_decode_next_frame_ex(pMP3, pPCMFrames); + if (pcmFramesRead == 0) { + return MA_FALSE; + } + } + pMP3->currentPCMFrame = seekPoint.pcmFrameIndex - seekPoint.pcmFramesToDiscard; + leftoverFrames = frameIndex - pMP3->currentPCMFrame; + return ma_dr_mp3_seek_forward_by_pcm_frames__brute_force(pMP3, leftoverFrames); +} +MA_API ma_bool32 ma_dr_mp3_seek_to_pcm_frame(ma_dr_mp3* pMP3, ma_uint64 frameIndex) +{ + if (pMP3 == NULL || pMP3->onSeek == NULL) { + return MA_FALSE; + } + if (frameIndex == 0) { + return ma_dr_mp3_seek_to_start_of_stream(pMP3); + } + if (pMP3->pSeekPoints != NULL && pMP3->seekPointCount > 0) { + return ma_dr_mp3_seek_to_pcm_frame__seek_table(pMP3, frameIndex); + } else { + return ma_dr_mp3_seek_to_pcm_frame__brute_force(pMP3, frameIndex); + } +} +MA_API ma_bool32 ma_dr_mp3_get_mp3_and_pcm_frame_count(ma_dr_mp3* pMP3, ma_uint64* pMP3FrameCount, ma_uint64* pPCMFrameCount) +{ + ma_uint64 currentPCMFrame; + ma_uint64 totalPCMFrameCount; + ma_uint64 totalMP3FrameCount; + if (pMP3 == NULL) { + return MA_FALSE; + } + if (pMP3->onSeek == NULL) { + return MA_FALSE; + } + currentPCMFrame = pMP3->currentPCMFrame; + if (!ma_dr_mp3_seek_to_start_of_stream(pMP3)) { + return MA_FALSE; + } + totalPCMFrameCount = 0; + totalMP3FrameCount = 0; + for (;;) { + ma_uint32 pcmFramesInCurrentMP3Frame; + pcmFramesInCurrentMP3Frame = ma_dr_mp3_decode_next_frame_ex(pMP3, NULL); + if (pcmFramesInCurrentMP3Frame == 0) { + break; + } + totalPCMFrameCount += pcmFramesInCurrentMP3Frame; + totalMP3FrameCount += 1; + } + if (!ma_dr_mp3_seek_to_start_of_stream(pMP3)) { + return MA_FALSE; + } + if (!ma_dr_mp3_seek_to_pcm_frame(pMP3, currentPCMFrame)) { + return MA_FALSE; + } + if (pMP3FrameCount != NULL) { + *pMP3FrameCount = totalMP3FrameCount; + } + if (pPCMFrameCount != NULL) { + *pPCMFrameCount = totalPCMFrameCount; + } + return MA_TRUE; +} +MA_API ma_uint64 ma_dr_mp3_get_pcm_frame_count(ma_dr_mp3* pMP3) +{ + ma_uint64 totalPCMFrameCount; + if (!ma_dr_mp3_get_mp3_and_pcm_frame_count(pMP3, NULL, &totalPCMFrameCount)) { + return 0; + } + return totalPCMFrameCount; +} +MA_API ma_uint64 ma_dr_mp3_get_mp3_frame_count(ma_dr_mp3* pMP3) +{ + ma_uint64 totalMP3FrameCount; + if (!ma_dr_mp3_get_mp3_and_pcm_frame_count(pMP3, &totalMP3FrameCount, NULL)) { + return 0; + } + return totalMP3FrameCount; +} +static void ma_dr_mp3__accumulate_running_pcm_frame_count(ma_dr_mp3* pMP3, ma_uint32 pcmFrameCountIn, ma_uint64* pRunningPCMFrameCount, float* pRunningPCMFrameCountFractionalPart) +{ + float srcRatio; + float pcmFrameCountOutF; + ma_uint32 pcmFrameCountOut; + srcRatio = (float)pMP3->mp3FrameSampleRate / (float)pMP3->sampleRate; + MA_DR_MP3_ASSERT(srcRatio > 0); + pcmFrameCountOutF = *pRunningPCMFrameCountFractionalPart + (pcmFrameCountIn / srcRatio); + pcmFrameCountOut = (ma_uint32)pcmFrameCountOutF; + *pRunningPCMFrameCountFractionalPart = pcmFrameCountOutF - pcmFrameCountOut; + *pRunningPCMFrameCount += pcmFrameCountOut; +} +typedef struct +{ + ma_uint64 bytePos; + ma_uint64 pcmFrameIndex; +} ma_dr_mp3__seeking_mp3_frame_info; +MA_API ma_bool32 ma_dr_mp3_calculate_seek_points(ma_dr_mp3* pMP3, ma_uint32* pSeekPointCount, ma_dr_mp3_seek_point* pSeekPoints) +{ + ma_uint32 seekPointCount; + ma_uint64 currentPCMFrame; + ma_uint64 totalMP3FrameCount; + ma_uint64 totalPCMFrameCount; + if (pMP3 == NULL || pSeekPointCount == NULL || pSeekPoints == NULL) { + return MA_FALSE; + } + seekPointCount = *pSeekPointCount; + if (seekPointCount == 0) { + return MA_FALSE; + } + currentPCMFrame = pMP3->currentPCMFrame; + if (!ma_dr_mp3_get_mp3_and_pcm_frame_count(pMP3, &totalMP3FrameCount, &totalPCMFrameCount)) { + return MA_FALSE; + } + if (totalMP3FrameCount < MA_DR_MP3_SEEK_LEADING_MP3_FRAMES+1) { + seekPointCount = 1; + pSeekPoints[0].seekPosInBytes = 0; + pSeekPoints[0].pcmFrameIndex = 0; + pSeekPoints[0].mp3FramesToDiscard = 0; + pSeekPoints[0].pcmFramesToDiscard = 0; + } else { + ma_uint64 pcmFramesBetweenSeekPoints; + ma_dr_mp3__seeking_mp3_frame_info mp3FrameInfo[MA_DR_MP3_SEEK_LEADING_MP3_FRAMES+1]; + ma_uint64 runningPCMFrameCount = 0; + float runningPCMFrameCountFractionalPart = 0; + ma_uint64 nextTargetPCMFrame; + ma_uint32 iMP3Frame; + ma_uint32 iSeekPoint; + if (seekPointCount > totalMP3FrameCount-1) { + seekPointCount = (ma_uint32)totalMP3FrameCount-1; + } + pcmFramesBetweenSeekPoints = totalPCMFrameCount / (seekPointCount+1); + if (!ma_dr_mp3_seek_to_start_of_stream(pMP3)) { + return MA_FALSE; + } + for (iMP3Frame = 0; iMP3Frame < MA_DR_MP3_SEEK_LEADING_MP3_FRAMES+1; ++iMP3Frame) { + ma_uint32 pcmFramesInCurrentMP3FrameIn; + MA_DR_MP3_ASSERT(pMP3->streamCursor >= pMP3->dataSize); + mp3FrameInfo[iMP3Frame].bytePos = pMP3->streamCursor - pMP3->dataSize; + mp3FrameInfo[iMP3Frame].pcmFrameIndex = runningPCMFrameCount; + pcmFramesInCurrentMP3FrameIn = ma_dr_mp3_decode_next_frame_ex(pMP3, NULL); + if (pcmFramesInCurrentMP3FrameIn == 0) { + return MA_FALSE; + } + ma_dr_mp3__accumulate_running_pcm_frame_count(pMP3, pcmFramesInCurrentMP3FrameIn, &runningPCMFrameCount, &runningPCMFrameCountFractionalPart); + } + nextTargetPCMFrame = 0; + for (iSeekPoint = 0; iSeekPoint < seekPointCount; ++iSeekPoint) { + nextTargetPCMFrame += pcmFramesBetweenSeekPoints; + for (;;) { + if (nextTargetPCMFrame < runningPCMFrameCount) { + pSeekPoints[iSeekPoint].seekPosInBytes = mp3FrameInfo[0].bytePos; + pSeekPoints[iSeekPoint].pcmFrameIndex = nextTargetPCMFrame; + pSeekPoints[iSeekPoint].mp3FramesToDiscard = MA_DR_MP3_SEEK_LEADING_MP3_FRAMES; + pSeekPoints[iSeekPoint].pcmFramesToDiscard = (ma_uint16)(nextTargetPCMFrame - mp3FrameInfo[MA_DR_MP3_SEEK_LEADING_MP3_FRAMES-1].pcmFrameIndex); + break; + } else { + size_t i; + ma_uint32 pcmFramesInCurrentMP3FrameIn; + for (i = 0; i < MA_DR_MP3_COUNTOF(mp3FrameInfo)-1; ++i) { + mp3FrameInfo[i] = mp3FrameInfo[i+1]; + } + mp3FrameInfo[MA_DR_MP3_COUNTOF(mp3FrameInfo)-1].bytePos = pMP3->streamCursor - pMP3->dataSize; + mp3FrameInfo[MA_DR_MP3_COUNTOF(mp3FrameInfo)-1].pcmFrameIndex = runningPCMFrameCount; + pcmFramesInCurrentMP3FrameIn = ma_dr_mp3_decode_next_frame_ex(pMP3, NULL); + if (pcmFramesInCurrentMP3FrameIn == 0) { + pSeekPoints[iSeekPoint].seekPosInBytes = mp3FrameInfo[0].bytePos; + pSeekPoints[iSeekPoint].pcmFrameIndex = nextTargetPCMFrame; + pSeekPoints[iSeekPoint].mp3FramesToDiscard = MA_DR_MP3_SEEK_LEADING_MP3_FRAMES; + pSeekPoints[iSeekPoint].pcmFramesToDiscard = (ma_uint16)(nextTargetPCMFrame - mp3FrameInfo[MA_DR_MP3_SEEK_LEADING_MP3_FRAMES-1].pcmFrameIndex); + break; + } + ma_dr_mp3__accumulate_running_pcm_frame_count(pMP3, pcmFramesInCurrentMP3FrameIn, &runningPCMFrameCount, &runningPCMFrameCountFractionalPart); + } + } + } + if (!ma_dr_mp3_seek_to_start_of_stream(pMP3)) { + return MA_FALSE; + } + if (!ma_dr_mp3_seek_to_pcm_frame(pMP3, currentPCMFrame)) { + return MA_FALSE; + } + } + *pSeekPointCount = seekPointCount; + return MA_TRUE; +} +MA_API ma_bool32 ma_dr_mp3_bind_seek_table(ma_dr_mp3* pMP3, ma_uint32 seekPointCount, ma_dr_mp3_seek_point* pSeekPoints) +{ + if (pMP3 == NULL) { + return MA_FALSE; + } + if (seekPointCount == 0 || pSeekPoints == NULL) { + pMP3->seekPointCount = 0; + pMP3->pSeekPoints = NULL; + } else { + pMP3->seekPointCount = seekPointCount; + pMP3->pSeekPoints = pSeekPoints; + } + return MA_TRUE; +} +static float* ma_dr_mp3__full_read_and_close_f32(ma_dr_mp3* pMP3, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount) +{ + ma_uint64 totalFramesRead = 0; + ma_uint64 framesCapacity = 0; + float* pFrames = NULL; + float temp[4096]; + MA_DR_MP3_ASSERT(pMP3 != NULL); + for (;;) { + ma_uint64 framesToReadRightNow = MA_DR_MP3_COUNTOF(temp) / pMP3->channels; + ma_uint64 framesJustRead = ma_dr_mp3_read_pcm_frames_f32(pMP3, framesToReadRightNow, temp); + if (framesJustRead == 0) { + break; + } + if (framesCapacity < totalFramesRead + framesJustRead) { + ma_uint64 oldFramesBufferSize; + ma_uint64 newFramesBufferSize; + ma_uint64 newFramesCap; + float* pNewFrames; + newFramesCap = framesCapacity * 2; + if (newFramesCap < totalFramesRead + framesJustRead) { + newFramesCap = totalFramesRead + framesJustRead; + } + oldFramesBufferSize = framesCapacity * pMP3->channels * sizeof(float); + newFramesBufferSize = newFramesCap * pMP3->channels * sizeof(float); + if (newFramesBufferSize > (ma_uint64)MA_SIZE_MAX) { + break; + } + pNewFrames = (float*)ma_dr_mp3__realloc_from_callbacks(pFrames, (size_t)newFramesBufferSize, (size_t)oldFramesBufferSize, &pMP3->allocationCallbacks); + if (pNewFrames == NULL) { + ma_dr_mp3__free_from_callbacks(pFrames, &pMP3->allocationCallbacks); + break; + } + pFrames = pNewFrames; + framesCapacity = newFramesCap; + } + MA_DR_MP3_COPY_MEMORY(pFrames + totalFramesRead*pMP3->channels, temp, (size_t)(framesJustRead*pMP3->channels*sizeof(float))); + totalFramesRead += framesJustRead; + if (framesJustRead != framesToReadRightNow) { + break; + } + } + if (pConfig != NULL) { + pConfig->channels = pMP3->channels; + pConfig->sampleRate = pMP3->sampleRate; + } + ma_dr_mp3_uninit(pMP3); + if (pTotalFrameCount) { + *pTotalFrameCount = totalFramesRead; + } + return pFrames; +} +static ma_int16* ma_dr_mp3__full_read_and_close_s16(ma_dr_mp3* pMP3, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount) +{ + ma_uint64 totalFramesRead = 0; + ma_uint64 framesCapacity = 0; + ma_int16* pFrames = NULL; + ma_int16 temp[4096]; + MA_DR_MP3_ASSERT(pMP3 != NULL); + for (;;) { + ma_uint64 framesToReadRightNow = MA_DR_MP3_COUNTOF(temp) / pMP3->channels; + ma_uint64 framesJustRead = ma_dr_mp3_read_pcm_frames_s16(pMP3, framesToReadRightNow, temp); + if (framesJustRead == 0) { + break; + } + if (framesCapacity < totalFramesRead + framesJustRead) { + ma_uint64 newFramesBufferSize; + ma_uint64 oldFramesBufferSize; + ma_uint64 newFramesCap; + ma_int16* pNewFrames; + newFramesCap = framesCapacity * 2; + if (newFramesCap < totalFramesRead + framesJustRead) { + newFramesCap = totalFramesRead + framesJustRead; + } + oldFramesBufferSize = framesCapacity * pMP3->channels * sizeof(ma_int16); + newFramesBufferSize = newFramesCap * pMP3->channels * sizeof(ma_int16); + if (newFramesBufferSize > (ma_uint64)MA_SIZE_MAX) { + break; + } + pNewFrames = (ma_int16*)ma_dr_mp3__realloc_from_callbacks(pFrames, (size_t)newFramesBufferSize, (size_t)oldFramesBufferSize, &pMP3->allocationCallbacks); + if (pNewFrames == NULL) { + ma_dr_mp3__free_from_callbacks(pFrames, &pMP3->allocationCallbacks); + break; + } + pFrames = pNewFrames; + framesCapacity = newFramesCap; + } + MA_DR_MP3_COPY_MEMORY(pFrames + totalFramesRead*pMP3->channels, temp, (size_t)(framesJustRead*pMP3->channels*sizeof(ma_int16))); + totalFramesRead += framesJustRead; + if (framesJustRead != framesToReadRightNow) { + break; + } + } + if (pConfig != NULL) { + pConfig->channels = pMP3->channels; + pConfig->sampleRate = pMP3->sampleRate; + } + ma_dr_mp3_uninit(pMP3); + if (pTotalFrameCount) { + *pTotalFrameCount = totalFramesRead; + } + return pFrames; +} +MA_API float* ma_dr_mp3_open_and_read_pcm_frames_f32(ma_dr_mp3_read_proc onRead, ma_dr_mp3_seek_proc onSeek, void* pUserData, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_mp3 mp3; + if (!ma_dr_mp3_init(&mp3, onRead, onSeek, pUserData, pAllocationCallbacks)) { + return NULL; + } + return ma_dr_mp3__full_read_and_close_f32(&mp3, pConfig, pTotalFrameCount); +} +MA_API ma_int16* ma_dr_mp3_open_and_read_pcm_frames_s16(ma_dr_mp3_read_proc onRead, ma_dr_mp3_seek_proc onSeek, void* pUserData, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_mp3 mp3; + if (!ma_dr_mp3_init(&mp3, onRead, onSeek, pUserData, pAllocationCallbacks)) { + return NULL; + } + return ma_dr_mp3__full_read_and_close_s16(&mp3, pConfig, pTotalFrameCount); +} +MA_API float* ma_dr_mp3_open_memory_and_read_pcm_frames_f32(const void* pData, size_t dataSize, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_mp3 mp3; + if (!ma_dr_mp3_init_memory(&mp3, pData, dataSize, pAllocationCallbacks)) { + return NULL; + } + return ma_dr_mp3__full_read_and_close_f32(&mp3, pConfig, pTotalFrameCount); +} +MA_API ma_int16* ma_dr_mp3_open_memory_and_read_pcm_frames_s16(const void* pData, size_t dataSize, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_mp3 mp3; + if (!ma_dr_mp3_init_memory(&mp3, pData, dataSize, pAllocationCallbacks)) { + return NULL; + } + return ma_dr_mp3__full_read_and_close_s16(&mp3, pConfig, pTotalFrameCount); +} +#ifndef MA_DR_MP3_NO_STDIO +MA_API float* ma_dr_mp3_open_file_and_read_pcm_frames_f32(const char* filePath, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_mp3 mp3; + if (!ma_dr_mp3_init_file(&mp3, filePath, pAllocationCallbacks)) { + return NULL; + } + return ma_dr_mp3__full_read_and_close_f32(&mp3, pConfig, pTotalFrameCount); +} +MA_API ma_int16* ma_dr_mp3_open_file_and_read_pcm_frames_s16(const char* filePath, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks) +{ + ma_dr_mp3 mp3; + if (!ma_dr_mp3_init_file(&mp3, filePath, pAllocationCallbacks)) { + return NULL; + } + return ma_dr_mp3__full_read_and_close_s16(&mp3, pConfig, pTotalFrameCount); +} +#endif +MA_API void* ma_dr_mp3_malloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pAllocationCallbacks != NULL) { + return ma_dr_mp3__malloc_from_callbacks(sz, pAllocationCallbacks); + } else { + return ma_dr_mp3__malloc_default(sz, NULL); + } +} +MA_API void ma_dr_mp3_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks) +{ + if (pAllocationCallbacks != NULL) { + ma_dr_mp3__free_from_callbacks(p, pAllocationCallbacks); + } else { + ma_dr_mp3__free_default(p, NULL); + } +} +#endif +/* dr_mp3_c end */ +#endif /* MA_DR_MP3_IMPLEMENTATION */ +#endif /* MA_NO_MP3 */ + + +/* End globally disabled warnings. */ +#if defined(_MSC_VER) + #pragma warning(pop) +#endif + +#endif /* miniaudio_c */ +#endif /* MINIAUDIO_IMPLEMENTATION */ + + +/* +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 2023 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/vendor/github.com/go-text/typesetting/LICENSE b/vendor/github.com/go-text/typesetting/LICENSE new file mode 100644 index 0000000..789e7cd --- /dev/null +++ b/vendor/github.com/go-text/typesetting/LICENSE @@ -0,0 +1,55 @@ +This project is provided under the terms of the UNLICENSE or +the BSD license denoted by the following SPDX identifier: + +SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +You may use the project under the terms of either license. + +Both licenses are reproduced below. + +---- +The BSD 3 Clause License + +Copyright 2021 The go-text authors + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. 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. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. +--- + + + +--- +The UNLICENSE + +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/vendor/github.com/go-text/typesetting/di/README.md b/vendor/github.com/go-text/typesetting/di/README.md new file mode 100644 index 0000000..f25a5db --- /dev/null +++ b/vendor/github.com/go-text/typesetting/di/README.md @@ -0,0 +1,3 @@ +# di + +di is a library that converts bi-directional text into uni-directional text diff --git a/vendor/github.com/go-text/typesetting/di/direction.go b/vendor/github.com/go-text/typesetting/di/direction.go new file mode 100644 index 0000000..0a0fca4 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/di/direction.go @@ -0,0 +1,130 @@ +package di + +import ( + "github.com/go-text/typesetting/harfbuzz" +) + +// Direction indicates the layout direction of a piece of text. +type Direction uint8 + +const ( + // DirectionLTR is for Left-to-Right text. + DirectionLTR Direction = iota + // DirectionRTL is for Right-to-Left text. + DirectionRTL + // DirectionTTB is for Top-to-Bottom text. + DirectionTTB + // DirectionBTT is for Bottom-to-Top text. + DirectionBTT +) + +const ( + progression Direction = 1 << iota + // axisVertical is the bit for the axis, 0 for horizontal, 1 for vertical + axisVertical + + // If this flag is set, the orientation is chosen + // using the [verticalSideways] flag. + // Otherwise, the segmenter will resolve the orientation based + // on unicode properties + verticalOrientationSet + // verticalSideways is set for 'sideways', unset for 'upright' + // It implies BVerticalOrientationSet is set + verticalSideways +) + +// IsVertical returns whether d is laid out on a vertical +// axis. If the return value is false, d is on the horizontal +// axis. +func (d Direction) IsVertical() bool { return d&axisVertical != 0 } + +// Axis returns the layout axis for d. +func (d Direction) Axis() Axis { + if d.IsVertical() { + return Vertical + } + return Horizontal +} + +// SwitchAxis switches from horizontal to vertical (and vice versa), preserving +// the progression. +func (d Direction) SwitchAxis() Direction { return d ^ axisVertical } + +// Progression returns the text layout progression for d. +func (d Direction) Progression() Progression { + if d&progression == 0 { + return FromTopLeft + } + return TowardTopLeft +} + +// SetProgression sets the progression, preserving the others bits. +func (d *Direction) SetProgression(p Progression) { + if p == FromTopLeft { + *d &= ^progression + } else { + *d |= progression + } +} + +// Axis indicates the axis of layout for a piece of text. +type Axis bool + +const ( + Horizontal Axis = false + Vertical Axis = true +) + +// Progression indicates how text is read within its Axis relative +// to the top left corner. +type Progression bool + +const ( + // FromTopLeft indicates text in which a reader starts reading + // at the top left corner of the text and moves away from it. + // DirectionLTR and DirectionTTB are examples of FromTopLeft + // Progression. + FromTopLeft Progression = false + // TowardTopLeft indicates text in which a reader starts reading + // at the opposite end of the text's Axis from the top left corner + // and moves towards it. DirectionRTL and DirectionBTT are examples + // of TowardTopLeft progression. + TowardTopLeft Progression = true +) + +// HasVerticalOrientation returns true if the direction has set up +// an orientation for vertical text (typically using [SetSideways] or [SetUpright]) +func (d Direction) HasVerticalOrientation() bool { return d&verticalOrientationSet != 0 } + +// IsSideways returns true if the direction is vertical with a 'sideways' +// orientation. +// +// When shaping vertical text, 'sideways' means that the glyphs are rotated +// by 90°, clock-wise. This flag should be used by renderers to properly +// rotate the glyphs when drawing. +func (d Direction) IsSideways() bool { return d.IsVertical() && d&verticalSideways != 0 } + +// SetSideways makes d vertical with 'sideways' or 'upright' orientation, preserving only the +// progression. +func (d *Direction) SetSideways(sideways bool) { + *d |= axisVertical | verticalOrientationSet + if sideways { + *d |= verticalSideways + } else { + *d &= ^verticalSideways + } +} + +// Harfbuzz returns the equivalent direction used by harfbuzz. +func (d Direction) Harfbuzz() harfbuzz.Direction { + switch d & (progression | axisVertical) { + case DirectionRTL: + return harfbuzz.RightToLeft + case DirectionBTT: + return harfbuzz.BottomToTop + case DirectionTTB: + return harfbuzz.TopToBottom + default: + return harfbuzz.LeftToRight + } +} diff --git a/vendor/github.com/go-text/typesetting/font/README.md b/vendor/github.com/go-text/typesetting/font/README.md new file mode 100644 index 0000000..aad132a --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/README.md @@ -0,0 +1,6 @@ +# font + +font is a library that handles loading and utilizing Opentype fonts. + +`font/opentype` implements the low level parsing of a font file and its tables, +and `font` provides an higher level API usable by shapers and renderers. diff --git a/vendor/github.com/go-text/typesetting/font/aat_layout_kern_kerx.go b/vendor/github.com/go-text/typesetting/font/aat_layout_kern_kerx.go new file mode 100644 index 0000000..fca912f --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/aat_layout_kern_kerx.go @@ -0,0 +1,322 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package font + +import ( + "encoding/binary" + + "github.com/go-text/typesetting/font/opentype/tables" +) + +// Kernx represents a 'kern' or 'kerx' kerning table. +// It supports both Microsoft and Apple formats. +type Kernx []KernSubtable + +func newKernxFromKerx(kerx tables.Kerx) Kernx { + if len(kerx.Tables) == 0 { + return nil + } + out := make(Kernx, len(kerx.Tables)) + for i, ta := range kerx.Tables { + out[i] = newKerxSubtable(ta) + } + return out +} + +func newKernxFromKern(kern tables.Kern) Kernx { + if len(kern.Tables) == 0 { + return nil + } + out := make(Kernx, len(kern.Tables)) + for i, ta := range kern.Tables { + out[i] = newKernSubtable(ta) + } + return out +} + +// KernSubtable represents a 'kern' or 'kerx' subtable. +type KernSubtable struct { + Data interface{ isKernSubtable() } + + // high bit of the Coverage field, following 'kerx' conventions + coverage byte + + // IsExtended [true] for AAT `kerx` subtables, false for 'kern' subtables + IsExtended bool + + // 0 for scalar values + TupleCount int +} + +func newKernSubtable(table tables.KernSubtable) (out KernSubtable) { + out.IsExtended = false + switch table := table.(type) { + case tables.OTKernSubtableHeader: + // synthesize a coverage flag following kerx conventions + const ( + Horizontal = 0x01 + CrossStream = 0x04 + ) + if table.Coverage&Horizontal == 0 { // vertical + out.coverage |= kerxVertical + } + if table.Coverage&CrossStream != 0 { + out.coverage |= kerxCrossStream + } + case tables.AATKernSubtableHeader: + out.coverage = table.Coverage + out.TupleCount = int(table.TupleCount) + } + switch data := table.Data().(type) { + case tables.KernData0: + out.Data = newKern0(data) + case tables.KernData1: + out.Data = newKern1(data) + case tables.KernData2: + out.Data = newKern2(data) + case tables.KernData3: + out.Data = Kern3(data) + } + return out +} + +func newKerxSubtable(table tables.KerxSubtable) (out KernSubtable) { + out.IsExtended = true + out.TupleCount = int(table.TupleCount) + out.coverage = byte(table.Coverage >> 8) // high bit only + + switch data := table.Data.(type) { + case tables.KerxData0: + out.Data = newKern0x(data) + case tables.KerxData1: + out.Data = newKern1x(data) + case tables.KerxData2: + out.Data = Kern2(data) + case tables.KerxData4: + out.Data = newKern4(data) + case tables.KerxData6: + out.Data = Kern6(data) + } + return out +} + +func (Kern0) isKernSubtable() {} +func (Kern1) isKernSubtable() {} +func (Kern2) isKernSubtable() {} +func (Kern3) isKernSubtable() {} +func (Kern4) isKernSubtable() {} +func (Kern6) isKernSubtable() {} + +var ( + _ SimpleKerns = Kern0(nil) + _ SimpleKerns = (*Kern2)(nil) + _ SimpleKerns = (*Kern3)(nil) + _ SimpleKerns = (*Kern6)(nil) +) + +// SimpleKerns store a compact form of the kerning values, +// which is restricted to (one direction) kerning pairs. +// It is only implemented by [Kern0], [Kern2], [Kern3] and [Kern6], +// where [Kern1] and [Kern4] requires a state machine to be interpreted. +type SimpleKerns interface { + // KernPair return the kern value for the given pair, or zero. + // The value is expressed in glyph units and + // is negative when glyphs should be closer. + KernPair(left, right GID) int16 +} + +// kernx coverage flags +const ( + kerxBackwards = 1 << (12 - 8) + kerxVariation = 1 << (13 - 8) + kerxCrossStream = 1 << (14 - 8) + kerxVertical = 1 << (15 - 8) +) + +// IsHorizontal returns true if the subtable has horizontal kerning values. +func (k KernSubtable) IsHorizontal() bool { return k.coverage&kerxVertical == 0 } + +// IsBackwards returns true if state-table based should process the glyphs backwards. +func (k KernSubtable) IsBackwards() bool { return k.coverage&kerxBackwards != 0 } + +// IsCrossStream returns true if the subtable has cross-stream kerning values. +func (k KernSubtable) IsCrossStream() bool { return k.coverage&kerxCrossStream != 0 } + +// IsVariation returns true if the subtable has variation kerning values. +func (k KernSubtable) IsVariation() bool { return k.coverage&kerxVariation != 0 } + +type Kern0 []tables.Kernx0Record + +func newKern0(k tables.KernData0) Kern0 { return k.Pairs } +func newKern0x(k tables.KerxData0) Kern0 { return k.Pairs } + +func kernPair(records []tables.Kernx0Record, left, right GID) int16 { + key := uint32(left)<<16 | uint32(right) + low, high := 0, len(records) + for low < high { + mid := low + (high-low)/2 // avoid overflow when computing mid + p := recordKey(records[mid]) + if key < p { + high = mid + } else if key > p { + low = mid + 1 + } else { + return records[mid].Value + } + } + return 0 +} + +func recordKey(kp tables.Kernx0Record) uint32 { return uint32(kp.Left)<<16 | uint32(kp.Right) } + +func (kd Kern0) KernPair(left, right GID) int16 { return kernPair(kd, left, right) } + +type Kern1 struct { + Values []int16 // After successful parsing, may be safely indexed by AATStateEntry.AsKernxIndex() from `Machine` + Machine AATStateTable +} + +// convert from non extended to extended +func newKern1(k tables.KernData1) Kern1 { + class := tables.AATLoopkup8{ + AATLoopkup8Data: tables.AATLoopkup8Data{ + FirstGlyph: k.ClassTable.StartGlyph, + Values: make([]uint16, len(k.ClassTable.Values)), + }, + } + for i, b := range k.ClassTable.Values { + class.Values[i] = uint16(b) + } + states := make([][]uint16, len(k.States)) + for i, row := range k.States { + v := make([]uint16, len(row)) + for j, b := range row { + v[j] = uint16(b) + } + states[i] = v + } + return Kern1{ + Values: k.Values, + Machine: AATStateTable{ + nClass: uint32(k.StateSize), + class: class, + states: states, + entries: k.Entries, + }, + } +} + +func newKern1x(k tables.KerxData1) Kern1 { + return Kern1{Values: k.Values, Machine: newAATStableTable(k.AATStateTableExt)} +} + +type Kern2 tables.KerxData2 + +// convert from non extended to extended +func newKern2(k tables.KernData2) Kern2 { + return Kern2{ + Left: tables.AATLoopkup8{AATLoopkup8Data: k.Left}, + Right: tables.AATLoopkup8{AATLoopkup8Data: k.Right}, + KerningStart: tables.Offset32(k.KerningStart), + KerningData: k.KerningData, + } +} + +func (kd Kern2) KernPair(left, right GID) int16 { + l, _ := kd.Left.Class(tables.GlyphID(left)) + r, _ := kd.Right.Class(tables.GlyphID(right)) + index := int(l) + int(r) + if len(kd.KerningData) < index+2 || index < int(kd.KerningStart) { + return 0 + } + kernVal := binary.BigEndian.Uint16(kd.KerningData[index:]) + return int16(kernVal) +} + +type Kern3 tables.KernData3 + +func (kd Kern3) KernPair(left, right GID) int16 { + if int(left) >= len(kd.LeftClass) || int(right) >= len(kd.RightClass) { // should not happend + return 0 + } + + lc, rc := int(kd.LeftClass[left]), int(kd.RightClass[right]) + index := kd.KernIndex[lc*int(kd.RightClassCount)+rc] // sanitized during parsing + return kd.Kernings[index] // sanitized during parsing +} + +type Kern4 struct { + Anchors tables.KerxAnchors + Machine AATStateTable + flags uint32 +} + +func newKern4(k tables.KerxData4) Kern4 { + return Kern4{ + Machine: newAATStableTable(k.AATStateTableExt), + Anchors: k.Anchors, + flags: k.Flags, + } +} + +// ActionType returns 0, 1 or 2 . +func (k Kern4) ActionType() uint8 { + const ActionType = 0xC0000000 // A two-bit field containing the action type. + return uint8(k.flags & ActionType >> 30) +} + +type Kern6 tables.KerxData6 + +func (kd Kern6) KernPair(left, right GID) int16 { + l := kd.Row.ClassUint32(tables.GlyphID(left)) + r := kd.Column.ClassUint32(tables.GlyphID(right)) + index := int(l) + int(r) + if len(kd.Kernings) <= index { + return 0 + } + return kd.Kernings[index] +} + +// --------------------------------------- state machine --------------------------------------- + +// AATStateTable supports both regular and extended AAT state machines +type AATStateTable struct { + nClass uint32 + class tables.AATLookup + states [][]uint16 // each sub array has length stateSize + entries []tables.AATStateEntry // length is the maximum state + 1 +} + +func newAATStableTable(k tables.AATStateTableExt) AATStateTable { + return AATStateTable{ + nClass: k.StateSize, + class: k.Class, + states: k.States, + entries: k.Entries, + } +} + +// GetClass return the class for the given glyph, with the correct default value. +func (st *AATStateTable) GetClass(glyph GID) uint16 { + if glyph == 0xFFFF { // deleted glyph + return 2 // class deleted + } + c, ok := st.class.Class(tables.GlyphID(glyph)) + if !ok { + return 1 // class out of bounds + } + return c // class for a state table can't be uint32 +} + +// GetEntry return the entry for the given state and class, +// and handle invalid values (by returning an empty entry). +func (st *AATStateTable) GetEntry(state, class uint16) tables.AATStateEntry { + if uint32(class) >= st.nClass { + class = 1 // class out of bounds + } + if int(state) >= len(st.states) { + return tables.AATStateEntry{} + } + entry := st.states[state][class] // access check when parsing + return st.entries[entry] // access check when parsing +} diff --git a/vendor/github.com/go-text/typesetting/font/aat_layout_morx.go b/vendor/github.com/go-text/typesetting/font/aat_layout_morx.go new file mode 100644 index 0000000..193e4d8 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/aat_layout_morx.go @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package font + +import "github.com/go-text/typesetting/font/opentype/tables" + +type Morx []MorxChain + +func newMorx(table tables.Morx) Morx { + if len(table.Chains) == 0 { + return nil + } + out := make(Morx, len(table.Chains)) + for i, c := range table.Chains { + out[i] = newMorxChain(c) + } + return out +} + +type MorxChain struct { + Features []tables.AATFeature + Subtables []MorxSubtable + DefaultFlags uint32 +} + +func newMorxChain(table tables.MorxChain) (out MorxChain) { + out.DefaultFlags = table.Flags + out.Features = table.Features + out.Subtables = make([]MorxSubtable, len(table.Subtables)) + for i, s := range table.Subtables { + out.Subtables[i] = newMorxSubtable(s) + } + return out +} + +type MorxSubtable struct { + Data interface{ isMorxSubtable() } + Coverage uint8 // high byte of the coverage flag + Flags uint32 // Mask identifying which subtable this is. +} + +func (MorxRearrangementSubtable) isMorxSubtable() {} +func (MorxContextualSubtable) isMorxSubtable() {} +func (MorxLigatureSubtable) isMorxSubtable() {} +func (MorxNonContextualSubtable) isMorxSubtable() {} +func (MorxInsertionSubtable) isMorxSubtable() {} + +func newMorxSubtable(table tables.MorxChainSubtable) (out MorxSubtable) { + out.Coverage = table.Coverage + out.Flags = table.SubFeatureFlags + switch data := table.Data.(type) { + case tables.MorxSubtableRearrangement: + out.Data = MorxRearrangementSubtable(newAATStableTable(data.AATStateTableExt)) + case tables.MorxSubtableContextual: + out.Data = MorxContextualSubtable{ + Machine: newAATStableTable(data.AATStateTableExt), + Substitutions: data.Substitutions.Substitutions, + } + case tables.MorxSubtableLigature: + s := MorxLigatureSubtable{ + Machine: newAATStableTable(data.AATStateTableExt), + LigatureAction: data.LigActions, + Components: data.Components, + Ligatures: make([]GID, len(data.Ligatures)), + } + for i, g := range data.Ligatures { + s.Ligatures[i] = GID(g) + } + out.Data = s + case tables.MorxSubtableNonContextual: + out.Data = MorxNonContextualSubtable{Class: data.Class} + case tables.MorxSubtableInsertion: + s := MorxInsertionSubtable{ + Machine: newAATStableTable(data.AATStateTableExt), + Insertions: make([]GID, len(data.Insertions)), + } + for i, g := range data.Insertions { + s.Insertions[i] = GID(g) + } + out.Data = s + } + return out +} + +type MorxRearrangementSubtable AATStateTable + +type MorxContextualSubtable struct { + Substitutions []tables.AATLookup + Machine AATStateTable +} + +type MorxLigatureSubtable struct { + LigatureAction []uint32 + Components []uint16 + Ligatures []GID + Machine AATStateTable +} + +type MorxNonContextualSubtable struct { + Class tables.AATLookup // the lookup value is interpreted as a GlyphIndex +} + +type MorxInsertionSubtable struct { + // After successul parsing, this array may be safely + // indexed by the indexes and counts from Machine entries. + Insertions []GID + Machine AATStateTable +} diff --git a/vendor/github.com/go-text/typesetting/font/bitmaps.go b/vendor/github.com/go-text/typesetting/font/bitmaps.go new file mode 100644 index 0000000..0457d0b --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/bitmaps.go @@ -0,0 +1,476 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package font + +import ( + "errors" + "fmt" + "math" + + ot "github.com/go-text/typesetting/font/opentype" + "github.com/go-text/typesetting/font/opentype/tables" +) + +// sbix + +type sbix []tables.Strike + +func newSbix(table tables.Sbix) sbix { return table.Strikes } + +// chooseStrike selects the best match for the given resolution. +// It returns nil only if the table is empty +func (sb sbix) chooseStrike(xPpem, yPpem uint16) *tables.Strike { + if len(sb) == 0 { + return nil + } + + request := maxu16(xPpem, yPpem) + if request == 0 { + request = math.MaxUint16 // choose largest strike + } + + var ( + bestIndex = 0 + bestPpem = sb[0].Ppem + ) + for i, s := range sb { + ppem := s.Ppem + if request <= ppem && ppem < bestPpem || request > bestPpem && ppem > bestPpem { + bestIndex = i + bestPpem = ppem + } + } + return &sb[bestIndex] +} + +func (sb sbix) availableSizes(horizontal *tables.Hhea, avgWidth, upem uint16) []BitmapSize { + out := make([]BitmapSize, 0, len(sb)) + for _, size := range sb { + v := strikeSizeMetrics(size, horizontal, avgWidth, upem) + // only use strikes with valid PPEM values + if v.XPpem == 0 || v.YPpem == 0 { + continue + } + out = append(out, v) + } + return out +} + +func strikeSizeMetrics(b tables.Strike, hori *tables.Hhea, avgWidth, upem uint16) (out BitmapSize) { + out.XPpem, out.YPpem = b.Ppem, b.Ppem + out.Height = mulDiv(uint16(hori.Ascender-hori.Descender+hori.LineGap), b.Ppem, upem) + + inferBitmapWidth(&out, avgWidth, upem) + + return out +} + +// ---------------------------- bitmap ---------------------------- + +func loadBitmap(ld *ot.Loader, tagLoc, tagData ot.Tag) (bitmap, error) { + raw, err := ld.RawTable(tagLoc) + if err != nil { + return nil, err + } + loc, _, err := tables.ParseCBLC(raw) + if err != nil { + return nil, err + } + imageTable, err := ld.RawTable(tagData) + if err != nil { + return nil, err + } + return newBitmap(loc, imageTable) +} + +// CBLC/CBDT or EBLC/EBDT or BLOC/BDAT +type bitmap []bitmapStrike + +func newBitmap(table tables.EBLC, imageTable []byte) (bitmap, error) { + out := make(bitmap, len(table.BitmapSizes)) + for i, strike := range table.BitmapSizes { + subtables := table.IndexSubTables[i] + out[i] = bitmapStrike{ + subTables: make([]bitmapSubtable, len(subtables)), + hori: strike.Hori, + vert: strike.Vert, + ppemX: uint16(strike.PpemX), + ppemY: uint16(strike.PpemY), + } + for j, subtable := range subtables { + var err error + out[i].subTables[j], err = newBitmapSubtable(subtable, imageTable) + if err != nil { + return nil, err + } + } + } + return out, nil +} + +func (t bitmap) availableSizes(avgWidth, upem uint16) []BitmapSize { + out := make([]BitmapSize, 0, len(t)) + for _, size := range t { + v := size.sizeMetrics(avgWidth, upem) + // only use strikes with valid PPEM values + if v.XPpem == 0 || v.YPpem == 0 { + continue + } + out = append(out, v) + } + return out +} + +type bitmapStrike struct { + subTables []bitmapSubtable + hori, vert tables.SbitLineMetrics + ppemX, ppemY uint16 +} + +// chooseStrike selects the best match for the given resolution. +// It returns nil only if the table is empty +func (bt bitmap) chooseStrike(xPpem, yPpem uint16) *bitmapStrike { + if len(bt) == 0 { + return nil + } + request := maxu16(xPpem, yPpem) + if request == 0 { + request = math.MaxUint16 // choose largest strike + } + var ( + bestIndex = 0 + bestPpem = maxu16(bt[0].ppemX, bt[0].ppemY) + ) + for i, s := range bt { + ppem := maxu16(s.ppemX, s.ppemY) + if request <= ppem && ppem < bestPpem || request > bestPpem && ppem > bestPpem { + bestIndex = i + bestPpem = ppem + } + } + return &bt[bestIndex] +} + +func (b *bitmapStrike) sizeMetrics(avgWidth, upem uint16) (out BitmapSize) { + out.XPpem, out.YPpem = b.ppemX, b.ppemY + ascender := int16(b.hori.Ascender) + descender := int16(b.hori.Descender) + + maxBeforeBl := b.hori.MaxBeforeBL + minAfterBl := b.hori.MinAfterBL + + /* Due to fuzzy wording in the EBLC documentation, we find both */ + /* positive and negative values for `descender'. Additionally, */ + /* many fonts have both `ascender' and `descender' set to zero */ + /* (which is definitely wrong). MS Windows simply ignores all */ + /* those values... For these reasons we apply some heuristics */ + /* to get a reasonable, non-zero value for the height. */ + + if descender > 0 { + if minAfterBl < 0 { + descender = -descender + } + } else if descender == 0 { + if ascender == 0 { + /* sanitize buggy ascender and descender values */ + if maxBeforeBl != 0 || minAfterBl != 0 { + ascender = int16(maxBeforeBl) + descender = int16(minAfterBl) + } else { + ascender = int16(out.YPpem) + descender = 0 + } + } + } + + if h := ascender - descender; h > 0 { + out.Height = uint16(h) + } else { + out.Height = out.YPpem + } + + inferBitmapWidth(&out, avgWidth, upem) + + return out +} + +func inferBitmapWidth(size *BitmapSize, avgWidth, upem uint16) { + size.Width = uint16((uint32(avgWidth)*uint32(size.XPpem) + uint32(upem/2)) / uint32(upem)) +} + +// return nil when not found +func (b *bitmapStrike) findTable(glyph gID) *bitmapSubtable { + for i, subtable := range b.subTables { + if subtable.first <= glyph && glyph <= subtable.last { + return &b.subTables[i] + } + } + return nil +} + +type bitmapSubtable struct { + first gID // First glyph ID of this range. + last gID // Last glyph ID of this range (inclusive). + imageFormat uint16 + index bitmapIndex +} + +func newBitmapSubtable(header tables.BitmapSubtable, dataTable []byte) (bitmapSubtable, error) { + out := bitmapSubtable{ + first: header.FirstGlyph, + last: header.LastGlyph, + imageFormat: header.ImageFormat, + } + if L, E := len(dataTable), int(header.ImageDataOffset); L < E { + return bitmapSubtable{}, errors.New("invalid bitmap table (EOF)") + } + imageData := dataTable[header.ImageDataOffset:] + + var err error + switch index := header.IndexData.(type) { + case tables.IndexData1: + out.index, err = parseIndexSubTable1(header, index, imageData) + case tables.IndexData2: + out.index, err = parseIndexSubTable2(header, index, imageData) + case tables.IndexData3: + out.index, err = parseIndexSubTable3(header, index, imageData) + case tables.IndexData4: + out.index, err = parseIndexSubTable4(header, index, imageData) + case tables.IndexData5: + out.index, err = parseIndexSubTable5(header, index, imageData) + } + return out, err +} + +func (subT *bitmapSubtable) image(glyph gID) *bitmapImage { + return subT.index.imageFor(glyph, subT.first, subT.last) +} + +type bitmapIndex interface { + // first, last is the range of the subtable + imageFor(glyph gID, first, last gID) *bitmapImage +} + +type bitmapImage struct { + image []byte + metrics tables.SmallGlyphMetrics +} + +type indexSubTable1And3 struct { + // length lastGlyph - firstGlyph + 1, elements may be nil + glyphs []bitmapImage + format uint16 +} + +func (idx indexSubTable1And3) imageFor(gid gID, first, last gID) *bitmapImage { + if gid < first || gid > last { + return nil + } + return &idx.glyphs[gid-first] +} + +// imageData starts at the image (table[imageDataOffset:]) +func parseIndexSubTable1(header tables.BitmapSubtable, index tables.IndexData1, imageData []byte) (indexSubTable1And3, error) { + out := indexSubTable1And3{ + format: header.ImageFormat, + glyphs: make([]bitmapImage, len(index.SbitOffsets)-1), + } + for i := range out.glyphs { + if index.SbitOffsets[i] == index.SbitOffsets[i+1] { + continue + } + var err error + out.glyphs[i], err = parseBitmapDataMetrics(imageData, index.SbitOffsets[i], index.SbitOffsets[i+1], header.ImageFormat) + if err != nil { + return out, fmt.Errorf("invalid bitmap index format 1: %s", err) + } + } + return out, nil +} + +func parseIndexSubTable3(header tables.BitmapSubtable, index tables.IndexData3, imageData []byte) (indexSubTable1And3, error) { + out := indexSubTable1And3{ + format: header.ImageFormat, + glyphs: make([]bitmapImage, len(index.SbitOffsets)-1), + } + for i := range out.glyphs { + if index.SbitOffsets[i] == index.SbitOffsets[i+1] { + continue + } + var err error + out.glyphs[i], err = parseBitmapDataMetrics(imageData, tables.Offset32(index.SbitOffsets[i]), tables.Offset32(index.SbitOffsets[i+1]), header.ImageFormat) + if err != nil { + return out, fmt.Errorf("invalid bitmap index format 1: %s", err) + } + } + return out, nil +} + +type bitmapDataStandalone []byte + +type indexSubTable2 struct { + glyphs []bitmapDataStandalone + format uint16 + metrics tables.BigGlyphMetrics +} + +func (idx indexSubTable2) imageFor(gid gID, first, last gID) *bitmapImage { + if gid < first || gid > last { + return nil + } + return &bitmapImage{image: idx.glyphs[gid-first], metrics: idx.metrics.SmallGlyphMetrics} +} + +// imageData starts at the image (table[imageDataOffset:]) +func parseIndexSubTable2(header tables.BitmapSubtable, index tables.IndexData2, imageData []byte) (indexSubTable2, error) { + out := indexSubTable2{ + format: header.ImageFormat, + metrics: index.BigMetrics, + glyphs: make([]bitmapDataStandalone, int(header.LastGlyph)-int(header.FirstGlyph)+1), + } + for i := range out.glyphs { + var err error + out.glyphs[i], err = parseBitmapDataStandalone(imageData, index.ImageSize*uint32(i), index.ImageSize*uint32(i+1), header.ImageFormat) + if err != nil { + return out, fmt.Errorf("invalid bitmap index format 2: %s", err) + } + } + return out, nil +} + +type indexedBitmapGlyph struct { + data bitmapImage + glyph gID +} + +type indexSubTable4 struct { + glyphs []indexedBitmapGlyph + format uint16 +} + +func (idx indexSubTable4) imageFor(gid gID, first, last gID) *bitmapImage { + if gid < first || gid > last { + return nil + } + for i, g := range idx.glyphs { + if g.glyph == gid { + return &idx.glyphs[i].data + } + } + return nil +} + +// imageData starts at the image (table[imageDataOffset:]) +func parseIndexSubTable4(header tables.BitmapSubtable, index tables.IndexData4, imageData []byte) (indexSubTable4, error) { + out := indexSubTable4{ + format: header.ImageFormat, + glyphs: make([]indexedBitmapGlyph, len(index.GlyphArray)-1), + } + for i := range out.glyphs { + current, next := index.GlyphArray[i], index.GlyphArray[i+1] + out.glyphs[i].glyph = current.GlyphID + var err error + out.glyphs[i].data, err = parseBitmapDataMetrics(imageData, tables.Offset32(current.SbitOffset), tables.Offset32(next.SbitOffset), header.ImageFormat) + if err != nil { + return out, fmt.Errorf("invalid bitmap index format 4: %s", err) + } + } + return out, nil +} + +type indexSubTable5 struct { + glyphIndexes []gID // sorted by glyph index + glyphs []bitmapDataStandalone // corresponding to glyphIndexes + format uint16 + metrics tables.BigGlyphMetrics +} + +func (idx indexSubTable5) imageFor(gid gID, first, last gID) *bitmapImage { + if gid < first || gid > last { + return nil + } + // binary search + for i, j := 0, len(idx.glyphIndexes); i < j; { + h := i + (j-i)/2 + entry := idx.glyphIndexes[h] + if gid < entry { + j = h + } else if entry < gid { + i = h + 1 + } else { + return &bitmapImage{image: idx.glyphs[h], metrics: idx.metrics.SmallGlyphMetrics} + } + } + return nil +} + +// imageData starts at the image (table[imageDataOffset:]) +func parseIndexSubTable5(header tables.BitmapSubtable, index tables.IndexData5, imageData []byte) (indexSubTable5, error) { + out := indexSubTable5{ + format: header.ImageFormat, + metrics: index.BigMetrics, + glyphIndexes: index.GlyphIdArray, + glyphs: make([]bitmapDataStandalone, len(index.GlyphIdArray)), + } + + for i := range out.glyphs { + var err error + out.glyphs[i], err = parseBitmapDataStandalone(imageData, index.ImageSize*uint32(i), (index.ImageSize+1)*uint32(i), header.ImageFormat) + if err != nil { + return out, fmt.Errorf("invalid bitmap index format 5: %s", err) + } + } + return out, nil +} + +func parseBitmapDataMetrics(imageData []byte, start, end tables.Offset32, imageFormat uint16) (bitmapImage, error) { + if len(imageData) < int(end) || start > end { + return bitmapImage{}, errors.New("invalid bitmap data table (EOF)") + } + imageData = imageData[start:end] + switch imageFormat { + case 1, 6, 7, 8, 9: + return bitmapImage{}, fmt.Errorf("valid but currently not implemented bitmap image format: %d", imageFormat) + case 2: + data, _, err := tables.ParseBitmapData2(imageData) + return bitmapImage{metrics: data.SmallGlyphMetrics, image: data.Image}, err + case 17: + data, _, err := tables.ParseBitmapData17(imageData) + return bitmapImage{metrics: data.SmallGlyphMetrics, image: data.Image}, err + case 18: + data, _, err := tables.ParseBitmapData18(imageData) + return bitmapImage{metrics: data.SmallGlyphMetrics, image: data.Image}, err + default: + return bitmapImage{}, fmt.Errorf("unsupported bitmap image format: %d", imageFormat) + } +} + +func parseBitmapDataStandalone(imageData []byte, start, end uint32, format uint16) (bitmapDataStandalone, error) { + if len(imageData) < int(end) || start > end { + return nil, fmt.Errorf("invalid bitmap data table (EOF for [%d,%d])", start, end) + } + imageData = imageData[start:end] + switch format { + case 4: + return nil, fmt.Errorf("valid but currently not implemented bitmap image format: %d", format) + case 5: + data, _, err := tables.ParseBitmapData5(imageData) + return data.Image, err + case 19: + data, _, err := tables.ParseBitmapData19(imageData) + return data.Image, err + default: + return nil, fmt.Errorf("unsupported bitmap image format: %d", format) + } +} + +func maxu16(a, b uint16) uint16 { + if a > b { + return a + } + return b +} + +func mulDiv(a, b, c uint16) uint16 { + return uint16(uint32(a) * uint32(b) / uint32(c)) +} diff --git a/vendor/github.com/go-text/typesetting/font/cache.go b/vendor/github.com/go-text/typesetting/font/cache.go new file mode 100644 index 0000000..b767668 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/cache.go @@ -0,0 +1,41 @@ +package font + +type glyphExtents struct { + valid bool + extents GlyphExtents +} + +type extentsCache []glyphExtents + +func (ec extentsCache) get(gid GID) (GlyphExtents, bool) { + if int(gid) >= len(ec) { + return GlyphExtents{}, false + } + ge := ec[gid] + return ge.extents, ge.valid +} + +func (ec extentsCache) set(gid GID, extents GlyphExtents) { + if int(gid) >= len(ec) { + return + } + ec[gid].valid = true + ec[gid].extents = extents +} + +func (ec extentsCache) reset() { + for i := range ec { + ec[i] = glyphExtents{} + } +} + +func (f *Face) GlyphExtents(glyph GID) (GlyphExtents, bool) { + if e, ok := f.extentsCache.get(glyph); ok { + return e, ok + } + e, ok := f.glyphExtentsRaw(glyph) + if ok { + f.extentsCache.set(glyph, e) + } + return e, ok +} diff --git a/vendor/github.com/go-text/typesetting/font/cff/cff2.go b/vendor/github.com/go-text/typesetting/font/cff/cff2.go new file mode 100644 index 0000000..18f721b --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/cff/cff2.go @@ -0,0 +1,260 @@ +package cff + +import ( + "encoding/binary" + "errors" + "fmt" + + ps "github.com/go-text/typesetting/font/cff/interpreter" + "github.com/go-text/typesetting/font/opentype/tables" +) + +//go:generate ../../../../typesetting-utils/generators/binarygen/cmd/generator . _src.go + +// CFF2 represents a parsed 'CFF2' Opentype table. +type CFF2 struct { + fdSelect fdSelect // maybe nil if there is only one font dict + + // Charstrings contains the actual glyph definition. + // It has a length of numGlyphs and is indexed by glyph ID. + // See `LoadGlyph` for a way to intepret the glyph data. + Charstrings [][]byte + + globalSubrs [][]byte + + // array of length 1 if fdSelect is nil + // otherwise, it can be safely indexed by `fdSelect` output + fonts []privateFonts + + VarStore tables.ItemVarStore // optional +} + +type privateFonts struct { + localSubrs [][]byte + defaultVSIndex int32 +} + +// ParseCFF2 parses 'src', which must be the content of a 'CFF2' Opentype table. +// +// See also https://learn.microsoft.com/en-us/typography/opentype/spec/cff2 +func ParseCFF2(src []byte) (*CFF2, error) { + if L := len(src); L < 5 { + return nil, fmt.Errorf("reading header: EOF: expected length: 5, got %d", L) + } + var header header2 + header.mustParse(src) + topDictEnd := int(header.headerSize) + int(header.topDictLength) + if L := len(src); L < topDictEnd { + return nil, fmt.Errorf("reading topDict: EOF: expected length: %d, got %d", topDictEnd, L) + } + topDictSrc := src[header.headerSize:topDictEnd] + + var ( + tp topDict2 + psi ps.Machine + ) + if err := psi.Run(topDictSrc, nil, nil, &tp); err != nil { + return nil, fmt.Errorf("reading top dict: %s", err) + } + + var ( + out CFF2 + err error + ) + + out.globalSubrs, err = parseIndex2(src, topDictEnd) + if err != nil { + return nil, err + } + + // parse charstrings + out.Charstrings, err = parseIndex2(src, int(tp.charStrings)) + if err != nil { + return nil, err + } + + fdIndex, err := parseIndex2(src, int(tp.fdArray)) + if err != nil { + return nil, err + } + + out.fonts = make([]privateFonts, len(fdIndex)) + // private dict reference + for i, font := range fdIndex { + var fd fontDict2 + err = psi.Run(font, nil, nil, &fd) + if err != nil { + return nil, fmt.Errorf("reading font dict: %s", err) + } + end := int(fd.privateDictOffset + fd.privateDictSize) + if L := len(src); L < end { + return nil, fmt.Errorf("reading private dict: EOF: expected length: %d, got %d", end, L) + } + // parse private dict + var pd privateDict2 + err = psi.Run(src[fd.privateDictOffset:end], nil, nil, &pd) + if err != nil { + return nil, fmt.Errorf("reading private dict: %s", err) + } + + out.fonts[i].defaultVSIndex = pd.vsindex + // if required, parse the local subroutines + if pd.subrsOffset != 0 { + out.fonts[i].localSubrs, err = parseIndex2(src, int(pd.subrsOffset)) + if err != nil { + return nil, err + } + } + } + + if len(fdIndex) > 1 { + // parse the fdSelect + if L := len(src); L < int(tp.fdSelect) { + return nil, fmt.Errorf("reading fdSelect: EOF: expected length: %d, got %d", tp.fdSelect, L) + } + out.fdSelect, _, err = parseFdSelect(src[tp.fdSelect:], len(out.Charstrings)) + if err != nil { + return nil, err + } + + // sanitize fdSelect outputs + indexExtent := out.fdSelect.extent() + if len(fdIndex) < indexExtent { + return nil, fmt.Errorf("invalid number of font dicts: %d (for %d)", len(fdIndex), indexExtent) + } + } + + // parse variation store + if tp.vstore != 0 { + // See https://learn.microsoft.com/en-us/typography/opentype/spec/cff2#variationstore-data-contents + if E, L := int(tp.vstore)+2, len(src); L < E { + return nil, fmt.Errorf("reading variation store: EOF: expected length: %d, got %d", E, L) + } + size := int(binary.BigEndian.Uint16(src[tp.vstore:])) + end := int(tp.vstore) + 2 + size + if L := len(src); L < end { + return nil, fmt.Errorf("reading variation store: EOF: expected length: %d, got %d", end, L) + } + vstore := src[tp.vstore+2 : end] + out.VarStore, _, err = tables.ParseItemVarStore(vstore) + if err != nil { + return nil, err + } + } + return &out, nil +} + +func parseIndex2(src []byte, offset int) ([][]byte, error) { + if L := len(src); L < offset+5 { + return nil, fmt.Errorf("reading INDEX: EOF: expected length: %d, got %d", offset+5, L) + } + var is indexStart + is.mustParse(src[offset:]) + out, _, err := parseIndexContent(src[offset+5:], is) + return out, err +} + +type topDict2 struct { + charStrings int32 // offset + fdArray int32 // offset + fdSelect int32 // offset + vstore int32 // offset +} + +func (tp *topDict2) Context() ps.Context { return ps.TopDict } + +func (tp *topDict2) Apply(state *ps.Machine, op ps.Operator) error { + switch op { + case ps.Operator{Operator: 7, IsEscaped: true}: // FontMatrix + // skip + state.ArgStack.Clear() + return nil + case ps.Operator{Operator: 17, IsEscaped: false}: // CharStrings + if state.ArgStack.Top < 1 { + return fmt.Errorf("invalid number of arguments for operator %s in Top Dict", op) + } + tp.charStrings = int32(state.ArgStack.Pop()) + case ps.Operator{Operator: 36, IsEscaped: true}: // FDArray + if state.ArgStack.Top < 1 { + return fmt.Errorf("invalid number of arguments for operator %s in Top Dict", op) + } + tp.fdArray = int32(state.ArgStack.Pop()) + case ps.Operator{Operator: 37, IsEscaped: true}: // FDSelect + if state.ArgStack.Top < 1 { + return fmt.Errorf("invalid number of arguments for operator %s in Top Dict", op) + } + tp.fdSelect = int32(state.ArgStack.Pop()) + case ps.Operator{Operator: 24, IsEscaped: false}: // vstore + if state.ArgStack.Top < 1 { + return fmt.Errorf("invalid number of arguments for operator %s in Top Dict", op) + } + tp.vstore = int32(state.ArgStack.Pop()) + default: + return fmt.Errorf("invalid operator %s in Top Dict", op) + } + return nil +} + +type fontDict2 struct { + privateDictSize int32 + privateDictOffset int32 +} + +func (fd *fontDict2) Context() ps.Context { return ps.TopDict } + +func (fd *fontDict2) Apply(state *ps.Machine, op ps.Operator) error { + switch op { + case ps.Operator{Operator: 18, IsEscaped: false}: // Private + if state.ArgStack.Top < 2 { + return fmt.Errorf("invalid number of arguments for operator %s in Font Dict", op) + } + fd.privateDictOffset = int32(state.ArgStack.Pop()) + fd.privateDictSize = int32(state.ArgStack.Pop()) + return nil + default: + return fmt.Errorf("invalid operator %s in Font Dict", op) + } +} + +// privateDict2 contains fields specific to the Private DICT context. +type privateDict2 struct { + subrsOffset int32 + vsindex int32 // itemVariationData index in the VariationStore structure table. +} + +func (privateDict2) Context() ps.Context { return ps.PrivateDict } + +// The Private DICT operators are defined by 5176.CFF.pdf Table 23 "Private +// DICT Operators". +func (priv *privateDict2) Apply(state *ps.Machine, op ps.Operator) error { + if !op.IsEscaped { // 1-byte operators. + switch op.Operator { + case 6, 7, 8, 9: // "BlueValues" "OtherBlues" "FamilyBlues" "FamilyOtherBlues" + return state.ArgStack.PopN(-2) + case 10, 11: // "StdHW" "StdVW" + return state.ArgStack.PopN(1) + case 19: // "Subrs" pop 1 + if state.ArgStack.Top < 1 { + return errors.New("invalid stack size for 'subrs' in private Dict charstring") + } + priv.subrsOffset = int32(state.ArgStack.Pop()) + return nil + case 22: // "vsindex" + if state.ArgStack.Top < 1 { + return fmt.Errorf("invalid stack size for %s in private Dict", op) + } + priv.vsindex = int32(state.ArgStack.Pop()) + return nil + case 23: // "blend" + return nil + } + } else { // 2-byte operators. The first byte is the escape byte. + switch op.Operator { + case 9, 10, 11, 17, 18: // "BlueScale" "BlueShift" "BlueFuzz" "LanguageGroup" "ExpansionFactor" + return state.ArgStack.PopN(1) + case 12, 13: // "StemSnapH" "StemSnapV" + return state.ArgStack.PopN(-2) + } + } + return errors.New("invalid operand in private Dict charstring") +} diff --git a/vendor/github.com/go-text/typesetting/font/cff/cff_gen.go b/vendor/github.com/go-text/typesetting/font/cff/cff_gen.go new file mode 100644 index 0000000..53ede58 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/cff/cff_gen.go @@ -0,0 +1,151 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package cff + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from cff2_src.go. DO NOT EDIT + +func (item *header2) mustParse(src []byte) { + _ = src[4] // early bound checking + item.majorVersion = src[0] + item.minorVersion = src[1] + item.headerSize = src[2] + item.topDictLength = binary.BigEndian.Uint16(src[3:]) +} + +func (item *indexStart) mustParse(src []byte) { + _ = src[4] // early bound checking + item.count = binary.BigEndian.Uint32(src[0:]) + item.offSize = src[4] +} + +func parseFdSelect(src []byte, fdsCount int) (fdSelect, int, error) { + var item fdSelect + + if L := len(src); L < 1 { + return item, 0, fmt.Errorf("reading fdSelect: "+"EOF: expected length: 1, got %d", L) + } + format := uint8(src[0]) + var ( + read int + err error + ) + switch format { + case 0: + item, read, err = parseFdSelect0(src[0:], fdsCount) + case 3: + item, read, err = parseFdSelect3(src[0:]) + case 4: + item, read, err = parseFdSelect4(src[0:]) + default: + err = fmt.Errorf("unsupported fdSelect format %d", format) + } + if err != nil { + return item, 0, fmt.Errorf("reading fdSelect: %s", err) + } + + return item, read, nil +} + +func parseFdSelect0(src []byte, fdsCount int) (fdSelect0, int, error) { + var item fdSelect0 + n := 0 + if L := len(src); L < 1 { + return item, 0, fmt.Errorf("reading fdSelect0: "+"EOF: expected length: 1, got %d", L) + } + item.format = src[0] + n += 1 + + { + + L := int(1 + fdsCount) + if len(src) < L { + return item, 0, fmt.Errorf("reading fdSelect0: "+"EOF: expected length: %d, got %d", L, len(src)) + } + item.fds = src[1:L] + n = L + } + return item, n, nil +} + +func parseFdSelect3(src []byte) (fdSelect3, int, error) { + var item fdSelect3 + n := 0 + if L := len(src); L < 3 { + return item, 0, fmt.Errorf("reading fdSelect3: "+"EOF: expected length: 3, got %d", L) + } + _ = src[2] // early bound checking + item.format = src[0] + item.nRanges = binary.BigEndian.Uint16(src[1:]) + n += 3 + + { + arrayLength := int(item.nRanges) + + if L := len(src); L < 3+arrayLength*3 { + return item, 0, fmt.Errorf("reading fdSelect3: "+"EOF: expected length: %d, got %d", 3+arrayLength*3, L) + } + + item.ranges = make([]range3, arrayLength) // allocation guarded by the previous check + for i := range item.ranges { + item.ranges[i].mustParse(src[3+i*3:]) + } + n += arrayLength * 3 + } + if L := len(src); L < n+2 { + return item, 0, fmt.Errorf("reading fdSelect3: "+"EOF: expected length: n + 2, got %d", L) + } + item.sentinel = binary.BigEndian.Uint16(src[n:]) + n += 2 + + return item, n, nil +} + +func parseFdSelect4(src []byte) (fdSelect4, int, error) { + var item fdSelect4 + n := 0 + if L := len(src); L < 5 { + return item, 0, fmt.Errorf("reading fdSelect4: "+"EOF: expected length: 5, got %d", L) + } + _ = src[4] // early bound checking + item.format = src[0] + item.nRanges = binary.BigEndian.Uint32(src[1:]) + n += 5 + + { + arrayLength := int(item.nRanges) + + if L := len(src); L < 5+arrayLength*6 { + return item, 0, fmt.Errorf("reading fdSelect4: "+"EOF: expected length: %d, got %d", 5+arrayLength*6, L) + } + + item.ranges = make([]range4, arrayLength) // allocation guarded by the previous check + for i := range item.ranges { + item.ranges[i].mustParse(src[5+i*6:]) + } + n += arrayLength * 6 + } + if L := len(src); L < n+4 { + return item, 0, fmt.Errorf("reading fdSelect4: "+"EOF: expected length: n + 4, got %d", L) + } + item.sentinel = binary.BigEndian.Uint32(src[n:]) + n += 4 + + return item, n, nil +} + +func (item *range3) mustParse(src []byte) { + _ = src[2] // early bound checking + item.first = binary.BigEndian.Uint16(src[0:]) + item.fd = src[2] +} + +func (item *range4) mustParse(src []byte) { + _ = src[5] // early bound checking + item.first = binary.BigEndian.Uint32(src[0:]) + item.fd = binary.BigEndian.Uint16(src[4:]) +} diff --git a/vendor/github.com/go-text/typesetting/font/cff/cff_src.go b/vendor/github.com/go-text/typesetting/font/cff/cff_src.go new file mode 100644 index 0000000..dbfe540 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/cff/cff_src.go @@ -0,0 +1,162 @@ +package cff + +import ( + "errors" + + "github.com/go-text/typesetting/font/opentype/tables" +) + +//go:generate ../../../../../typesetting-utils/generators/binarygen/cmd/generator . _src.go + +type header2 struct { + majorVersion uint8 // Format major version. Set to 2. + minorVersion uint8 // Format minor version. Set to zero. + headerSize uint8 // Header size (bytes). + topDictLength uint16 // Length of Top DICT structure in bytes. +} + +type indexStart struct { + count uint32 // Number of objects stored in INDEX + offSize uint8 // Offset array element size + // then + // offset []Offset + // data []byte +} + +//lint:ignore U1000 this type is required so that the code generator add a ParseFdSelect function +type dummy struct { + fd fdSelect +} + +// fdSelect holds a CFF font's Font Dict Select data. +type fdSelect interface { + isFdSelect() + + fontDictIndex(glyph tables.GlyphID) (byte, error) + // return the maximum index + 1 (it's the length of an array + // which can be safely indexed by the indexes) + extent() int +} + +func (fdSelect0) isFdSelect() {} +func (fdSelect3) isFdSelect() {} +func (fdSelect4) isFdSelect() {} + +type fdSelect0 struct { + format uint8 `unionTag:"0"` // Set to 0 + fds []uint8 // [nGlyphs] FD selector array +} + +var errGlyph = errors.New("invalid glyph index") + +func (fds fdSelect0) fontDictIndex(glyph tables.GlyphID) (byte, error) { + if int(glyph) >= len(fds.fds) { + return 0, errGlyph + } + return fds.fds[glyph], nil +} + +func (fds fdSelect0) extent() int { + max := -1 + for _, b := range fds.fds { + if int(b) > max { + max = int(b) + } + } + return max + 1 +} + +type fdSelect3 struct { + format uint8 `unionTag:"3"` // Set to 3 + nRanges uint16 // Number of ranges + ranges []range3 `arrayCount:"ComputedField-nRanges"` // [nRanges] Array of Range3 records (see below) + sentinel uint16 // Sentinel GID +} + +type range3 struct { + first tables.GlyphID // First glyph index in range + fd uint8 // FD index for all glyphs in range +} + +func (fds fdSelect3) fontDictIndex(x tables.GlyphID) (byte, error) { + lo, hi := 0, len(fds.ranges) + for lo < hi { + i := (lo + hi) / 2 + r := fds.ranges[i] + xlo := r.first + if x < xlo { + hi = i + continue + } + xhi := fds.sentinel + if i < len(fds.ranges)-1 { + xhi = fds.ranges[i+1].first + } + if xhi <= x { + lo = i + 1 + continue + } + return r.fd, nil + } + return 0, errGlyph +} + +func (fds fdSelect3) extent() int { + max := -1 + for _, b := range fds.ranges { + if int(b.fd) > max { + max = int(b.fd) + } + } + return max + 1 +} + +type fdSelect4 struct { + format uint8 `unionTag:"4"` // Set to 4 + nRanges uint32 // Number of ranges + ranges []range4 `arrayCount:"ComputedField-nRanges"` // [nRanges] Array of Range4 records (see below) + sentinel uint32 // Sentinel GID +} + +type range4 struct { + first uint32 // First glyph index in range + fd uint16 // FD index for all glyphs in range +} + +func (fds fdSelect4) fontDictIndex(x tables.GlyphID) (byte, error) { + fd, err := fds.fontDictIndex32(uint32(x)) + return byte(fd), err +} + +func (fds fdSelect4) fontDictIndex32(x uint32) (uint16, error) { + lo, hi := 0, len(fds.ranges) + for lo < hi { + i := (lo + hi) / 2 + r := fds.ranges[i] + xlo := r.first + if x < xlo { + hi = i + continue + } + xhi := fds.sentinel + if i < len(fds.ranges)-1 { + xhi = fds.ranges[i+1].first + } + if xhi <= x { + lo = i + 1 + continue + } + return r.fd, nil + } + return 0, errGlyph +} + +func (fds fdSelect4) extent() int { + max := -1 + for _, b := range fds.ranges { + if int(b.fd) > max { + max = int(b.fd) + } + } + return max + 1 +} diff --git a/vendor/github.com/go-text/typesetting/font/cff/charsets.go b/vendor/github.com/go-text/typesetting/font/cff/charsets.go new file mode 100644 index 0000000..bc2fb02 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/cff/charsets.go @@ -0,0 +1,423 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package cff + +var ( + charsetISOAdobe = [229]uint16{ + 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, 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, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, + 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, + 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 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, 195, 196, 197, + 198, 199, 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, + } + + charsetExpert = [166]uint16{ + 0, 1, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 13, 14, 15, 99, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 27, 28, 249, 250, 251, 252, 253, 254, + 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 109, 110, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, + 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 158, 155, + 163, 319, 320, 321, 322, 323, 324, 325, 326, 150, 164, 169, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, + 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, + } + + charsetExpertSubset = [87]uint16{ + 0, 1, 231, 232, 235, 236, 237, 238, 13, 14, 15, 99, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 27, 28, 249, 250, 251, 253, 254, + 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 109, 110, 267, 268, 269, 270, 272, 300, 301, 302, 305, 314, 315, 158, 155, 163, 320, + 321, 322, 323, 324, 325, 326, 150, 164, 169, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, + } +) + +var stdStrings = [391]string{ + ".notdef", + "space", + "exclam", + "quotedbl", + "numbersign", + "dollar", + "percent", + "ampersand", + "quoteright", + "parenleft", + "parenright", + "asterisk", + "plus", + "comma", + "hyphen", + "period", + "slash", + "zero", + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", + "colon", + "semicolon", + "less", + "equal", + "greater", + "question", + "at", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + "bracketleft", + "backslash", + "bracketright", + "asciicircum", + "underscore", + "quoteleft", + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "braceleft", + "bar", + "braceright", + "asciitilde", + "exclamdown", + "cent", + "sterling", + "fraction", + "yen", + "florin", + "section", + "currency", + "quotesingle", + "quotedblleft", + "guillemotleft", + "guilsinglleft", + "guilsinglright", + "fi", + "fl", + "endash", + "dagger", + "daggerdbl", + "periodcentered", + "paragraph", + "bullet", + "quotesinglbase", + "quotedblbase", + "quotedblright", + "guillemotright", + "ellipsis", + "perthousand", + "questiondown", + "grave", + "acute", + "circumflex", + "tilde", + "macron", + "breve", + "dotaccent", + "dieresis", + "ring", + "cedilla", + "hungarumlaut", + "ogonek", + "caron", + "emdash", + "AE", + "ordfeminine", + "Lslash", + "Oslash", + "OE", + "ordmasculine", + "ae", + "dotlessi", + "lslash", + "oslash", + "oe", + "germandbls", + "onesuperior", + "logicalnot", + "mu", + "trademark", + "Eth", + "onehalf", + "plusminus", + "Thorn", + "onequarter", + "divide", + "brokenbar", + "degree", + "thorn", + "threequarters", + "twosuperior", + "registered", + "minus", + "eth", + "multiply", + "threesuperior", + "copyright", + "Aacute", + "Acircumflex", + "Adieresis", + "Agrave", + "Aring", + "Atilde", + "Ccedilla", + "Eacute", + "Ecircumflex", + "Edieresis", + "Egrave", + "Iacute", + "Icircumflex", + "Idieresis", + "Igrave", + "Ntilde", + "Oacute", + "Ocircumflex", + "Odieresis", + "Ograve", + "Otilde", + "Scaron", + "Uacute", + "Ucircumflex", + "Udieresis", + "Ugrave", + "Yacute", + "Ydieresis", + "Zcaron", + "aacute", + "acircumflex", + "adieresis", + "agrave", + "aring", + "atilde", + "ccedilla", + "eacute", + "ecircumflex", + "edieresis", + "egrave", + "iacute", + "icircumflex", + "idieresis", + "igrave", + "ntilde", + "oacute", + "ocircumflex", + "odieresis", + "ograve", + "otilde", + "scaron", + "uacute", + "ucircumflex", + "udieresis", + "ugrave", + "yacute", + "ydieresis", + "zcaron", + "exclamsmall", + "Hungarumlautsmall", + "dollaroldstyle", + "dollarsuperior", + "ampersandsmall", + "Acutesmall", + "parenleftsuperior", + "parenrightsuperior", + "twodotenleader", + "onedotenleader", + "zerooldstyle", + "oneoldstyle", + "twooldstyle", + "threeoldstyle", + "fouroldstyle", + "fiveoldstyle", + "sixoldstyle", + "sevenoldstyle", + "eightoldstyle", + "nineoldstyle", + "commasuperior", + "threequartersemdash", + "periodsuperior", + "questionsmall", + "asuperior", + "bsuperior", + "centsuperior", + "dsuperior", + "esuperior", + "isuperior", + "lsuperior", + "msuperior", + "nsuperior", + "osuperior", + "rsuperior", + "ssuperior", + "tsuperior", + "ff", + "ffi", + "ffl", + "parenleftinferior", + "parenrightinferior", + "Circumflexsmall", + "hyphensuperior", + "Gravesmall", + "Asmall", + "Bsmall", + "Csmall", + "Dsmall", + "Esmall", + "Fsmall", + "Gsmall", + "Hsmall", + "Ismall", + "Jsmall", + "Ksmall", + "Lsmall", + "Msmall", + "Nsmall", + "Osmall", + "Psmall", + "Qsmall", + "Rsmall", + "Ssmall", + "Tsmall", + "Usmall", + "Vsmall", + "Wsmall", + "Xsmall", + "Ysmall", + "Zsmall", + "colonmonetary", + "onefitted", + "rupiah", + "Tildesmall", + "exclamdownsmall", + "centoldstyle", + "Lslashsmall", + "Scaronsmall", + "Zcaronsmall", + "Dieresissmall", + "Brevesmall", + "Caronsmall", + "Dotaccentsmall", + "Macronsmall", + "figuredash", + "hypheninferior", + "Ogoneksmall", + "Ringsmall", + "Cedillasmall", + "questiondownsmall", + "oneeighth", + "threeeighths", + "fiveeighths", + "seveneighths", + "onethird", + "twothirds", + "zerosuperior", + "foursuperior", + "fivesuperior", + "sixsuperior", + "sevensuperior", + "eightsuperior", + "ninesuperior", + "zeroinferior", + "oneinferior", + "twoinferior", + "threeinferior", + "fourinferior", + "fiveinferior", + "sixinferior", + "seveninferior", + "eightinferior", + "nineinferior", + "centinferior", + "dollarinferior", + "periodinferior", + "commainferior", + "Agravesmall", + "Aacutesmall", + "Acircumflexsmall", + "Atildesmall", + "Adieresissmall", + "Aringsmall", + "AEsmall", + "Ccedillasmall", + "Egravesmall", + "Eacutesmall", + "Ecircumflexsmall", + "Edieresissmall", + "Igravesmall", + "Iacutesmall", + "Icircumflexsmall", + "Idieresissmall", + "Ethsmall", + "Ntildesmall", + "Ogravesmall", + "Oacutesmall", + "Ocircumflexsmall", + "Otildesmall", + "Odieresissmall", + "OEsmall", + "Oslashsmall", + "Ugravesmall", + "Uacutesmall", + "Ucircumflexsmall", + "Udieresissmall", + "Yacutesmall", + "Thornsmall", + "Ydieresissmall", + "001.000", + "001.001", + "001.002", + "001.003", + "Black", + "Bold", + "Book", + "Light", + "Medium", + "Regular", + "Roman", + "Semibold", +} diff --git a/vendor/github.com/go-text/typesetting/font/cff/charstring.go b/vendor/github.com/go-text/typesetting/font/cff/charstring.go new file mode 100644 index 0000000..9cb42f6 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/cff/charstring.go @@ -0,0 +1,315 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package cff + +import ( + "errors" + "fmt" + + ps "github.com/go-text/typesetting/font/cff/interpreter" + ot "github.com/go-text/typesetting/font/opentype" + "github.com/go-text/typesetting/font/opentype/tables" +) + +// LoadGlyph parses the glyph charstring to compute segments and path bounds. +// It returns an error if the glyph is invalid or if decoding the charstring fails. +func (f *CFF) LoadGlyph(glyph tables.GlyphID) ([]ot.Segment, ps.PathBounds, error) { + if int(glyph) >= len(f.Charstrings) { + return nil, ps.PathBounds{}, errGlyph + } + + var ( + psi ps.Machine + loader type2CharstringHandler + index byte = 0 + err error + ) + if f.fdSelect != nil { + index, err = f.fdSelect.fontDictIndex(glyph) + if err != nil { + return nil, ps.PathBounds{}, err + } + } + + subrs := f.localSubrs[index] + err = psi.Run(f.Charstrings[glyph], subrs, f.globalSubrs, &loader) + return loader.cs.Segments, loader.cs.Bounds, err +} + +// type2CharstringHandler implements operators needed to fetch Type2 charstring metrics +type type2CharstringHandler struct { + cs ps.CharstringReader + + // found in private DICT, needed since we can't differenciate + // no width set from 0 width + // `width` must be initialized to default width + nominalWidthX float64 + width float64 +} + +func (type2CharstringHandler) Context() ps.Context { return ps.Type2Charstring } + +func (met *type2CharstringHandler) Apply(state *ps.Machine, op ps.Operator) error { + var err error + if !op.IsEscaped { + switch op.Operator { + case 11: // return + return state.Return() // do not clear the arg stack + case 14: // endchar + if state.ArgStack.Top > 0 { // width is optional + met.width = met.nominalWidthX + state.ArgStack.Vals[0] + } + met.cs.ClosePath() + return ps.ErrInterrupt + case 10: // callsubr + return ps.LocalSubr(state) // do not clear the arg stack + case 29: // callgsubr + return ps.GlobalSubr(state) // do not clear the arg stack + case 21: // rmoveto + if state.ArgStack.Top > 2 { // width is optional + met.width = met.nominalWidthX + state.ArgStack.Vals[0] + } + err = met.cs.Rmoveto(state) + case 22: // hmoveto + if state.ArgStack.Top > 1 { // width is optional + met.width = met.nominalWidthX + state.ArgStack.Vals[0] + } + err = met.cs.Hmoveto(state) + case 4: // vmoveto + if state.ArgStack.Top > 1 { // width is optional + met.width = met.nominalWidthX + state.ArgStack.Vals[0] + } + err = met.cs.Vmoveto(state) + case 1, 18: // hstem, hstemhm + met.cs.Hstem(state) + case 3, 23: // vstem, vstemhm + met.cs.Vstem(state) + case 19, 20: // hintmask, cntrmask + // variable number of arguments, but always even + // for xxxmask, if there are arguments on the stack, then this is an impliied stem + if state.ArgStack.Top&1 != 0 { + met.width = met.nominalWidthX + state.ArgStack.Vals[0] + } + met.cs.Hintmask(state) + // the stack is managed by the previous call + return nil + + case 5: // rlineto + met.cs.Rlineto(state) + case 6: // hlineto + met.cs.Hlineto(state) + case 7: // vlineto + met.cs.Vlineto(state) + case 8: // rrcurveto + met.cs.Rrcurveto(state) + case 24: // rcurveline + err = met.cs.Rcurveline(state) + case 25: // rlinecurve + err = met.cs.Rlinecurve(state) + case 26: // vvcurveto + met.cs.Vvcurveto(state) + case 27: // hhcurveto + met.cs.Hhcurveto(state) + case 30: // vhcurveto + met.cs.Vhcurveto(state) + case 31: // hvcurveto + met.cs.Hvcurveto(state) + default: + // no other operands are allowed before the ones handled above + err = fmt.Errorf("invalid operator %s in charstring", op) + } + } else { + switch op.Operator { + case 34: // hflex + err = met.cs.Hflex(state) + case 35: // flex + err = met.cs.Flex(state) + case 36: // hflex1 + err = met.cs.Hflex1(state) + case 37: // flex1 + err = met.cs.Flex1(state) + default: + // no other operands are allowed before the ones handled above + err = fmt.Errorf("invalid operator %s in charstring", op) + } + } + state.ArgStack.Clear() + return err +} + +// ---------------------------- CFF2 format ---------------------------- + +// LoadGlyph parses the glyph charstring to compute segments and path bounds. +// It returns an error if the glyph is invalid or if decoding the charstring fails. +// +// [coords] must either have the same length as the variations axis, or be empty, +// and be normalized +func (f *CFF2) LoadGlyph(glyph tables.GlyphID, coords []tables.Coord) ([]ot.Segment, ps.PathBounds, error) { + if int(glyph) >= len(f.Charstrings) { + return nil, ps.PathBounds{}, errGlyph + } + + var ( + psi ps.Machine + loader cff2CharstringHandler + index byte = 0 + err error + ) + if f.fdSelect != nil { + index, err = f.fdSelect.fontDictIndex(glyph) + if err != nil { + return nil, ps.PathBounds{}, err + } + } + + font := f.fonts[index] + + loader.coords = coords + loader.vars = f.VarStore + loader.setVSIndex(int(font.defaultVSIndex)) + + err = psi.Run(f.Charstrings[glyph], font.localSubrs, f.globalSubrs, &loader) + + return loader.cs.Segments, loader.cs.Bounds, err +} + +// cff2CharstringHandler implements operators needed to fetch CFF2 charstring metrics +type cff2CharstringHandler struct { + cs ps.CharstringReader + + coords []tables.Coord // normalized variation coordinates + vars tables.ItemVarStore + + // the currently active ItemVariationData subtable (default to 0) + scalars []float32 // computed from the currently active ItemVariationData subtable +} + +func (cff2CharstringHandler) Context() ps.Context { return ps.Type2Charstring } + +func (met *cff2CharstringHandler) setVSIndex(index int) error { + // if the font has variations, always build the scalar + // slice, even if no variations are activated by the user: + // the blend operator needs to know how many args to skip. + if len(met.vars.ItemVariationDatas) == 0 { + return nil + } + + if index >= len(met.vars.ItemVariationDatas) { + return fmt.Errorf("invalid 'vsindex' %d", index) + } + + vars := met.vars.ItemVariationDatas[index] + k := int32(len(vars.RegionIndexes)) // number of regions + met.scalars = append(met.scalars[:0], make([]float32, k)...) + for i, regionIndex := range vars.RegionIndexes { + region := met.vars.VariationRegionList.VariationRegions[regionIndex] + met.scalars[i] = region.Evaluate(met.coords) + } + return nil +} + +func (met *cff2CharstringHandler) blend(state *ps.Machine) error { + // blend requires n*(k+1) + 1 arguments + if state.ArgStack.Top < 1 { + return errors.New("missing n argument for blend operator") + } + n := int32(state.ArgStack.Pop()) + k := int32(len(met.scalars)) + if state.ArgStack.Top < n*(k+1) { + return errors.New("missing arguments for blend operator") + } + + // actually apply the deltas only if the user has activated variations + if len(met.coords) != 0 { + args := state.ArgStack.Vals[state.ArgStack.Top-n*(k+1) : state.ArgStack.Top] + // the first n values are the 'default' arguments + for i := int32(0); i < n; i++ { + baseValue := args[i] + deltas := args[n+i*k : n+(i+1)*k] // all the regions, for one operand + v := 0. + for ik, delta := range deltas { + v += float64(met.scalars[ik]) * delta + } + args[i] = baseValue + v // update the stack with the blended value + } + } + + // clear the stack, keeping only n arguments + state.ArgStack.Top -= n * k + + return nil +} + +func (met *cff2CharstringHandler) Apply(state *ps.Machine, op ps.Operator) error { + var err error + if !op.IsEscaped { + switch op.Operator { + case 1, 18: // hstem, hstemhm + met.cs.Hstem(state) + case 3, 23: // vstem, vstemhm + met.cs.Vstem(state) + case 4: // vmoveto + err = met.cs.Vmoveto(state) + case 5: // rlineto + met.cs.Rlineto(state) + case 6: // hlineto + met.cs.Hlineto(state) + case 7: // vlineto + met.cs.Vlineto(state) + case 8: // rrcurveto + met.cs.Rrcurveto(state) + case 10: // callsubr + return ps.LocalSubr(state) // do not clear the arg stack + case 15: // vsindex + if state.ArgStack.Top < 1 { + return errors.New("missing argument for vsindex operator") + } + err = met.setVSIndex(int(state.ArgStack.Pop())) + case 16: // blend + return met.blend(state) // do not clear the arg stack + case 19, 20: // hintmask, cntrmask + // variable number of arguments, but always even + // for xxxmask, if there are arguments on the stack, then this is an impliied stem + met.cs.Hintmask(state) + // the stack is managed by the previous call + return nil + case 21: // rmoveto + err = met.cs.Rmoveto(state) + case 22: // hmoveto + err = met.cs.Hmoveto(state) + case 24: // rcurveline + err = met.cs.Rcurveline(state) + case 25: // rlinecurve + err = met.cs.Rlinecurve(state) + case 26: // vvcurveto + met.cs.Vvcurveto(state) + case 27: // hhcurveto + met.cs.Hhcurveto(state) + case 29: // callgsubr + return ps.GlobalSubr(state) // do not clear the arg stack + case 30: // vhcurveto + met.cs.Vhcurveto(state) + case 31: // hvcurveto + met.cs.Hvcurveto(state) + default: + // no other operands are allowed before the ones handled above + err = fmt.Errorf("invalid operator %s in charstring", op) + } + } else { + switch op.Operator { + case 34: // hflex + err = met.cs.Hflex(state) + case 35: // flex + err = met.cs.Flex(state) + case 36: // hflex1 + err = met.cs.Hflex1(state) + case 37: // flex1 + err = met.cs.Flex1(state) + default: + // no other operands are allowed before the ones handled above + err = fmt.Errorf("invalid operator %s in charstring", op) + } + } + state.ArgStack.Clear() + return err +} diff --git a/vendor/github.com/go-text/typesetting/font/cff/interpreter/charstrings.go b/vendor/github.com/go-text/typesetting/font/cff/interpreter/charstrings.go new file mode 100644 index 0000000..a33f1fb --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/cff/interpreter/charstrings.go @@ -0,0 +1,586 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package psinterpreter + +import ( + "errors" + "fmt" + "math" + + ot "github.com/go-text/typesetting/font/opentype" +) + +// PathBounds represents a control bounds for +// a glyph outline (in font units). +type PathBounds struct { + Min, Max Point +} + +// Enlarge enlarges the bounds to include pt +func (b *PathBounds) Enlarge(pt Point) { + if pt.X < b.Min.X { + b.Min.X = pt.X + } + if pt.X > b.Max.X { + b.Max.X = pt.X + } + if pt.Y < b.Min.Y { + b.Min.Y = pt.Y + } + if pt.Y > b.Max.Y { + b.Max.Y = pt.Y + } +} + +// ToExtents converts a path bounds to the corresponding glyph extents. +func (b *PathBounds) ToExtents() ot.GlyphExtents { + xBearing, yBearing := math.Round(b.Min.X), math.Round(b.Max.Y) + return ot.GlyphExtents{ + XBearing: float32(xBearing), + YBearing: float32(yBearing), + Width: float32(math.Round(b.Max.X - xBearing)), + Height: float32(math.Round(b.Min.Y - yBearing)), + } +} + +// Point is a 2D Point in font units. +type Point struct{ X, Y float64 } + +// Move translates the Point. +func (p *Point) Move(dx, dy float64) { + p.X += dx + p.Y += dy +} + +func (p Point) toSP() ot.SegmentPoint { + return ot.SegmentPoint{X: float32(p.X), Y: float32(p.Y)} +} + +// CharstringReader provides implementation +// of the operators found in a font charstring. +type CharstringReader struct { + // Acumulated segments for the glyph outlines + Segments []ot.Segment + // Acumulated bounds for the glyph outlines + Bounds PathBounds + + vstemCount int32 + hstemCount int32 + hintmaskSize int32 + + CurrentPoint Point + firstPoint Point // first point in path, required to check if a path is closed + isPathOpen bool + + seenHintmask bool + + // bounds for an empty path is {0,0,0,0} + // however, for the first point in the path, + // we must not compare the coordinates with {0,0,0,0} + seenPoint bool +} + +// enlarges the current bounds to include the Point (x,y). +func (out *CharstringReader) updateBounds(pt Point) { + if !out.seenPoint { + out.Bounds.Min, out.Bounds.Max = pt, pt + out.seenPoint = true + return + } + out.Bounds.Enlarge(pt) +} + +func (out *CharstringReader) Hstem(state *Machine) { + out.hstemCount += state.ArgStack.Top / 2 +} + +func (out *CharstringReader) Vstem(state *Machine) { + out.vstemCount += state.ArgStack.Top / 2 +} + +func (out *CharstringReader) determineHintmaskSize(state *Machine) { + if !out.seenHintmask { + out.vstemCount += state.ArgStack.Top / 2 + out.hintmaskSize = (out.hstemCount + out.vstemCount + 7) >> 3 + out.seenHintmask = true + } +} + +func (out *CharstringReader) Hintmask(state *Machine) { + out.determineHintmaskSize(state) + state.SkipBytes(out.hintmaskSize) +} + +func (out *CharstringReader) move(pt Point) { + out.ensureClosePath() + + out.CurrentPoint.Move(pt.X, pt.Y) + out.isPathOpen = false + out.firstPoint = out.CurrentPoint + out.Segments = append(out.Segments, ot.Segment{ + Op: ot.SegmentOpMoveTo, + Args: [3]ot.SegmentPoint{out.CurrentPoint.toSP()}, + }) +} + +// pt is in absolute coordinates +func (out *CharstringReader) line(pt Point) { + if !out.isPathOpen { + out.isPathOpen = true + out.updateBounds(out.CurrentPoint) + } + out.CurrentPoint = pt + out.updateBounds(pt) + out.Segments = append(out.Segments, ot.Segment{ + Op: ot.SegmentOpLineTo, + Args: [3]ot.SegmentPoint{pt.toSP()}, + }) +} + +func (out *CharstringReader) curve(pt1, pt2, pt3 Point) { + if !out.isPathOpen { + out.isPathOpen = true + out.updateBounds(out.CurrentPoint) + } + /* include control Points */ + out.updateBounds(pt1) + out.updateBounds(pt2) + out.CurrentPoint = pt3 + out.updateBounds(pt3) + out.Segments = append(out.Segments, ot.Segment{ + Op: ot.SegmentOpCubeTo, + Args: [3]ot.SegmentPoint{pt1.toSP(), pt2.toSP(), pt3.toSP()}, + }) +} + +func (out *CharstringReader) doubleCurve(pt1, pt2, pt3, pt4, pt5, pt6 Point) { + out.curve(pt1, pt2, pt3) + out.curve(pt4, pt5, pt6) +} + +func (out *CharstringReader) ensureClosePath() { + if out.firstPoint != out.CurrentPoint { + out.Segments = append(out.Segments, ot.Segment{ + Op: ot.SegmentOpLineTo, + Args: [3]ot.SegmentPoint{out.firstPoint.toSP()}, + }) + } +} + +// ------------------------------------------------------------ + +// LocalSubr pops the subroutine index and call it +func LocalSubr(state *Machine) error { + if state.ArgStack.Top < 1 { + return errors.New("invalid callsubr operator (empty stack)") + } + index := int32(state.ArgStack.Pop()) + return state.CallSubroutine(index, true) +} + +// GlobalSubr pops the subroutine index and call it +func GlobalSubr(state *Machine) error { + if state.ArgStack.Top < 1 { + return errors.New("invalid callgsubr operator (empty stack)") + } + index := int32(state.ArgStack.Pop()) + return state.CallSubroutine(index, false) +} + +// ClosePath closes the current contour, adding +// a segment to the first point if needed. +func (out *CharstringReader) ClosePath() { + out.ensureClosePath() + out.isPathOpen = false +} + +func (out *CharstringReader) Rmoveto(state *Machine) error { + if state.ArgStack.Top < 2 { + return errors.New("invalid rmoveto operator") + } + y := state.ArgStack.Pop() + x := state.ArgStack.Pop() + out.move(Point{x, y}) + return nil +} + +func (out *CharstringReader) Vmoveto(state *Machine) error { + if state.ArgStack.Top < 1 { + return errors.New("invalid vmoveto operator") + } + y := state.ArgStack.Pop() + out.move(Point{0, y}) + return nil +} + +func (out *CharstringReader) Hmoveto(state *Machine) error { + if state.ArgStack.Top < 1 { + return errors.New("invalid hmoveto operator") + } + x := state.ArgStack.Pop() + out.move(Point{x, 0}) + return nil +} + +func (out *CharstringReader) Rlineto(state *Machine) { + for i := int32(0); i+2 <= state.ArgStack.Top; i += 2 { + newPoint := out.CurrentPoint + newPoint.Move(state.ArgStack.Vals[i], state.ArgStack.Vals[i+1]) + out.line(newPoint) + } + state.ArgStack.Clear() +} + +func (out *CharstringReader) Hlineto(state *Machine) { + var i int32 + for ; i+2 <= state.ArgStack.Top; i += 2 { + newPoint := out.CurrentPoint + newPoint.X += state.ArgStack.Vals[i] + out.line(newPoint) + newPoint.Y += state.ArgStack.Vals[i+1] + out.line(newPoint) + } + if i < state.ArgStack.Top { + newPoint := out.CurrentPoint + newPoint.X += state.ArgStack.Vals[i] + out.line(newPoint) + } +} + +func (out *CharstringReader) Vlineto(state *Machine) { + var i int32 + for ; i+2 <= state.ArgStack.Top; i += 2 { + newPoint := out.CurrentPoint + newPoint.Y += state.ArgStack.Vals[i] + out.line(newPoint) + newPoint.X += state.ArgStack.Vals[i+1] + out.line(newPoint) + } + if i < state.ArgStack.Top { + newPoint := out.CurrentPoint + newPoint.Y += state.ArgStack.Vals[i] + out.line(newPoint) + } +} + +// RelativeCurveTo draws a curve with controls points computed from +// the current point and `arg1`, `arg2`, `arg3` +func (out *CharstringReader) RelativeCurveTo(arg1, arg2, arg3 Point) { + pt1 := out.CurrentPoint + pt1.Move(arg1.X, arg1.Y) + pt2 := pt1 + pt2.Move(arg2.X, arg2.Y) + pt3 := pt2 + pt3.Move(arg3.X, arg3.Y) + out.curve(pt1, pt2, pt3) +} + +func (out *CharstringReader) Rrcurveto(state *Machine) { + for i := int32(0); i+6 <= state.ArgStack.Top; i += 6 { + out.RelativeCurveTo( + Point{state.ArgStack.Vals[i], state.ArgStack.Vals[i+1]}, + Point{state.ArgStack.Vals[i+2], state.ArgStack.Vals[i+3]}, + Point{state.ArgStack.Vals[i+4], state.ArgStack.Vals[i+5]}, + ) + } +} + +func (out *CharstringReader) Hhcurveto(state *Machine) { + var ( + i int32 + pt1 = out.CurrentPoint + ) + if (state.ArgStack.Top & 1) != 0 { + pt1.Y += (state.ArgStack.Vals[i]) + i++ + } + for ; i+4 <= state.ArgStack.Top; i += 4 { + pt1.X += state.ArgStack.Vals[i] + pt2 := pt1 + pt2.Move(state.ArgStack.Vals[i+1], state.ArgStack.Vals[i+2]) + pt3 := pt2 + pt3.X += state.ArgStack.Vals[i+3] + out.curve(pt1, pt2, pt3) + pt1 = out.CurrentPoint + } +} + +func (out *CharstringReader) Vhcurveto(state *Machine) { + var i int32 + if (state.ArgStack.Top % 8) >= 4 { + pt1 := out.CurrentPoint + pt1.Y += state.ArgStack.Vals[i] + pt2 := pt1 + pt2.Move(state.ArgStack.Vals[i+1], state.ArgStack.Vals[i+2]) + pt3 := pt2 + pt3.X += state.ArgStack.Vals[i+3] + i += 4 + + for ; i+8 <= state.ArgStack.Top; i += 8 { + out.curve(pt1, pt2, pt3) + pt1 = out.CurrentPoint + pt1.X += (state.ArgStack.Vals[i]) + pt2 = pt1 + pt2.Move(state.ArgStack.Vals[i+1], state.ArgStack.Vals[i+2]) + pt3 = pt2 + pt3.Y += (state.ArgStack.Vals[i+3]) + out.curve(pt1, pt2, pt3) + + pt1 = pt3 + pt1.Y += (state.ArgStack.Vals[i+4]) + pt2 = pt1 + pt2.Move(state.ArgStack.Vals[i+5], state.ArgStack.Vals[i+6]) + pt3 = pt2 + pt3.X += (state.ArgStack.Vals[i+7]) + } + if i < state.ArgStack.Top { + pt3.Y += (state.ArgStack.Vals[i]) + } + out.curve(pt1, pt2, pt3) + } else { + for ; i+8 <= state.ArgStack.Top; i += 8 { + pt1 := out.CurrentPoint + pt1.Y += (state.ArgStack.Vals[i]) + pt2 := pt1 + pt2.Move(state.ArgStack.Vals[i+1], state.ArgStack.Vals[i+2]) + pt3 := pt2 + pt3.X += (state.ArgStack.Vals[i+3]) + out.curve(pt1, pt2, pt3) + + pt1 = pt3 + pt1.X += (state.ArgStack.Vals[i+4]) + pt2 = pt1 + pt2.Move(state.ArgStack.Vals[i+5], state.ArgStack.Vals[i+6]) + pt3 = pt2 + pt3.Y += (state.ArgStack.Vals[i+7]) + if (state.ArgStack.Top-i < 16) && ((state.ArgStack.Top & 1) != 0) { + pt3.X += (state.ArgStack.Vals[i+8]) + } + out.curve(pt1, pt2, pt3) + } + } +} + +func (out *CharstringReader) Hvcurveto(state *Machine) { + var i int32 + if (state.ArgStack.Top % 8) >= 4 { + pt1 := out.CurrentPoint + pt1.X += (state.ArgStack.Vals[i]) + pt2 := pt1 + pt2.Move(state.ArgStack.Vals[i+1], state.ArgStack.Vals[i+2]) + pt3 := pt2 + pt3.Y += (state.ArgStack.Vals[i+3]) + i += 4 + + for ; i+8 <= state.ArgStack.Top; i += 8 { + out.curve(pt1, pt2, pt3) + pt1 = out.CurrentPoint + pt1.Y += (state.ArgStack.Vals[i]) + pt2 = pt1 + pt2.Move(state.ArgStack.Vals[i+1], state.ArgStack.Vals[i+2]) + pt3 = pt2 + pt3.X += (state.ArgStack.Vals[i+3]) + out.curve(pt1, pt2, pt3) + + pt1 = pt3 + pt1.X += state.ArgStack.Vals[i+4] + pt2 = pt1 + pt2.Move(state.ArgStack.Vals[i+5], state.ArgStack.Vals[i+6]) + pt3 = pt2 + pt3.Y += state.ArgStack.Vals[i+7] + } + if i < state.ArgStack.Top { + pt3.X += (state.ArgStack.Vals[i]) + } + out.curve(pt1, pt2, pt3) + } else { + for ; i+8 <= state.ArgStack.Top; i += 8 { + pt1 := out.CurrentPoint + pt1.X += (state.ArgStack.Vals[i]) + pt2 := pt1 + pt2.Move(state.ArgStack.Vals[i+1], state.ArgStack.Vals[i+2]) + pt3 := pt2 + pt3.Y += (state.ArgStack.Vals[i+3]) + out.curve(pt1, pt2, pt3) + + pt1 = pt3 + pt1.Y += (state.ArgStack.Vals[i+4]) + pt2 = pt1 + pt2.Move(state.ArgStack.Vals[i+5], state.ArgStack.Vals[i+6]) + pt3 = pt2 + pt3.X += (state.ArgStack.Vals[i+7]) + if (state.ArgStack.Top-i < 16) && ((state.ArgStack.Top & 1) != 0) { + pt3.Y += state.ArgStack.Vals[i+8] + } + out.curve(pt1, pt2, pt3) + } + } +} + +func (out *CharstringReader) Rcurveline(state *Machine) error { + argCount := state.ArgStack.Top + if argCount < 8 { + return fmt.Errorf("expected at least 8 operands for , got %d", argCount) + } + + var i int32 + curveLimit := argCount - 2 + for ; i+6 <= curveLimit; i += 6 { + pt1 := out.CurrentPoint + pt1.Move(state.ArgStack.Vals[i], state.ArgStack.Vals[i+1]) + pt2 := pt1 + pt2.Move(state.ArgStack.Vals[i+2], state.ArgStack.Vals[i+3]) + pt3 := pt2 + pt3.Move(state.ArgStack.Vals[i+4], state.ArgStack.Vals[i+5]) + out.curve(pt1, pt2, pt3) + } + + pt1 := out.CurrentPoint + pt1.Move(state.ArgStack.Vals[i], state.ArgStack.Vals[i+1]) + out.line(pt1) + + return nil +} + +func (out *CharstringReader) Rlinecurve(state *Machine) error { + argCount := state.ArgStack.Top + if argCount < 8 { + return fmt.Errorf("expected at least 8 operands for , got %d", argCount) + } + var i int32 + lineLimit := argCount - 6 + for ; i+2 <= lineLimit; i += 2 { + pt1 := out.CurrentPoint + pt1.Move(state.ArgStack.Vals[i], state.ArgStack.Vals[i+1]) + out.line(pt1) + } + + pt1 := out.CurrentPoint + pt1.Move(state.ArgStack.Vals[i], state.ArgStack.Vals[i+1]) + pt2 := pt1 + pt2.Move(state.ArgStack.Vals[i+2], state.ArgStack.Vals[i+3]) + pt3 := pt2 + pt3.Move(state.ArgStack.Vals[i+4], state.ArgStack.Vals[i+5]) + out.curve(pt1, pt2, pt3) + + return nil +} + +func (out *CharstringReader) Vvcurveto(state *Machine) { + var i int32 + pt1 := out.CurrentPoint + if (state.ArgStack.Top & 1) != 0 { + pt1.X += state.ArgStack.Vals[i] + i++ + } + for ; i+4 <= state.ArgStack.Top; i += 4 { + pt1.Y += state.ArgStack.Vals[i] + pt2 := pt1 + pt2.Move(state.ArgStack.Vals[i+1], state.ArgStack.Vals[i+2]) + pt3 := pt2 + pt3.Y += state.ArgStack.Vals[i+3] + out.curve(pt1, pt2, pt3) + pt1 = out.CurrentPoint + } +} + +func (out *CharstringReader) Hflex(state *Machine) error { + if state.ArgStack.Top != 7 { + return fmt.Errorf("expected 7 operands for , got %d", state.ArgStack.Top) + } + + pt1 := out.CurrentPoint + pt1.X += state.ArgStack.Vals[0] + pt2 := pt1 + pt2.Move(state.ArgStack.Vals[1], state.ArgStack.Vals[2]) + pt3 := pt2 + pt3.X += state.ArgStack.Vals[3] + pt4 := pt3 + pt4.X += state.ArgStack.Vals[4] + pt5 := pt4 + pt5.X += state.ArgStack.Vals[5] + pt5.Y = pt1.Y + pt6 := pt5 + pt6.X += state.ArgStack.Vals[6] + + out.doubleCurve(pt1, pt2, pt3, pt4, pt5, pt6) + return nil +} + +func (out *CharstringReader) Flex(state *Machine) error { + if state.ArgStack.Top != 13 { + return fmt.Errorf("expected 13 operands for , got %d", state.ArgStack.Top) + } + + pt1 := out.CurrentPoint + pt1.Move(state.ArgStack.Vals[0], state.ArgStack.Vals[1]) + pt2 := pt1 + pt2.Move(state.ArgStack.Vals[2], state.ArgStack.Vals[3]) + pt3 := pt2 + pt3.Move(state.ArgStack.Vals[4], state.ArgStack.Vals[5]) + pt4 := pt3 + pt4.Move(state.ArgStack.Vals[6], state.ArgStack.Vals[7]) + pt5 := pt4 + pt5.Move(state.ArgStack.Vals[8], state.ArgStack.Vals[9]) + pt6 := pt5 + pt6.Move(state.ArgStack.Vals[10], state.ArgStack.Vals[11]) + + out.doubleCurve(pt1, pt2, pt3, pt4, pt5, pt6) + return nil +} + +func (out *CharstringReader) Hflex1(state *Machine) error { + if state.ArgStack.Top != 9 { + return fmt.Errorf("expected 9 operands for , got %d", state.ArgStack.Top) + } + pt1 := out.CurrentPoint + pt1.Move(state.ArgStack.Vals[0], state.ArgStack.Vals[1]) + pt2 := pt1 + pt2.Move(state.ArgStack.Vals[2], state.ArgStack.Vals[3]) + pt3 := pt2 + pt3.X += state.ArgStack.Vals[4] + pt4 := pt3 + pt4.X += state.ArgStack.Vals[5] + pt5 := pt4 + pt5.Move(state.ArgStack.Vals[6], state.ArgStack.Vals[7]) + pt6 := pt5 + pt6.X += state.ArgStack.Vals[8] + pt6.Y = out.CurrentPoint.Y + + out.doubleCurve(pt1, pt2, pt3, pt4, pt5, pt6) + return nil +} + +func (out *CharstringReader) Flex1(state *Machine) error { + if state.ArgStack.Top != 11 { + return fmt.Errorf("expected 11 operands for , got %d", state.ArgStack.Top) + } + + var d Point + for i := 0; i < 10; i += 2 { + d.Move(state.ArgStack.Vals[i], state.ArgStack.Vals[i+1]) + } + + pt1 := out.CurrentPoint + pt1.Move(state.ArgStack.Vals[0], state.ArgStack.Vals[1]) + pt2 := pt1 + pt2.Move(state.ArgStack.Vals[2], state.ArgStack.Vals[3]) + pt3 := pt2 + pt3.Move(state.ArgStack.Vals[4], state.ArgStack.Vals[5]) + pt4 := pt3 + pt4.Move(state.ArgStack.Vals[6], state.ArgStack.Vals[7]) + pt5 := pt4 + pt5.Move(state.ArgStack.Vals[8], state.ArgStack.Vals[9]) + pt6 := pt5 + + if math.Abs(d.X) > math.Abs(d.Y) { + pt6.X += state.ArgStack.Vals[10] + pt6.Y = out.CurrentPoint.Y + } else { + pt6.X = out.CurrentPoint.X + pt6.Y += state.ArgStack.Vals[10] + } + + out.doubleCurve(pt1, pt2, pt3, pt4, pt5, pt6) + return nil +} diff --git a/vendor/github.com/go-text/typesetting/font/cff/interpreter/interpreter.go b/vendor/github.com/go-text/typesetting/font/cff/interpreter/interpreter.go new file mode 100644 index 0000000..a24c635 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/cff/interpreter/interpreter.go @@ -0,0 +1,370 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +// Package psinterpreter implement a Postscript interpreter +// required to parse .CFF files, and Type1 and Type2 Charstrings. +// This package provides the low-level mechanisms needed to +// read such formats; the data is consumed in higher level packages, +// which implement `PsOperatorHandler`. +// It also provides helpers to interpret glyph outline descriptions, +// shared between Type1 and CFF font formats. +// +// See https://adobe-type-tools.github.io/font-tech-notes/pdfs/5177.Type2.pdf +package psinterpreter + +import ( + "encoding/binary" + "errors" + "fmt" + "strconv" +) + +var ( + + // ErrInterrupt signals the interpreter to stop early, without erroring. + ErrInterrupt = errors.New("interruption") + + errInvalidCFFTable = errors.New("invalid ps instructions") + errUnsupportedRealNumberEncoding = errors.New("unsupported real number encoding") + + be = binary.BigEndian +) + +const ( + // psArgStackSize is the argument stack size for a PostScript interpreter, + // set to 513 in CFF2 + // See https://learn.microsoft.com/en-us/typography/opentype/spec/cff2#appendixD + psArgStackSize = 513 + + // Similarly, Appendix B says "Subr nesting, stack limit 10". + psCallStackSize = 10 + + maxRealNumberStrLen = 64 // Maximum length in bytes of the "-123.456E-7" representation. +) + +// Context is the flavour of the Postcript language. +type Context uint32 + +const ( + TopDict Context = iota // Top dict in CFF files + PrivateDict // Private dict in CFF files + Type2Charstring // Charstring in CFF files + Type1Charstring // Charstring in Type1 font files +) + +type ArgStack struct { + Vals [psArgStackSize]float64 // we have to use float64 to properly store floats and int32 values + // Effecive size currently in use. The first value to + // pop is at index Top-1 + Top int32 +} + +// Uint16 returns the top level value as uint16, +// without popping the stack. +func (a *ArgStack) Uint16() uint16 { return uint16(a.Vals[a.Top-1]) } + +// Pop returns the top level value and decrease `Top` +// It will panic if the stack is empty. +func (a *ArgStack) Pop() float64 { + a.Top-- + return a.Vals[a.Top] +} + +// Clear clears the stack +func (a *ArgStack) Clear() { a.Top = 0 } + +// PopN check and remove the n top levels entries. +// Passing a negative `numPop` clears all the stack. +func (a *ArgStack) PopN(numPop int32) error { + if a.Top < numPop { + return fmt.Errorf("invalid number of operands in PS stack: %d", numPop) + } + if numPop < 0 { // pop all + a.Top = 0 + } else { + a.Top -= numPop + } + return nil +} + +// Machine is a PostScript interpreter. +// A same interpreter may be re-used using muliples `Run` calls. +type Machine struct { + localSubrs [][]byte + globalSubrs [][]byte + + instructions []byte + + callStack struct { + vals [psCallStackSize][]byte // parent instructions + top int32 // effecive size currently in use + } + ArgStack ArgStack + + parseNumberBuf [maxRealNumberStrLen]byte + ctx Context +} + +// SkipBytes skips the next `count` bytes from the instructions, and clears the argument stack. +// It does nothing if `count` exceed the length of the instructions. +func (p *Machine) SkipBytes(count int32) { + if int(count) >= len(p.instructions) { + return + } + p.instructions = p.instructions[count:] + p.ArgStack.Clear() +} + +// 5176.CFF.pdf section 4 "DICT Data" says that "Two-byte operators have an +// initial escape byte of 12". +const escapeByte = 12 + +// Run runs the instructions in the PostScript context asked by `handler`. +// `localSubrs` and `globalSubrs` contains the subroutines that may be called in the instructions. +func (p *Machine) Run(instructions []byte, localSubrs, globalSubrs [][]byte, handler OperatorHandler) error { + p.ctx = handler.Context() + p.instructions = instructions + p.localSubrs = localSubrs + p.globalSubrs = globalSubrs + p.ArgStack.Top = 0 + p.callStack.top = 0 + + for len(p.instructions) > 0 { + // Push a numeric operand on the stack, if applicable. + if hasResult, err := p.parseNumber(); hasResult { + if err != nil { + return err + } + continue + } + + // Otherwise, execute an operator. + b := p.instructions[0] + p.instructions = p.instructions[1:] + + // check for the escape byte + escaped := b == escapeByte + if escaped { + if len(p.instructions) <= 0 { + return errInvalidCFFTable + } + b = p.instructions[0] + p.instructions = p.instructions[1:] + } + + err := handler.Apply(p, Operator{Operator: b, IsEscaped: escaped}) + if err == ErrInterrupt { // stop cleanly + return nil + } + if err != nil { + return err + } + + } + return nil +} + +// See 5176.CFF.pdf section 4 "DICT Data". +func (p *Machine) parseNumber() (hasResult bool, err error) { + number := 0. + switch b := p.instructions[0]; { + case b == 28: + if len(p.instructions) < 3 { + return true, errInvalidCFFTable + } + number, hasResult = float64(int16(be.Uint16(p.instructions[1:]))), true + p.instructions = p.instructions[3:] + + case b == 29 && p.ctx != Type2Charstring: + if len(p.instructions) < 5 { + return true, errInvalidCFFTable + } + number, hasResult = float64(int32(be.Uint32(p.instructions[1:]))), true + p.instructions = p.instructions[5:] + + case b == 30 && p.ctx != Type2Charstring && p.ctx != Type1Charstring: + // Parse a real number. This isn't listed in 5176.CFF.pdf Table 3 + // "Operand Encoding" but that table lists integer encodings. Further + // down the page it says "A real number operand is provided in addition + // to integer operands. This operand begins with a byte value of 30 + // followed by a variable-length sequence of bytes." + + s := p.parseNumberBuf[:0] + p.instructions = p.instructions[1:] + loop: + for { + if len(p.instructions) == 0 { + return true, errInvalidCFFTable + } + by := p.instructions[0] + p.instructions = p.instructions[1:] + // Process by's two nibbles, high then low. + for i := 0; i < 2; i++ { + nib := by >> 4 + by = by << 4 + if nib == 0x0f { + f, err := strconv.ParseFloat(string(s), 32) + if err != nil { + return true, errInvalidCFFTable + } + number, hasResult = float64(f), true + break loop + } + if nib == 0x0d { + return true, errInvalidCFFTable + } + if len(s)+maxNibbleDefsLength > len(p.parseNumberBuf) { + return true, errUnsupportedRealNumberEncoding + } + s = append(s, nibbleDefs[nib]...) + } + } + + case b < 32: + // not a number: no-op. + case b < 247: + p.instructions = p.instructions[1:] + number, hasResult = float64(b)-139, true + case b < 251: + if len(p.instructions) < 2 { + return true, errInvalidCFFTable + } + b1 := p.instructions[1] + p.instructions = p.instructions[2:] + number, hasResult = float64(+int32(b-247)*256+int32(b1)+108), true + case b < 255: + if len(p.instructions) < 2 { + return true, errInvalidCFFTable + } + b1 := p.instructions[1] + p.instructions = p.instructions[2:] + number, hasResult = float64(-int32(b-251)*256-int32(b1)-108), true + case b == 255 && (p.ctx == Type2Charstring || p.ctx == Type1Charstring): + if len(p.instructions) < 5 { + return true, errInvalidCFFTable + } + intValue := int32(be.Uint32(p.instructions[1:])) + if p.ctx == Type2Charstring { + // 5177.Type2.pdf section 3.2 "Charstring Number Encoding" says "If the + // charstring byte contains the value 255... [this] number is + // interpreted as a Fixed; that is, a signed number with 16 bits of + // fraction". + // + // we just round the 16.16 fixed point number to the closest integer value + number = float64(intValue) / (1 << 16) + hasResult = true + } else { + number, hasResult = float64(intValue), true + } + p.instructions = p.instructions[5:] + } + + if hasResult { + if p.ArgStack.Top == psArgStackSize { + return true, errInvalidCFFTable + } + p.ArgStack.Vals[p.ArgStack.Top] = number + p.ArgStack.Top++ + } + return hasResult, nil +} + +const maxNibbleDefsLength = len("E-") + +// nibbleDefs encodes 5176.CFF.pdf Table 5 "Nibble Definitions". +var nibbleDefs = [16]string{ + 0x00: "0", + 0x01: "1", + 0x02: "2", + 0x03: "3", + 0x04: "4", + 0x05: "5", + 0x06: "6", + 0x07: "7", + 0x08: "8", + 0x09: "9", + 0x0a: ".", + 0x0b: "E", + 0x0c: "E-", + 0x0d: "", + 0x0e: "-", + 0x0f: "", +} + +// subrBias returns the subroutine index bias as per 5177.Type2.pdf section 4.7 +// "Subroutine Operators". +func subrBias(numSubroutines int) int32 { + if numSubroutines < 1240 { + return 107 + } + if numSubroutines < 33900 { + return 1131 + } + return 32768 +} + +// CallSubroutine calls the subroutine, identified by its index, as found +// in the instructions (that is, before applying the subroutine biased). +// `isLocal` controls whether the local or global subroutines are used. +// No argument stack modification is performed. +func (p *Machine) CallSubroutine(index int32, isLocal bool) error { + subrs := p.globalSubrs + if isLocal { + subrs = p.localSubrs + } + + // no bias in type1 fonts + if p.ctx == Type2Charstring { + index += subrBias(len(subrs)) + } + + if index < 0 || int(index) >= len(subrs) { + return fmt.Errorf("invalid subroutine index %d (for length %d)", index, len(subrs)) + } + if p.callStack.top == psCallStackSize { + return errors.New("maximum call stack size reached") + } + // save the current instructions + p.callStack.vals[p.callStack.top] = p.instructions + p.callStack.top++ + + // activate the subroutine + p.instructions = subrs[index] + return nil +} + +// Return returns from a subroutine call. +func (p *Machine) Return() error { + if p.callStack.top <= 0 { + return errors.New("no subroutine has been called") + } + p.callStack.top-- + // restore the previous instructions + p.instructions = p.callStack.vals[p.callStack.top] + return nil +} + +// Operator is a postcript command, which may be escaped. +type Operator struct { + Operator byte + IsEscaped bool +} + +func (p Operator) String() string { + if p.IsEscaped { + return fmt.Sprintf("2-byte operator (12 %d)", p.Operator) + } + return fmt.Sprintf("1-byte operator (%d)", p.Operator) +} + +// OperatorHandler defines the behaviour of an operator. +type OperatorHandler interface { + // Context defines the precise behaviour of the interpreter, + // which has small nuances depending on the context. + Context() Context + + // Apply implements the operator defined by `operator` (which is the second byte if `escaped` is true). + // + // Returning `ErrInterrupt` stop the parsing of the instructions, without reporting an error. + // It can be used as an optimization. + Apply(state *Machine, operator Operator) error +} diff --git a/vendor/github.com/go-text/typesetting/font/cff/parser.go b/vendor/github.com/go-text/typesetting/font/cff/parser.go new file mode 100644 index 0000000..7bb78bd --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/cff/parser.go @@ -0,0 +1,709 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package cff + +// code is adapted from golang.org/x/image/font/sfnt + +import ( + "encoding/binary" + "errors" + "fmt" + + ps "github.com/go-text/typesetting/font/cff/interpreter" + "github.com/go-text/typesetting/font/opentype" +) + +var errUnsupportedCFFVersion = errors.New("unsupported CFF version") + +// CFF represents a parsed CFF font, as found in the 'CFF ' Opentype table. +type CFF struct { + userStrings userStrings + fdSelect fdSelect // only valid for CIDFonts + charset []uint16 // indexed by glyph ID + + cidFontName string + + // Charstrings contains the actual glyph definition. + // It has a length of numGlyphs and is indexed by glyph ID. + // See `LoadGlyph` for a way to intepret the glyph data. + Charstrings [][]byte + + fontName []byte // name from the Name INDEX + globalSubrs [][]byte + + // array of length 1 for non CIDFonts + // For CIDFonts, it can be safely indexed by `fdSelect` output + localSubrs [][][]byte +} + +// Parse parses a .cff font file. +// Although CFF enables multiple font or CIDFont programs to be bundled together in a +// single file, embedded CFF font file in PDF or in TrueType/OpenType fonts +// shall consist of exactly one font or CIDFont. Thus, this function +// returns an error if the file contains more than one font. +func Parse(file []byte) (*CFF, error) { + // read 4 bytes to check if its a supported CFF file + if L := len(file); L < 4 { + return nil, fmt.Errorf("EOF: expected length: %d, got %d", 4, L) + } + if file[0] != 1 || file[1] != 0 || file[2] != 4 { + return nil, errUnsupportedCFFVersion + } + p := cffParser{src: file, offset: 4} + out, err := p.parse() + if err != nil { + return nil, err + } + + if len(out) > 1 { + return nil, errors.New("only one font is allowed CFF table") + } + + return &out[0], nil +} + +// GlyphName returns the name of the glyph or an empty string if not found. +func (f *CFF) GlyphName(glyph opentype.GID) string { + if f.fdSelect != nil || int(glyph) >= len(f.charset) { + return "" + } + out, _ := f.userStrings.getString(f.charset[glyph]) + return out +} + +// since SID = 0 means .notdef, we use a reserved value +// to mean unset +const unsetSID = uint16(0xFFFF) + +type userStrings [][]byte + +// return either the predefined string or the user defined one +func (u userStrings) getString(sid uint16) (string, error) { + if sid == unsetSID { + return "", nil + } + if sid < 391 { + return stdStrings[sid], nil + } + sid -= 391 + if int(sid) >= len(u) { + return "", fmt.Errorf("invalid glyph index %d", sid) + } + return string(u[sid]), nil +} + +// Compact Font Format (CFF) fonts are written in PostScript, a stack-based +// programming language. +// +// A fundamental concept is a DICT, or a key-value map, expressed in reverse +// Polish notation. For example, this sequence of operations: +// - push the number 379 +// - version operator +// - push the number 392 +// - Notice operator +// - etc +// - push the number 100 +// - push the number 0 +// - push the number 500 +// - push the number 800 +// - FontBBox operator +// - etc +// +// defines a DICT that maps "version" to the String ID (SID) 379, "Notice" to +// the SID 392, "FontBBox" to the four numbers [100, 0, 500, 800], etc. +// +// The first 391 String IDs (starting at 0) are predefined as per the CFF spec +// Appendix A, in 5176.CFF.pdf referenced below. For example, 379 means +// "001.000". String ID 392 is not predefined, and is mapped by a separate +// structure, the "String INDEX", inside the CFF data. (String ID 391 is also +// not predefined. Specifically for go-opentype-testdata/data/toys/CFFTest.otf, 391 means +// "uni4E2D", as this font contains a glyph for U+4E2D). +// +// The actual glyph vectors are similarly encoded (in PostScript), in a format +// called Type 2 Charstrings. The wire encoding is similar to but not exactly +// the same as CFF's. For example, the byte 0x05 means FontBBox for CFF DICTs, +// but means rlineto (relative line-to) for Type 2 Charstrings. See +// 5176.CFF.pdf Appendix H and 5177.Type2.pdf Appendix A in the PDF files +// referenced below. +// +// The relevant specifications are: +// - http://wwwimages.adobe.com/content/dam/Adobe/en/devnet/font/pdfs/5176.CFF.pdf +// - http://wwwimages.adobe.com/content/dam/Adobe/en/devnet/font/pdfs/5177.Type2.pdf +type cffParser struct { + src []byte // whole input + offset int // current position +} + +func (p *cffParser) parse() ([]CFF, error) { + // header was checked prior to this call + + // Parse the Name INDEX. + fontNames, err := p.parseNames() + if err != nil { + return nil, err + } + + topDicts, err := p.parseTopDicts() + if err != nil { + return nil, err + } + // 5176.CFF.pdf section 8 "Top DICT INDEX" says that the count here + // should match the count of the Name INDEX + if len(topDicts) != len(fontNames) { + return nil, fmt.Errorf("top DICT length doest not match Names (%d, %d)", len(topDicts), + len(fontNames)) + } + + // parse the String INDEX. + strs, err := p.parseUserStrings() + if err != nil { + return nil, err + } + + out := make([]CFF, len(topDicts)) + + // use the strings to fetch the PSInfo + for i, topDict := range topDicts { + out[i].fontName = fontNames[i] + out[i].userStrings = strs + + // skip PSInfo, and cidFontName + + out[i].cidFontName, err = strs.getString(topDict.cidFontName) + if err != nil { + return nil, err + } + } + + // Parse the Global Subrs [Subroutines] INDEX, + // shared among all fonts. + globalSubrs, err := p.parseIndex() + if err != nil { + return nil, err + } + + for i, topDict := range topDicts { + out[i].globalSubrs = globalSubrs + + // Parse the CharStrings INDEX, whose location was found in the Top DICT. + if err = p.seek(topDict.charStringsOffset); err != nil { + return nil, err + } + out[i].Charstrings, err = p.parseIndex() + if err != nil { + return nil, err + } + numGlyphs := uint16(len(out[i].Charstrings)) + + out[i].charset, err = p.parseCharset(topDict.charsetOffset, numGlyphs) + if err != nil { + return nil, err + } + + // skip encoding + + if !topDict.isCIDFont { + // Parse the Private DICT, whose location was found in the Top DICT. + var localSubrs [][]byte + localSubrs, err = p.parsePrivateDICT(topDict.privateDictOffset, topDict.privateDictLength) + if err != nil { + return nil, err + } + out[i].localSubrs = [][][]byte{localSubrs} + } else { + // Parse the Font Dict Select data, whose location was found in the Top + // DICT. + out[i].fdSelect, err = p.parseFDSelect(topDict.fdSelect, numGlyphs) + if err != nil { + return nil, err + } + indexExtent := out[i].fdSelect.extent() + + // Parse the Font Dicts. Each one contains its own Private DICT. + if err = p.seek(topDict.fdArray); err != nil { + return nil, err + } + topDicts, err := p.parseTopDicts() + if err != nil { + return nil, err + } + if len(topDicts) < indexExtent { + return nil, fmt.Errorf("invalid number of font dicts: %d (for %d)", + len(topDicts), indexExtent) + } + multiSubrs := make([][][]byte, len(topDicts)) + for i, topDict := range topDicts { + multiSubrs[i], err = p.parsePrivateDICT(topDict.privateDictOffset, topDict.privateDictLength) + if err != nil { + return nil, err + } + } + out[i].localSubrs = multiSubrs + } + } + + return out, nil +} + +func (p *cffParser) parseTopDicts() ([]topDict, error) { + // Parse the Top DICT INDEX. + instructions, err := p.parseIndex() + if err != nil { + return nil, err + } + + out := make([]topDict, len(instructions)) // guarded by uint16 max size + var psi ps.Machine + for i, buf := range instructions { + topDict := &out[i] + + // set default value before parsing + topDict.underlinePosition = -100 + topDict.underlineThickness = 50 + topDict.version = unsetSID + topDict.notice = unsetSID + topDict.fullName = unsetSID + topDict.familyName = unsetSID + topDict.weight = unsetSID + topDict.cidFontName = unsetSID + + if err = psi.Run(buf, nil, nil, topDict); err != nil { + return nil, err + } + } + return out, nil +} + +// src does NOT includes header, but starts at the array offset +// also returns the length read from 'src' +func parseIndexContent(src []byte, header indexStart) ([][]byte, int, error) { + if header.count == 0 { + return nil, 0, nil + } + oSize := int(header.offSize) + offsetArraySize := int(header.count+1) * oSize + if L := len(src); L < offsetArraySize { + return nil, 0, fmt.Errorf("reading INDEX offsets: EOF: expected length: %d, got %d", offsetArraySize, L) + } + out := make([][]byte, header.count) + data := src[offsetArraySize:] + + prev := 0 + for i := range out { + // In the same paragraph, "Therefore the first element of the offset + // array is always 1" before correcting for the off-by-1. + loc := int(bigEndian(src[(i+1)*oSize : (i+2)*oSize])) + + // Locations are off by 1 byte. 5176.CFF.pdf section 5 "INDEX Data" + // says that "Offsets in the offset array are relative to the byte that + // precedes the object data... This ensures that every object has a + // corresponding offset which is always nonzero". + if loc == 0 { + return nil, 0, errors.New("invalid INDEX locations (0)") + } + loc-- + + if loc < prev { // Check that locations are increasing + return nil, 0, errors.New("invalid INDEX locations (not increasing)") + } + + // Check that locations are in bounds, that is offsetsLength + loc <= len(src) + if int(loc) > len(data) { + return nil, 0, errors.New("invalid INDEX locations (out of bounds)") + } + + out[i] = data[prev:loc] + prev = loc + } + return out, offsetArraySize + prev, nil +} + +// parse the general form of an index +func (p *cffParser) parseIndex() ([][]byte, error) { + count, offSize, err := p.parseIndexHeader() + if err != nil { + return nil, err + } + + out, read, err := parseIndexContent(p.src[p.offset:], indexStart{count: uint32(count), offSize: offSize}) + p.offset += read + + return out, err +} + +// parse the Name INDEX +func (p *cffParser) parseNames() ([][]byte, error) { + return p.parseIndex() +} + +// parse the String INDEX +func (p *cffParser) parseUserStrings() (userStrings, error) { + index, err := p.parseIndex() + return userStrings(index), err +} + +// Parse the charset data, whose location was found in the Top DICT. +func (p *cffParser) parseCharset(charsetOffset int32, numGlyphs uint16) ([]uint16, error) { + // Predefined charset may have offset of 0 to 2 // Table 22 + var charset []uint16 + switch charsetOffset { + case 0: // ISOAdobe + charset = charsetISOAdobe[:] + case 1: // Expert + charset = charsetExpert[:] + case 2: // ExpertSubset + charset = charsetExpertSubset[:] + default: // custom + if err := p.seek(charsetOffset); err != nil { + return nil, err + } + buf, err := p.read(1) + if err != nil { + return nil, err + } + charset = make([]uint16, numGlyphs) + switch buf[0] { // format + case 0: + buf, err = p.read(2 * (int(numGlyphs) - 1)) // ".notdef" is omited, and has an implicit SID of 0 + if err != nil { + return nil, err + } + for i := uint16(1); i < numGlyphs; i++ { + charset[i] = binary.BigEndian.Uint16(buf[2*i-2:]) + } + case 1: + for i := uint16(1); i < numGlyphs; { + buf, err = p.read(3) + if err != nil { + return nil, err + } + first, nLeft := binary.BigEndian.Uint16(buf), uint16(buf[2]) + for j := uint16(0); j <= nLeft && i < numGlyphs; j++ { + charset[i] = first + j + i++ + } + } + case 2: + for i := uint16(1); i < numGlyphs; { + buf, err = p.read(4) + if err != nil { + return nil, err + } + first, nLeft := binary.BigEndian.Uint16(buf), binary.BigEndian.Uint16(buf[2:]) + for j := uint16(0); j <= nLeft && i < numGlyphs; j++ { + charset[i] = first + j + i++ + } + } + default: + return nil, fmt.Errorf("invalid custom charset format %d", buf[0]) + } + } + return charset, nil +} + +// parseFDSelect parses the Font Dict Select data as per 5176.CFF.pdf section +// 19 "FDSelect". +func (p *cffParser) parseFDSelect(offset int32, numGlyphs uint16) (fdSelect, error) { + if err := p.seek(offset); err != nil { + return nil, err + } + out, _, err := parseFdSelect(p.src[offset:], int(numGlyphs)) + if err != nil { + return nil, err + } + return out, err +} + +// Parse Private DICT and the Local Subrs [Subroutines] INDEX +func (p *cffParser) parsePrivateDICT(offset, length int32) ([][]byte, error) { + if length == 0 { + return nil, nil + } + if err := p.seek(offset); err != nil { + return nil, err + } + buf, err := p.read(int(length)) + if err != nil { + return nil, err + } + var ( + psi ps.Machine + priv privateDict + ) + if err = psi.Run(buf, nil, nil, &priv); err != nil { + return nil, err + } + + if priv.subrsOffset == 0 { + return nil, nil + } + + // "The local subrs offset is relative to the beginning of the Private DICT data" + if err = p.seek(offset + priv.subrsOffset); err != nil { + return nil, errors.New("invalid local subroutines offset") + } + subrs, err := p.parseIndex() + if err != nil { + return nil, err + } + return subrs, nil +} + +// read returns the n bytes from p.offset and advances p.offset by n. +func (p *cffParser) read(n int) ([]byte, error) { + if n < 0 || len(p.src) < p.offset+n { + return nil, errors.New("invalid CFF font file (EOF)") + } + out := p.src[p.offset : p.offset+n] + p.offset += n + return out, nil +} + +func (p *cffParser) seek(offset int32) error { + if offset < 0 || len(p.src) < int(offset) { + return errors.New("invalid CFF font file (EOF)") + } + p.offset = int(offset) + return nil +} + +func bigEndian(b []byte) uint32 { + switch len(b) { + case 1: + return uint32(b[0]) + case 2: + return uint32(b[0])<<8 | uint32(b[1]) + case 3: + return uint32(b[0])<<16 | uint32(b[1])<<8 | uint32(b[2]) + case 4: + return uint32(b[0])<<24 | uint32(b[1])<<16 | uint32(b[2])<<8 | uint32(b[3]) + } + panic("unreachable") +} + +func (p *cffParser) parseIndexHeader() (count uint16, offSize uint8, err error) { + buf, err := p.read(2) + if err != nil { + return 0, 0, err + } + count = binary.BigEndian.Uint16(buf) + // 5176.CFF.pdf section 5 "INDEX Data" says that "An empty INDEX is + // represented by a count field with a 0 value and no additional fields. + // Thus, the total size of an empty INDEX is 2 bytes". + if count == 0 { + return count, 0, nil + } + buf, err = p.read(1) + if err != nil { + return 0, 0, err + } + offSize = buf[0] + if offSize < 1 || 4 < offSize { + return 0, 0, fmt.Errorf("invalid offset size %d", offSize) + } + return count, offSize, nil +} + +// topDict contains fields specific to the Top DICT context. +type topDict struct { + // SIDs, to be decoded using the string index + version, notice, fullName, familyName, weight uint16 + isFixedPitch bool + italicAngle, underlinePosition, underlineThickness float32 + charsetOffset int32 + encodingOffset int32 + charStringsOffset int32 + fdArray int32 + fdSelect int32 + isCIDFont bool + cidFontName uint16 + privateDictOffset int32 + privateDictLength int32 +} + +func (tp *topDict) Context() ps.Context { return ps.TopDict } + +func (tp *topDict) Apply(state *ps.Machine, op ps.Operator) error { + ops := topDictOperators[0] + if op.IsEscaped { + ops = topDictOperators[1] + } + if int(op.Operator) >= len(ops) { + return fmt.Errorf("invalid operator %s in Top Dict", op) + } + opFunc := ops[op.Operator] + if opFunc.run == nil { + return fmt.Errorf("invalid operator %s in Top Dict", op) + } + if state.ArgStack.Top < opFunc.numPop { + return fmt.Errorf("invalid number of arguments for operator %s in Top Dict", op) + } + err := opFunc.run(tp, state) + if err != nil { + return err + } + err = state.ArgStack.PopN(opFunc.numPop) + return err +} + +// The Top DICT operators are defined by 5176.CFF.pdf Table 9 "Top DICT +// Operator Entries" and Table 10 "CIDFont Operator Extensions". +type topDictOperator struct { + // run is the function that implements the operator. Nil means that we + // ignore the operator, other than popping its arguments off the stack. + run func(*topDict, *ps.Machine) error + + // numPop is the number of stack values to pop. -1 means "array" and -2 + // means "delta" as per 5176.CFF.pdf Table 6 "Operand Types". + numPop int32 +} + +func topDictNoOp(*topDict, *ps.Machine) error { return nil } + +var topDictOperators = [2][]topDictOperator{ + // 1-byte operators. + { + 0: {func(t *topDict, s *ps.Machine) error { + t.version = s.ArgStack.Uint16() + return nil + }, +1 /*version*/}, + 1: {func(t *topDict, s *ps.Machine) error { + t.notice = s.ArgStack.Uint16() + return nil + }, +1 /*Notice*/}, + 2: {func(t *topDict, s *ps.Machine) error { + t.fullName = s.ArgStack.Uint16() + return nil + }, +1 /*FullName*/}, + 3: {func(t *topDict, s *ps.Machine) error { + t.familyName = s.ArgStack.Uint16() + return nil + }, +1 /*FamilyName*/}, + 4: {func(t *topDict, s *ps.Machine) error { + t.weight = s.ArgStack.Uint16() + return nil + }, +1 /*Weight*/}, + 5: {topDictNoOp, -1 /*FontBBox*/}, + 13: {topDictNoOp, +1 /*UniqueID*/}, + 14: {topDictNoOp, -1 /*XUID*/}, + 15: {func(t *topDict, s *ps.Machine) error { + t.charsetOffset = int32(s.ArgStack.Vals[s.ArgStack.Top-1]) + return nil + }, +1 /*charset*/}, + 16: {func(t *topDict, s *ps.Machine) error { + t.encodingOffset = int32(s.ArgStack.Vals[s.ArgStack.Top-1]) + return nil + }, +1 /*Encoding*/}, + 17: {func(t *topDict, s *ps.Machine) error { + t.charStringsOffset = int32(s.ArgStack.Vals[s.ArgStack.Top-1]) + return nil + }, +1 /*CharStrings*/}, + 18: {func(t *topDict, s *ps.Machine) error { + t.privateDictLength = int32(s.ArgStack.Vals[s.ArgStack.Top-2]) + t.privateDictOffset = int32(s.ArgStack.Vals[s.ArgStack.Top-1]) + return nil + }, +2 /*Private*/}, + }, + // 2-byte operators. The first byte is the escape byte. + { + 0: {topDictNoOp, +1 /*Copyright*/}, + 1: {func(t *topDict, s *ps.Machine) error { + t.isFixedPitch = s.ArgStack.Vals[s.ArgStack.Top-1] == 1 + return nil + }, +1 /*isFixedPitch*/}, + 2: {func(t *topDict, s *ps.Machine) error { + t.italicAngle = float32(s.ArgStack.Vals[s.ArgStack.Top-1]) + return nil + }, +1 /*ItalicAngle*/}, + 3: {func(t *topDict, s *ps.Machine) error { + t.underlinePosition = float32(s.ArgStack.Vals[s.ArgStack.Top-1]) + return nil + }, +1 /*UnderlinePosition*/}, + 4: {func(t *topDict, s *ps.Machine) error { + t.underlineThickness = float32(s.ArgStack.Vals[s.ArgStack.Top-1]) + return nil + }, +1 /*UnderlineThickness*/}, + 5: {topDictNoOp, +1 /*PaintType*/}, + 6: {func(_ *topDict, i *ps.Machine) error { + if version := int(i.ArgStack.Vals[i.ArgStack.Top-1]); version != 2 { + return fmt.Errorf("charstring type %d not supported", version) + } + return nil + }, +1 /*CharstringType*/}, + 7: {topDictNoOp, -1 /*FontMatrix*/}, + 8: {topDictNoOp, +1 /*StrokeWidth*/}, + 20: {topDictNoOp, +1 /*SyntheticBase*/}, + 21: {topDictNoOp, +1 /*PostScript*/}, + 22: {topDictNoOp, +1 /*BaseFontName*/}, + 23: {topDictNoOp, -2 /*BaseFontBlend*/}, + 30: {func(t *topDict, _ *ps.Machine) error { + t.isCIDFont = true + return nil + }, +3 /*ROS*/}, + 31: {topDictNoOp, +1 /*CIDFontVersion*/}, + 32: {topDictNoOp, +1 /*CIDFontRevision*/}, + 33: {topDictNoOp, +1 /*CIDFontType*/}, + 34: {topDictNoOp, +1 /*CIDCount*/}, + 35: {topDictNoOp, +1 /*UIDBase*/}, + 36: {func(t *topDict, s *ps.Machine) error { + t.fdArray = int32(s.ArgStack.Vals[s.ArgStack.Top-1]) + return nil + }, +1 /*FDArray*/}, + 37: {func(t *topDict, s *ps.Machine) error { + t.fdSelect = int32(s.ArgStack.Vals[s.ArgStack.Top-1]) + return nil + }, +1 /*FDSelect*/}, + 38: {func(t *topDict, s *ps.Machine) error { + t.cidFontName = s.ArgStack.Uint16() + return nil + }, +1 /*FontName*/}, + }, +} + +// privateDict contains fields specific to the Private DICT context. +type privateDict struct { + subrsOffset int32 + defaultWidthX, nominalWidthX float64 +} + +func (privateDict) Context() ps.Context { return ps.PrivateDict } + +// The Private DICT operators are defined by 5176.CFF.pdf Table 23 "Private +// DICT Operators". +func (priv *privateDict) Apply(state *ps.Machine, op ps.Operator) error { + if !op.IsEscaped { // 1-byte operators. + switch op.Operator { + case 6, 7, 8, 9: // "BlueValues" "OtherBlues" "FamilyBlues" "FamilyOtherBlues" + return state.ArgStack.PopN(-2) + case 10, 11: // "StdHW" "StdVW" + return state.ArgStack.PopN(1) + case 20: // "defaultWidthX" + if state.ArgStack.Top < 1 { + return errors.New("invalid stack size for 'defaultWidthX' in private Dict charstring") + } + priv.defaultWidthX = state.ArgStack.Vals[state.ArgStack.Top-1] + return state.ArgStack.PopN(1) + case 21: // "nominalWidthX" + if state.ArgStack.Top < 1 { + return errors.New("invalid stack size for 'nominalWidthX' in private Dict charstring") + } + priv.nominalWidthX = state.ArgStack.Vals[state.ArgStack.Top-1] + return state.ArgStack.PopN(1) + case 19: // "Subrs" pop 1 + if state.ArgStack.Top < 1 { + return errors.New("invalid stack size for 'subrs' in private Dict charstring") + } + priv.subrsOffset = int32(state.ArgStack.Vals[state.ArgStack.Top-1]) + return state.ArgStack.PopN(1) + } + } else { // 2-byte operators. The first byte is the escape byte. + switch op.Operator { + case 9, 10, 11, 14, 17, 18, 19: // "BlueScale" "BlueShift" "BlueFuzz" "ForceBold" "LanguageGroup" "ExpansionFactor" "initialRandomSeed" + return state.ArgStack.PopN(1) + case 12, 13: // "StemSnapH" "StemSnapV" + return state.ArgStack.PopN(-2) + } + } + return errors.New("invalid operand in private Dict charstring") +} diff --git a/vendor/github.com/go-text/typesetting/font/cmap.go b/vendor/github.com/go-text/typesetting/font/cmap.go new file mode 100644 index 0000000..2998d22 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/cmap.go @@ -0,0 +1,702 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package font + +import ( + "encoding/binary" + "errors" + + "github.com/go-text/typesetting/font/opentype/tables" +) + +// This file implements the logic needed to use a cmap. + +var ( + _ Cmap = cmap0(nil) + _ Cmap = cmap4(nil) + _ Cmap = (*cmap6or10)(nil) + _ Cmap = cmap12(nil) + _ Cmap = cmap13(nil) + + _ CmapIter = (*cmap0Iter)(nil) + _ CmapIter = (*cmap4Iter)(nil) + _ CmapIter = (*cmap6Or10Iter)(nil) + _ CmapIter = (*cmap12Iter)(nil) + _ CmapIter = (*cmap13Iter)(nil) +) + +// CmapIter is an iterator over a Cmap. +type CmapIter interface { + // Next returns true if the iterator still has data to yield + Next() bool + + // Char must be called only when `Next` has returned `true` + Char() (rune, GID) +} + +// Cmap stores a compact representation of a cmap, +// offering both on-demand rune lookup and full rune range. +// It is conceptually equivalent to a map[rune]GID, but is often +// implemented more efficiently. +type Cmap interface { + // Iter returns a new iterator over the cmap + // Multiple iterators may be used over the same cmap + // The returned interface is garanted not to be nil. + Iter() CmapIter + + // Lookup avoid the construction of a map and provides + // an alternative when only few runes need to be fetched. + // It returns a default value and false when no glyph is provided. + Lookup(rune) (GID, bool) +} + +// ProcessCmap sanitize the given 'cmap' subtable, and select the best encoding +// when several subtables are given. +// When present, the variation selectors are returned. +// [os2FontPage] is used for legacy arabic fonts. +// +// The returned values are copied from the input 'cmap', meaning they do not +// retain any reference on the input storage. +func ProcessCmap(cmap tables.Cmap, os2FontPage tables.FontPage) (Cmap, UnicodeVariations, error) { + var ( + candidateIds []cmapID + candidates []Cmap + uv UnicodeVariations + ) + for _, table := range cmap.Records { + id := cmapID{platform: table.PlatformID, encoding: table.EncodingID} + switch table := table.Subtable.(type) { + case tables.CmapSubtable0: + candidates = append(candidates, newCmap0(table)) + candidateIds = append(candidateIds, id) + case tables.CmapSubtable2: + // we dont support this deprecated format + continue + case tables.CmapSubtable4: + cmap, err := newCmap4(table) + if err != nil { + return nil, nil, err + } + candidates = append(candidates, cmap) + candidateIds = append(candidateIds, id) + case tables.CmapSubtable6: + candidates = append(candidates, newCmap6(table)) + candidateIds = append(candidateIds, id) + case tables.CmapSubtable10: + candidates = append(candidates, newCmap10(table)) + candidateIds = append(candidateIds, id) + case tables.CmapSubtable12: + candidates = append(candidates, newCmap12(table)) + candidateIds = append(candidateIds, id) + case tables.CmapSubtable13: + candidates = append(candidates, newCmap13(table)) + candidateIds = append(candidateIds, id) + case tables.CmapSubtable14: + // quoting the spec : + // This subtable format must only be used under platform ID 0 and encoding ID 5. + if !(id.platform == 0 && id.encoding == 5) { + return nil, nil, errors.New("invalid cmap subtable format 14 platform or encoding") + } + uv = newUnicodeVariations(table) + } + } + + // now find the best cmap, following harfbuzz/src/hb-ot-cmap-table.hh + + // Prefer symbol if available. + if index := findSubtable(cmapID{tables.PlatformMicrosoft, tables.PEMicrosoftSymbolCs}, candidateIds); index != -1 { + cm := candidates[index] + switch os2FontPage { + case tables.FPNone: + cm = remaperSymbol{cm} + case tables.FPSimpArabic: + cm = remaperPUASimp{cm} + case tables.FPTradArabic: + cm = remaperPUATrad{cm} + } + return cm, uv, nil + } + + /* 32-bit subtables. */ + if index := findSubtable(cmapID{tables.PlatformMicrosoft, tables.PEMicrosoftUcs4}, candidateIds); index != -1 { + return candidates[index], uv, nil + } + if index := findSubtable(cmapID{tables.PlatformUnicode, tables.PEUnicodeFull13}, candidateIds); index != -1 { + return candidates[index], uv, nil + } + if index := findSubtable(cmapID{tables.PlatformUnicode, tables.PEUnicodeFull}, candidateIds); index != -1 { + return candidates[index], uv, nil + } + + /* 16-bit subtables. */ + if index := findSubtable(cmapID{tables.PlatformMicrosoft, tables.PEMicrosoftUnicodeCs}, candidateIds); index != -1 { + return candidates[index], uv, nil + } + if index := findSubtable(cmapID{tables.PlatformUnicode, tables.PEUnicodeBMP}, candidateIds); index != -1 { + return candidates[index], uv, nil + } + if index := findSubtable(cmapID{tables.PlatformUnicode, 2}, candidateIds); index != -1 { // deprecated + return candidates[index], uv, nil + } + if index := findSubtable(cmapID{tables.PlatformUnicode, 1}, candidateIds); index != -1 { // deprecated + return candidates[index], uv, nil + } + if index := findSubtable(cmapID{tables.PlatformUnicode, 0}, candidateIds); index != -1 { // deprecated + return candidates[index], uv, nil + } + + // uuh... fallback to the first cmap and hope for the best + if len(candidates) != 0 { + return candidates[0], uv, nil + } + return nil, nil, errors.New("unsupported cmap table") +} + +// cmapID groups the platform and encoding of a Cmap subtable. +type cmapID struct { + platform tables.PlatformID + encoding tables.EncodingID +} + +func (c cmapID) key() uint32 { return uint32(c.platform)<<16 | uint32(c.encoding) } + +// findSubtable returns the cmap index for the given platform and encoding, or -1 if not found. +func findSubtable(id cmapID, cmaps []cmapID) int { + key := id.key() + // binary search + for i, j := 0, len(cmaps); i < j; { + h := i + (j-i)/2 + entryKey := cmaps[h].key() + if key < entryKey { + j = h + } else if entryKey < key { + i = h + 1 + } else { + return h + } + } + return -1 +} + +// ---------------------------------- Format 0 ---------------------------------- + +// use Macintosh encoding, storing indexIntoEncoding -> glyphIndex +type cmap0 map[rune]uint8 + +func newCmap0(cm tables.CmapSubtable0) cmap0 { + out := make(cmap0) + for b, gid := range cm.GlyphIdArray { + if b == 0 { + continue + } + out[tables.DecodeMacintoshByte(byte(b))] = gid + } + return out +} + +type cmap0Iter struct { + data cmap0 + keys []rune + pos int +} + +func (it *cmap0Iter) Next() bool { + return it.pos < len(it.keys) +} + +func (it *cmap0Iter) Char() (rune, GID) { + r := it.keys[it.pos] + it.pos++ + return r, GID(it.data[r]) +} + +func (s cmap0) Iter() CmapIter { + keys := make([]rune, 0, len(s)) + for k := range s { + keys = append(keys, k) + } + return &cmap0Iter{data: s, keys: keys} +} + +func (s cmap0) Lookup(r rune) (GID, bool) { + v, ok := s[r] // will be 0 if r is not in s + return GID(v), ok +} + +// ---------------------------------- Format 4 ---------------------------------- + +// if indexes is nil, delta is used +type cmapEntry16 struct { + // we prefere not to keep a link to a buffer (via an offset) + // and eagerly resolve it + indexes []tables.GlyphID // length end - start + 1 + end, start uint16 + delta uint16 // arithmetic modulo 0xFFFF +} + +type cmap4 []cmapEntry16 + +func newCmap4(cm tables.CmapSubtable4) (cmap4, error) { + segCount := len(cm.EndCode) + out := make(cmap4, segCount) + for i := range out { + entry := cmapEntry16{ + end: cm.EndCode[i], + start: cm.StartCode[i], + delta: cm.IdDelta[i], + } + idRangeOffset := int(cm.IdRangeOffsets[i]) + + // some fonts use 0xFFFF for idRangeOff for the last segment + if entry.start != 0xFFFF && idRangeOffset != 0 { + // we resolve the indexes + entry.indexes = make([]tables.GlyphID, entry.end-entry.start+1) + indexStart := idRangeOffset/2 + i - segCount + if len(cm.GlyphIDArray) < 2*(indexStart+len(entry.indexes)) { + return nil, errors.New("invalid cmap subtable format 4 glyphs array length") + } + for j := range entry.indexes { + index := indexStart + j + entry.indexes[j] = tables.GlyphID(binary.BigEndian.Uint16(cm.GlyphIDArray[2*index:])) + } + } + out[i] = entry + } + return out, nil +} + +type cmap4Iter struct { + data cmap4 + pos1 int // into data + pos2 int // either into data[pos1].indexes or an offset between start and end +} + +func (it *cmap4Iter) Next() bool { + return it.pos1 < len(it.data) +} + +func (it *cmap4Iter) Char() (r rune, gy GID) { + entry := it.data[it.pos1] + if entry.indexes == nil { + r = rune(it.pos2 + int(entry.start)) + gy = GID(uint16(it.pos2) + entry.start + entry.delta) + if uint16(it.pos2) == entry.end-entry.start { + // we have read the last glyph in this part + it.pos2 = 0 + it.pos1++ + } else { + it.pos2++ + } + } else { // pos2 is the array index + r = rune(it.pos2) + rune(entry.start) + gy = GID(entry.indexes[it.pos2]) + if gy != 0 { + gy += GID(entry.delta) + } + if it.pos2 == len(entry.indexes)-1 { + // we have read the last glyph in this part + it.pos2 = 0 + it.pos1++ + } else { + it.pos2++ + } + } + + return r, gy +} + +func (s cmap4) Iter() CmapIter { return &cmap4Iter{data: s} } + +func (s cmap4) Lookup(r rune) (GID, bool) { + if uint32(r) > 0xffff { + return 0, false + } + // binary search + c := uint16(r) + for i, j := 0, len(s); i < j; { + h := i + (j-i)/2 + entry := s[h] + if c < entry.start { + j = h + } else if entry.end < c { + i = h + 1 + } else if entry.indexes == nil { + return GID(c + entry.delta), true + } else { + glyph := entry.indexes[c-entry.start] + if glyph == 0 { + return 0, false + } + return GID(uint16(glyph) + entry.delta), true + } + } + return 0, false +} + +// ---------------------------------- Format 6 and 10 ---------------------------------- + +type cmap6or10 struct { + entries []tables.GlyphID + firstCode rune +} + +func newCmap6(cm tables.CmapSubtable6) cmap6or10 { + return cmap6or10{entries: cm.GlyphIdArray, firstCode: rune(cm.FirstCode)} +} + +func newCmap10(cm tables.CmapSubtable10) cmap6or10 { + return cmap6or10{entries: cm.GlyphIdArray, firstCode: rune(cm.StartCharCode)} +} + +type cmap6Or10Iter struct { + data cmap6or10 + pos int // index into data.entries +} + +func (it *cmap6Or10Iter) Next() bool { + return it.pos < len(it.data.entries) +} + +func (it *cmap6Or10Iter) Char() (rune, GID) { + entry := it.data.entries[it.pos] + r := rune(it.pos) + it.data.firstCode + gy := GID(entry) + it.pos++ + return r, gy +} + +func (s cmap6or10) Iter() CmapIter { + return &cmap6Or10Iter{data: s} +} + +func (s cmap6or10) Lookup(r rune) (GID, bool) { + if r < s.firstCode { + return 0, false + } + c := int(r - s.firstCode) + if c >= len(s.entries) { + return 0, false + } + return GID(s.entries[c]), true +} + +// ---------------------------------- Format 12 ---------------------------------- + +type cmap12 []tables.SequentialMapGroup + +func newCmap12(cm tables.CmapSubtable12) cmap12 { return cm.Groups } + +type cmap12Iter struct { + data cmap12 + pos1 int // into data + pos2 int // offset from start +} + +func (it *cmap12Iter) Next() bool { return it.pos1 < len(it.data) } + +func (it *cmap12Iter) Char() (r rune, gy GID) { + entry := it.data[it.pos1] + r = rune(it.pos2 + int(entry.StartCharCode)) + gy = GID(it.pos2 + int(entry.StartGlyphID)) + if uint32(it.pos2) == entry.EndCharCode-entry.StartCharCode { + // we have read the last glyph in this part + it.pos2 = 0 + it.pos1++ + } else { + it.pos2++ + } + + return r, gy +} + +func (s cmap12) Iter() CmapIter { return &cmap12Iter{data: s} } + +func (s cmap12) Lookup(r rune) (GID, bool) { + c := uint32(r) + // binary search + for i, j := 0, len(s); i < j; { + h := i + (j-i)/2 + entry := s[h] + if c < entry.StartCharCode { + j = h + } else if entry.EndCharCode < c { + i = h + 1 + } else { + return GID(c - entry.StartCharCode + entry.StartGlyphID), true + } + } + return 0, false +} + +// ---------------------------------- Format 13 ---------------------------------- + +type cmap13 []tables.SequentialMapGroup + +func newCmap13(cm tables.CmapSubtable13) cmap13 { return cm.Groups } + +type cmap13Iter struct { + data cmap13 + pos1 int // into data + pos2 int // offset from start +} + +func (it *cmap13Iter) Next() bool { + return it.pos1 < len(it.data) +} + +func (it *cmap13Iter) Char() (r rune, gy GID) { + entry := it.data[it.pos1] + r = rune(it.pos2 + int(entry.StartCharCode)) + gy = GID(entry.StartGlyphID) + if uint32(it.pos2) == entry.EndCharCode-entry.StartCharCode { + // we have read the last glyph in this part + it.pos2 = 0 + it.pos1++ + } else { + it.pos2++ + } + + return r, gy +} + +func (s cmap13) Iter() CmapIter { return &cmap13Iter{data: s} } + +func (s cmap13) Lookup(r rune) (GID, bool) { + c := uint32(r) + // binary search + for i, j := 0, len(s); i < j; { + h := i + (j-i)/2 + entry := s[h] + if c < entry.StartCharCode { + j = h + } else if entry.EndCharCode < c { + i = h + 1 + } else { + return GID(entry.StartGlyphID), true + } + } + return 0, false +} + +// -------------------------------- Unicode selectors -------------------------------- + +type unicodeRange struct { + start rune + additionalCount uint8 // 0 for a singleton range +} + +type uvsMapping struct { + unicode rune + glyphID tables.GlyphID +} + +type variationSelector struct { + defaultUVS []unicodeRange + nonDefaultUVS []uvsMapping + varSelector rune +} + +func (vs variationSelector) getGlyph(r rune) (GID, uint8) { + // binary search + for i, j := 0, len(vs.defaultUVS); i < j; { + h := i + (j-i)/2 + entry := vs.defaultUVS[h] + if r < entry.start { + j = h + } else if entry.start+rune(entry.additionalCount) < r { + i = h + 1 + } else { + return 0, VariantUseDefault + } + } + + for i, j := 0, len(vs.nonDefaultUVS); i < j; { + h := i + (j-i)/2 + entry := vs.nonDefaultUVS[h].unicode + if r < entry { + j = h + } else if entry < r { + i = h + 1 + } else { + return GID(vs.nonDefaultUVS[h].glyphID), VariantFound + } + } + + return 0, VariantNotFound +} + +// same as binary.BigEndian.Uint32, but for 24 bit uint +func parseUint24(b [3]byte) rune { + return rune(b[0])<<16 | rune(b[1])<<8 | rune(b[2]) +} + +type UnicodeVariations []variationSelector + +func newUnicodeVariations(cm tables.CmapSubtable14) UnicodeVariations { + out := make([]variationSelector, len(cm.VarSelectors)) + for i, sel := range cm.VarSelectors { + vs := variationSelector{ + varSelector: parseUint24(sel.VarSelector), + defaultUVS: make([]unicodeRange, len(sel.DefaultUVS.Ranges)), + nonDefaultUVS: make([]uvsMapping, len(sel.NonDefaultUVS.Ranges)), + } + for i, r := range sel.DefaultUVS.Ranges { + vs.defaultUVS[i] = unicodeRange{start: parseUint24(r.StartUnicodeValue), additionalCount: r.AdditionalCount} + } + for i, r := range sel.NonDefaultUVS.Ranges { + vs.nonDefaultUVS[i] = uvsMapping{unicode: parseUint24(r.UnicodeValue), glyphID: r.GlyphID} + } + out[i] = vs + } + return out +} + +const ( + // VariantNotFound is returned when the font does not have a glyph for + // the given rune and selector. + VariantNotFound = iota + // VariantUseDefault is returned when the regular glyph should be used (ignoring the selector). + VariantUseDefault + // VariantFound is returned when the font has a variant for the glyph and selector. + VariantFound +) + +// GetGlyphVariant returns the glyph index to used to [r] combined with [selector], +// with one of the tri-state flags [VariantNotFound, VariantUseDefault, VariantFound] +func (t UnicodeVariations) GetGlyphVariant(r, selector rune) (GID, uint8) { + // binary search + for i, j := 0, len(t); i < j; { + h := i + (j-i)/2 + entryKey := t[h].varSelector + if selector < entryKey { + j = h + } else if entryKey < selector { + i = h + 1 + } else { + return t[h].getGlyph(r) + } + } + return 0, VariantNotFound +} + +// Handle legacy font with remap +// TODO: the Iter() and RuneRanges() method does not include the additional mapping + +type remaperSymbol struct { + Cmap +} + +func (rs remaperSymbol) Lookup(r rune) (GID, bool) { + // try without map first + if g, ok := rs.Cmap.Lookup(r); ok { + return g, true + } + + if r <= 0x00FF { + /* For symbol-encoded OpenType fonts, we duplicate the + * U+F000..F0FF range at U+0000..U+00FF. That's what + * Windows seems to do, and that's hinted about at: + * https://docs.microsoft.com/en-us/typography/opentype/spec/recom + * under "Non-Standard (Symbol) Fonts". */ + mapped := 0xF000 + r + return rs.Lookup(mapped) + } + + return 0, false +} + +type remaperPUASimp struct { + Cmap +} + +func (rs remaperPUASimp) Lookup(r rune) (GID, bool) { + // try without map first + if g, ok := rs.Cmap.Lookup(r); ok { + return g, true + } + + if mapped := arabicPUASimpMap(r); mapped != 0 { + return rs.Lookup(mapped) + } + + return 0, false +} + +type remaperPUATrad struct { + Cmap +} + +func (rs remaperPUATrad) Lookup(r rune) (GID, bool) { + // try without map first + if g, ok := rs.Cmap.Lookup(r); ok { + return g, true + } + + if mapped := arabicPUATradMap(r); mapped != 0 { + return rs.Lookup(mapped) + } + + return 0, false +} + +// ---------------------------- efficent rune set support ----------------------------------------- + +// CmapRuneRanger is implemented by cmaps whose coverage is defined in terms +// of rune ranges +type CmapRuneRanger interface { + // RuneRanges returns a list of (start, end) rune pairs, both included. + // `dst` is an optional buffer used to reduce allocations + RuneRanges(dst [][2]rune) [][2]rune +} + +var ( + _ CmapRuneRanger = cmap4(nil) + _ CmapRuneRanger = (*cmap6or10)(nil) + _ CmapRuneRanger = cmap12(nil) + _ CmapRuneRanger = cmap13(nil) +) + +func (cm cmap4) RuneRanges(dst [][2]rune) [][2]rune { + if cap(dst) < len(cm) { + dst = make([][2]rune, 0, len(cm)) + } + dst = dst[:0] + for _, e := range cm { + start, end := rune(e.start), rune(e.end) + if L := len(dst); L != 0 && dst[L-1][1] == start { + // grow the previous range + dst[L-1][1] = end + } else { + dst = append(dst, [2]rune{start, end}) + } + } + return dst +} + +func (cm *cmap6or10) RuneRanges(dst [][2]rune) [][2]rune { + if cap(dst) < 1 { + dst = [][2]rune{{}} + } + dst = dst[:1] + dst[0] = [2]rune{cm.firstCode, cm.firstCode + rune(len(cm.entries)) - 1} + return dst +} + +func (cm cmap12) RuneRanges(dst [][2]rune) [][2]rune { + if cap(dst) < len(cm) { + dst = make([][2]rune, 0, len(cm)) + } + dst = dst[:0] + for _, e := range cm { + start, end := rune(e.StartCharCode), rune(e.EndCharCode) + if L := len(dst); L != 0 && dst[L-1][1] == start { + // grow the previous range + dst[L-1][1] = end + } else { + dst = append(dst, [2]rune{start, end}) + } + } + return dst +} + +func (cm cmap13) RuneRanges(dst [][2]rune) [][2]rune { return cmap12(cm).RuneRanges(dst) } diff --git a/vendor/github.com/go-text/typesetting/font/cmap_arabic_pua_table.go b/vendor/github.com/go-text/typesetting/font/cmap_arabic_pua_table.go new file mode 100644 index 0000000..f1a086b --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/cmap_arabic_pua_table.go @@ -0,0 +1,161 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package font + +// Code generated by typesettings-utils/generators/unicodedata/cmd/main.go DO NOT EDIT. + +// Legacy Simplified Arabic encoding. Returns 0 if not found. +func arabicPUASimpMap(r rune) rune { + switch { + case 0x20 <= r && r <= 0x22: + return [...]rune{0xf120, 0xf121, 0xf122}[r-0x20] + case 0x25 == r: + return 0xf125 + case 0x28 <= r && r <= 0x3b: + return [...]rune{0xf128, 0xf129, 0xf12a, 0xf12b, 0xf15e, 0xf12d, 0xf12e, 0xf12f, 0xf1b0, 0xf1b1, 0xf1b2, 0xf1b3, 0xf1b4, 0xf1b5, 0xf1b6, 0xf1b7, 0xf1b8, 0xf1b9, 0xf13a, 0xf13b}[r-0x28] + case 0x3d == r: + return 0xf13d + case 0x3f == r: + return 0xf13f + case 0x5b <= r && r <= 0x5d: + return [...]rune{0xf15b, 0xf15c, 0xf15d}[r-0x5b] + case 0xab == r: + return 0xf123 + case 0xbb == r: + return 0xf124 + case 0xd7 == r: + return 0xf126 + case 0xf7 == r: + return 0xf127 + case 0x60c == r: + return 0xf12c + case 0x61b == r: + return 0xf13b + case 0x61f == r: + return 0xf13f + case 0x621 <= r && r <= 0x65e: + return [...]rune{0xf1ad, 0xf145, 0xf143, 0xf1bb, 0xf147, 0xf1ba, 0xf141, 0xf14a, 0xf1a9, 0xf14c, 0xf14e, 0xf151, 0xf154, 0xf157, 0xf158, 0xf159, 0xf15a, 0xf160, 0xf162, 0xf164, 0xf166, 0xf168, 0xf169, 0xf16a, 0xf16e, 0xf172, 0xf100, 0xf100, 0xf100, 0xf100, 0xf100, 0xf15f, 0xf175, 0xf178, 0xf17a, 0xf17c, 0xf17e, 0xf1e1, 0xf1a4, 0xf1a5, 0xf1ac, 0xf1a8, 0xf1c7, 0xf1c8, 0xf1cb, 0xf1c4, 0xf1c5, 0xf1ca, 0xf1c9, 0xf1c6, 0xf100, 0xf100, 0xf100, 0xf100, 0xf100, 0xf100, 0xf100, 0xf100, 0xf100, 0xf100, 0xf100, 0xf100}[r-0x621] + case 0x660 <= r && r <= 0x669: + return [...]rune{0xf130, 0xf131, 0xf132, 0xf133, 0xf134, 0xf135, 0xf136, 0xf137, 0xf138, 0xf139}[r-0x660] + case 0x66b <= r && r <= 0x66c: + return [...]rune{0xf15e, 0xf15e}[r-0x66b] + case 0x200c <= r && r <= 0x200f: + return [...]rune{0xf10c, 0xf10d, 0xf10e, 0xf10f}[r-0x200c] + case 0x2018 <= r && r <= 0x2019: + return [...]rune{0xf13c, 0xf13e}[r-0x2018] + case 0xfe81 <= r && r <= 0xfefc: + return [...]rune{0xf145, 0xf146, 0xf143, 0xf144, 0xf1bb, 0xf1bb, 0xf147, 0xf148, 0xf1ba, 0xf1af, 0xf1ae, 0xf1ae, 0xf141, 0xf142, 0xf14a, 0xf14a, 0xf149, 0xf149, 0xf1a9, 0xf1aa, 0xf14c, 0xf14c, 0xf14b, 0xf14b, 0xf14e, 0xf14e, 0xf14d, 0xf14d, 0xf151, 0xf150, 0xf14f, 0xf14f, 0xf154, 0xf153, 0xf152, 0xf152, 0xf157, 0xf156, 0xf155, 0xf155, 0xf158, 0xf158, 0xf159, 0xf159, 0xf15a, 0xf15a, 0xf160, 0xf160, 0xf162, 0xf162, 0xf161, 0xf161, 0xf164, 0xf164, 0xf163, 0xf163, 0xf166, 0xf166, 0xf165, 0xf165, 0xf168, 0xf168, 0xf167, 0xf167, 0xf169, 0xf169, 0xf169, 0xf169, 0xf16a, 0xf16a, 0xf16a, 0xf16a, 0xf16e, 0xf16d, 0xf16b, 0xf16c, 0xf172, 0xf171, 0xf16f, 0xf170, 0xf175, 0xf175, 0xf173, 0xf174, 0xf178, 0xf178, 0xf176, 0xf177, 0xf17a, 0xf17a, 0xf179, 0xf179, 0xf17c, 0xf17c, 0xf17b, 0xf17b, 0xf17e, 0xf17e, 0xf17d, 0xf17d, 0xf1e1, 0xf1e1, 0xf17f, 0xf17f, 0xf1a4, 0xf1a3, 0xf1a1, 0xf1a2, 0xf1a5, 0xf1a5, 0xf1ac, 0xf1ab, 0xf1a8, 0xf1a7, 0xf1a6, 0xf1a6, 0xf1c0, 0xf1c1, 0xf1be, 0xf1bf, 0xf1c2, 0xf1c3, 0xf1bd, 0xf1bc}[r-0xfe81] + } + return 0 +} + +// Legacy Traditional Arabic encoding. Returns 0 if not found. +func arabicPUATradMap(r rune) rune { + switch { + case 0x20 <= r && r <= 0x22: + return [...]rune{0xf220, 0xf221, 0xf222}[r-0x20] + case 0x25 == r: + return 0xf225 + case 0x28 <= r && r <= 0x2f: + return [...]rune{0xf228, 0xf229, 0xf22a, 0xf22b, 0xf25e, 0xf22d, 0xf22e, 0xf22f}[r-0x28] + case 0x3a <= r && r <= 0x3b: + return [...]rune{0xf23a, 0xf23b}[r-0x3a] + case 0x3d == r: + return 0xf23d + case 0x3f == r: + return 0xf23f + case 0x5b == r: + return 0xf25b + case 0x5d == r: + return 0xf25d + case 0xab == r: + return 0xf223 + case 0xbb == r: + return 0xf224 + case 0xd7 == r: + return 0xf226 + case 0xf7 == r: + return 0xf227 + case 0x60c == r: + return 0xf22c + case 0x61b == r: + return 0xf23b + case 0x61f == r: + return 0xf23f + case 0x621 <= r && r <= 0x65e: + return [...]rune{0xf2d5, 0xf245, 0xf243, 0xf2da, 0xf247, 0xf2d9, 0xf241, 0xf24c, 0xf2d1, 0xf250, 0xf254, 0xf258, 0xf260, 0xf264, 0xf265, 0xf267, 0xf269, 0xf26b, 0xf270, 0xf274, 0xf278, 0xf27e, 0xf2a2, 0xf2a3, 0xf2aa, 0xf2ae, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf25f, 0xf2b2, 0xf2b6, 0xf2ba, 0xf2be, 0xf2c2, 0xf2c6, 0xf2ca, 0xf2cb, 0xf2d4, 0xf2d0, 0xf2e7, 0xf2e8, 0xf2eb, 0xf2e4, 0xf2e5, 0xf2ea, 0xf2e9, 0xf2e6, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200}[r-0x621] + case 0x660 <= r && r <= 0x669: + return [...]rune{0xf230, 0xf231, 0xf232, 0xf233, 0xf234, 0xf235, 0xf236, 0xf237, 0xf238, 0xf239}[r-0x660] + case 0x66b <= r && r <= 0x66c: + return [...]rune{0xf25e, 0xf25e}[r-0x66b] + case 0x200c <= r && r <= 0x200f: + return [...]rune{0xf20c, 0xf20d, 0xf20e, 0xf20f}[r-0x200c] + case 0x201c <= r && r <= 0x201d: + return [...]rune{0xf23c, 0xf23e}[r-0x201c] + case 0xfc08 == r: + return 0xf202 + case 0xfc0a == r: + return 0xf21d + case 0xfc0e == r: + return 0xf203 + case 0xfc10 == r: + return 0xf21e + case 0xfc12 == r: + return 0xf204 + case 0xfc32 == r: + return 0xf29f + case 0xfc3f <= r && r <= 0xfc42: + return [...]rune{0xf212, 0xf213, 0xf214, 0xf205}[r-0xfc3f] + case 0xfc44 == r: + return 0xf21c + case 0xfc4e == r: + return 0xf206 + case 0xfc50 == r: + return 0xf21f + case 0xfc5e == r: + return 0xf2ef + case 0xfc60 <= r && r <= 0xfc62: + return [...]rune{0xf2ec, 0xf2ed, 0xf2f0}[r-0xfc60] + case 0xfc6a == r: + return 0xf215 + case 0xfc6d == r: + return 0xf292 + case 0xfc70 == r: + return 0xf216 + case 0xfc73 == r: + return 0xf293 + case 0xfc86 == r: + return 0xf295 + case 0xfc91 == r: + return 0xf217 + case 0xfc94 == r: + return 0xf294 + case 0xfc9c <= r && r <= 0xfc9f: + return [...]rune{0xf280, 0xf281, 0xf282, 0xf296}[r-0xfc9c] + case 0xfca1 <= r && r <= 0xfca4: + return [...]rune{0xf283, 0xf284, 0xf285, 0xf297}[r-0xfca1] + case 0xfca8 == r: + return 0xf29a + case 0xfcaa == r: + return 0xf29b + case 0xfcac == r: + return 0xf29c + case 0xfcb0 == r: + return 0xf218 + case 0xfcc9 <= r && r <= 0xfcd3: + return [...]rune{0xf286, 0xf287, 0xf288, 0xf29d, 0xf21a, 0xf289, 0xf28a, 0xf28b, 0xf29e, 0xf28d, 0xf28e}[r-0xfcc9] + case 0xfcd5 == r: + return 0xf298 + case 0xfcda <= r && r <= 0xfcdd: + return [...]rune{0xf28f, 0xf290, 0xf291, 0xf299}[r-0xfcda] + case 0xfd30 == r: + return 0xf219 + case 0xfd3e <= r && r <= 0xfd3f: + return [...]rune{0xf27b, 0xf27d}[r-0xfd3e] + case 0xfd88 == r: + return 0xf210 + case 0xfe81 <= r && r <= 0xfefc: + return [...]rune{0xf245, 0xf246, 0xf243, 0xf244, 0xf2da, 0xf2db, 0xf247, 0xf248, 0xf2d9, 0xf2d8, 0xf2d6, 0xf2d7, 0xf241, 0xf242, 0xf24c, 0xf24b, 0xf249, 0xf24a, 0xf2d1, 0xf2d2, 0xf250, 0xf24f, 0xf24d, 0xf24e, 0xf254, 0xf253, 0xf251, 0xf252, 0xf258, 0xf257, 0xf255, 0xf256, 0xf260, 0xf25c, 0xf259, 0xf25a, 0xf264, 0xf263, 0xf261, 0xf262, 0xf265, 0xf266, 0xf267, 0xf268, 0xf269, 0xf26a, 0xf26b, 0xf26c, 0xf270, 0xf26f, 0xf26d, 0xf26e, 0xf274, 0xf273, 0xf271, 0xf272, 0xf278, 0xf277, 0xf275, 0xf276, 0xf27e, 0xf27c, 0xf279, 0xf27a, 0xf2a2, 0xf2a1, 0xf27f, 0xf2f1, 0xf2a6, 0xf2a5, 0xf2a3, 0xf2a4, 0xf2aa, 0xf2a9, 0xf2a7, 0xf2a8, 0xf2ae, 0xf2ad, 0xf2ab, 0xf2ac, 0xf2b2, 0xf2b1, 0xf2af, 0xf2b0, 0xf2b6, 0xf2b5, 0xf2b3, 0xf2b4, 0xf2ba, 0xf2b9, 0xf2b7, 0xf2b8, 0xf2be, 0xf2bd, 0xf2bb, 0xf2bc, 0xf2c2, 0xf2c1, 0xf2bf, 0xf2c0, 0xf2c6, 0xf2c5, 0xf2c3, 0xf2c4, 0xf2ca, 0xf2c9, 0xf2c7, 0xf2c8, 0xf2cb, 0xf2cc, 0xf2d4, 0xf2d3, 0xf2d0, 0xf2cf, 0xf2cd, 0xf2ce, 0xf2e0, 0xf2e1, 0xf2de, 0xf2df, 0xf2e2, 0xf2e3, 0xf2dc, 0xf2dd}[r-0xfe81] + } + return 0 +} diff --git a/vendor/github.com/go-text/typesetting/font/font.go b/vendor/github.com/go-text/typesetting/font/font.go new file mode 100644 index 0000000..93614e9 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/font.go @@ -0,0 +1,525 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +// Package font provides an high level API to access +// Opentype font properties. +// See packages [opentype] and [opentype/tables] for a lower level, more detailled API. +package font + +import ( + "errors" + "fmt" + "math" + + "github.com/go-text/typesetting/font/cff" + ot "github.com/go-text/typesetting/font/opentype" + "github.com/go-text/typesetting/font/opentype/tables" +) + +type ( + // GID is used to identify glyphs in a font. + // It is mostly internal to the font and should not be confused with + // Unicode code points. + // Note that, despite Opentype font files using uint16, we choose to use uint32, + // to allow room for future extension. + GID = ot.GID + + // Tag represents an open-type name. + // These are technically uint32's, but are usually + // displayed in ASCII as they are all acronyms. + // See https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6.html#Overview + Tag = ot.Tag + + // VarCoord stores font variation coordinates, + // which are real numbers in [-1;1], stored as fixed 2.14 integer. + VarCoord = tables.Coord + + // Resource is a combination of io.Reader, io.Seeker and io.ReaderAt. + // This interface is satisfied by most things that you'd want + // to parse, for example *os.File, io.SectionReader or *bytes.Reader. + Resource = ot.Resource + + // GlyphExtents exposes extent values, measured in font units. + // Note that height is negative in coordinate systems that grow up. + GlyphExtents = ot.GlyphExtents +) + +// ParseTTF parse an Opentype font file (.otf, .ttf). +// See ParseTTC for support for collections. +func ParseTTF(file Resource) (*Face, error) { + ld, err := ot.NewLoader(file) + if err != nil { + return nil, err + } + ft, err := NewFont(ld) + if err != nil { + return nil, err + } + return NewFace(ft), nil +} + +// ParseTTC parse an Opentype font file, with support for collections. +// Single font files are supported, returning a slice with length 1. +func ParseTTC(file Resource) ([]*Face, error) { + lds, err := ot.NewLoaders(file) + if err != nil { + return nil, err + } + out := make([]*Face, len(lds)) + for i, ld := range lds { + ft, err := NewFont(ld) + if err != nil { + return nil, fmt.Errorf("reading font %d of collection: %s", i, err) + } + out[i] = NewFace(ft) + } + + return out, nil +} + +// EmptyGlyph represents an invisible glyph, which should not be drawn, +// but whose advance and offsets should still be accounted for when rendering. +const EmptyGlyph GID = math.MaxUint32 + +// FontExtents exposes font-wide extent values, measured in font units. +// Note that typically ascender is positive and descender negative in coordinate systems that grow up. +type FontExtents struct { + Ascender float32 // Typographic ascender. + Descender float32 // Typographic descender. + LineGap float32 // Suggested line spacing gap. +} + +// LineMetric identifies one metric about the font. +type LineMetric uint8 + +const ( + // Distance above the baseline of the top of the underline. + // Since most fonts have underline positions beneath the baseline, this value is typically negative. + UnderlinePosition LineMetric = iota + + // Suggested thickness to draw for the underline. + UnderlineThickness + + // Distance above the baseline of the top of the strikethrough. + StrikethroughPosition + + // Suggested thickness to draw for the strikethrough. + StrikethroughThickness + + SuperscriptEmYSize + SuperscriptEmXOffset + + SubscriptEmYSize + SubscriptEmYOffset + SubscriptEmXOffset + + CapHeight + XHeight +) + +// FontID represents an identifier of a font (possibly in a collection), +// and an optional variable instance. +type FontID struct { + File string // The filename or identifier of the font file. + + // The index of the face in a collection. It is always 0 for + // single font files. + Index uint16 + + // For variable fonts, stores 1 + the instance index. + // It is set to 0 to ignore variations, or for non variable fonts. + Instance uint16 +} + +// Font represents one Opentype font file (or one sub font of a collection). +// It is an educated view of the underlying font file, optimized for quick access +// to information required by text layout engines. +// +// All its methods are read-only and a [*Font] object is thus safe for concurrent use. +type Font struct { + // Cmap is the 'cmap' table + Cmap Cmap + cmapVar UnicodeVariations + + hhea *tables.Hhea + vhea *tables.Vhea + vorg *tables.VORG // optional + cff *cff.CFF // optional + cff2 *cff.CFF2 // optional + post post // optional + svg svg // optional + + glyf tables.Glyf + hmtx tables.Hmtx + vmtx tables.Vmtx + bitmap bitmap + sbix sbix + + os2 os2 + names tables.Name + head tables.Head + + // Optional, only present in variable fonts + + fvar fvar // optional + hvar *tables.HVAR // optional + vvar *tables.VVAR // optional + avar tables.Avar + mvar mvar + gvar gvar + + // Advanced layout tables. + + GDEF tables.GDEF // An absent table has a nil GlyphClassDef + Trak tables.Trak + Ankr tables.Ankr + Feat tables.Feat + Ltag tables.Ltag + Morx Morx + Kern Kernx + Kerx Kernx + GSUB GSUB // An absent table has a nil slice of lookups + GPOS GPOS // An absent table has a nil slice of lookups + + upem uint16 // cached value + nGlyphs int +} + +// NewFont loads all the font tables, sanitizing them. +// An error is returned only when required tables 'cmap', 'head', 'maxp' are invalid (or missing). +// More control on errors is available by using package [tables]. +func NewFont(ld *ot.Loader) (*Font, error) { + var ( + out Font + err error + ) + + // 'cmap' handling depend on os2 + raw, _ := ld.RawTable(ot.MustNewTag("OS/2")) + os2, _, _ := tables.ParseOs2(raw) + fontPage := os2.FontPage() + out.os2, _ = newOs2(os2) + + raw, err = ld.RawTable(ot.MustNewTag("cmap")) + if err != nil { + return nil, err + } + tb, _, err := tables.ParseCmap(raw) + if err != nil { + return nil, err + } + out.Cmap, out.cmapVar, err = ProcessCmap(tb, fontPage) + if err != nil { + return nil, err + } + + out.head, _, err = LoadHeadTable(ld, nil) + if err != nil { + return nil, err + } + + raw, err = ld.RawTable(ot.MustNewTag("maxp")) + if err != nil { + return nil, err + } + maxp, _, err := tables.ParseMaxp(raw) + if err != nil { + return nil, err + } + out.nGlyphs = int(maxp.NumGlyphs) + + // We considerer all the following tables as optional, + // since, in practice, users won't have much control on the + // font files they use + // + // Ignoring the errors on `RawTable` is OK : it will trigger an error on the next tables.ParseXXX, + // which in turn will return a zero value + + raw, _ = ld.RawTable(ot.MustNewTag("fvar")) + fvar, _, _ := tables.ParseFvar(raw) + out.fvar = newFvar(fvar) + + raw, _ = ld.RawTable(ot.MustNewTag("avar")) + out.avar, _, _ = tables.ParseAvar(raw) + + out.upem = out.head.Upem() + + raw, _ = ld.RawTable(ot.MustNewTag("glyf")) + locaRaw, _ := ld.RawTable(ot.MustNewTag("loca")) + loca, err := tables.ParseLoca(locaRaw, out.nGlyphs, out.head.IndexToLocFormat == 1) + if err == nil { // ParseGlyf panics if len(loca) == 0 + out.glyf, _ = tables.ParseGlyf(raw, loca) + } + + out.bitmap = selectBitmapTable(ld) + + raw, _ = ld.RawTable(ot.MustNewTag("sbix")) + sbix, _, _ := tables.ParseSbix(raw, out.nGlyphs) + out.sbix = newSbix(sbix) + + out.cff, _ = loadCff(ld, out.nGlyphs) + out.cff2, _ = loadCff2(ld, out.nGlyphs, len(out.fvar)) + + raw, _ = ld.RawTable(ot.MustNewTag("post")) + post, _, _ := tables.ParsePost(raw) + out.post, _ = newPost(post) + + raw, _ = ld.RawTable(ot.MustNewTag("SVG ")) + svg, _, _ := tables.ParseSVG(raw) + out.svg, _ = newSvg(svg) + + out.hhea, out.hmtx, _ = loadHmtx(ld, out.nGlyphs) + out.vhea, out.vmtx, _ = loadVmtx(ld, out.nGlyphs) + + if axisCount := len(out.fvar); axisCount != 0 { + raw, _ = ld.RawTable(ot.MustNewTag("MVAR")) + mvar, _, _ := tables.ParseMVAR(raw) + out.mvar, _ = newMvar(mvar, axisCount) + + raw, _ = ld.RawTable(ot.MustNewTag("gvar")) + gvar, _, _ := tables.ParseGvar(raw) + out.gvar, _ = newGvar(gvar, out.glyf) + + raw, _ = ld.RawTable(ot.MustNewTag("HVAR")) + hvar, _, err := tables.ParseHVAR(raw) + if err == nil { + out.hvar = &hvar + } + + raw, _ = ld.RawTable(ot.MustNewTag("VVAR")) + vvar, _, err := tables.ParseHVAR(raw) + if err == nil { + out.vvar = &vvar + } + } + + raw, _ = ld.RawTable(ot.MustNewTag("VORG")) + vorg, _, err := tables.ParseVORG(raw) + if err == nil { + out.vorg = &vorg + } + + raw, _ = ld.RawTable(ot.MustNewTag("name")) + out.names, _, _ = tables.ParseName(raw) + + // layout tables + out.GDEF, _ = loadGDEF(ld, len(out.fvar)) + + raw, _ = ld.RawTable(ot.MustNewTag("GSUB")) + layout, _, err := tables.ParseLayout(raw) + // harfbuzz relies on GSUB.Loookups being nil when the table is absent + if err == nil { + out.GSUB, _ = newGSUB(layout) + } + + raw, _ = ld.RawTable(ot.MustNewTag("GPOS")) + layout, _, err = tables.ParseLayout(raw) + // harfbuzz relies on GPOS.Loookups being nil when the table is absent + if err == nil { + out.GPOS, _ = newGPOS(layout) + } + + raw, _ = ld.RawTable(ot.MustNewTag("morx")) + morx, _, _ := tables.ParseMorx(raw, out.nGlyphs) + out.Morx = newMorx(morx) + + raw, _ = ld.RawTable(ot.MustNewTag("kerx")) + kerx, _, _ := tables.ParseKerx(raw, out.nGlyphs) + out.Kerx = newKernxFromKerx(kerx) + + raw, _ = ld.RawTable(ot.MustNewTag("kern")) + kern, _, _ := tables.ParseKern(raw) + out.Kern = newKernxFromKern(kern) + + raw, _ = ld.RawTable(ot.MustNewTag("ankr")) + out.Ankr, _, _ = tables.ParseAnkr(raw, out.nGlyphs) + + raw, _ = ld.RawTable(ot.MustNewTag("trak")) + out.Trak, _, _ = tables.ParseTrak(raw) + + raw, _ = ld.RawTable(ot.MustNewTag("feat")) + out.Feat, _, _ = tables.ParseFeat(raw) + + raw, _ = ld.RawTable(ot.MustNewTag("ltag")) + out.Ltag, _, _ = tables.ParseLtag(raw) + + return &out, nil +} + +var bhedTag = ot.MustNewTag("bhed") + +// LoadHeadTable loads the 'head' or the 'bhed' table. +// +// If a 'bhed' Apple table is present, it replaces the 'head' one. +// +// [buffer] may be provided to reduce allocations; the returned [tables.Head] is guaranteed +// not to retain any reference on [buffer]. +// If [buffer] is nil or has not enough capacity, a new slice is allocated (and returned). +func LoadHeadTable(ld *ot.Loader, buffer []byte) (tables.Head, []byte, error) { + var err error + // check 'bhed' first + if ld.HasTable(bhedTag) { + buffer, err = ld.RawTableTo(bhedTag, buffer) + } else { + buffer, err = ld.RawTableTo(ot.MustNewTag("head"), buffer) + } + if err != nil { + return tables.Head{}, nil, errors.New("missing required head (or bhed) table") + } + out, _, err := tables.ParseHead(buffer) + return out, buffer, err +} + +// return nil if no table is valid (or present) +func selectBitmapTable(ld *ot.Loader) bitmap { + color, err := loadBitmap(ld, ot.MustNewTag("CBLC"), ot.MustNewTag("CBDT")) + if err == nil { + return color + } + + gray, err := loadBitmap(ld, ot.MustNewTag("EBLC"), ot.MustNewTag("EBDT")) + if err == nil { + return gray + } + + apple, err := loadBitmap(ld, ot.MustNewTag("bloc"), ot.MustNewTag("bdat")) + if err == nil { + return apple + } + + return nil +} + +// return nil if the table is missing or invalid +func loadCff(ld *ot.Loader, numGlyphs int) (*cff.CFF, error) { + raw, err := ld.RawTable(ot.MustNewTag("CFF ")) + if err != nil { + return nil, err + } + cff, err := cff.Parse(raw) + if err != nil { + return nil, err + } + + if N := len(cff.Charstrings); N != numGlyphs { + return nil, fmt.Errorf("invalid number of glyphs in CFF table (%d != %d)", N, numGlyphs) + } + return cff, nil +} + +// return nil if the table is missing or invalid +func loadCff2(ld *ot.Loader, numGlyphs, axisCount int) (*cff.CFF2, error) { + raw, err := ld.RawTable(ot.MustNewTag("CFF2")) + if err != nil { + return nil, err + } + cff2, err := cff.ParseCFF2(raw) + if err != nil { + return nil, err + } + + if N := len(cff2.Charstrings); N != numGlyphs { + return nil, fmt.Errorf("invalid number of glyphs in CFF table (%d != %d)", N, numGlyphs) + } + + if got := cff2.VarStore.AxisCount(); got != -1 && got != axisCount { + return nil, fmt.Errorf("invalid number of axis in CFF table (%d != %d)", got, axisCount) + } + return cff2, nil +} + +func loadHVtmx(hheaRaw, htmxRaw []byte, numGlyphs int) (*tables.Hhea, tables.Hmtx, error) { + hhea, _, err := tables.ParseHhea(hheaRaw) + if err != nil { + return nil, tables.Hmtx{}, err + } + + hmtx, _, err := tables.ParseHmtx(htmxRaw, int(hhea.NumOfLongMetrics), numGlyphs-int(hhea.NumOfLongMetrics)) + if err != nil { + return nil, tables.Hmtx{}, err + } + return &hhea, hmtx, nil +} + +func loadHmtx(ld *ot.Loader, numGlyphs int) (*tables.Hhea, tables.Hmtx, error) { + rawHead, err := ld.RawTable(ot.MustNewTag("hhea")) + if err != nil { + return nil, tables.Hmtx{}, err + } + + rawMetrics, err := ld.RawTable(ot.MustNewTag("hmtx")) + if err != nil { + return nil, tables.Hmtx{}, err + } + + return loadHVtmx(rawHead, rawMetrics, numGlyphs) +} + +func loadVmtx(ld *ot.Loader, numGlyphs int) (*tables.Hhea, tables.Hmtx, error) { + rawHead, err := ld.RawTable(ot.MustNewTag("vhea")) + if err != nil { + return nil, tables.Hmtx{}, err + } + + rawMetrics, err := ld.RawTable(ot.MustNewTag("vmtx")) + if err != nil { + return nil, tables.Hmtx{}, err + } + + return loadHVtmx(rawHead, rawMetrics, numGlyphs) +} + +func loadGDEF(ld *ot.Loader, axisCount int) (tables.GDEF, error) { + raw, err := ld.RawTable(ot.MustNewTag("GDEF")) + if err != nil { + return tables.GDEF{}, err + } + GDEF, _, err := tables.ParseGDEF(raw) + if err != nil { + return tables.GDEF{}, err + } + + err = sanitizeGDEF(GDEF, axisCount) + if err != nil { + return tables.GDEF{}, err + } + return GDEF, nil +} + +// Face is a font with user-provided settings. +// Contrary to the [*Font] objects, Faces are NOT safe for concurrent use. +// A Face caches glyph extents and should be reused when possible. +type Face struct { + *Font + + extentsCache extentsCache + + coords []tables.Coord + xPpem, yPpem uint16 +} + +// NewFace wraps [font] and initializes glyph caches. +func NewFace(font *Font) *Face { + return &Face{Font: font, extentsCache: make(extentsCache, font.nGlyphs)} +} + +// Ppem returns the horizontal and vertical pixels-per-em (ppem), used to select bitmap sizes. +func (f *Face) Ppem() (x, y uint16) { return f.xPpem, f.yPpem } + +// SetPpem applies horizontal and vertical pixels-per-em (ppem). +func (f *Face) SetPpem(x, y uint16) { + f.xPpem, f.yPpem = x, y + // invalid the cache + f.extentsCache.reset() +} + +// Coords return a read-only slice of the current variable coordinates, expressed in normalized units. +// It is empty for non variable fonts. +func (f *Face) Coords() []tables.Coord { return f.coords } + +// SetCoords applies a list of variation coordinates, expressed in normalized units. +// Use [NormalizeVariations] to convert from design (user) space units. +func (f *Face) SetCoords(coords []tables.Coord) { + f.coords = coords + // invalid the cache + f.extentsCache.reset() +} diff --git a/vendor/github.com/go-text/typesetting/font/glyphs.go b/vendor/github.com/go-text/typesetting/font/glyphs.go new file mode 100644 index 0000000..8a32953 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/glyphs.go @@ -0,0 +1,351 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package font + +import ( + "bytes" + "encoding/binary" + "fmt" + "image" + "image/jpeg" + "image/png" + + ot "github.com/go-text/typesetting/font/opentype" + "github.com/go-text/typesetting/font/opentype/tables" + "golang.org/x/image/tiff" +) + +type contourPoint struct { + SegmentPoint + + isOnCurve bool + isEndPoint bool // this point is the last of the current contour + isExplicit bool // this point is referenced, i.e., explicit deltas specified */ +} + +func (c *contourPoint) translate(x, y float32) { + c.X += x + c.Y += y +} + +func (c *contourPoint) transform(matrix [4]float32) { + px := c.X*matrix[0] + c.Y*matrix[2] + c.Y = c.X*matrix[1] + c.Y*matrix[3] + c.X = px +} + +const ( + phantomLeft = iota + phantomRight + phantomTop + phantomBottom + phantomCount +) + +const maxCompositeNesting = 20 // protect against malicious fonts + +// use the `glyf` table to fetch the contour points, +// applying variation if needed. +// for composite, recursively calls itself; allPoints includes phantom points and will be at least of length 4 +func (f *Face) getPointsForGlyph(gid tables.GlyphID, currentDepth int, allPoints *[]contourPoint /* OUT */) { + // adapted from harfbuzz/src/hb-ot-glyf-table.hh + + if currentDepth > maxCompositeNesting || int(gid) >= len(f.glyf) { + return + } + + g := f.glyf[gid] + + var points []contourPoint + if data, ok := g.Data.(tables.SimpleGlyph); ok { + points = getContourPoints(data) // fetch the "real" points + } else { // zeros values are enough + points = make([]contourPoint, pointNumbersCount(g)) + } + + // init phantom point + points = append(points, make([]contourPoint, phantomCount)...) + phantoms := points[len(points)-phantomCount:] + + hDelta := float32(g.XMin - getSideBearing(gid, f.hmtx)) + vOrig := float32(g.YMax + getSideBearing(gid, f.vmtx)) + hAdv := float32(f.getBaseAdvance(gid, f.hmtx, false)) + vAdv := float32(f.getBaseAdvance(gid, f.vmtx, true)) + phantoms[phantomLeft].X = hDelta + phantoms[phantomRight].X = hAdv + hDelta + phantoms[phantomTop].Y = vOrig + phantoms[phantomBottom].Y = vOrig - vAdv + + if f.isVar() { + f.gvar.applyDeltasToPoints(gid, f.coords, points) + } + + switch data := g.Data.(type) { + case tables.SimpleGlyph: + *allPoints = append(*allPoints, points...) + case tables.CompositeGlyph: + for compIndex, item := range data.Glyphs { + // recurse on component + var compPoints []contourPoint + + f.getPointsForGlyph(item.GlyphIndex, currentDepth+1, &compPoints) + + LC := len(compPoints) + if LC < phantomCount { // in case of max depth reached + return + } + + /* Copy phantom points from component if USE_MY_METRICS flag set */ + if item.HasUseMyMetrics() { + copy(phantoms, compPoints[LC-phantomCount:]) + } + + /* Apply component transformation & translation */ + transformPoints(&item, compPoints) + + /* Apply translation from gvar */ + tx, ty := points[compIndex].X, points[compIndex].Y + for i := range compPoints { + compPoints[i].translate(tx, ty) + } + + if item.IsAnchored() { + p1, p2 := item.ArgsAsIndices() + if p1 < len(*allPoints) && p2 < LC { + tx, ty := (*allPoints)[p1].X-compPoints[p2].X, (*allPoints)[p1].Y-compPoints[p2].Y + for i := range compPoints { + compPoints[i].translate(tx, ty) + } + } + } + + *allPoints = append(*allPoints, compPoints[0:LC-phantomCount]...) + } + + *allPoints = append(*allPoints, phantoms...) + default: // no data for the glyph + *allPoints = append(*allPoints, phantoms...) + } + + // apply at top level + if currentDepth == 0 { + /* Undocumented rasterizer behavior: + * Shift points horizontally by the updated left side bearing */ + tx := -phantoms[phantomLeft].X + for i := range *allPoints { + (*allPoints)[i].translate(tx, 0) + } + } +} + +// does not includes phantom points +func pointNumbersCount(g tables.Glyph) int { + switch g := g.Data.(type) { + case tables.SimpleGlyph: + return len(g.Points) + case tables.CompositeGlyph: + /* pseudo component points for each component in composite glyph */ + return len(g.Glyphs) + } + return 0 +} + +// return all the contour points, without phantoms +func getContourPoints(sg tables.SimpleGlyph) []contourPoint { + const flagOnCurve = 1 << 0 // 0x0001 + + points := make([]contourPoint, len(sg.Points)) + for _, end := range sg.EndPtsOfContours { + points[end].isEndPoint = true + } + for i, p := range sg.Points { + points[i].X, points[i].Y = float32(p.X), float32(p.Y) + points[i].isOnCurve = p.Flag&flagOnCurve != 0 + } + return points +} + +func extentsFromPoints(allPoints []contourPoint) (ext GlyphExtents) { + truePoints := allPoints[:len(allPoints)-phantomCount] + if len(truePoints) == 0 { + // zero extent for the empty glyph + return ext + } + minX, minY := truePoints[0].X, truePoints[0].Y + maxX, maxY := minX, minY + for _, p := range truePoints { + minX = minF(minX, p.X) + minY = minF(minY, p.Y) + maxX = maxF(maxX, p.X) + maxY = maxF(maxY, p.Y) + } + ext.XBearing = minX + ext.YBearing = maxY + ext.Width = maxX - minX + ext.Height = minY - maxY + return ext +} + +// walk through the contour points of the given glyph to compute its extends and its phantom points +// As an optimization, if `computeExtents` is false, the extents computation is skipped (a zero value is returned). +func (f *Face) getGlyfPoints(gid tables.GlyphID, computeExtents bool) (ext GlyphExtents, ph [phantomCount]contourPoint) { + if int(gid) >= len(f.glyf) { + return + } + var allPoints []contourPoint + f.getPointsForGlyph(gid, 0, &allPoints) + + copy(ph[:], allPoints[len(allPoints)-phantomCount:]) + + if computeExtents { + ext = extentsFromPoints(allPoints) + } + + return ext, ph +} + +func min16(a, b int16) int16 { + if a < b { + return a + } + return b +} + +func max16(a, b int16) int16 { + if a > b { + return a + } + return b +} + +func minC(a, b VarCoord) VarCoord { + if a < b { + return a + } + return b +} + +func maxC(a, b VarCoord) VarCoord { + if a > b { + return a + } + return b +} + +func minF(a, b float32) float32 { + if a < b { + return a + } + return b +} + +func maxF(a, b float32) float32 { + if a > b { + return a + } + return b +} + +func transformPoints(c *tables.CompositeGlyphPart, points []contourPoint) { + var transX, transY float32 + if !c.IsAnchored() { + arg1, arg2 := c.ArgsAsTranslation() + transX, transY = float32(arg1), float32(arg2) + } + + scale := c.Scale + // shortcut identity transform + if transX == 0 && transY == 0 && scale == [4]float32{1, 0, 0, 1} { + return + } + + if c.IsScaledOffsets() { + for i := range points { + points[i].translate(transX, transY) + points[i].transform(scale) + } + } else { + for i := range points { + points[i].transform(scale) + points[i].translate(transX, transY) + } + } +} + +func getGlyphExtents(g tables.Glyph, metrics tables.Hmtx, gid gID) GlyphExtents { + var extents GlyphExtents + /* Undocumented rasterizer behavior: shift glyph to the left by (lsb - xMin), i.e., xMin = lsb */ + /* extents.XBearing = hb_min (glyph_header.xMin, glyph_header.xMax); */ + extents.XBearing = float32(getSideBearing(gid, metrics)) + + extents.YBearing = float32(max16(g.YMin, g.YMax)) + extents.Width = float32(max16(g.XMin, g.XMax) - min16(g.XMin, g.XMax)) + extents.Height = float32(min16(g.YMin, g.YMax) - max16(g.YMin, g.YMax)) + return extents +} + +// sbix + +var ( + dupe = ot.MustNewTag("dupe") + // tagPNG identifies bitmap glyph with png format + tagPNG = ot.MustNewTag("png ") + // tagTIFF identifies bitmap glyph with tiff format + tagTIFF = ot.MustNewTag("tiff") + // tagJPG identifies bitmap glyph with jpg format + tagJPG = ot.MustNewTag("jpg ") +) + +// strikeGlyph return the data for [glyph], or a zero value if not found. +func strikeGlyph(b *tables.Strike, glyph gID, recursionLevel int) tables.BitmapGlyphData { + const maxRecursionLevel = 8 + + if int(glyph) >= len(b.GlyphDatas) { + return tables.BitmapGlyphData{} + } + out := b.GlyphDatas[glyph] + if out.GraphicType == dupe { + if len(out.Data) < 2 || recursionLevel > maxRecursionLevel { + return tables.BitmapGlyphData{} + } + glyph = gID(binary.BigEndian.Uint16(out.Data)) + return strikeGlyph(b, glyph, recursionLevel+1) + } + return out +} + +// decodeBitmapConfig parse the data to find the width and height +func decodeBitmapConfig(b tables.BitmapGlyphData) (width, height int, format BitmapFormat, err error) { + var config image.Config + switch b.GraphicType { + case tagPNG: + format = PNG + config, err = png.DecodeConfig(bytes.NewReader(b.Data)) + case tagTIFF: + format = TIFF + config, err = tiff.DecodeConfig(bytes.NewReader(b.Data)) + case tagJPG: + format = JPG + config, err = jpeg.DecodeConfig(bytes.NewReader(b.Data)) + default: + err = fmt.Errorf("unsupported graphic type in sbix table: %s", b.GraphicType) + } + if err != nil { + return 0, 0, 0, err + } + return config.Width, config.Height, format, nil +} + +// return the extents computed from the data +// should only be called on valid, non nil glyph data +func bitmapGlyphExtents(b tables.BitmapGlyphData) (out GlyphExtents, ok bool) { + width, height, _, err := decodeBitmapConfig(b) + if err != nil { + return out, false + } + out.XBearing = float32(b.OriginOffsetX) + out.YBearing = float32(height) + float32(b.OriginOffsetY) + out.Width = float32(width) + out.Height = -float32(height) + return out, true +} diff --git a/vendor/github.com/go-text/typesetting/font/metadata.go b/vendor/github.com/go-text/typesetting/font/metadata.go new file mode 100644 index 0000000..ed53836 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/metadata.go @@ -0,0 +1,453 @@ +package font + +import ( + "strings" + + ot "github.com/go-text/typesetting/font/opentype" + "github.com/go-text/typesetting/font/opentype/tables" +) + +// name values corresponding to the xxxConsts arrays +var ( + styleStrings [len(styleConsts)]string + weightStrings [len(weightConsts)]string + stretchStrings [len(stretchConsts)]string +) + +func init() { + for i, v := range styleConsts { + styleStrings[i] = v.name + } + for i, v := range weightConsts { + weightStrings[i] = v.name + } + for i, v := range stretchConsts { + stretchStrings[i] = v.name + } +} + +var styleConsts = [...]struct { + name string + value Style +}{ + {"italic", StyleItalic}, + {"kursiv", StyleItalic}, + {"oblique", StyleItalic}, // map Oblique to Italic +} + +var weightConsts = [...]struct { + name string + value Weight +}{ + {"thin", WeightThin}, + {"extralight", WeightExtraLight}, + {"ultralight", WeightExtraLight}, + {"light", WeightLight}, + {"demilight", (WeightLight + WeightNormal) / 2}, + {"semilight", (WeightLight + WeightNormal) / 2}, + {"book", WeightNormal - 20}, + {"regular", WeightNormal}, + {"normal", WeightNormal}, + {"medium", WeightMedium}, + {"demibold", WeightSemibold}, + {"demi", WeightSemibold}, + {"semibold", WeightSemibold}, + {"extrabold", WeightExtraBold}, + {"superbold", WeightExtraBold}, + {"ultrabold", WeightExtraBold}, + {"bold", WeightBold}, + {"ultrablack", WeightBlack + 20}, + {"superblack", WeightBlack + 20}, + {"extrablack", WeightBlack + 20}, + {"black", WeightBlack}, + {"heavy", WeightBlack}, +} + +var stretchConsts = [...]struct { + name string + value Stretch +}{ + {"ultracondensed", StretchUltraCondensed}, + {"extracondensed", StretchExtraCondensed}, + {"semicondensed", StretchSemiCondensed}, + {"condensed", StretchCondensed}, + {"normal", StretchNormal}, + {"semiexpanded", StretchSemiExpanded}, + {"extraexpanded", StretchExtraExpanded}, + {"ultraexpanded", StretchUltraExpanded}, + {"expanded", StretchExpanded}, + {"extended", StretchExpanded}, +} + +// Style (also called slant) allows italic or oblique faces to be selected. +type Style uint8 + +// note that we use the 0 value to indicate no style has been found yet +const ( + // A face that is neither italic not obliqued. + StyleNormal Style = iota + 1 + // A form that is generally cursive in nature or slanted. + // This groups what is usually called Italic or Oblique. + StyleItalic +) + +// Weight is the degree of blackness or stroke thickness of a font. +// This value ranges from 100.0 to 900.0, with 400.0 as normal. +type Weight float32 + +const ( + // Thin weight (100), the thinnest value. + WeightThin Weight = 100 + // Extra light weight (200). + WeightExtraLight Weight = 200 + // Light weight (300). + WeightLight Weight = 300 + // Normal (400). + WeightNormal Weight = 400 + // Medium weight (500, higher than normal). + WeightMedium Weight = 500 + // Semibold weight (600). + WeightSemibold Weight = 600 + // Bold weight (700). + WeightBold Weight = 700 + // Extra-bold weight (800). + WeightExtraBold Weight = 800 + // Black weight (900), the thickest value. + WeightBlack Weight = 900 +) + +// Stretch is the width of a font as an approximate fraction of the normal width. +// Widths range from 0.5 to 2.0 inclusive, with 1.0 as the normal width. +type Stretch float32 + +const ( + // Ultra-condensed width (50%), the narrowest possible. + StretchUltraCondensed Stretch = 0.5 + // Extra-condensed width (62.5%). + StretchExtraCondensed Stretch = 0.625 + // Condensed width (75%). + StretchCondensed Stretch = 0.75 + // Semi-condensed width (87.5%). + StretchSemiCondensed Stretch = 0.875 + // Normal width (100%). + StretchNormal Stretch = 1.0 + // Semi-expanded width (112.5%). + StretchSemiExpanded Stretch = 1.125 + // Expanded width (125%). + StretchExpanded Stretch = 1.25 + // Extra-expanded width (150%). + StretchExtraExpanded Stretch = 1.5 + // Ultra-expanded width (200%), the widest possible. + StretchUltraExpanded Stretch = 2.0 +) + +// Aspect stores the properties that specify which font in a family to use: +// style, weight, and stretchiness. +type Aspect struct { + Style Style + Weight Weight + Stretch Stretch +} + +// aspect returns the [aspect] of the font, +// defaulting to regular style. +func (fd *fontDescriptor) aspect() Aspect { + // use rawAspect and additionalStyle to infer the Aspect + + out := fd.rawAspect() // load the aspect properties ... + + // ... try to fill the missing one with the "style" + out.inferFromStyle(fd.additionalStyle()) + + // ... and finally add default to regular values : + // StyleNormal, WeightNormal, StretchNormal + out.SetDefaults() + + return out +} + +// some fonts includes aspect information in a string description, +// usually called "style" +// inferFromStyle scans such a string and fills the missing fields, +func (as *Aspect) inferFromStyle(additionalStyle string) { + additionalStyle = NormalizeFamily(additionalStyle) + + if as.Style == 0 { + if index := stringContainsConst(additionalStyle, styleStrings[:]); index != -1 { + as.Style = styleConsts[index].value + } + } + + if as.Weight == 0 { + if index := stringContainsConst(additionalStyle, weightStrings[:]); index != -1 { + as.Weight = weightConsts[index].value + } + } + + if as.Stretch == 0 { + if index := stringContainsConst(additionalStyle, stretchStrings[:]); index != -1 { + as.Stretch = stretchConsts[index].value + } + } +} + +// SetDefaults replace unspecified values by the default values: StyleNormal, WeightNormal, StretchNormal +func (as *Aspect) SetDefaults() { + if as.Style == 0 { + as.Style = StyleNormal + } + + if as.Stretch == 0 { + as.Stretch = StretchNormal + } + + if as.Weight == 0 { + as.Weight = WeightNormal + } +} + +func (fd *fontDescriptor) additionalStyle() string { + var style string + if fd.os2 != nil && fd.os2.fsSelection&256 != 0 { + style = fd.names.Name(namePreferredSubfamily) + if style == "" { + style = fd.names.Name(nameFontSubfamily) + } + } else { + style = fd.names.Name(nameWWSSubfamily) + if style == "" { + style = fd.names.Name(namePreferredSubfamily) + } + if style == "" { + style = fd.names.Name(nameFontSubfamily) + } + } + style = strings.TrimSpace(style) + return style +} + +func (fd *fontDescriptor) rawAspect() Aspect { + var ( + style Style + weight Weight + stretch Stretch + ) + + if fd.os2 != nil { + // We have an OS/2 table; use the `fsSelection' field. Bit 9 + // indicates an oblique font face. This flag has been + // introduced in version 1.5 of the OpenType specification. + if fd.os2.fsSelection&(1<<9) != 0 || fd.os2.fsSelection&1 != 0 { + style = StyleItalic + } + + weight = Weight(fd.os2.usWeightClass) + + switch fd.os2.usWidthClass { + case 1: + stretch = StretchUltraCondensed + case 2: + stretch = StretchExtraCondensed + case 3: + stretch = StretchCondensed + case 4: + stretch = StretchSemiCondensed + case 5: + stretch = StretchNormal + case 6: + stretch = StretchSemiExpanded + case 7: + stretch = StretchExpanded + case 8: + stretch = StretchExtraExpanded + case 9: + stretch = StretchUltraExpanded + } + + } else { + // this is an old Mac font, use the header field + if isItalic := fd.head.MacStyle&2 != 0; isItalic { + style = StyleItalic + } + if isBold := fd.head.MacStyle&1 != 0; isBold { + weight = WeightBold + } + } + + return Aspect{style, weight, stretch} +} + +var rp = strings.NewReplacer(" ", "", "\t", "") + +// NormalizeFamily removes spaces and lower the given string. +func NormalizeFamily(family string) string { return rp.Replace(strings.ToLower(family)) } + +// returns the index in `constants` of a constant contained in `str`, +// or -1 +func stringContainsConst(str string, constants []string) int { + for i, c := range constants { + if strings.Contains(str, c) { + return i + } + } + return -1 +} + +const ( + nameFontFamily tables.NameID = 1 + nameFontSubfamily tables.NameID = 2 + namePreferredFamily tables.NameID = 16 // or Typographic Family + namePreferredSubfamily tables.NameID = 17 // or Typographic Subfamily + nameWWSFamily tables.NameID = 21 // + nameWWSSubfamily tables.NameID = 22 // +) + +type os2Desc struct { + usWeightClass uint16 + usWidthClass uint16 + fsSelection uint16 +} + +func newOS2Desc(os tables.Os2) *os2Desc { + return &os2Desc{ + usWeightClass: os.USWeightClass, + usWidthClass: os.USWidthClass, + fsSelection: os.FsSelection, + } +} + +// fontDescriptor provides access to family and aspect +type fontDescriptor struct { + // these tables are required both in Family + // and Aspect + os2 *os2Desc // optional + names tables.Name + head tables.Head +} + +func newFontDescriptor(ld *ot.Loader, buffer []byte) (fontDescriptor, []byte) { + var desc fontDescriptor + + // load tables, all considered optional + buffer, _ = ld.RawTableTo(ot.MustNewTag("OS/2"), buffer) + if os2, _, err := tables.ParseOs2(buffer); err == nil { + desc.os2 = newOS2Desc(os2) + } + + desc.head, buffer, _ = LoadHeadTable(ld, buffer) + + buffer, _ = ld.RawTableTo(ot.MustNewTag("name"), buffer) + desc.names, _, _ = tables.ParseName(buffer) + + return desc, buffer +} + +// family returns the font family name. +func (fd *fontDescriptor) family() string { + var family string + if fd.os2 != nil && fd.os2.fsSelection&256 != 0 { + family = fd.names.Name(namePreferredFamily) + if family == "" { + family = fd.names.Name(nameFontFamily) + } + } else { + family = fd.names.Name(nameWWSFamily) + if family == "" { + family = fd.names.Name(namePreferredFamily) + } + if family == "" { + family = fd.names.Name(nameFontFamily) + } + } + return family +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} + +func approximatelyEqual(x, y int) bool { return abs(x-y)*33 <= max(abs(x), abs(y)) } + +// IsMonospace returns 'true' if the font is monospace, +// by inspecting the horizontal advances of its glyphs. +func (fd *Font) IsMonospace() bool { + // code adapted from fontconfig + + // try the fast shortcuts + if fd.post.isFixedPitch { + return true + } + + if fd.hmtx.IsEmpty() { + // we can't be sure, so be conservative + return false + } + + if len(fd.hmtx.Metrics) == 1 { + return true + } + + // directly read the advances in the 'hmtx' table + var firstAdvance int + for gid, metric := range fd.hmtx.Metrics { + if gid == 0 { // ignore the 'unset' glyph, which may be different + continue + } + advance := int(metric.AdvanceWidth) + if advance == 0 { // do not count zero as a proper width + continue + } + + if firstAdvance == 0 { + firstAdvance = advance + continue + } + + if approximatelyEqual(advance, firstAdvance) { + continue + } + + // two distinct advances : the font is not monospace + return false + } + + return true +} + +// Description provides font metadata. +type Description struct { + Family string + Aspect Aspect +} + +// Describe provides access to family and aspect. +// +// 'buffer' may be provided to reduce allocations. +// +// It provides an efficient API, loading only the mininum +// tables required. See also the method [Font.Describe] +// if you already have loaded the font. +func Describe(ld *ot.Loader, buffer []byte) (Description, []byte) { + desc, buffer := newFontDescriptor(ld, buffer) + return Description{desc.family(), desc.aspect()}, buffer +} + +// Describe provides access to family and aspect. +// +// See also the package level function [Describe], +// which is more efficient if you only need the font +// metadata. +func (ft *Font) Describe() Description { + desc := fontDescriptor{ft.os2.os2Desc, ft.names, ft.head} + return Description{desc.family(), desc.aspect()} +} diff --git a/vendor/github.com/go-text/typesetting/font/metrics.go b/vendor/github.com/go-text/typesetting/font/metrics.go new file mode 100644 index 0000000..9c626d6 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/metrics.go @@ -0,0 +1,419 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package font + +import ( + "math" + + ot "github.com/go-text/typesetting/font/opentype" + "github.com/go-text/typesetting/font/opentype/tables" +) + +type gID = tables.GlyphID + +func (f *Font) GetGlyphContourPoint(glyph GID, pointIndex uint16) (x, y int32, ok bool) { + // harfbuzz seems not to implement this feature + return 0, 0, false +} + +// GlyphName returns the name of the given glyph, or an empty +// string if the glyph is invalid or has no name. +func (f *Font) GlyphName(glyph GID) string { + if postNames := f.post.names; postNames != nil { + if name := postNames.glyphName(glyph); name != "" { + return name + } + } + if f.cff != nil { + return f.cff.GlyphName(glyph) + } + return "" +} + +// Upem returns the units per em of the font file. +// This value is only relevant for scalable fonts. +func (f *Font) Upem() uint16 { return f.upem } + +var ( + metricsTagHorizontalAscender = ot.MustNewTag("hasc") + metricsTagHorizontalDescender = ot.MustNewTag("hdsc") + metricsTagHorizontalLineGap = ot.MustNewTag("hlgp") + metricsTagVerticalAscender = ot.MustNewTag("vasc") + metricsTagVerticalDescender = ot.MustNewTag("vdsc") + metricsTagVerticalLineGap = ot.MustNewTag("vlgp") +) + +func fixAscenderDescender(value float32, metricsTag Tag) float32 { + if metricsTag == metricsTagHorizontalAscender || metricsTag == metricsTagVerticalAscender { + return float32(math.Abs(float64(value))) + } + if metricsTag == metricsTagHorizontalDescender || metricsTag == metricsTagVerticalDescender { + return float32(-math.Abs(float64(value))) + } + return value +} + +func (f *Font) getPositionCommon(metricTag Tag, varCoords []VarCoord) (float32, bool) { + deltaVar := f.mvar.getVar(metricTag, varCoords) + switch metricTag { + case metricsTagHorizontalAscender: + if f.os2.useTypoMetrics { + return fixAscenderDescender(float32(f.os2.sTypoAscender)+deltaVar, metricTag), true + } else if f.hhea != nil { + return fixAscenderDescender(float32(f.hhea.Ascender)+deltaVar, metricTag), true + } + + case metricsTagHorizontalDescender: + if f.os2.useTypoMetrics { + return fixAscenderDescender(float32(f.os2.sTypoDescender)+deltaVar, metricTag), true + } else if f.hhea != nil { + return fixAscenderDescender(float32(f.hhea.Descender)+deltaVar, metricTag), true + } + case metricsTagHorizontalLineGap: + if f.os2.useTypoMetrics { + return fixAscenderDescender(float32(f.os2.sTypoLineGap)+deltaVar, metricTag), true + } else if f.hhea != nil { + return fixAscenderDescender(float32(f.hhea.LineGap)+deltaVar, metricTag), true + } + case metricsTagVerticalAscender: + if f.vhea != nil { + return fixAscenderDescender(float32(f.vhea.Ascender)+deltaVar, metricTag), true + } + case metricsTagVerticalDescender: + if f.vhea != nil { + return fixAscenderDescender(float32(f.vhea.Descender)+deltaVar, metricTag), true + } + case metricsTagVerticalLineGap: + if f.vhea != nil { + return fixAscenderDescender(float32(f.vhea.LineGap)+deltaVar, metricTag), true + } + } + return 0, false +} + +// FontHExtents returns the extents of the font for horizontal text, or false +// it not available, in font units. +func (f *Face) FontHExtents() (FontExtents, bool) { + var ( + out FontExtents + ok1, ok2, ok3 bool + ) + out.Ascender, ok1 = f.Font.getPositionCommon(metricsTagHorizontalAscender, f.coords) + out.Descender, ok2 = f.Font.getPositionCommon(metricsTagHorizontalDescender, f.coords) + out.LineGap, ok3 = f.Font.getPositionCommon(metricsTagHorizontalLineGap, f.coords) + return out, ok1 && ok2 && ok3 +} + +// FontVExtents is the same as `FontHExtents`, but for vertical text. +func (f *Face) FontVExtents() (FontExtents, bool) { + var ( + out FontExtents + ok1, ok2, ok3 bool + ) + out.Ascender, ok1 = f.Font.getPositionCommon(metricsTagVerticalAscender, f.coords) + out.Descender, ok2 = f.Font.getPositionCommon(metricsTagVerticalDescender, f.coords) + out.LineGap, ok3 = f.Font.getPositionCommon(metricsTagVerticalLineGap, f.coords) + return out, ok1 && ok2 && ok3 +} + +var ( + tagStrikeoutSize = ot.MustNewTag("strs") + tagStrikeoutOffset = ot.MustNewTag("stro") + tagUnderlineSize = ot.MustNewTag("unds") + tagUnderlineOffset = ot.MustNewTag("undo") + tagSuperscriptYSize = ot.MustNewTag("spys") + tagSuperscriptXOffset = ot.MustNewTag("spxo") + tagSubscriptYSize = ot.MustNewTag("sbys") + tagSubscriptYOffset = ot.MustNewTag("sbyo") + tagSubscriptXOffset = ot.MustNewTag("sbxo") + tagXHeight = ot.MustNewTag("xhgt") + tagCapHeight = ot.MustNewTag("cpht") +) + +// LineMetric returns the metric identified by `metric` (in fonts units). +func (f *Face) LineMetric(metric LineMetric) float32 { + switch metric { + case UnderlinePosition: + return f.post.underlinePosition + f.mvar.getVar(tagUnderlineOffset, f.coords) + case UnderlineThickness: + return f.post.underlineThickness + f.mvar.getVar(tagUnderlineSize, f.coords) + case StrikethroughPosition: + return float32(f.os2.yStrikeoutPosition) + f.mvar.getVar(tagStrikeoutOffset, f.coords) + case StrikethroughThickness: + return float32(f.os2.yStrikeoutSize) + f.mvar.getVar(tagStrikeoutSize, f.coords) + case SuperscriptEmYSize: + return float32(f.os2.ySuperscriptYSize) + f.mvar.getVar(tagSuperscriptYSize, f.coords) + case SuperscriptEmXOffset: + return float32(f.os2.ySuperscriptXOffset) + f.mvar.getVar(tagSuperscriptXOffset, f.coords) + case SubscriptEmYSize: + return float32(f.os2.ySubscriptYSize) + f.mvar.getVar(tagSubscriptYSize, f.coords) + case SubscriptEmYOffset: + return float32(f.os2.ySubscriptYOffset) + f.mvar.getVar(tagSubscriptYOffset, f.coords) + case SubscriptEmXOffset: + return float32(f.os2.ySubscriptXOffset) + f.mvar.getVar(tagSubscriptXOffset, f.coords) + case CapHeight: + return float32(f.os2.sCapHeight) + f.mvar.getVar(tagCapHeight, f.coords) + case XHeight: + return float32(f.os2.sxHeigh) + f.mvar.getVar(tagXHeight, f.coords) + default: + return 0 + } +} + +// NominalGlyph returns the glyph used to represent the given rune, +// or false if not found. +// Note that it only looks into the cmap, without taking account substitutions +// nor variation selectors. +func (f *Font) NominalGlyph(ch rune) (GID, bool) { return f.Cmap.Lookup(ch) } + +// VariationGlyph retrieves the glyph ID for a specified Unicode code point +// followed by a specified Variation Selector code point, or false if not found +func (f *Font) VariationGlyph(ch, varSelector rune) (GID, bool) { + gid, kind := f.cmapVar.GetGlyphVariant(ch, varSelector) + switch kind { + case VariantNotFound: + return 0, false + case VariantFound: + return gid, true + default: // VariantUseDefault + return f.NominalGlyph(ch) + } +} + +// do not take into account variations +func (f *Font) getBaseAdvance(gid gID, table tables.Hmtx, isVertical bool) int16 { + /* If `table` is empty, it means we don't have the metrics table + * for this direction: return default advance. Otherwise, it means that the + * glyph index is out of bound: return zero. */ + if table.IsEmpty() { + if isVertical { + return int16(f.upem) + } + return int16(f.upem / 2) + } + + return table.Advance(gid) +} + +// return the base side bearing, handling invalid glyph index +func getSideBearing(gid gID, table tables.Hmtx) int16 { + LM, LS := len(table.Metrics), len(table.LeftSideBearings) + index := int(gid) + if index < LM { + return table.Metrics[index].LeftSideBearing + } else if index < LS+LM { + return table.LeftSideBearings[index-LM] + } else { + return 0 + } +} + +func clamp(v float32) float32 { + if v < 0 { + v = 0 + } + return v +} + +func ceil(v float32) int16 { + return int16(math.Ceil(float64(v))) +} + +func (f *Face) getGlyphAdvanceVar(gid gID, isVertical bool) float32 { + _, phantoms := f.getGlyfPoints(gid, false) + if isVertical { + return clamp(phantoms[phantomTop].Y - phantoms[phantomBottom].Y) + } + return clamp(phantoms[phantomRight].X - phantoms[phantomLeft].X) +} + +func (f *Face) HorizontalAdvance(gid GID) float32 { + advance := f.getBaseAdvance(gID(gid), f.hmtx, false) + if !f.isVar() { + return float32(advance) + } + if f.hvar != nil { + return float32(advance) + getAdvanceDeltaUnscaled(f.hvar, gID(gid), f.coords) + } + return f.getGlyphAdvanceVar(gID(gid), false) +} + +// return `true` is the font is variable and `Coords` is valid +func (f *Face) isVar() bool { + return len(f.coords) != 0 && len(f.coords) == len(f.Font.fvar) +} + +// HasVerticalMetrics returns true if a the 'vmtx' table is present. +// If not, client should avoid calls to [VerticalAdvance], which will returns a +// defaut value. +func (f *Font) HasVerticalMetrics() bool { return !f.vmtx.IsEmpty() } + +func (f *Face) VerticalAdvance(gid GID) float32 { + // return the opposite of the advance from the font + advance := f.getBaseAdvance(gID(gid), f.vmtx, true) + if !f.isVar() { + return -float32(advance) + } + if f.vvar != nil { + return -float32(advance) - getAdvanceDeltaUnscaled(f.vvar, gID(gid), f.coords) + } + return -f.getGlyphAdvanceVar(gID(gid), true) +} + +func (f *Face) getGlyphSideBearingVar(gid gID, isVertical bool) int16 { + extents, phantoms := f.getGlyfPoints(gid, true) + if isVertical { + return ceil(phantoms[phantomTop].Y - extents.YBearing) + } + return int16(phantoms[phantomLeft].X) +} + +// take variations into account +func (f *Face) getVerticalSideBearing(glyph gID) int16 { + // base side bearing + sideBearing := getSideBearing(glyph, f.vmtx) + if !f.isVar() { + return sideBearing + } + if f.vvar != nil { + return sideBearing + int16(getLsbDeltaUnscaled(f.vvar, glyph, f.coords)) + } + return f.getGlyphSideBearingVar(glyph, true) +} + +func (f *Font) GlyphHOrigin(GID) (x, y int32, found bool) { + // zero is the right value here + return 0, 0, true +} + +func (f *Face) GlyphVOrigin(glyph GID) (x, y int32, found bool) { + x = int32(f.HorizontalAdvance(glyph) / 2) + + if f.vorg != nil { + y = int32(f.vorg.YOrigin(gID(glyph))) + return x, y, true + } + + if extents, ok := f.getExtentsFromGlyf(gID(glyph)); ok { + if f.HasVerticalMetrics() { + tsb := f.getVerticalSideBearing(gID(glyph)) + y = int32(extents.YBearing) + int32(tsb) + return x, y, true + } + + fontExtents, _ := f.FontHExtents() + advance := fontExtents.Ascender - fontExtents.Descender + diff := advance - -extents.Height + y = int32(extents.YBearing + (diff / 2)) + return x, y, true + } + + fontExtents, ok := f.FontHExtents() + y = int32(fontExtents.Ascender) + + return x, y, ok +} + +func (f *Face) getExtentsFromGlyf(glyph gID) (GlyphExtents, bool) { + if int(glyph) >= len(f.glyf) { + return GlyphExtents{}, false + } + if f.isVar() { // we have to compute the outline points and apply variations + extents, _ := f.getGlyfPoints(glyph, true) + return extents, true + } + return getGlyphExtents(f.glyf[glyph], f.hmtx, glyph), true +} + +func (f *Font) getExtentsFromBitmap(glyph gID, xPpem, yPpem uint16) (GlyphExtents, bool) { + strike := f.bitmap.chooseStrike(xPpem, yPpem) + if strike == nil || strike.ppemX == 0 || strike.ppemY == 0 { + return GlyphExtents{}, false + } + subtable := strike.findTable(glyph) + if subtable == nil { + return GlyphExtents{}, false + } + image := subtable.image(glyph) + if image == nil { + return GlyphExtents{}, false + } + extents := GlyphExtents{ + XBearing: float32(image.metrics.BearingX), + YBearing: float32(image.metrics.BearingY), + Width: float32(image.metrics.Width), + Height: -float32(image.metrics.Height), + } + + /* convert to font units. */ + xScale := float32(f.upem) / float32(strike.ppemX) + yScale := float32(f.upem) / float32(strike.ppemY) + extents.XBearing *= xScale + extents.YBearing *= yScale + extents.Width *= xScale + extents.Height *= yScale + return extents, true +} + +func (f *Font) getExtentsFromSbix(glyph gID, xPpem, yPpem uint16) (GlyphExtents, bool) { + strike := f.sbix.chooseStrike(xPpem, yPpem) + if strike == nil || strike.Ppem == 0 { + return GlyphExtents{}, false + } + data := strikeGlyph(strike, glyph, 0) + if data.GraphicType == 0 { + return GlyphExtents{}, false + } + extents, ok := bitmapGlyphExtents(data) + + /* convert to font units. */ + scale := float32(f.upem) / float32(strike.Ppem) + extents.XBearing *= scale + extents.YBearing *= scale + extents.Width *= scale + extents.Height *= scale + return extents, ok +} + +func (f *Font) getExtentsFromCff1(glyph gID) (GlyphExtents, bool) { + if f.cff == nil { + return GlyphExtents{}, false + } + _, bounds, err := f.cff.LoadGlyph(glyph) + if err != nil { + return GlyphExtents{}, false + } + return bounds.ToExtents(), true +} + +func (f *Face) getExtentsFromCff2(glyph gID) (GlyphExtents, bool) { + if f.cff2 == nil { + return GlyphExtents{}, false + } + _, bounds, err := f.cff2.LoadGlyph(glyph, f.coords) + if err != nil { + return GlyphExtents{}, false + } + return bounds.ToExtents(), true +} + +func (f *Face) glyphExtentsRaw(glyph GID) (GlyphExtents, bool) { + out, ok := f.getExtentsFromSbix(gID(glyph), f.xPpem, f.yPpem) + if ok { + return out, ok + } + out, ok = f.getExtentsFromGlyf(gID(glyph)) + if ok { + return out, ok + } + out, ok = f.getExtentsFromCff1(gID(glyph)) + if ok { + return out, ok + } + out, ok = f.getExtentsFromCff2(gID(glyph)) + if ok { + return out, ok + } + out, ok = f.getExtentsFromBitmap(gID(glyph), f.xPpem, f.yPpem) + return out, ok +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/opentype.go b/vendor/github.com/go-text/typesetting/font/opentype/opentype.go new file mode 100644 index 0000000..85b026a --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/opentype.go @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +// Package opentype provides the low level routines +// required to read and write Opentype font files, including collections. +// +// This package is designed to provide an efficient, lazy, reading API. +// +// For the parsing of the various tables, see package [tables]. +package opentype + +type Tag uint32 + +// NewTag returns the tag for . +func NewTag(a, b, c, d byte) Tag { + return Tag(uint32(d) | uint32(c)<<8 | uint32(b)<<16 | uint32(a)<<24) +} + +// MustNewTag gives you the Tag corresponding to the acronym. +// This function will panic if the string passed in is not 4 bytes long. +func MustNewTag(str string) Tag { + if len(str) != 4 { + panic("invalid tag: must be exactly 4 bytes") + } + _ = str[3] + return NewTag(str[0], str[1], str[2], str[3]) +} + +// String return the ASCII form of the tag. +func (t Tag) String() string { + return string([]byte{ + byte(t >> 24), + byte(t >> 16), + byte(t >> 8), + byte(t), + }) +} + +type GID uint32 + +type GlyphExtents struct { + XBearing float32 // Left side of glyph from origin + YBearing float32 // Top side of glyph from origin + Width float32 // Distance from left to right side + Height float32 // Distance from top to bottom side +} + +type SegmentOp uint8 + +const ( + SegmentOpMoveTo SegmentOp = iota + SegmentOpLineTo + SegmentOpQuadTo + SegmentOpCubeTo +) + +type SegmentPoint struct { + X, Y float32 // expressed in fonts units +} + +// Move translates the point. +func (pt *SegmentPoint) Move(dx, dy float32) { + pt.X += dx + pt.Y += dy +} + +type Segment struct { + Op SegmentOp + // Args is up to three (x, y) coordinates, depending on the + // operation. + // The Y axis increases up. + Args [3]SegmentPoint +} + +// ArgsSlice returns the effective slice of points +// used (whose length is between 1 and 3). +func (s *Segment) ArgsSlice() []SegmentPoint { + switch s.Op { + case SegmentOpMoveTo, SegmentOpLineTo: + return s.Args[0:1] + case SegmentOpQuadTo: + return s.Args[0:2] + case SegmentOpCubeTo: + return s.Args[0:3] + default: + panic("unreachable") + } +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/reader.go b/vendor/github.com/go-text/typesetting/font/opentype/reader.go new file mode 100644 index 0000000..312901c --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/reader.go @@ -0,0 +1,371 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package opentype + +import ( + "compress/zlib" + "encoding/binary" + "errors" + "fmt" + "io" + "sort" +) + +var ( + // TrueType is the first four bytes of an OpenType file containing a TrueType font + TrueType = Tag(0x00010000) + // AppleTrueType is the first four bytes of an OpenType file containing a TrueType font + // (specifically one designed for Apple products, it's recommended to use TrueType instead) + AppleTrueType = MustNewTag("true") + // PostScript1 is the first four bytes of an OpenType file containing a PostScript 1 font + PostScript1 = MustNewTag("typ1") + // OpenType is the first four bytes of an OpenType file containing a PostScript Type 2 font + // as specified by OpenType + OpenType = MustNewTag("OTTO") + + // signatureWOFF is the magic number at the start of a WOFF file. + signatureWOFF = MustNewTag("wOFF") + + ttcTag = MustNewTag("ttcf") + + errInvalidDfont = errors.New("invalid dfont") +) + +// dfontResourceDataOffset is the assumed value of a dfont file's resource data +// offset. +// +// https://github.com/kreativekorp/ksfl/wiki/Macintosh-Resource-File-Format +// says that "A Mac OS resource file... [starts with an] offset from start of +// file to start of resource data section... [usually] 0x0100". In theory, +// 0x00000100 isn't always a magic number for identifying dfont files. In +// practice, it seems to work. +const dfontResourceDataOffset = 0x00000100 + +type Resource interface { + Read([]byte) (int, error) + ReadAt([]byte, int64) (int, error) + Seek(int64, int) (int64, error) +} + +// tableSection represents a table within the font file. +type tableSection struct { + offset uint32 // Offset into the file this table starts. + length uint32 // Length of this table within the file. + zLength uint32 // Uncompressed length of this table. +} + +// Loader is the low level font reader, providing +// full control over table loading. +type Loader struct { + file Resource // source, needed to parse each table + tables map[Tag]tableSection // header only, contents is processed on demand + + // Type represents the kind of this font being loaded. + // It is one of TrueType, TrueTypeApple, PostScript1, OpenType + Type Tag +} + +// NewLoader reads the `file` header and returns +// a new lazy ot. +// `file` will be used to parse tables, and should not be close. +func NewLoader(file Resource) (*Loader, error) { + return parseOneFont(file, 0, false) +} + +// NewLoaders is the same as `NewLoader`, but supports collections. +func NewLoaders(file Resource) ([]*Loader, error) { + _, err := file.Seek(0, io.SeekStart) // file might have been used before + if err != nil { + return nil, err + } + + var bytes [4]byte + _, err = file.Read(bytes[:]) + if err != nil { + return nil, err + } + magic := NewTag(bytes[0], bytes[1], bytes[2], bytes[3]) + + file.Seek(0, io.SeekStart) + + var ( + pr *Loader + offsets []uint32 + relativeOffset bool + ) + switch magic { + case signatureWOFF, TrueType, OpenType, PostScript1, AppleTrueType: + pr, err = parseOneFont(file, 0, false) + case ttcTag: + offsets, err = parseTTCHeader(file) + case dfontResourceDataOffset: + offsets, err = parseDfont(file) + relativeOffset = true + default: + return nil, fmt.Errorf("unsupported font format %v", bytes) + } + if err != nil { + return nil, err + } + + // only one font + if pr != nil { + return []*Loader{pr}, nil + } + + // collection + out := make([]*Loader, len(offsets)) + for i, o := range offsets { + out[i], err = parseOneFont(file, o, relativeOffset) + if err != nil { + return nil, err + } + } + return out, nil +} + +// dst is an optional storage which may be provided to reduce allocations. +func (pr *Loader) findTableBuffer(s tableSection, dst []byte) ([]byte, error) { + if s.length != 0 && s.length < s.zLength { + zbuf := io.NewSectionReader(pr.file, int64(s.offset), int64(s.length)) + r, err := zlib.NewReader(zbuf) + if err != nil { + return nil, err + } + defer r.Close() + + if cap(dst) < int(s.zLength) { + dst = make([]byte, s.zLength) + } + dst = dst[0:s.zLength] + if _, err := io.ReadFull(r, dst); err != nil { + return nil, err + } + } else { + if cap(dst) < int(s.length) { + dst = make([]byte, s.length) + } + dst = dst[0:s.length] + if _, err := pr.file.ReadAt(dst, int64(s.offset)); err != nil { + return nil, err + } + } + return dst, nil +} + +// HasTable returns true if [table] is present. +func (pr *Loader) HasTable(table Tag) bool { + _, has := pr.tables[table] + return has +} + +// Tables returns all the tables found in the file, +// as a sorted slice. +func (ld *Loader) Tables() []Tag { + out := make([]Tag, 0, len(ld.tables)) + for tag := range ld.tables { + out = append(out, tag) + } + sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) + return out +} + +// RawTable returns the binary content of the given table, +// or an error if not found. +func (pr *Loader) RawTable(tag Tag) ([]byte, error) { + return pr.RawTableTo(tag, nil) +} + +// RawTable writes the binary content of the given table to [dst], returning it, +// or an error if not found. +func (pr *Loader) RawTableTo(tag Tag, dst []byte) ([]byte, error) { + s, found := pr.tables[tag] + if !found { + return nil, fmt.Errorf("missing table %s", tag) + } + + return pr.findTableBuffer(s, dst) +} + +func parseOneFont(file Resource, offset uint32, relativeOffset bool) (parser *Loader, err error) { + _, err = file.Seek(int64(offset), io.SeekStart) + if err != nil { + return nil, fmt.Errorf("invalid offset: %s", err) + } + + var bytes [4]byte + _, err = file.Read(bytes[:]) + if err != nil { + return nil, err + } + magic := NewTag(bytes[0], bytes[1], bytes[2], bytes[3]) + + switch magic { + case signatureWOFF: + parser, err = parseWOFF(file, offset, relativeOffset) + case TrueType, OpenType, PostScript1, AppleTrueType: + parser, err = parseOTF(file, offset, relativeOffset) + case ttcTag, dfontResourceDataOffset: // no more collections allowed here + return nil, errors.New("collections not allowed") + default: + return nil, fmt.Errorf("unknown font format tag %v", bytes) + } + + if err != nil { + return nil, err + } + + return parser, nil +} + +// support for collections + +const maxNumFonts = 2048 // security implementation limit + +// returns the offsets of each font +func parseTTCHeader(r io.Reader) ([]uint32, error) { + // The https://www.microsoft.com/typography/otspec/otff.htm "Font + // Collections" section describes the TTC header. + var buf [12]byte + if _, err := r.Read(buf[:]); err != nil { + return nil, err + } + // skip versions + numFonts := binary.BigEndian.Uint32(buf[8:]) + if numFonts == 0 { + return nil, errors.New("empty font collection") + } + if numFonts > maxNumFonts { + return nil, fmt.Errorf("number of fonts (%d) in collection exceed implementation limit (%d)", + numFonts, maxNumFonts) + } + + offsetsBytes := make([]byte, numFonts*4) + _, err := io.ReadFull(r, offsetsBytes) + if err != nil { + return nil, err + } + return parseUint32s(offsetsBytes, int(numFonts)), nil +} + +// parseDfont parses a dfont resource map, as per +// https://github.com/kreativekorp/ksfl/wiki/Macintosh-Resource-File-Format +// +// That unofficial wiki page lists all of its fields as *signed* integers, +// which looks unusual. The actual file format might use *unsigned* integers in +// various places, but until we have either an official specification or an +// actual dfont file where this matters, we'll use signed integers and treat +// negative values as invalid. +func parseDfont(r Resource) ([]uint32, error) { + var buf [16]byte + if _, err := r.Read(buf[:]); err != nil { + return nil, err + } + resourceMapOffset := binary.BigEndian.Uint32(buf[4:]) + resourceMapLength := binary.BigEndian.Uint32(buf[12:]) + + const ( + // (maxTableOffset + maxTableLength) will not overflow an int32. + maxTableLength = 1 << 29 + maxTableOffset = 1 << 29 + ) + if resourceMapOffset > maxTableOffset || resourceMapLength > maxTableLength { + return nil, errors.New("unsupported table offset or length") + } + + const headerSize = 28 + if resourceMapLength < headerSize { + return nil, errInvalidDfont + } + _, err := r.ReadAt(buf[:2], int64(resourceMapOffset+24)) + if err != nil { + return nil, err + } + typeListOffset := int64(int16(binary.BigEndian.Uint16(buf[:]))) + if typeListOffset < headerSize || resourceMapLength < uint32(typeListOffset)+2 { + return nil, errInvalidDfont + } + _, err = r.ReadAt(buf[:2], int64(resourceMapOffset)+typeListOffset) + if err != nil { + return nil, err + } + typeCount := int(binary.BigEndian.Uint16(buf[:])) // The number of types, minus one. + if typeCount == 0xFFFF { + return nil, errInvalidDfont + } + typeCount += 1 + + const tSize = 8 + if tSize*uint32(typeCount) > resourceMapLength-uint32(typeListOffset)-2 { + return nil, errInvalidDfont + } + + typeList := make([]byte, tSize*typeCount) + _, err = r.ReadAt(typeList, int64(resourceMapOffset)+typeListOffset+2) + if err != nil { + return nil, err + } + numFonts, resourceListOffset := 0, 0 + for i := 0; i < typeCount; i++ { + if binary.BigEndian.Uint32(typeList[tSize*i:]) != 0x73666e74 { // "sfnt". + continue + } + + numFonts = int(int16(binary.BigEndian.Uint16(typeList[tSize*i+4:]))) + if numFonts < 0 { + return nil, errInvalidDfont + } + // https://github.com/kreativekorp/ksfl/wiki/Macintosh-Resource-File-Format + // says that the value in the wire format is "the number of + // resources of this type, minus one." + numFonts++ + + resourceListOffset = int(int16(binary.BigEndian.Uint16((typeList[tSize*i+6:])))) + if resourceListOffset < 0 { + return nil, errInvalidDfont + } + } + if numFonts == 0 { + return nil, errInvalidDfont + } + if numFonts > maxNumFonts { + return nil, fmt.Errorf("number of fonts (%d) in collection exceed implementation limit (%d)", + numFonts, maxNumFonts) + } + + const rSize = 12 + o, n := uint32(int(typeListOffset)+resourceListOffset), rSize*uint32(numFonts) + if o > resourceMapLength || n > resourceMapLength-o { + return nil, errInvalidDfont + } + + offsetsBytes := make([]byte, n) + _, err = r.ReadAt(offsetsBytes, int64(resourceMapOffset+o)) + if err != nil { + return nil, err + } + + offsets := make([]uint32, numFonts) + for i := range offsets { + o := 0xffffff & binary.BigEndian.Uint32(offsetsBytes[rSize*i+4:]) + // Offsets are relative to the resource data start, not the file start. + // A particular resource's data also starts with a 4-byte length, which + // we skip. + o += dfontResourceDataOffset + 4 + if o > maxTableOffset { + return nil, errors.New("unsupported table offset or length") + } + offsets[i] = o + } + + return offsets, nil +} + +// data length must have been checked +func parseUint32s(data []byte, count int) []uint32 { + out := make([]uint32, count) + for i := range out { + out[i] = binary.BigEndian.Uint32(data[4*i:]) + } + return out +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/reader_otf.go b/vendor/github.com/go-text/typesetting/font/opentype/reader_otf.go new file mode 100644 index 0000000..ca77c39 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/reader_otf.go @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package opentype + +import ( + "encoding/binary" + "errors" + "fmt" + "io" +) + +// An Entry in an OpenType table. +type otfEntry struct { + Tag Tag + CheckSum uint32 + Offset uint32 + Length uint32 +} + +const ( + otfHeaderSize = 12 + otfEntrySize = 16 +) + +func readOTFHeader(r io.Reader) (flavor Tag, numTables uint16, err error) { + var buf [otfHeaderSize]byte + if _, err := r.Read(buf[:]); err != nil { + return 0, 0, fmt.Errorf("invalid OpenType header: %s", err) + } + + return NewTag(buf[0], buf[1], buf[2], buf[3]), binary.BigEndian.Uint16(buf[4:6]), nil +} + +func readOTFEntry(r io.Reader) (otfEntry, error) { + var ( + buf [otfEntrySize]byte + entry otfEntry + ) + if _, err := io.ReadFull(r, buf[:]); err != nil { + return entry, fmt.Errorf("invalid directory entry: %s", err) + } + + entry.Tag = Tag(binary.BigEndian.Uint32(buf[0:4])) + entry.CheckSum = binary.BigEndian.Uint32(buf[4:8]) + entry.Offset = binary.BigEndian.Uint32(buf[8:12]) + entry.Length = binary.BigEndian.Uint32(buf[12:16]) + + return entry, nil +} + +// parseOTF reads an OpenTyp (.otf) or TrueType (.ttf) file and returns a Font. +// If the parsing fails, then an error is returned and Font will be nil. +// `offset` is the beginning of the ressource in the file (non zero for collections) +// `relativeOffset` is true when the table offset are expresed relatively to the ressource start +// (that is, `offset`) rather than to the file start. +func parseOTF(file Resource, offset uint32, relativeOffset bool) (*Loader, error) { + _, err := file.Seek(int64(offset), io.SeekStart) + if err != nil { + return nil, fmt.Errorf("invalid offset: %s", err) + } + + flavor, numTables, err := readOTFHeader(file) + if err != nil { + return nil, err + } + + pr := &Loader{ + file: file, + tables: make(map[Tag]tableSection, numTables), + Type: flavor, + } + + for i := 0; i < int(numTables); i++ { + entry, err := readOTFEntry(file) + if err != nil { + return nil, err + } + + if _, found := pr.tables[entry.Tag]; found { + // ignore duplicate tables – the first one wins + continue + } + + sec := tableSection{ + offset: entry.Offset, + length: entry.Length, + } + // adapt the relative offsets + if relativeOffset { + sec.offset += offset + if sec.offset < offset { // check for overflow + return nil, errors.New("unsupported table offset or length") + } + } + pr.tables[entry.Tag] = sec + } + + return pr, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/reader_woff.go b/vendor/github.com/go-text/typesetting/font/opentype/reader_woff.go new file mode 100644 index 0000000..1860be3 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/reader_woff.go @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package opentype + +import ( + "encoding/binary" + "errors" + "io" +) + +type woffEntry struct { + Tag Tag + Offset uint32 + CompLength uint32 + OrigLength uint32 + OrigChecksum uint32 +} + +const ( + woffHeaderSize = 44 // for the full header, but we only read Flavor and NumTables + woffEntrySize = 20 +) + +func readWOFFHeader(r io.Reader) (flavor Tag, numTables uint16, err error) { + var buf [woffHeaderSize]byte + if _, err := io.ReadFull(r, buf[:]); err != nil { + return 0, 0, err + } + + return NewTag(buf[4], buf[5], buf[6], buf[7]), binary.BigEndian.Uint16(buf[12:14]), nil +} + +func readWOFFEntry(r io.Reader) (woffEntry, error) { + var ( + buf [woffEntrySize]byte + entry woffEntry + ) + if _, err := io.ReadFull(r, buf[:]); err != nil { + return entry, err + } + entry.Tag = NewTag(buf[0], buf[1], buf[2], buf[3]) + entry.Offset = binary.BigEndian.Uint32(buf[4:8]) + entry.CompLength = binary.BigEndian.Uint32(buf[8:12]) + entry.OrigLength = binary.BigEndian.Uint32(buf[12:16]) + entry.OrigChecksum = binary.BigEndian.Uint32(buf[16:20]) + return entry, nil +} + +// `offset` is the beginning of the ressource in the file (non zero for collections) +// `relativeOffset` is true when the table offset are expresed relatively ot the ressource +// (that is, `offset`) rather than to the file +func parseWOFF(file Resource, offset uint32, relativeOffset bool) (*Loader, error) { + _, err := file.Seek(int64(offset), io.SeekStart) + if err != nil { + return nil, err + } + + flavor, numTables, err := readWOFFHeader(file) + if err != nil { + return nil, err + } + + fontParser := &Loader{ + file: file, + tables: make(map[Tag]tableSection, numTables), + Type: flavor, + } + for i := 0; i < int(numTables); i++ { + entry, err := readWOFFEntry(file) + if err != nil { + return nil, err + } + + if _, found := fontParser.tables[entry.Tag]; found { + // ignore duplicate tables – the first one wins + continue + } + + sec := tableSection{ + offset: entry.Offset, + length: entry.CompLength, + zLength: entry.OrigLength, + } + // adapt the relative offsets + if relativeOffset { + sec.offset += offset + if sec.offset < offset { // check for overflow + return nil, errors.New("unsupported table offset or length") + } + } + + fontParser.tables[entry.Tag] = sec + } + + return fontParser, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_ankr_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_ankr_gen.go new file mode 100644 index 0000000..c7633cd --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_ankr_gen.go @@ -0,0 +1,345 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from aat_ankr_src.go. DO NOT EDIT + +func (item *AnkrAnchor) mustParse(src []byte) { + _ = src[3] // early bound checking + item.X = int16(binary.BigEndian.Uint16(src[0:])) + item.Y = int16(binary.BigEndian.Uint16(src[2:])) +} + +func (item *LookupRecord2) mustParse(src []byte) { + _ = src[5] // early bound checking + item.LastGlyph = binary.BigEndian.Uint16(src[0:]) + item.FirstGlyph = binary.BigEndian.Uint16(src[2:]) + item.Value = binary.BigEndian.Uint16(src[4:]) +} + +func ParseAATLookup(src []byte, valuesCount int) (AATLookup, int, error) { + var item AATLookup + + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading AATLookup: "+"EOF: expected length: 2, got %d", L) + } + format := uint16(binary.BigEndian.Uint16(src[0:])) + var ( + read int + err error + ) + switch format { + case 0: + item, read, err = ParseAATLoopkup0(src[0:], valuesCount) + case 10: + item, read, err = ParseAATLoopkup10(src[0:]) + case 2: + item, read, err = ParseAATLoopkup2(src[0:]) + case 4: + item, read, err = ParseAATLoopkup4(src[0:]) + case 6: + item, read, err = ParseAATLoopkup6(src[0:]) + case 8: + item, read, err = ParseAATLoopkup8(src[0:]) + default: + err = fmt.Errorf("unsupported AATLookup format %d", format) + } + if err != nil { + return item, 0, fmt.Errorf("reading AATLookup: %s", err) + } + + return item, read, nil +} + +func ParseAATLookupRecord4(src []byte, parentSrc []byte) (AATLookupRecord4, int, error) { + var item AATLookupRecord4 + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading AATLookupRecord4: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.LastGlyph = binary.BigEndian.Uint16(src[0:]) + item.FirstGlyph = binary.BigEndian.Uint16(src[2:]) + offsetValues := int(binary.BigEndian.Uint16(src[4:])) + n += 6 + + { + + if offsetValues != 0 { // ignore null offset + if L := len(parentSrc); L < offsetValues { + return item, 0, fmt.Errorf("reading AATLookupRecord4: "+"EOF: expected length: %d, got %d", offsetValues, L) + } + + arrayLength := int(item.nValues()) + + if L := len(parentSrc); L < offsetValues+arrayLength*2 { + return item, 0, fmt.Errorf("reading AATLookupRecord4: "+"EOF: expected length: %d, got %d", offsetValues+arrayLength*2, L) + } + + item.Values = make([]uint16, arrayLength) // allocation guarded by the previous check + for i := range item.Values { + item.Values[i] = binary.BigEndian.Uint16(parentSrc[offsetValues+i*2:]) + } + offsetValues += arrayLength * 2 + } + } + return item, n, nil +} + +func ParseAATLoopkup0(src []byte, valuesCount int) (AATLoopkup0, int, error) { + var item AATLoopkup0 + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading AATLoopkup0: "+"EOF: expected length: 2, got %d", L) + } + item.version = binary.BigEndian.Uint16(src[0:]) + n += 2 + + { + + if L := len(src); L < 2+valuesCount*2 { + return item, 0, fmt.Errorf("reading AATLoopkup0: "+"EOF: expected length: %d, got %d", 2+valuesCount*2, L) + } + + item.Values = make([]uint16, valuesCount) // allocation guarded by the previous check + for i := range item.Values { + item.Values[i] = binary.BigEndian.Uint16(src[2+i*2:]) + } + n += valuesCount * 2 + } + return item, n, nil +} + +func ParseAATLoopkup10(src []byte) (AATLoopkup10, int, error) { + var item AATLoopkup10 + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading AATLoopkup10: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.version = binary.BigEndian.Uint16(src[0:]) + item.unitSize = binary.BigEndian.Uint16(src[2:]) + item.FirstGlyph = binary.BigEndian.Uint16(src[4:]) + arrayLengthValues := int(binary.BigEndian.Uint16(src[6:])) + n += 8 + + { + + if L := len(src); L < 8+arrayLengthValues*2 { + return item, 0, fmt.Errorf("reading AATLoopkup10: "+"EOF: expected length: %d, got %d", 8+arrayLengthValues*2, L) + } + + item.Values = make([]uint16, arrayLengthValues) // allocation guarded by the previous check + for i := range item.Values { + item.Values[i] = binary.BigEndian.Uint16(src[8+i*2:]) + } + n += arrayLengthValues * 2 + } + return item, n, nil +} + +func ParseAATLoopkup2(src []byte) (AATLoopkup2, int, error) { + var item AATLoopkup2 + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading AATLoopkup2: "+"EOF: expected length: 12, got %d", L) + } + _ = src[11] // early bound checking + item.version = binary.BigEndian.Uint16(src[0:]) + item.binSearchHeader.mustParse(src[2:]) + n += 12 + + { + arrayLength := int(item.nUnits) + + if L := len(src); L < 12+arrayLength*6 { + return item, 0, fmt.Errorf("reading AATLoopkup2: "+"EOF: expected length: %d, got %d", 12+arrayLength*6, L) + } + + item.Records = make([]LookupRecord2, arrayLength) // allocation guarded by the previous check + for i := range item.Records { + item.Records[i].mustParse(src[12+i*6:]) + } + n += arrayLength * 6 + } + return item, n, nil +} + +func ParseAATLoopkup4(src []byte) (AATLoopkup4, int, error) { + var item AATLoopkup4 + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading AATLoopkup4: "+"EOF: expected length: 12, got %d", L) + } + _ = src[11] // early bound checking + item.version = binary.BigEndian.Uint16(src[0:]) + item.binSearchHeader.mustParse(src[2:]) + n += 12 + + { + arrayLength := int(item.nUnits - 1) + + offset := 12 + for i := 0; i < arrayLength; i++ { + elem, read, err := ParseAATLookupRecord4(src[offset:], src) + if err != nil { + return item, 0, fmt.Errorf("reading AATLoopkup4: %s", err) + } + item.Records = append(item.Records, elem) + offset += read + } + n = offset + } + return item, n, nil +} + +func ParseAATLoopkup6(src []byte) (AATLoopkup6, int, error) { + var item AATLoopkup6 + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading AATLoopkup6: "+"EOF: expected length: 12, got %d", L) + } + _ = src[11] // early bound checking + item.version = binary.BigEndian.Uint16(src[0:]) + item.binSearchHeader.mustParse(src[2:]) + n += 12 + + { + arrayLength := int(item.nUnits) + + if L := len(src); L < 12+arrayLength*4 { + return item, 0, fmt.Errorf("reading AATLoopkup6: "+"EOF: expected length: %d, got %d", 12+arrayLength*4, L) + } + + item.Records = make([]loopkupRecord6, arrayLength) // allocation guarded by the previous check + for i := range item.Records { + item.Records[i].mustParse(src[12+i*4:]) + } + n += arrayLength * 4 + } + return item, n, nil +} + +func ParseAATLoopkup8(src []byte) (AATLoopkup8, int, error) { + var item AATLoopkup8 + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading AATLoopkup8: "+"EOF: expected length: 2, got %d", L) + } + item.version = binary.BigEndian.Uint16(src[0:]) + n += 2 + + { + var ( + err error + read int + ) + item.AATLoopkup8Data, read, err = ParseAATLoopkup8Data(src[2:]) + if err != nil { + return item, 0, fmt.Errorf("reading AATLoopkup8: %s", err) + } + n += read + } + return item, n, nil +} + +func ParseAATLoopkup8Data(src []byte) (AATLoopkup8Data, int, error) { + var item AATLoopkup8Data + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading AATLoopkup8Data: "+"EOF: expected length: 4, got %d", L) + } + _ = src[3] // early bound checking + item.FirstGlyph = binary.BigEndian.Uint16(src[0:]) + arrayLengthValues := int(binary.BigEndian.Uint16(src[2:])) + n += 4 + + { + + if L := len(src); L < 4+arrayLengthValues*2 { + return item, 0, fmt.Errorf("reading AATLoopkup8Data: "+"EOF: expected length: %d, got %d", 4+arrayLengthValues*2, L) + } + + item.Values = make([]uint16, arrayLengthValues) // allocation guarded by the previous check + for i := range item.Values { + item.Values[i] = binary.BigEndian.Uint16(src[4+i*2:]) + } + n += arrayLengthValues * 2 + } + return item, n, nil +} + +func ParseAnkr(src []byte, valuesCount int) (Ankr, int, error) { + var item Ankr + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading Ankr: "+"EOF: expected length: 12, got %d", L) + } + _ = src[11] // early bound checking + item.version = binary.BigEndian.Uint16(src[0:]) + item.flags = binary.BigEndian.Uint16(src[2:]) + offsetLookupTable := int(binary.BigEndian.Uint32(src[4:])) + offsetGlyphDataTable := int(binary.BigEndian.Uint32(src[8:])) + n += 12 + + { + + if offsetLookupTable != 0 { // ignore null offset + if L := len(src); L < offsetLookupTable { + return item, 0, fmt.Errorf("reading Ankr: "+"EOF: expected length: %d, got %d", offsetLookupTable, L) + } + + var ( + err error + read int + ) + item.lookupTable, read, err = ParseAATLookup(src[offsetLookupTable:], valuesCount) + if err != nil { + return item, 0, fmt.Errorf("reading Ankr: %s", err) + } + offsetLookupTable += read + } + } + { + + if offsetGlyphDataTable != 0 { // ignore null offset + if L := len(src); L < offsetGlyphDataTable { + return item, 0, fmt.Errorf("reading Ankr: "+"EOF: expected length: %d, got %d", offsetGlyphDataTable, L) + } + + item.glyphDataTable = src[offsetGlyphDataTable:] + } + } + return item, n, nil +} + +func ParseAnkrAnchor(src []byte) (AnkrAnchor, int, error) { + var item AnkrAnchor + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading AnkrAnchor: "+"EOF: expected length: 4, got %d", L) + } + item.mustParse(src) + n += 4 + return item, n, nil +} + +func (item *binSearchHeader) mustParse(src []byte) { + _ = src[9] // early bound checking + item.unitSize = binary.BigEndian.Uint16(src[0:]) + item.nUnits = binary.BigEndian.Uint16(src[2:]) + item.searchRange = binary.BigEndian.Uint16(src[4:]) + item.entrySelector = binary.BigEndian.Uint16(src[6:]) + item.rangeShift = binary.BigEndian.Uint16(src[8:]) +} + +func (item *loopkupRecord6) mustParse(src []byte) { + _ = src[3] // early bound checking + item.Glyph = binary.BigEndian.Uint16(src[0:]) + item.Value = binary.BigEndian.Uint16(src[2:]) +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_ankr_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_ankr_src.go new file mode 100644 index 0000000..330811a --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_ankr_src.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import "encoding/binary" + +// Ankr is the anchor point table +// See - https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6ankr.html +type Ankr struct { + version uint16 // Version number (set to zero) + flags uint16 // Flags (currently unused; set to zero) + // Offset to the table's lookup table; currently this is always 0x0000000C + // The lookup table returns uint16 offset from the beginning of the glyph data table, not indices. + lookupTable AATLookup `offsetSize:"Offset32"` + // Offset to the glyph data table + glyphDataTable []byte `offsetSize:"Offset32" arrayCount:"ToEnd"` +} + +// GetAnchor return the i-th anchor for `glyph`, or {0,0} if not found. +func (ank Ankr) GetAnchor(glyph GlyphID, index int) (anchor AnkrAnchor) { + offset, ok := ank.lookupTable.Class(glyph) + if !ok || int(offset)+4 >= len(ank.glyphDataTable) { + return anchor + } + + count := int(binary.BigEndian.Uint32(ank.glyphDataTable[offset:])) + if index >= count { + return anchor // invalid index + } + + indexStart := int(offset) + 4 + 4*index + if len(ank.glyphDataTable) < indexStart+4 { + return anchor // invalid table + } + anchor.X = int16(binary.BigEndian.Uint16(ank.glyphDataTable[indexStart:])) + anchor.Y = int16(binary.BigEndian.Uint16(ank.glyphDataTable[indexStart+2:])) + return anchor +} + +// AnkrAnchor is a point within the coordinate space of a given glyph +// independent of the control points used to render the glyph +type AnkrAnchor struct { + X, Y int16 +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_common.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_common.go new file mode 100644 index 0000000..f9ee7de --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_common.go @@ -0,0 +1,350 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// AAT layout + +// State table header, without the actual data +// See https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6Tables.html +type AATStateTable struct { + StateSize uint16 // Size of a state, in bytes. The size is limited to 8 bits, although the field is 16 bits for alignment. + ClassTable ClassTable `offsetSize:"Offset16"` // Byte offset from the beginning of the state table to the class subtable. + stateArray Offset16 // Byte offset from the beginning of the state table to the state array. + entryTable Offset16 // Byte offset from the beginning of the state table to the entry subtable. + States [][]uint8 `isOpaque:""` + Entries []AATStateEntry `isOpaque:""` // entry data are empty +} + +func (state *AATStateTable) parseStates(src []byte) error { + if state.stateArray > state.entryTable { + return fmt.Errorf("invalid AAT state offsets (%d > %d)", state.stateArray, state.entryTable) + } + if L := len(src); L < int(state.entryTable) { + return fmt.Errorf("EOF: expected length: %d, got %d", state.entryTable, L) + } + states := src[state.stateArray:state.entryTable] + + nC := int(state.StateSize) + // Ensure pre-defined classes fit. + if nC < 4 { + return fmt.Errorf("invalid number of classes in AAT state table: %d", nC) + } + state.States = make([][]uint8, len(states)/nC) + for i := range state.States { + state.States[i] = states[i*nC : (i+1)*nC] + } + + return nil +} + +func (state *AATStateTable) parseEntries(src []byte) (int, error) { + // find max index + var maxi uint8 + for _, l := range state.States { + for _, stateIndex := range l { + if stateIndex > maxi { + maxi = stateIndex + } + } + } + + src = src[state.entryTable:] // checked in parseStates + count := int(maxi) + 1 + var err error + state.Entries, err = parseAATStateEntries(src, count, 0) + if err != nil { + return 0, err + } + + // newState is an offset: convert back to index + for i, entry := range state.Entries { + state.Entries[i].NewState = uint16((int(entry.NewState) - int(state.stateArray)) / int(state.StateSize)) + } + + // the own header data stop at the entryTable offset + return 8, err +} + +// src starts at the entryTable +func parseAATStateEntries(src []byte, count, entryDataSize int) ([]AATStateEntry, error) { + entrySize := 4 + entryDataSize + if L := len(src); L < count*entrySize { + return nil, fmt.Errorf("EOF: expected length: %d, got %d", count*entrySize, L) + } + out := make([]AATStateEntry, count) + for i := range out { + out[i].NewState = binary.BigEndian.Uint16(src[i*entrySize:]) + out[i].Flags = binary.BigEndian.Uint16(src[i*entrySize+2:]) + copy(out[i].data[:], src[i*entrySize+4:(i+1)*entrySize]) + } + + return out, nil +} + +// ClassTable is the same as AATLookup8, but with no format and with bytes instead of uint16s +type ClassTable struct { + StartGlyph GlyphID + Values []byte `arrayCount:"FirstUint16"` +} + +// Extended state table, including the data +// See https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6Tables.html - State tables +// binarygen: argument=entryDataSize int +type AATStateTableExt struct { + StateSize uint32 // Size of a state, in bytes. The size is limited to 8 bits, although the field is 16 bits for alignment. + Class AATLookup `offsetSize:"Offset32"` // Byte offset from the beginning of the state table to the class subtable. + stateArray Offset32 // Byte offset from the beginning of the state table to the state array. + entryTable Offset32 // Byte offset from the beginning of the state table to the entry subtable. + States [][]uint16 `isOpaque:""` // each sub array has length stateSize + Entries []AATStateEntry `isOpaque:""` // length is the maximum state + 1 +} + +func (state *AATStateTableExt) parseStates(src []byte, _, _ int) error { + if state.stateArray > state.entryTable { + return fmt.Errorf("invalid AAT state offsets (%d > %d)", state.stateArray, state.entryTable) + } + if L := len(src); L < int(state.entryTable) { + return fmt.Errorf("EOF: expected length: %d, got %d", state.entryTable, L) + } + + statesArray := src[state.stateArray:state.entryTable] + states, err := ParseUint16s(statesArray, len(statesArray)/2) + if err != nil { + return err + } + + nC := int(state.StateSize) + // Ensure pre-defined classes fit. + if nC < 4 { + return fmt.Errorf("invalid number of classes in AAT state table: %d", nC) + } + state.States = make([][]uint16, len(states)/nC) + for i := range state.States { + state.States[i] = states[i*nC : (i+1)*nC] + } + return nil +} + +func (state *AATStateTableExt) parseEntries(src []byte, _, entryDataSize int) (int, error) { + // find max index + var maxi uint16 + for _, l := range state.States { + for _, stateIndex := range l { + if stateIndex > maxi { + maxi = stateIndex + } + } + } + + src = src[state.entryTable:] // checked in parseStates + count := int(maxi) + 1 + var err error + state.Entries, err = parseAATStateEntries(src, count, entryDataSize) + + // the own header data stop at the entryTable offset + return 16, err +} + +// AATStateEntry is shared between old and extended state tables, +// and between the different kind of entries. +// See the various AsXXX() methods. +type AATStateEntry struct { + NewState uint16 + Flags uint16 // Table specific. + data [4]byte // Table specific. +} + +// AsMorxContextual reads the internal data for entries in morx contextual subtable. +// The returned indexes use 0xFFFF as empty value. +func (e AATStateEntry) AsMorxContextual() (markIndex, currentIndex uint16) { + markIndex = binary.BigEndian.Uint16(e.data[:]) + currentIndex = binary.BigEndian.Uint16(e.data[2:]) + return +} + +// AsMorxInsertion reads the internal data for entries in morx insertion subtable. +// The returned indexes use 0xFFFF as empty value. +func (e AATStateEntry) AsMorxInsertion() (currentIndex, markedIndex uint16) { + currentIndex = binary.BigEndian.Uint16(e.data[:]) + markedIndex = binary.BigEndian.Uint16(e.data[2:]) + return +} + +// AsMorxLigature reads the internal data for entries in morx ligature subtable. +func (e AATStateEntry) AsMorxLigature() (ligActionIndex uint16) { + return binary.BigEndian.Uint16(e.data[:]) +} + +// AsKernxIndex reads the internal data for entries in 'kern/x' subtable format 1 or 4. +// An entry with no index returns 0xFFFF +func (e AATStateEntry) AsKernxIndex() uint16 { + // for kern table, during parsing, we store the resolved index + // at the same place as kerx tables + return binary.BigEndian.Uint16(e.data[:]) +} + +type binSearchHeader struct { + unitSize uint16 + nUnits uint16 + searchRange uint16 // The value of unitSize times the largest power of 2 that is less than or equal to the value of nUnits. + entrySelector uint16 // The log base 2 of the largest power of 2 less than or equal to the value of nUnits. + rangeShift uint16 // The value of unitSize times the difference of the value of nUnits minus the largest power of 2 less than or equal to the value of nUnits. +} + +// AATLookup is conceptually a map[GlyphID]uint16, but it may +// be implemented more efficiently. +type AATLookup interface { + AatLookupMixed + + isAATLookup() + + // Class returns the class ID for the provided glyph, or (0, false) + // for glyphs not covered by this class. + Class(g GlyphID) (uint16, bool) +} + +func (AATLoopkup0) isAATLookup() {} +func (AATLoopkup2) isAATLookup() {} +func (AATLoopkup4) isAATLookup() {} +func (AATLoopkup6) isAATLookup() {} +func (AATLoopkup8) isAATLookup() {} +func (AATLoopkup10) isAATLookup() {} + +type AATLoopkup0 struct { + version uint16 `unionTag:"0"` + Values []uint16 `arrayCount:""` +} + +type AATLoopkup2 struct { + version uint16 `unionTag:"2"` + binSearchHeader + Records []LookupRecord2 `arrayCount:"ComputedField-nUnits"` +} + +type LookupRecord2 struct { + LastGlyph GlyphID + FirstGlyph GlyphID + Value uint16 +} + +type AATLoopkup4 struct { + version uint16 `unionTag:"4"` + binSearchHeader + // Do not include the termination segment + Records []AATLookupRecord4 `arrayCount:"ComputedField-nUnits-1"` +} + +type AATLookupRecord4 struct { + LastGlyph GlyphID + FirstGlyph GlyphID + // offset to an array of []uint16 (or []uint32 for extended) with length last - first + 1 + Values []uint16 `offsetSize:"Offset16" offsetRelativeTo:"Parent" arrayCount:"ComputedField-nValues()"` +} + +func (lk AATLookupRecord4) nValues() int { return int(lk.LastGlyph) - int(lk.FirstGlyph) + 1 } + +type AATLoopkup6 struct { + version uint16 `unionTag:"6"` + binSearchHeader + Records []loopkupRecord6 `arrayCount:"ComputedField-nUnits"` +} + +type loopkupRecord6 struct { + Glyph GlyphID + Value uint16 +} + +type AATLoopkup8 struct { + version uint16 `unionTag:"8"` + AATLoopkup8Data +} + +type AATLoopkup8Data struct { + FirstGlyph GlyphID + Values []uint16 `arrayCount:"FirstUint16"` +} + +type AATLoopkup10 struct { + version uint16 `unionTag:"10"` + unitSize uint16 + FirstGlyph GlyphID + Values []uint16 `arrayCount:"FirstUint16"` +} + +// extended versions + +// AATLookupExt is the same as AATLookup, but class values are uint32 +type AATLookupExt interface { + AatLookupMixed + + isAATLookupExt() + + // Class returns the class ID for the provided glyph, or (0, false) + // for glyphs not covered by this class. + Class(g GlyphID) (uint32, bool) +} + +func (AATLoopkupExt0) isAATLookupExt() {} +func (AATLoopkupExt2) isAATLookupExt() {} +func (AATLoopkupExt4) isAATLookupExt() {} +func (AATLoopkupExt6) isAATLookupExt() {} +func (AATLoopkupExt8) isAATLookupExt() {} +func (AATLoopkupExt10) isAATLookupExt() {} + +type AATLoopkupExt0 struct { + version uint16 `unionTag:"0"` + Values []uint32 `arrayCount:""` +} + +type AATLoopkupExt2 struct { + version uint16 `unionTag:"2"` + binSearchHeader + Records []lookupRecordExt2 `arrayCount:"ComputedField-nUnits"` +} + +type lookupRecordExt2 struct { + LastGlyph GlyphID + FirstGlyph GlyphID + Value uint32 +} + +type AATLoopkupExt4 struct { + version uint16 `unionTag:"4"` + binSearchHeader + // the values pointed by the record are uint32 + Records []loopkupRecordExt4 `arrayCount:"ComputedField-nUnits"` +} + +type loopkupRecordExt4 struct { + LastGlyph GlyphID + FirstGlyph GlyphID + // offset to an array of []uint16 (or []uint32 for extended) with length last - first + 1 + Values []uint32 `offsetSize:"Offset16" offsetRelativeTo:"Parent" arrayCount:"ComputedField-nValues()"` +} + +func (lk loopkupRecordExt4) nValues() int { return int(lk.LastGlyph) - int(lk.FirstGlyph) + 1 } + +type AATLoopkupExt6 struct { + version uint16 `unionTag:"6"` + binSearchHeader + Records []loopkupRecordExt6 `arrayCount:"ComputedField-nUnits"` +} + +type loopkupRecordExt6 struct { + Glyph GlyphID + Value uint32 +} + +type AATLoopkupExt8 AATLoopkup8 + +type AATLoopkupExt10 struct { + version uint16 `unionTag:"10"` + unitSize uint16 + FirstGlyph GlyphID + Values []uint32 `arrayCount:"FirstUint16"` +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_feat_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_feat_gen.go new file mode 100644 index 0000000..9f3d618 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_feat_gen.go @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from aat_feat_src.go. DO NOT EDIT + +func (item *FeatureSettingName) mustParse(src []byte) { + _ = src[3] // early bound checking + item.Setting = binary.BigEndian.Uint16(src[0:]) + item.NameIndex = binary.BigEndian.Uint16(src[2:]) +} + +func ParseFeat(src []byte) (Feat, int, error) { + var item Feat + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading Feat: "+"EOF: expected length: 12, got %d", L) + } + _ = src[11] // early bound checking + item.version = binary.BigEndian.Uint32(src[0:]) + item.featureNameCount = binary.BigEndian.Uint16(src[4:]) + item.none1 = binary.BigEndian.Uint16(src[6:]) + item.none2 = binary.BigEndian.Uint32(src[8:]) + n += 12 + + { + arrayLength := int(item.featureNameCount) + + offset := 12 + for i := 0; i < arrayLength; i++ { + elem, read, err := ParseFeatureName(src[offset:], src) + if err != nil { + return item, 0, fmt.Errorf("reading Feat: %s", err) + } + item.Names = append(item.Names, elem) + offset += read + } + n = offset + } + return item, n, nil +} + +func ParseFeatureName(src []byte, parentSrc []byte) (FeatureName, int, error) { + var item FeatureName + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading FeatureName: "+"EOF: expected length: 12, got %d", L) + } + _ = src[11] // early bound checking + item.Feature = binary.BigEndian.Uint16(src[0:]) + item.nSettings = binary.BigEndian.Uint16(src[2:]) + offsetSettingTable := int(binary.BigEndian.Uint32(src[4:])) + item.FeatureFlags = binary.BigEndian.Uint16(src[8:]) + item.NameIndex = binary.BigEndian.Uint16(src[10:]) + n += 12 + + { + + if offsetSettingTable != 0 { // ignore null offset + if L := len(parentSrc); L < offsetSettingTable { + return item, 0, fmt.Errorf("reading FeatureName: "+"EOF: expected length: %d, got %d", offsetSettingTable, L) + } + + arrayLength := int(item.nSettings) + + if L := len(parentSrc); L < offsetSettingTable+arrayLength*4 { + return item, 0, fmt.Errorf("reading FeatureName: "+"EOF: expected length: %d, got %d", offsetSettingTable+arrayLength*4, L) + } + + item.SettingTable = make([]FeatureSettingName, arrayLength) // allocation guarded by the previous check + for i := range item.SettingTable { + item.SettingTable[i].mustParse(parentSrc[offsetSettingTable+i*4:]) + } + offsetSettingTable += arrayLength * 4 + } + } + return item, n, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_feat_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_feat_src.go new file mode 100644 index 0000000..0dbcd90 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_feat_src.go @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +// Feat is the feature name table. +// See - https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6feat.html +type Feat struct { + version uint32 // Version number of the feature name table (0x00010000 for the current version). + featureNameCount uint16 // The number of entries in the feature name array. + none1 uint16 // Reserved (set to zero). + none2 uint32 // Reserved (set to zero). + Names []FeatureName `arrayCount:"ComputedField-featureNameCount"` // The feature name array. +} + +type FeatureName struct { + Feature uint16 // Feature type. + nSettings uint16 // The number of records in the setting name array. + SettingTable []FeatureSettingName `offsetSize:"Offset32" offsetRelativeTo:"Parent" arrayCount:"ComputedField-nSettings"` // Offset in bytes from the beginning of the 'feat' table to this feature's setting name array. The actual type of record this offset refers to will depend on the exclusivity value, as described below. + FeatureFlags uint16 // Single-bit flags associated with the feature type. + NameIndex uint16 // The name table index for the feature's name. This index has values greater than 255 and less than 32768. +} + +type FeatureSettingName struct { + Setting uint16 // The setting. + NameIndex uint16 // The name table index for the setting's name. The nameIndex must be greater than 255 and less than 32768. +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_kerx_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_kerx_gen.go new file mode 100644 index 0000000..10c47b3 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_kerx_gen.go @@ -0,0 +1,646 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from aat_kerx_src.go. DO NOT EDIT + +func (item *KAAnchor) mustParse(src []byte) { + _ = src[3] // early bound checking + item.Mark = binary.BigEndian.Uint16(src[0:]) + item.Current = binary.BigEndian.Uint16(src[2:]) +} + +func (item *KAControl) mustParse(src []byte) { + _ = src[3] // early bound checking + item.Mark = binary.BigEndian.Uint16(src[0:]) + item.Current = binary.BigEndian.Uint16(src[2:]) +} + +func (item *KACoordinates) mustParse(src []byte) { + _ = src[7] // early bound checking + item.MarkX = int16(binary.BigEndian.Uint16(src[0:])) + item.MarkY = int16(binary.BigEndian.Uint16(src[2:])) + item.CurrentX = int16(binary.BigEndian.Uint16(src[4:])) + item.CurrentY = int16(binary.BigEndian.Uint16(src[6:])) +} + +func (item *Kernx0Record) mustParse(src []byte) { + _ = src[5] // early bound checking + item.Left = binary.BigEndian.Uint16(src[0:]) + item.Right = binary.BigEndian.Uint16(src[2:]) + item.Value = int16(binary.BigEndian.Uint16(src[4:])) +} + +func ParseAATLookupExt(src []byte, valuesCount int) (AATLookupExt, int, error) { + var item AATLookupExt + + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading AATLookupExt: "+"EOF: expected length: 2, got %d", L) + } + format := uint16(binary.BigEndian.Uint16(src[0:])) + var ( + read int + err error + ) + switch format { + case 0: + item, read, err = ParseAATLoopkupExt0(src[0:], valuesCount) + case 10: + item, read, err = ParseAATLoopkupExt10(src[0:]) + case 2: + item, read, err = ParseAATLoopkupExt2(src[0:]) + case 4: + item, read, err = ParseAATLoopkupExt4(src[0:]) + case 6: + item, read, err = ParseAATLoopkupExt6(src[0:]) + case 8: + item, read, err = ParseAATLoopkupExt8(src[0:]) + default: + err = fmt.Errorf("unsupported AATLookupExt format %d", format) + } + if err != nil { + return item, 0, fmt.Errorf("reading AATLookupExt: %s", err) + } + + return item, read, nil +} + +func ParseAATLoopkupExt0(src []byte, valuesCount int) (AATLoopkupExt0, int, error) { + var item AATLoopkupExt0 + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading AATLoopkupExt0: "+"EOF: expected length: 2, got %d", L) + } + item.version = binary.BigEndian.Uint16(src[0:]) + n += 2 + + { + + if L := len(src); L < 2+valuesCount*4 { + return item, 0, fmt.Errorf("reading AATLoopkupExt0: "+"EOF: expected length: %d, got %d", 2+valuesCount*4, L) + } + + item.Values = make([]uint32, valuesCount) // allocation guarded by the previous check + for i := range item.Values { + item.Values[i] = binary.BigEndian.Uint32(src[2+i*4:]) + } + n += valuesCount * 4 + } + return item, n, nil +} + +func ParseAATLoopkupExt10(src []byte) (AATLoopkupExt10, int, error) { + var item AATLoopkupExt10 + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading AATLoopkupExt10: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.version = binary.BigEndian.Uint16(src[0:]) + item.unitSize = binary.BigEndian.Uint16(src[2:]) + item.FirstGlyph = binary.BigEndian.Uint16(src[4:]) + arrayLengthValues := int(binary.BigEndian.Uint16(src[6:])) + n += 8 + + { + + if L := len(src); L < 8+arrayLengthValues*4 { + return item, 0, fmt.Errorf("reading AATLoopkupExt10: "+"EOF: expected length: %d, got %d", 8+arrayLengthValues*4, L) + } + + item.Values = make([]uint32, arrayLengthValues) // allocation guarded by the previous check + for i := range item.Values { + item.Values[i] = binary.BigEndian.Uint32(src[8+i*4:]) + } + n += arrayLengthValues * 4 + } + return item, n, nil +} + +func ParseAATLoopkupExt2(src []byte) (AATLoopkupExt2, int, error) { + var item AATLoopkupExt2 + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading AATLoopkupExt2: "+"EOF: expected length: 12, got %d", L) + } + _ = src[11] // early bound checking + item.version = binary.BigEndian.Uint16(src[0:]) + item.binSearchHeader.mustParse(src[2:]) + n += 12 + + { + arrayLength := int(item.nUnits) + + if L := len(src); L < 12+arrayLength*8 { + return item, 0, fmt.Errorf("reading AATLoopkupExt2: "+"EOF: expected length: %d, got %d", 12+arrayLength*8, L) + } + + item.Records = make([]lookupRecordExt2, arrayLength) // allocation guarded by the previous check + for i := range item.Records { + item.Records[i].mustParse(src[12+i*8:]) + } + n += arrayLength * 8 + } + return item, n, nil +} + +func ParseAATLoopkupExt4(src []byte) (AATLoopkupExt4, int, error) { + var item AATLoopkupExt4 + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading AATLoopkupExt4: "+"EOF: expected length: 12, got %d", L) + } + _ = src[11] // early bound checking + item.version = binary.BigEndian.Uint16(src[0:]) + item.binSearchHeader.mustParse(src[2:]) + n += 12 + + { + arrayLength := int(item.nUnits) + + offset := 12 + for i := 0; i < arrayLength; i++ { + elem, read, err := parseLoopkupRecordExt4(src[offset:], src) + if err != nil { + return item, 0, fmt.Errorf("reading AATLoopkupExt4: %s", err) + } + item.Records = append(item.Records, elem) + offset += read + } + n = offset + } + return item, n, nil +} + +func ParseAATLoopkupExt6(src []byte) (AATLoopkupExt6, int, error) { + var item AATLoopkupExt6 + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading AATLoopkupExt6: "+"EOF: expected length: 12, got %d", L) + } + _ = src[11] // early bound checking + item.version = binary.BigEndian.Uint16(src[0:]) + item.binSearchHeader.mustParse(src[2:]) + n += 12 + + { + arrayLength := int(item.nUnits) + + if L := len(src); L < 12+arrayLength*6 { + return item, 0, fmt.Errorf("reading AATLoopkupExt6: "+"EOF: expected length: %d, got %d", 12+arrayLength*6, L) + } + + item.Records = make([]loopkupRecordExt6, arrayLength) // allocation guarded by the previous check + for i := range item.Records { + item.Records[i].mustParse(src[12+i*6:]) + } + n += arrayLength * 6 + } + return item, n, nil +} + +func ParseAATLoopkupExt8(src []byte) (AATLoopkupExt8, int, error) { + var item AATLoopkupExt8 + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading AATLoopkupExt8: "+"EOF: expected length: 2, got %d", L) + } + item.version = binary.BigEndian.Uint16(src[0:]) + n += 2 + + { + var ( + err error + read int + ) + item.AATLoopkup8Data, read, err = ParseAATLoopkup8Data(src[2:]) + if err != nil { + return item, 0, fmt.Errorf("reading AATLoopkupExt8: %s", err) + } + n += read + } + return item, n, nil +} + +func ParseAATStateTableExt(src []byte, valuesCount int, entryDataSize int) (AATStateTableExt, int, error) { + var item AATStateTableExt + n := 0 + if L := len(src); L < 16 { + return item, 0, fmt.Errorf("reading AATStateTableExt: "+"EOF: expected length: 16, got %d", L) + } + _ = src[15] // early bound checking + item.StateSize = binary.BigEndian.Uint32(src[0:]) + offsetClass := int(binary.BigEndian.Uint32(src[4:])) + item.stateArray = Offset32(binary.BigEndian.Uint32(src[8:])) + item.entryTable = Offset32(binary.BigEndian.Uint32(src[12:])) + n += 16 + + { + + if offsetClass != 0 { // ignore null offset + if L := len(src); L < offsetClass { + return item, 0, fmt.Errorf("reading AATStateTableExt: "+"EOF: expected length: %d, got %d", offsetClass, L) + } + + var ( + err error + read int + ) + item.Class, read, err = ParseAATLookup(src[offsetClass:], valuesCount) + if err != nil { + return item, 0, fmt.Errorf("reading AATStateTableExt: %s", err) + } + offsetClass += read + } + } + { + + err := item.parseStates(src[:], valuesCount, entryDataSize) + if err != nil { + return item, 0, fmt.Errorf("reading AATStateTableExt: %s", err) + } + } + { + + read, err := item.parseEntries(src[:], valuesCount, entryDataSize) + if err != nil { + return item, 0, fmt.Errorf("reading AATStateTableExt: %s", err) + } + n = read + } + return item, n, nil +} + +func ParseKerx(src []byte, valuesCount int) (Kerx, int, error) { + var item Kerx + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading Kerx: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.version = binary.BigEndian.Uint16(src[0:]) + item.padding = binary.BigEndian.Uint16(src[2:]) + item.nTables = binary.BigEndian.Uint32(src[4:]) + n += 8 + + { + arrayLength := int(item.nTables) + + offset := 8 + for i := 0; i < arrayLength; i++ { + elem, read, err := ParseKerxSubtable(src[offset:], valuesCount) + if err != nil { + return item, 0, fmt.Errorf("reading Kerx: %s", err) + } + item.Tables = append(item.Tables, elem) + offset += read + } + n = offset + } + return item, n, nil +} + +func ParseKerxAnchorAnchors(src []byte, anchorsCount int) (KerxAnchorAnchors, int, error) { + var item KerxAnchorAnchors + n := 0 + { + + if L := len(src); L < anchorsCount*4 { + return item, 0, fmt.Errorf("reading KerxAnchorAnchors: "+"EOF: expected length: %d, got %d", anchorsCount*4, L) + } + + item.Anchors = make([]KAAnchor, anchorsCount) // allocation guarded by the previous check + for i := range item.Anchors { + item.Anchors[i].mustParse(src[i*4:]) + } + n += anchorsCount * 4 + } + return item, n, nil +} + +func ParseKerxAnchorControls(src []byte, anchorsCount int) (KerxAnchorControls, int, error) { + var item KerxAnchorControls + n := 0 + { + + if L := len(src); L < anchorsCount*4 { + return item, 0, fmt.Errorf("reading KerxAnchorControls: "+"EOF: expected length: %d, got %d", anchorsCount*4, L) + } + + item.Anchors = make([]KAControl, anchorsCount) // allocation guarded by the previous check + for i := range item.Anchors { + item.Anchors[i].mustParse(src[i*4:]) + } + n += anchorsCount * 4 + } + return item, n, nil +} + +func ParseKerxAnchorCoordinates(src []byte, anchorsCount int) (KerxAnchorCoordinates, int, error) { + var item KerxAnchorCoordinates + n := 0 + { + + if L := len(src); L < anchorsCount*8 { + return item, 0, fmt.Errorf("reading KerxAnchorCoordinates: "+"EOF: expected length: %d, got %d", anchorsCount*8, L) + } + + item.Anchors = make([]KACoordinates, anchorsCount) // allocation guarded by the previous check + for i := range item.Anchors { + item.Anchors[i].mustParse(src[i*8:]) + } + n += anchorsCount * 8 + } + return item, n, nil +} + +func ParseKerxData0(src []byte, tupleCount int) (KerxData0, int, error) { + var item KerxData0 + n := 0 + if L := len(src); L < 16 { + return item, 0, fmt.Errorf("reading KerxData0: "+"EOF: expected length: 16, got %d", L) + } + _ = src[15] // early bound checking + item.nPairs = binary.BigEndian.Uint32(src[0:]) + item.searchRange = binary.BigEndian.Uint32(src[4:]) + item.entrySelector = binary.BigEndian.Uint32(src[8:]) + item.rangeShift = binary.BigEndian.Uint32(src[12:]) + n += 16 + + { + arrayLength := int(item.nPairs) + + if L := len(src); L < 16+arrayLength*6 { + return item, 0, fmt.Errorf("reading KerxData0: "+"EOF: expected length: %d, got %d", 16+arrayLength*6, L) + } + + item.Pairs = make([]Kernx0Record, arrayLength) // allocation guarded by the previous check + for i := range item.Pairs { + item.Pairs[i].mustParse(src[16+i*6:]) + } + n += arrayLength * 6 + } + var err error + n, err = item.parseEnd(src, tupleCount) + if err != nil { + return item, 0, fmt.Errorf("reading KerxData0: %s", err) + } + + return item, n, nil +} + +func ParseKerxData1(src []byte, tupleCount int, valuesCount int) (KerxData1, int, error) { + var item KerxData1 + n := 0 + { + var ( + err error + read int + ) + item.AATStateTableExt, read, err = ParseAATStateTableExt(src[0:], int(valuesCount), int(2)) + if err != nil { + return item, 0, fmt.Errorf("reading KerxData1: %s", err) + } + n += read + } + if L := len(src); L < n+4 { + return item, 0, fmt.Errorf("reading KerxData1: "+"EOF: expected length: n + 4, got %d", L) + } + item.valueTable = Offset32(binary.BigEndian.Uint32(src[n:])) + n += 4 + + { + + err := item.parseValues(src[:], tupleCount, valuesCount) + if err != nil { + return item, 0, fmt.Errorf("reading KerxData1: %s", err) + } + } + return item, n, nil +} + +func ParseKerxData2(src []byte, parentSrc []byte, valuesCount int) (KerxData2, int, error) { + var item KerxData2 + n := 0 + if L := len(src); L < 16 { + return item, 0, fmt.Errorf("reading KerxData2: "+"EOF: expected length: 16, got %d", L) + } + _ = src[15] // early bound checking + item.rowWidth = binary.BigEndian.Uint32(src[0:]) + offsetLeft := int(binary.BigEndian.Uint32(src[4:])) + offsetRight := int(binary.BigEndian.Uint32(src[8:])) + item.KerningStart = Offset32(binary.BigEndian.Uint32(src[12:])) + n += 16 + + { + + if offsetLeft != 0 { // ignore null offset + if L := len(parentSrc); L < offsetLeft { + return item, 0, fmt.Errorf("reading KerxData2: "+"EOF: expected length: %d, got %d", offsetLeft, L) + } + + var ( + err error + read int + ) + item.Left, read, err = ParseAATLookup(parentSrc[offsetLeft:], valuesCount) + if err != nil { + return item, 0, fmt.Errorf("reading KerxData2: %s", err) + } + offsetLeft += read + } + } + { + + if offsetRight != 0 { // ignore null offset + if L := len(parentSrc); L < offsetRight { + return item, 0, fmt.Errorf("reading KerxData2: "+"EOF: expected length: %d, got %d", offsetRight, L) + } + + var ( + err error + read int + ) + item.Right, read, err = ParseAATLookup(parentSrc[offsetRight:], valuesCount) + if err != nil { + return item, 0, fmt.Errorf("reading KerxData2: %s", err) + } + offsetRight += read + } + } + { + + item.KerningData = src[0:] + } + return item, n, nil +} + +func ParseKerxData4(src []byte, valuesCount int) (KerxData4, int, error) { + var item KerxData4 + n := 0 + { + var ( + err error + read int + ) + item.AATStateTableExt, read, err = ParseAATStateTableExt(src[0:], int(valuesCount), int(2)) + if err != nil { + return item, 0, fmt.Errorf("reading KerxData4: %s", err) + } + n += read + } + if L := len(src); L < n+4 { + return item, 0, fmt.Errorf("reading KerxData4: "+"EOF: expected length: n + 4, got %d", L) + } + item.Flags = binary.BigEndian.Uint32(src[n:]) + n += 4 + + { + + err := item.parseAnchors(src[:], valuesCount) + if err != nil { + return item, 0, fmt.Errorf("reading KerxData4: %s", err) + } + } + return item, n, nil +} + +func ParseKerxData6(src []byte, parentSrc []byte, tupleCount int, valuesCount int) (KerxData6, int, error) { + var item KerxData6 + n := 0 + if L := len(src); L < 24 { + return item, 0, fmt.Errorf("reading KerxData6: "+"EOF: expected length: 24, got %d", L) + } + _ = src[23] // early bound checking + item.flags = binary.BigEndian.Uint32(src[0:]) + item.rowCount = binary.BigEndian.Uint16(src[4:]) + item.columnCount = binary.BigEndian.Uint16(src[6:]) + item.rowIndexTableOffset = binary.BigEndian.Uint32(src[8:]) + item.columnIndexTableOffset = binary.BigEndian.Uint32(src[12:]) + item.kerningArrayOffset = binary.BigEndian.Uint32(src[16:]) + item.kerningVectorOffset = binary.BigEndian.Uint32(src[20:]) + n += 24 + + { + + err := item.parseRow(src[:], parentSrc, tupleCount, valuesCount) + if err != nil { + return item, 0, fmt.Errorf("reading KerxData6: %s", err) + } + } + { + + err := item.parseColumn(src[:], parentSrc, tupleCount, valuesCount) + if err != nil { + return item, 0, fmt.Errorf("reading KerxData6: %s", err) + } + } + { + + err := item.parseKernings(src[:], parentSrc, tupleCount, valuesCount) + if err != nil { + return item, 0, fmt.Errorf("reading KerxData6: %s", err) + } + } + return item, n, nil +} + +func ParseKerxSubtable(src []byte, valuesCount int) (KerxSubtable, int, error) { + var item KerxSubtable + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading KerxSubtable: "+"EOF: expected length: 12, got %d", L) + } + _ = src[11] // early bound checking + item.length = binary.BigEndian.Uint32(src[0:]) + item.Coverage = binary.BigEndian.Uint16(src[4:]) + item.padding = src[6] + item.version = kerxSTVersion(src[7]) + item.TupleCount = binary.BigEndian.Uint32(src[8:]) + n += 12 + + { + var ( + read int + err error + ) + switch item.version { + case kerxSTVersion0: + item.Data, read, err = ParseKerxData0(src[12:], int(item.TupleCount)) + case kerxSTVersion1: + item.Data, read, err = ParseKerxData1(src[12:], int(item.TupleCount), int(valuesCount)) + case kerxSTVersion2: + item.Data, read, err = ParseKerxData2(src[12:], src, int(valuesCount)) + case kerxSTVersion4: + item.Data, read, err = ParseKerxData4(src[12:], int(valuesCount)) + case kerxSTVersion6: + item.Data, read, err = ParseKerxData6(src[12:], src, int(item.TupleCount), int(valuesCount)) + default: + err = fmt.Errorf("unsupported KerxDataVersion %d", item.version) + } + if err != nil { + return item, 0, fmt.Errorf("reading KerxSubtable: %s", err) + } + n += read + } + var err error + n, err = item.parseEnd(src, valuesCount) + if err != nil { + return item, 0, fmt.Errorf("reading KerxSubtable: %s", err) + } + + return item, n, nil +} + +func (item *lookupRecordExt2) mustParse(src []byte) { + _ = src[7] // early bound checking + item.LastGlyph = binary.BigEndian.Uint16(src[0:]) + item.FirstGlyph = binary.BigEndian.Uint16(src[2:]) + item.Value = binary.BigEndian.Uint32(src[4:]) +} + +func (item *loopkupRecordExt6) mustParse(src []byte) { + _ = src[5] // early bound checking + item.Glyph = binary.BigEndian.Uint16(src[0:]) + item.Value = binary.BigEndian.Uint32(src[2:]) +} + +func parseLoopkupRecordExt4(src []byte, parentSrc []byte) (loopkupRecordExt4, int, error) { + var item loopkupRecordExt4 + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading loopkupRecordExt4: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.LastGlyph = binary.BigEndian.Uint16(src[0:]) + item.FirstGlyph = binary.BigEndian.Uint16(src[2:]) + offsetValues := int(binary.BigEndian.Uint16(src[4:])) + n += 6 + + { + + if offsetValues != 0 { // ignore null offset + if L := len(parentSrc); L < offsetValues { + return item, 0, fmt.Errorf("reading loopkupRecordExt4: "+"EOF: expected length: %d, got %d", offsetValues, L) + } + + arrayLength := int(item.nValues()) + + if L := len(parentSrc); L < offsetValues+arrayLength*4 { + return item, 0, fmt.Errorf("reading loopkupRecordExt4: "+"EOF: expected length: %d, got %d", offsetValues+arrayLength*4, L) + } + + item.Values = make([]uint32, arrayLength) // allocation guarded by the previous check + for i := range item.Values { + item.Values[i] = binary.BigEndian.Uint32(parentSrc[offsetValues+i*4:]) + } + offsetValues += arrayLength * 4 + } + } + return item, n, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_kerx_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_kerx_src.go new file mode 100644 index 0000000..89a8f84 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_kerx_src.go @@ -0,0 +1,320 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Kerx is the extended kerning table +// See https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6kerx.html +type Kerx struct { + version uint16 // The version number of the extended kerning table (currently 2, 3, or 4). + padding uint16 // Unused; set to zero. + nTables uint32 // The number of subtables included in the extended kerning table. + Tables []KerxSubtable `arrayCount:"ComputedField-nTables"` +} + +// extended versions + +// binarygen: argument=valuesCount int +type KerxSubtable struct { + length uint32 // The length of this subtable in bytes, including this header. + Coverage uint16 // Circumstances under which this table is used. + padding byte // unused + version kerxSTVersion + TupleCount uint32 // The tuple count. This value is only used with variation fonts and should be 0 for all other fonts. The subtable's tupleCount will be ignored if the 'kerx' table version is less than 4. + Data KerxData `unionField:"version" arguments:"tupleCount=.TupleCount, valuesCount=valuesCount"` +} + +// check and return the subtable length +func (ks *KerxSubtable) parseEnd(src []byte, _ int) (int, error) { + if L := len(src); L < int(ks.length) { + return 0, fmt.Errorf("EOF: expected length: %d, got %d", ks.length, L) + } + return int(ks.length), nil +} + +type kerxSTVersion byte + +const ( + kerxSTVersion0 kerxSTVersion = iota + kerxSTVersion1 + kerxSTVersion2 + _ + kerxSTVersion4 + _ + kerxSTVersion6 +) + +type KerxData interface { + isKerxData() +} + +func (KerxData0) isKerxData() {} +func (KerxData1) isKerxData() {} +func (KerxData2) isKerxData() {} +func (KerxData4) isKerxData() {} +func (KerxData6) isKerxData() {} + +// binarygen: argument=tupleCount int +type KerxData0 struct { + nPairs uint32 + searchRange uint32 + entrySelector uint32 + rangeShift uint32 + Pairs []Kernx0Record `arrayCount:"ComputedField-nPairs"` +} + +// resolve offset for variable fonts +func (kd *KerxData0) parseEnd(src []byte, tupleCount int) (int, error) { + if tupleCount != 0 { // interpret values as offset + for i, pair := range kd.Pairs { + if L, E := len(src), int(uint16(pair.Value))+2; L < E { + return 0, fmt.Errorf("EOF: expected length: %d, got %d", E, L) + } + kd.Pairs[i].Value = int16(binary.BigEndian.Uint16(src[pair.Value:])) + } + } + return len(src), nil +} + +type Kernx0Record struct { + Left, Right GlyphID + Value int16 +} + +// Kernx1 state entry flags +const ( + Kerx1Push = 0x8000 // If set, push this glyph on the kerning stack. + Kerx1DontAdvance = 0x4000 // If set, don't advance to the next glyph before going to the new state. + Kerx1Reset = 0x2000 // If set, reset the kerning data (clear the stack) + Kern1Offset = 0x3FFF // Byte offset from beginning of subtable to the value table for the glyphs on the kerning stack. +) + +// binarygen: argument=tupleCount int +// binarygen: argument=valuesCount int +type KerxData1 struct { + AATStateTableExt `arguments:"valuesCount=valuesCount, entryDataSize=2"` + valueTable Offset32 + Values []int16 `isOpaque:""` +} + +// From Apple 'kern' spec: +// Each pops one glyph from the kerning stack and applies the kerning value to it. +// The end of the list is marked by an odd value... +func parseKernx1Values(src []byte, entries []AATStateEntry, valueTableOffset, tupleCount int) ([]int16, error) { + // find the maximum index need in the values array + var maxi uint16 + for _, entry := range entries { + if index := entry.AsKernxIndex(); index != 0xFFFF && index > maxi { + maxi = index + } + } + + if tupleCount == 0 { + tupleCount = 1 + } + nbUint16Min := tupleCount * int(maxi+1) + if L, E := len(src), valueTableOffset+2*nbUint16Min; L < E { + return nil, fmt.Errorf("EOF: expected length: %d, got %d", E, L) + } + + src = src[valueTableOffset:] + out := make([]int16, 0, nbUint16Min) + for len(src) >= 2 { // gracefully handle missing odd value + v := int16(binary.BigEndian.Uint16(src)) + out = append(out, v) + src = src[2:] + if len(out) >= nbUint16Min && v&1 != 0 { + break + } + } + return out, nil +} + +func (kx *KerxData1) parseValues(src []byte, tupleCount, _ int) error { + var err error + kx.Values, err = parseKernx1Values(src, kx.Entries, int(kx.valueTable), tupleCount) + return err +} + +type KerxData2 struct { + rowWidth uint32 // The number of bytes in each row of the kerning value array + Left AATLookup `offsetSize:"Offset32" offsetRelativeTo:"Parent"` // Offset from beginning of this subtable to the left-hand offset table. + Right AATLookup `offsetSize:"Offset32" offsetRelativeTo:"Parent"` // Offset from beginning of this subtable to right-hand offset table. + KerningStart Offset32 // Offset from beginning of this subtable to the start of the kerning array. + KerningData []byte `subsliceStart:"AtStart" arrayCount:"ToEnd"` // indexed by Left + Right +} + +// binarygen: argument=valuesCount int +type KerxData4 struct { + AATStateTableExt `arguments:"valuesCount=valuesCount,entryDataSize=2"` + Flags uint32 + Anchors KerxAnchors `isOpaque:""` +} + +func (kd KerxData4) nAnchors() int { + // find the maximum index need in the actions array + var maxi uint16 + for _, entry := range kd.Entries { + if index := entry.AsKernxIndex(); index != 0xFFFF && index > maxi { + maxi = index + } + } + return int(maxi) + 1 +} + +func (kd *KerxData4) parseAnchors(src []byte, _ int) error { + nAnchors := kd.nAnchors() + const Offset = 0x00FFFFFF // Masks the offset in bytes from the beginning of the subtable to the beginning of the control point table. + controlOffset := int(kd.Flags & Offset) + if L := len(src); L < controlOffset { + return fmt.Errorf("EOF: expected length: %d, got %d", controlOffset, L) + } + var err error + switch kd.ActionType() { + case 0: + kd.Anchors, _, err = ParseKerxAnchorControls(src[controlOffset:], nAnchors) + case 1: + kd.Anchors, _, err = ParseKerxAnchorAnchors(src[controlOffset:], nAnchors) + case 2: + kd.Anchors, _, err = ParseKerxAnchorCoordinates(src[controlOffset:], nAnchors) + default: + return fmt.Errorf("invalid Kerx4 anchor format %d", kd.ActionType()) + } + return err +} + +// ActionType returns 0, 1 or 2, according to the anchor format : +// - 0 : KerxAnchorControls +// - 1 : KerxAnchorAnchors +// - 2 : KerxAnchorCoordinates +func (kd KerxData4) ActionType() uint8 { + const ActionType = 0xC0000000 // A two-bit field containing the action type. + return uint8((kd.Flags & ActionType) >> 30) +} + +type KerxAnchors interface { + isKerxAnchors() +} + +func (KerxAnchorControls) isKerxAnchors() {} +func (KerxAnchorAnchors) isKerxAnchors() {} +func (KerxAnchorCoordinates) isKerxAnchors() {} + +type KerxAnchorControls struct { + Anchors []KAControl +} +type KerxAnchorAnchors struct { + Anchors []KAAnchor +} +type KerxAnchorCoordinates struct { + Anchors []KACoordinates +} + +type KAControl struct { + Mark, Current uint16 +} + +type KAAnchor struct { + Mark, Current uint16 +} + +type KACoordinates struct { + MarkX, MarkY, CurrentX, CurrentY int16 +} + +// binarygen: argument=tupleCount int +// binarygen: argument=valuesCount int +type KerxData6 struct { + flags uint32 // Flags for this subtable. See below. + rowCount uint16 // The number of rows in the kerning value array + columnCount uint16 // The number of columns in the kerning value array + rowIndexTableOffset uint32 // Offset from beginning of this subtable to the row index lookup table. + columnIndexTableOffset uint32 // Offset from beginning of this subtable to column index offset table. + kerningArrayOffset uint32 // Offset from beginning of this subtable to the start of the kerning array. + kerningVectorOffset uint32 // Offset from beginning of this subtable to the start of the kerning vectors. This value is only present if the tupleCount for this subtable is 1 or more. + Row AatLookupMixed `isOpaque:"" offsetRelativeTo:"Parent"` // Values are pre-multiplied by `columnCount` + Column AatLookupMixed `isOpaque:"" offsetRelativeTo:"Parent"` + // with rowCount * columnCount + // for tuples the values are estParseKerx (Not yet run).the first element of the tuple + Kernings []int16 `isOpaque:"" offsetRelativeTo:"Parent"` +} + +func (kd *KerxData6) parseRow(_, parentSrc []byte, _, valuesCount int) error { + isExtended := kd.flags&1 != 0 + if L := len(parentSrc); L < int(kd.rowIndexTableOffset) { + return fmt.Errorf("EOF: expected length: %d, got %d", kd.rowIndexTableOffset, L) + } + var err error + if isExtended { + kd.Row, _, err = ParseAATLookupExt(parentSrc[kd.rowIndexTableOffset:], valuesCount) + } else { + kd.Row, _, err = ParseAATLookup(parentSrc[kd.rowIndexTableOffset:], valuesCount) + } + return err +} + +func (kd *KerxData6) parseColumn(_, parentSrc []byte, _, valuesCount int) error { + isExtended := kd.flags&1 != 0 + if L := len(parentSrc); L < int(kd.columnIndexTableOffset) { + return fmt.Errorf("EOF: expected length: %d, got %d", kd.columnIndexTableOffset, L) + } + var err error + if isExtended { + kd.Column, _, err = ParseAATLookupExt(parentSrc[kd.columnIndexTableOffset:], valuesCount) + } else { + kd.Column, _, err = ParseAATLookup(parentSrc[kd.columnIndexTableOffset:], valuesCount) + } + return err +} + +func (kd *KerxData6) parseKernings(_, parentSrc []byte, tupleCount, _ int) error { + isExtended := kd.flags&1 != 0 + + length := int(kd.rowCount) * int(kd.columnCount) + var tmp []uint32 + if isExtended { + if L, E := len(parentSrc), int(kd.kerningArrayOffset)+length*4; L < E { + return fmt.Errorf("EOF: expected length: %d, got %d", E, L) + } + tmp = make([]uint32, length) + for i := range tmp { + tmp[i] = binary.BigEndian.Uint32(parentSrc[int(kd.kerningArrayOffset)+4*i:]) + } + } else { + if L, E := len(parentSrc), int(kd.kerningArrayOffset)+length*2; L < E { + return fmt.Errorf("EOF: expected length: %d, got %d", E, L) + } + tmp = make([]uint32, length) + for i := range tmp { + tmp[i] = uint32(binary.BigEndian.Uint16(parentSrc[int(kd.kerningArrayOffset)+2*i:])) + } + } + + kd.Kernings = make([]int16, len(tmp)) + if tupleCount != 0 { // interpret kern values as offset + // If the tupleCount is 1 or more, then the kerning array contains offsets from the beginning + // of the kerningVectors table to a tupleCount-dimensional vector of FUnits controlling the kerning. + for i, v := range tmp { + kerningOffset := int(kd.kerningVectorOffset) + int(v) + if L := len(parentSrc); L < kerningOffset+2 { + return fmt.Errorf("EOF: expected length: %d, got %d", kerningOffset+2, L) + } + kd.Kernings[i] = int16(binary.BigEndian.Uint16(parentSrc[kerningOffset:])) + } + } else { + // a kerning value greater than an int16 should not happen + for i, v := range tmp { + kd.Kernings[i] = int16(v) + } + } + return nil +} + +//lint:ignore U1000 this type is required so that the code generator add a ParseAATLookupExt function +type dummy struct { + A AATLookupExt +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_ltag_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_ltag_gen.go new file mode 100644 index 0000000..972bba8 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_ltag_gen.go @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from aat_ltag_src.go. DO NOT EDIT + +func ParseLtag(src []byte) (Ltag, int, error) { + var item Ltag + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading Ltag: "+"EOF: expected length: 12, got %d", L) + } + _ = src[11] // early bound checking + item.version = binary.BigEndian.Uint32(src[0:]) + item.flags = binary.BigEndian.Uint32(src[4:]) + item.numTags = binary.BigEndian.Uint32(src[8:]) + n += 12 + + { + arrayLength := int(item.numTags) + + if L := len(src); L < 12+arrayLength*4 { + return item, 0, fmt.Errorf("reading Ltag: "+"EOF: expected length: %d, got %d", 12+arrayLength*4, L) + } + + item.tagRange = make([]stringRange, arrayLength) // allocation guarded by the previous check + for i := range item.tagRange { + item.tagRange[i].mustParse(src[12+i*4:]) + } + n += arrayLength * 4 + } + { + + item.stringData = src[0:] + n = len(src) + } + return item, n, nil +} + +func (item *stringRange) mustParse(src []byte) { + _ = src[3] // early bound checking + item.offset = binary.BigEndian.Uint16(src[0:]) + item.length = binary.BigEndian.Uint16(src[2:]) +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_ltag_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_ltag_src.go new file mode 100644 index 0000000..f8d2ac3 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_ltag_src.go @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import "github.com/go-text/typesetting/language" + +// Ltag is the language tags table +// See https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6ltag.html +type Ltag struct { + version uint32 // Table version; currently 1 + flags uint32 // Table flags; currently none defined + numTags uint32 // Number of language tags which follow + tagRange []stringRange `arrayCount:"ComputedField-numTags"` // Range for each tag's string + stringData []byte `subsliceStart:"AtStart" arrayCount:"ToEnd"` +} + +type stringRange struct { + offset uint16 // Offset from the start of the table to the beginning of the string + length uint16 // String length (in bytes) +} + +func (lt Ltag) Language(i uint16) language.Language { + r := lt.tagRange[i] + return language.NewLanguage(string(lt.stringData[r.offset : r.offset+r.length])) +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_mortx_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_mortx_gen.go new file mode 100644 index 0000000..d0bbbb0 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_mortx_gen.go @@ -0,0 +1,332 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from aat_mortx_src.go. DO NOT EDIT + +func (item *AATFeature) mustParse(src []byte) { + _ = src[11] // early bound checking + item.FeatureType = binary.BigEndian.Uint16(src[0:]) + item.FeatureSetting = binary.BigEndian.Uint16(src[2:]) + item.EnableFlags = binary.BigEndian.Uint32(src[4:]) + item.DisableFlags = binary.BigEndian.Uint32(src[8:]) +} + +func ParseMorx(src []byte, valuesCount int) (Morx, int, error) { + var item Morx + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading Morx: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.version = binary.BigEndian.Uint16(src[0:]) + item.unused = binary.BigEndian.Uint16(src[2:]) + item.nChains = binary.BigEndian.Uint32(src[4:]) + n += 8 + + { + arrayLength := int(item.nChains) + + offset := 8 + for i := 0; i < arrayLength; i++ { + elem, read, err := ParseMorxChain(src[offset:], valuesCount) + if err != nil { + return item, 0, fmt.Errorf("reading Morx: %s", err) + } + item.Chains = append(item.Chains, elem) + offset += read + } + n = offset + } + return item, n, nil +} + +func ParseMorxChain(src []byte, valuesCount int) (MorxChain, int, error) { + var item MorxChain + n := 0 + if L := len(src); L < 16 { + return item, 0, fmt.Errorf("reading MorxChain: "+"EOF: expected length: 16, got %d", L) + } + _ = src[15] // early bound checking + item.Flags = binary.BigEndian.Uint32(src[0:]) + item.chainLength = binary.BigEndian.Uint32(src[4:]) + item.nFeatureEntries = binary.BigEndian.Uint32(src[8:]) + item.nSubtable = binary.BigEndian.Uint32(src[12:]) + n += 16 + + { + arrayLength := int(item.nFeatureEntries) + + if L := len(src); L < 16+arrayLength*12 { + return item, 0, fmt.Errorf("reading MorxChain: "+"EOF: expected length: %d, got %d", 16+arrayLength*12, L) + } + + item.Features = make([]AATFeature, arrayLength) // allocation guarded by the previous check + for i := range item.Features { + item.Features[i].mustParse(src[16+i*12:]) + } + n += arrayLength * 12 + } + { + arrayLength := int(item.nSubtable) + + offset := n + for i := 0; i < arrayLength; i++ { + elem, read, err := ParseMorxChainSubtable(src[offset:], valuesCount) + if err != nil { + return item, 0, fmt.Errorf("reading MorxChain: %s", err) + } + item.Subtables = append(item.Subtables, elem) + offset += read + } + n = offset + } + return item, n, nil +} + +func ParseMorxChainSubtable(src []byte, valuesCount int) (MorxChainSubtable, int, error) { + var item MorxChainSubtable + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading MorxChainSubtable: "+"EOF: expected length: 12, got %d", L) + } + _ = src[11] // early bound checking + item.length = binary.BigEndian.Uint32(src[0:]) + item.Coverage = src[4] + item.ignored[0] = src[5] + item.ignored[1] = src[6] + item.version = MorxSubtableVersion(src[7]) + item.SubFeatureFlags = binary.BigEndian.Uint32(src[8:]) + n += 12 + + { + var ( + read int + err error + ) + switch item.version { + case MorxSubtableVersionContextual: + item.Data, read, err = ParseMorxSubtableContextual(src[12:], valuesCount) + case MorxSubtableVersionInsertion: + item.Data, read, err = ParseMorxSubtableInsertion(src[12:], valuesCount) + case MorxSubtableVersionLigature: + item.Data, read, err = ParseMorxSubtableLigature(src[12:], valuesCount) + case MorxSubtableVersionNonContextual: + item.Data, read, err = ParseMorxSubtableNonContextual(src[12:], valuesCount) + case MorxSubtableVersionRearrangement: + item.Data, read, err = ParseMorxSubtableRearrangement(src[12:], valuesCount) + default: + err = fmt.Errorf("unsupported MorxSubtableVersion %d", item.version) + } + if err != nil { + return item, 0, fmt.Errorf("reading MorxChainSubtable: %s", err) + } + n += read + } + var err error + n, err = item.parseEnd(src, valuesCount) + if err != nil { + return item, 0, fmt.Errorf("reading MorxChainSubtable: %s", err) + } + + return item, n, nil +} + +func ParseMorxSubtableContextual(src []byte, valuesCount int) (MorxSubtableContextual, int, error) { + var item MorxSubtableContextual + n := 0 + { + var ( + err error + read int + ) + item.AATStateTableExt, read, err = ParseAATStateTableExt(src[0:], int(valuesCount), int(4)) + if err != nil { + return item, 0, fmt.Errorf("reading MorxSubtableContextual: %s", err) + } + n += read + } + if L := len(src); L < n+4 { + return item, 0, fmt.Errorf("reading MorxSubtableContextual: "+"EOF: expected length: n + 4, got %d", L) + } + offsetSubstitutions := int(binary.BigEndian.Uint32(src[n:])) + n += 4 + + { + + if offsetSubstitutions != 0 { // ignore null offset + if L := len(src); L < offsetSubstitutions { + return item, 0, fmt.Errorf("reading MorxSubtableContextual: "+"EOF: expected length: %d, got %d", offsetSubstitutions, L) + } + + var err error + item.Substitutions, _, err = ParseSubstitutionsTable(src[offsetSubstitutions:], int(item.nSubs()), int(valuesCount)) + if err != nil { + return item, 0, fmt.Errorf("reading MorxSubtableContextual: %s", err) + } + + } + } + return item, n, nil +} + +func ParseMorxSubtableInsertion(src []byte, valuesCount int) (MorxSubtableInsertion, int, error) { + var item MorxSubtableInsertion + n := 0 + { + var ( + err error + read int + ) + item.AATStateTableExt, read, err = ParseAATStateTableExt(src[0:], int(valuesCount), int(4)) + if err != nil { + return item, 0, fmt.Errorf("reading MorxSubtableInsertion: %s", err) + } + n += read + } + if L := len(src); L < n+4 { + return item, 0, fmt.Errorf("reading MorxSubtableInsertion: "+"EOF: expected length: n + 4, got %d", L) + } + offsetInsertions := int(binary.BigEndian.Uint32(src[n:])) + n += 4 + + { + + if offsetInsertions != 0 { // ignore null offset + if L := len(src); L < offsetInsertions { + return item, 0, fmt.Errorf("reading MorxSubtableInsertion: "+"EOF: expected length: %d, got %d", offsetInsertions, L) + } + + arrayLength := int(item.nInsertions()) + + if L := len(src); L < offsetInsertions+arrayLength*2 { + return item, 0, fmt.Errorf("reading MorxSubtableInsertion: "+"EOF: expected length: %d, got %d", offsetInsertions+arrayLength*2, L) + } + + item.Insertions = make([]uint16, arrayLength) // allocation guarded by the previous check + for i := range item.Insertions { + item.Insertions[i] = binary.BigEndian.Uint16(src[offsetInsertions+i*2:]) + } + offsetInsertions += arrayLength * 2 + } + } + return item, n, nil +} + +func ParseMorxSubtableLigature(src []byte, valuesCount int) (MorxSubtableLigature, int, error) { + var item MorxSubtableLigature + n := 0 + { + var ( + err error + read int + ) + item.AATStateTableExt, read, err = ParseAATStateTableExt(src[0:], int(valuesCount), int(2)) + if err != nil { + return item, 0, fmt.Errorf("reading MorxSubtableLigature: %s", err) + } + n += read + } + if L := len(src); L < n+12 { + return item, 0, fmt.Errorf("reading MorxSubtableLigature: "+"EOF: expected length: n + 12, got %d", L) + } + _ = src[n+11] // early bound checking + item.ligActionOffset = Offset32(binary.BigEndian.Uint32(src[n:])) + item.componentOffset = Offset32(binary.BigEndian.Uint32(src[n+4:])) + item.ligatureOffset = Offset32(binary.BigEndian.Uint32(src[n+8:])) + n += 12 + + { + + err := item.parseLigActions(src[:], valuesCount) + if err != nil { + return item, 0, fmt.Errorf("reading MorxSubtableLigature: %s", err) + } + } + { + + err := item.parseComponents(src[:], valuesCount) + if err != nil { + return item, 0, fmt.Errorf("reading MorxSubtableLigature: %s", err) + } + } + { + + err := item.parseLigatures(src[:], valuesCount) + if err != nil { + return item, 0, fmt.Errorf("reading MorxSubtableLigature: %s", err) + } + } + return item, n, nil +} + +func ParseMorxSubtableNonContextual(src []byte, valuesCount int) (MorxSubtableNonContextual, int, error) { + var item MorxSubtableNonContextual + n := 0 + { + var ( + err error + read int + ) + item.Class, read, err = ParseAATLookup(src[0:], valuesCount) + if err != nil { + return item, 0, fmt.Errorf("reading MorxSubtableNonContextual: %s", err) + } + n += read + } + return item, n, nil +} + +func ParseMorxSubtableRearrangement(src []byte, valuesCount int) (MorxSubtableRearrangement, int, error) { + var item MorxSubtableRearrangement + n := 0 + { + var ( + err error + read int + ) + item.AATStateTableExt, read, err = ParseAATStateTableExt(src[0:], int(valuesCount), int(0)) + if err != nil { + return item, 0, fmt.Errorf("reading MorxSubtableRearrangement: %s", err) + } + n += read + } + return item, n, nil +} + +func ParseSubstitutionsTable(src []byte, substitutionsCount int, valuesCount int) (SubstitutionsTable, int, error) { + var item SubstitutionsTable + n := 0 + { + + if L := len(src); L < substitutionsCount*4 { + return item, 0, fmt.Errorf("reading SubstitutionsTable: "+"EOF: expected length: %d, got %d", substitutionsCount*4, L) + } + + item.Substitutions = make([]AATLookup, substitutionsCount) // allocation guarded by the previous check + for i := range item.Substitutions { + offset := int(binary.BigEndian.Uint32(src[i*4:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading SubstitutionsTable: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.Substitutions[i], _, err = ParseAATLookup(src[offset:], valuesCount) + if err != nil { + return item, 0, fmt.Errorf("reading SubstitutionsTable: %s", err) + } + } + n += substitutionsCount * 4 + } + return item, n, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_mortx_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_mortx_src.go new file mode 100644 index 0000000..534fc22 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_mortx_src.go @@ -0,0 +1,302 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "errors" + "fmt" +) + +// Morx is the extended glyph metamorphosis table +// See https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6morx.html +type Morx struct { + version uint16 // Version number of the extended glyph metamorphosis table (either 2 or 3) + unused uint16 // Set to 0 + nChains uint32 // Number of metamorphosis chains contained in this table. + Chains []MorxChain `arrayCount:"ComputedField-nChains"` +} + +// MorxChain is a set of subtables +type MorxChain struct { + Flags uint32 // The default specification for subtables. + chainLength uint32 // Total byte count, including this header; must be a multiple of 4. + nFeatureEntries uint32 // Number of feature subtable entries. + nSubtable uint32 // The number of subtables in the chain. + Features []AATFeature `arrayCount:"ComputedField-nFeatureEntries"` + Subtables []MorxChainSubtable `arrayCount:"ComputedField-nSubtable"` +} + +type AATFeature struct { + FeatureType uint16 + FeatureSetting uint16 + EnableFlags uint32 // Flags for the settings that this feature and setting enables. + DisableFlags uint32 // Complement of flags for the settings that this feature and setting disable. +} + +type MorxChainSubtable struct { + length uint32 // Total subtable length, including this header. + + // Coverage flags and subtable type. + Coverage byte + ignored [2]byte + version MorxSubtableVersion + + SubFeatureFlags uint32 // The 32-bit mask identifying which subtable this is (the subtable being executed if the AND of this value and the processed defaultFlags is nonzero) + + Data MorxSubtable `unionField:"version"` +} + +// check and return the subtable length +func (mc *MorxChainSubtable) parseEnd(src []byte, _ int) (int, error) { + if L := len(src); L < int(mc.length) { + return 0, fmt.Errorf("EOF: expected length: %d, got %d", mc.length, L) + } + return int(mc.length), nil +} + +// MorxSubtableVersion indicates the kind of 'morx' subtable. +// See the constants. +type MorxSubtableVersion uint8 + +const ( + MorxSubtableVersionRearrangement MorxSubtableVersion = iota + MorxSubtableVersionContextual + MorxSubtableVersionLigature + _ // reserved + MorxSubtableVersionNonContextual + MorxSubtableVersionInsertion +) + +type MorxSubtable interface { + isMorxSubtable() +} + +func (MorxSubtableRearrangement) isMorxSubtable() {} +func (MorxSubtableContextual) isMorxSubtable() {} +func (MorxSubtableLigature) isMorxSubtable() {} +func (MorxSubtableNonContextual) isMorxSubtable() {} +func (MorxSubtableInsertion) isMorxSubtable() {} + +// binarygen: argument=valuesCount int +type MorxSubtableRearrangement struct { + AATStateTableExt `arguments:"valuesCount=valuesCount,entryDataSize=0"` +} + +// binarygen: argument=valuesCount int +type MorxSubtableContextual struct { + AATStateTableExt `arguments:"valuesCount=valuesCount,entryDataSize=4"` + // Byte offset from the beginning of the state subtable to the beginning of the substitution tables : + // each value of the array is itself an offet to a aatLookupTable, and the number of + // items is computed from the header + Substitutions SubstitutionsTable `offsetSize:"Offset32" arguments:"substitutionsCount=.nSubs(), valuesCount=valuesCount"` +} + +type SubstitutionsTable struct { + Substitutions []AATLookup `offsetsArray:"Offset32"` +} + +func (ct *MorxSubtableContextual) nSubs() int { + // find the maximum index need in the substitution array + var maxi uint16 + for _, entry := range ct.Entries { + markIndex, currentIndex := entry.AsMorxContextual() + if markIndex != 0xFFFF && markIndex > maxi { + maxi = markIndex + } + if currentIndex != 0xFFFF && currentIndex > maxi { + maxi = currentIndex + } + } + return int(maxi) + 1 +} + +// binarygen: argument=valuesCount int +type MorxSubtableLigature struct { + AATStateTableExt `arguments:"valuesCount=valuesCount, entryDataSize=2"` + ligActionOffset Offset32 // Byte offset from stateHeader to the start of the ligature action table. + componentOffset Offset32 // Byte offset from stateHeader to the start of the component table. + ligatureOffset Offset32 // Byte offset from stateHeader to the start of the actual ligature lists. + LigActions []uint32 `isOpaque:""` + Components []uint16 `isOpaque:""` + Ligatures []GlyphID `isOpaque:""` +} + +// MorxLigatureSubtable flags +const ( + // Push this glyph onto the component stack for + // eventual processing. + MLSetComponent = 0x8000 + // Leave the glyph pointer at this glyph for the + // next iteration. + MLDontAdvance = 0x4000 + // Use the ligActionIndex to process a ligature group. + MLPerformAction = 0x2000 + // Byte offset from beginning of subtable to the + // ligature action list. This value must be a + // multiple of 4. + MLOffset = 0x3FFF + + // This is the last action in the list. This also + // implies storage. + MLActionLast = 1 << 31 + // Store the ligature at the current cumulated index + // in the ligature table in place of the marked + // (i.e. currently-popped) glyph. + MLActionStore = 1 << 30 + // A 30-bit value which is sign-extended to 32-bits + // and added to the glyph ID, resulting in an index + // into the component table. + MLActionOffset = 0x3FFFFFFF +) + +// the LigActions length is not specified. Instead, we have to parse uint32 one by one +// until we reach last action or reach EOF +func (lig *MorxSubtableLigature) parseLigActions(src []byte, _ int) error { + // fetch the maximum start index + maxIndex := -1 + for _, entry := range lig.Entries { + if entry.Flags&MLPerformAction == 0 { + continue + } + if index := int(entry.AsMorxLigature()); index > maxIndex { + maxIndex = index + } + } + + if L := len(src); L < int(lig.ligActionOffset)+4*int(maxIndex+1) { + return fmt.Errorf("EOF: expected length: %d, got %d", lig.ligActionOffset, L) + } + + // fetch the action table, up to the last entry + src = src[lig.ligActionOffset:] + for len(src) >= 4 { // stop gracefully if the last action was not found + action := binary.BigEndian.Uint32(src) + lig.LigActions = append(lig.LigActions, action) + src = src[4:] + // dont break before maxIndex + if len(lig.LigActions) > maxIndex && action&MLActionLast != 0 { + break + } + } + return nil +} + +func (lig *MorxSubtableLigature) parseComponents(src []byte, _ int) error { + // we rely on offset being sorted, which seems to be the case in practice + if lig.componentOffset > lig.ligatureOffset { + return errors.New("unsupported non sorted offsets") + } + if L := len(src); L < int(lig.componentOffset) { + return fmt.Errorf("EOF: expected length: %d, got %d", lig.componentOffset, L) + } + src = src[lig.componentOffset:] + componentCount := (lig.ligatureOffset - lig.componentOffset) / 2 + lig.Components = make([]uint16, componentCount) + for i := range lig.Components { + lig.Components[i] = binary.BigEndian.Uint16(src[2*i:]) + } + return nil +} + +func (lig *MorxSubtableLigature) parseLigatures(src []byte, _ int) error { + if L := len(src); L < int(lig.ligatureOffset) { + return fmt.Errorf("EOF: expected length: %d, got %d", lig.ligatureOffset, L) + } + src = src[lig.ligatureOffset:] + ligatureCount := len(src) / 2 + lig.Ligatures = make([]GlyphID, ligatureCount) + for i := range lig.Ligatures { + lig.Ligatures[i] = GlyphID(binary.BigEndian.Uint16(src[2*i:])) + } + return nil +} + +type MorxSubtableNonContextual struct { + // The lookup value is interpreted as a GlyphIndex + Class AATLookup +} + +// binarygen: argument=valuesCount int +type MorxSubtableInsertion struct { + AATStateTableExt `arguments:"valuesCount=valuesCount,entryDataSize=4"` + Insertions []GlyphID `offsetSize:"Offset32" arrayCount:"ComputedField-nInsertions()"` // Byte offset from stateHeader to the start of the insertion glyph table. +} + +// MorxInsertionSubtable flags +const ( + // If set, mark the current glyph. + MISetMark = 0x8000 + // If set, don't advance to the next glyph before + // going to the new state. This does not mean + // that the glyph pointed to is the same one as + // before. If you've made insertions immediately + // downstream of the current glyph, the next glyph + // processed would in fact be the first one + // inserted. + MIDontAdvance = 0x4000 + // If set, and the currentInsertList is nonzero, + // then the specified glyph list will be inserted + // as a kashida-like insertion, either before or + // after the current glyph (depending on the state + // of the currentInsertBefore flag). If clear, and + // the currentInsertList is nonzero, then the + // specified glyph list will be inserted as a + // split-vowel-like insertion, either before or + // after the current glyph (depending on the state + // of the currentInsertBefore flag). + MICurrentIsKashidaLike = 0x2000 + // If set, and the markedInsertList is nonzero, + // then the specified glyph list will be inserted + // as a kashida-like insertion, either before or + // after the marked glyph (depending on the state + // of the markedInsertBefore flag). If clear, and + // the markedInsertList is nonzero, then the + // specified glyph list will be inserted as a + // split-vowel-like insertion, either before or + // after the marked glyph (depending on the state + // of the markedInsertBefore flag). + MIMarkedIsKashidaLike = 0x1000 + // If set, specifies that insertions are to be made + // to the left of the current glyph. If clear, + // they're made to the right of the current glyph. + MICurrentInsertBefore = 0x0800 + // If set, specifies that insertions are to be + // made to the left of the marked glyph. If clear, + // they're made to the right of the marked glyph. + MIMarkedInsertBefore = 0x0400 + // This 5-bit field is treated as a count of the + // number of glyphs to insert at the current + // position. Since zero means no insertions, the + // largest number of insertions at any given + // current location is 31 glyphs. + MICurrentInsertCount = 0x3E0 + // This 5-bit field is treated as a count of the + // number of glyphs to insert at the marked + // position. Since zero means no insertions, the + // largest number of insertions at any given + // marked location is 31 glyphs. + MIMarkedInsertCount = 0x001F +) + +func (msi *MorxSubtableInsertion) nInsertions() int { + // find the maximum index needed in the insertions array, + // taking into account the number of insertions + var maxi uint16 + for _, entry := range msi.Entries { + currentIndex, markedIndex := entry.AsMorxInsertion() + if currentIndex != 0xFFFF { + indexEnd := currentIndex + (entry.Flags&MICurrentInsertCount)>>5 + if indexEnd > maxi { + maxi = indexEnd + } + } + if markedIndex != 0xFFFF { + indexEnd := markedIndex + entry.Flags&MIMarkedInsertCount + if indexEnd > maxi { + maxi = indexEnd + } + } + } + return int(maxi) +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_properties.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_properties.go new file mode 100644 index 0000000..9077df4 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_properties.go @@ -0,0 +1,268 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "sort" +) + +// This file implements routines used to simplify acces to the tables +// data. + +func (lk AATLoopkup0) Class(g GlyphID) (uint16, bool) { + if int(g) >= len(lk.Values) { + return 0, false + } + return lk.Values[g], true +} + +func (lk AATLoopkup2) Class(g GlyphID) (uint16, bool) { + // 'adapted' from golang/x/image/font/sfnt + c := lk.Records + num := len(c) + if num == 0 { + return 0, false + } + + // classRange is an array of startGlyphID, endGlyphID and target class ID. + // Ranges are non-overlapping. + // E.g. 130, 135, 1 137, 137, 5 etc + + idx := sort.Search(num, func(i int) bool { return g <= c[i].FirstGlyph }) + // idx either points to a matching start, or to the next range (or idx==num) + // e.g. with the range example from above: 130 points to 130-135 range, 133 points to 137-137 range + + // check if gi is the start of a range, but only if sort.Search returned a valid result + if idx < num { + if class := c[idx]; g == c[idx].FirstGlyph { + return class.Value, true + } + } + // check if gi is in previous range + if idx > 0 { + idx-- + if class := c[idx]; g >= class.FirstGlyph && g <= class.LastGlyph { + return class.Value, true + } + } + + return 0, false +} + +func (lk AATLoopkup4) Class(g GlyphID) (uint16, bool) { + // binary search + for i, j := 0, len(lk.Records); i < j; { + h := i + (j-i)/2 + entry := lk.Records[h] + if g < entry.FirstGlyph { + j = h + } else if entry.LastGlyph < g { + i = h + 1 + } else { + return entry.Values[g-entry.FirstGlyph], true + } + } + return 0, false +} + +func (lk AATLoopkup6) Class(g GlyphID) (uint16, bool) { + // binary search + for i, j := 0, len(lk.Records); i < j; { + h := i + (j-i)/2 + entry := lk.Records[h] + if g < entry.Glyph { + j = h + } else if entry.Glyph < g { + i = h + 1 + } else { + return entry.Value, true + } + } + return 0, false +} + +func (lk AATLoopkup8Data) Class(g GlyphID) (uint16, bool) { + if g < lk.FirstGlyph || g >= lk.FirstGlyph+GlyphID(len(lk.Values)) { + return 0, false + } + return lk.Values[g-lk.FirstGlyph], true +} + +func (lk AATLoopkup10) Class(g GlyphID) (uint16, bool) { + if g < lk.FirstGlyph || g >= lk.FirstGlyph+GlyphID(len(lk.Values)) { + return 0, false + } + return lk.Values[g-lk.FirstGlyph], true +} + +func (lk AATLoopkupExt0) Class(g GlyphID) (uint32, bool) { + if int(g) >= len(lk.Values) { + return 0, false + } + return lk.Values[g], true +} + +func (lk AATLoopkupExt2) Class(g GlyphID) (uint32, bool) { + // 'adapted' from golang/x/image/font/sfnt + c := lk.Records + num := len(c) + if num == 0 { + return 0, false + } + + // classRange is an array of startGlyphID, endGlyphID and target class ID. + // Ranges are non-overlapping. + // E.g. 130, 135, 1 137, 137, 5 etc + + idx := sort.Search(num, func(i int) bool { return g <= c[i].FirstGlyph }) + // idx either points to a matching start, or to the next range (or idx==num) + // e.g. with the range example from above: 130 points to 130-135 range, 133 points to 137-137 range + + // check if gi is the start of a range, but only if sort.Search returned a valid result + if idx < num { + if class := c[idx]; g == c[idx].FirstGlyph { + return class.Value, true + } + } + // check if gi is in previous range + if idx > 0 { + idx-- + if class := c[idx]; g >= class.FirstGlyph && g <= class.LastGlyph { + return class.Value, true + } + } + + return 0, false +} + +func (lk AATLoopkupExt4) Class(g GlyphID) (uint32, bool) { + // binary search + for i, j := 0, len(lk.Records); i < j; { + h := i + (j-i)/2 + entry := lk.Records[h] + if g < entry.FirstGlyph { + j = h + } else if entry.LastGlyph < g { + i = h + 1 + } else { + return entry.Values[g-entry.FirstGlyph], true + } + } + return 0, false +} + +func (lk AATLoopkupExt6) Class(g GlyphID) (uint32, bool) { + // binary search + for i, j := 0, len(lk.Records); i < j; { + h := i + (j-i)/2 + entry := lk.Records[h] + if g < entry.Glyph { + j = h + } else if entry.Glyph < g { + i = h + 1 + } else { + return entry.Value, true + } + } + return 0, false +} + +func (lk AATLoopkupExt8) Class(g GlyphID) (uint32, bool) { + v, ok := AATLoopkup8(lk).Class(g) + return uint32(v), ok +} + +func (lk AATLoopkupExt10) Class(g GlyphID) (uint32, bool) { + if g < lk.FirstGlyph || g >= lk.FirstGlyph+GlyphID(len(lk.Values)) { + return 0, false + } + return lk.Values[g-lk.FirstGlyph], true +} + +type AatLookupMixed interface { + // Returns 0 if not supported + ClassUint32(GlyphID) uint32 +} + +func (lk AATLoopkup0) ClassUint32(g GlyphID) uint32 { + v, _ := lk.Class(g) + return uint32(v) +} + +func (lk AATLoopkup2) ClassUint32(g GlyphID) uint32 { + v, _ := lk.Class(g) + return uint32(v) +} + +func (lk AATLoopkup4) ClassUint32(g GlyphID) uint32 { + v, _ := lk.Class(g) + return uint32(v) +} + +func (lk AATLoopkup6) ClassUint32(g GlyphID) uint32 { + v, _ := lk.Class(g) + return uint32(v) +} + +func (lk AATLoopkup8) ClassUint32(g GlyphID) uint32 { + v, _ := lk.Class(g) + return uint32(v) +} + +func (lk AATLoopkup10) ClassUint32(g GlyphID) uint32 { + v, _ := lk.Class(g) + return uint32(v) +} + +func (lk AATLoopkupExt0) ClassUint32(g GlyphID) uint32 { + v, _ := lk.Class(g) + return v +} + +func (lk AATLoopkupExt2) ClassUint32(g GlyphID) uint32 { + v, _ := lk.Class(g) + return v +} + +func (lk AATLoopkupExt4) ClassUint32(g GlyphID) uint32 { + v, _ := lk.Class(g) + return v +} + +func (lk AATLoopkupExt6) ClassUint32(g GlyphID) uint32 { + v, _ := lk.Class(g) + return v +} + +func (lk AATLoopkupExt8) ClassUint32(g GlyphID) uint32 { + v, _ := lk.Class(g) + return v +} + +func (lk AATLoopkupExt10) ClassUint32(g GlyphID) uint32 { + v, _ := lk.Class(g) + return v +} + +// GetFeature performs a binary seach into the names, using `Feature` as key, +// returning `nil` if not found. +func (ft Feat) GetFeature(feature uint16) *FeatureName { + for i, j := 0, len(ft.Names); i < j; { + h := i + (j-i)/2 + entry := ft.Names[h].Feature + if feature < entry { + j = h + } else if entry < feature { + i = h + 1 + } else { + return &ft.Names[h] + } + } + return nil +} + +// IsExclusive returns true if the feature settings are mutually exclusive. +func (feature *FeatureName) IsExclusive() bool { + const Exclusive = 0x8000 + return feature.FeatureFlags&Exclusive != 0 +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_trak_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_trak_gen.go new file mode 100644 index 0000000..ab355f9 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_trak_gen.go @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from aat_trak_src.go. DO NOT EDIT + +func ParseTrackData(src []byte, parentSrc []byte) (TrackData, int, error) { + var item TrackData + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading TrackData: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.nTracks = binary.BigEndian.Uint16(src[0:]) + item.nSizes = binary.BigEndian.Uint16(src[2:]) + offsetSizeTable := int(binary.BigEndian.Uint32(src[4:])) + n += 8 + + { + + if offsetSizeTable != 0 { // ignore null offset + if L := len(parentSrc); L < offsetSizeTable { + return item, 0, fmt.Errorf("reading TrackData: "+"EOF: expected length: %d, got %d", offsetSizeTable, L) + } + + arrayLength := int(item.nSizes) + + if L := len(parentSrc); L < offsetSizeTable+arrayLength*4 { + return item, 0, fmt.Errorf("reading TrackData: "+"EOF: expected length: %d, got %d", offsetSizeTable+arrayLength*4, L) + } + + item.SizeTable = make([]float32, arrayLength) // allocation guarded by the previous check + for i := range item.SizeTable { + item.SizeTable[i] = Float1616FromUint(binary.BigEndian.Uint32(parentSrc[offsetSizeTable+i*4:])) + } + offsetSizeTable += arrayLength * 4 + } + } + { + arrayLength := int(item.nTracks) + + offset := 8 + for i := 0; i < arrayLength; i++ { + elem, read, err := ParseTrackTableEntry(src[offset:], parentSrc, int(item.nSizes)) + if err != nil { + return item, 0, fmt.Errorf("reading TrackData: %s", err) + } + item.TrackTable = append(item.TrackTable, elem) + offset += read + } + n = offset + } + return item, n, nil +} + +func ParseTrackTableEntry(src []byte, grandParentSrc []byte, perSizeTrackingCount int) (TrackTableEntry, int, error) { + var item TrackTableEntry + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading TrackTableEntry: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.Track = Float1616FromUint(binary.BigEndian.Uint32(src[0:])) + item.NameIndex = binary.BigEndian.Uint16(src[4:]) + offsetPerSizeTracking := int(binary.BigEndian.Uint16(src[6:])) + n += 8 + + { + + if offsetPerSizeTracking != 0 { // ignore null offset + if L := len(grandParentSrc); L < offsetPerSizeTracking { + return item, 0, fmt.Errorf("reading TrackTableEntry: "+"EOF: expected length: %d, got %d", offsetPerSizeTracking, L) + } + + if L := len(grandParentSrc); L < offsetPerSizeTracking+perSizeTrackingCount*2 { + return item, 0, fmt.Errorf("reading TrackTableEntry: "+"EOF: expected length: %d, got %d", offsetPerSizeTracking+perSizeTrackingCount*2, L) + } + + item.PerSizeTracking = make([]int16, perSizeTrackingCount) // allocation guarded by the previous check + for i := range item.PerSizeTracking { + item.PerSizeTracking[i] = int16(binary.BigEndian.Uint16(grandParentSrc[offsetPerSizeTracking+i*2:])) + } + offsetPerSizeTracking += perSizeTrackingCount * 2 + } + } + return item, n, nil +} + +func ParseTrak(src []byte) (Trak, int, error) { + var item Trak + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading Trak: "+"EOF: expected length: 12, got %d", L) + } + _ = src[11] // early bound checking + item.version = binary.BigEndian.Uint32(src[0:]) + item.format = binary.BigEndian.Uint16(src[4:]) + offsetHoriz := int(binary.BigEndian.Uint16(src[6:])) + offsetVert := int(binary.BigEndian.Uint16(src[8:])) + item.reserved = binary.BigEndian.Uint16(src[10:]) + n += 12 + + { + + if offsetHoriz != 0 { // ignore null offset + if L := len(src); L < offsetHoriz { + return item, 0, fmt.Errorf("reading Trak: "+"EOF: expected length: %d, got %d", offsetHoriz, L) + } + + var err error + item.Horiz, _, err = ParseTrackData(src[offsetHoriz:], src) + if err != nil { + return item, 0, fmt.Errorf("reading Trak: %s", err) + } + + } + } + { + + if offsetVert != 0 { // ignore null offset + if L := len(src); L < offsetVert { + return item, 0, fmt.Errorf("reading Trak: "+"EOF: expected length: %d, got %d", offsetVert, L) + } + + var err error + item.Vert, _, err = ParseTrackData(src[offsetVert:], src) + if err != nil { + return item, 0, fmt.Errorf("reading Trak: %s", err) + } + + } + } + return item, n, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_trak_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_trak_src.go new file mode 100644 index 0000000..e54a98a --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/aat_trak_src.go @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +// Trak is the tracking table. +// See - https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6trak.html +type Trak struct { + version uint32 // Version number of the tracking table (0x00010000 for the current version). + format uint16 // Format of the tracking table (set to 0). + Horiz TrackData `offsetSize:"Offset16"` // Offset from start of tracking table to TrackData for horizontal text (or 0 if none). + Vert TrackData `offsetSize:"Offset16"` // Offset from start of tracking table to TrackData for vertical text (or 0 if none). + reserved uint16 // Reserved. Set to 0. +} + +// IsEmpty return `true` it the table has no entries. +func (t Trak) IsEmpty() bool { + return len(t.Horiz.TrackTable)+len(t.Vert.TrackTable) == 0 +} + +type TrackData struct { + nTracks uint16 // Number of separate tracks included in this table. + nSizes uint16 // Number of point sizes included in this table. + SizeTable []Float1616 `offsetSize:"Offset32" offsetRelativeTo:"Parent" arrayCount:"ComputedField-nSizes"` // Offset from start of the tracking table to the start of the size subtable. + TrackTable []TrackTableEntry `arrayCount:"ComputedField-nTracks" arguments:"perSizeTrackingCount=.nSizes"` // Array[nTracks] of TrackTableEntry records. +} + +type TrackTableEntry struct { + Track Float1616 // Track value for this record. + NameIndex uint16 // The 'name' table index for this track (a short word or phrase like "loose" or "very tight"). NameIndex has a value greater than 255 and less than 32768. + PerSizeTracking []int16 `offsetSize:"Offset16" offsetRelativeTo:"GrandParent"` // in font units, with length len(SizeTable) +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/cmap_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/cmap_gen.go new file mode 100644 index 0000000..20a0a75 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/cmap_gen.go @@ -0,0 +1,745 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from cmap_src.go. DO NOT EDIT + +func (item *CmapSubtable0) mustParse(src []byte) { + _ = src[261] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + item.length = binary.BigEndian.Uint16(src[2:]) + item.language = binary.BigEndian.Uint16(src[4:]) + item.GlyphIdArray[0] = src[6] + item.GlyphIdArray[1] = src[7] + item.GlyphIdArray[2] = src[8] + item.GlyphIdArray[3] = src[9] + item.GlyphIdArray[4] = src[10] + item.GlyphIdArray[5] = src[11] + item.GlyphIdArray[6] = src[12] + item.GlyphIdArray[7] = src[13] + item.GlyphIdArray[8] = src[14] + item.GlyphIdArray[9] = src[15] + item.GlyphIdArray[10] = src[16] + item.GlyphIdArray[11] = src[17] + item.GlyphIdArray[12] = src[18] + item.GlyphIdArray[13] = src[19] + item.GlyphIdArray[14] = src[20] + item.GlyphIdArray[15] = src[21] + item.GlyphIdArray[16] = src[22] + item.GlyphIdArray[17] = src[23] + item.GlyphIdArray[18] = src[24] + item.GlyphIdArray[19] = src[25] + item.GlyphIdArray[20] = src[26] + item.GlyphIdArray[21] = src[27] + item.GlyphIdArray[22] = src[28] + item.GlyphIdArray[23] = src[29] + item.GlyphIdArray[24] = src[30] + item.GlyphIdArray[25] = src[31] + item.GlyphIdArray[26] = src[32] + item.GlyphIdArray[27] = src[33] + item.GlyphIdArray[28] = src[34] + item.GlyphIdArray[29] = src[35] + item.GlyphIdArray[30] = src[36] + item.GlyphIdArray[31] = src[37] + item.GlyphIdArray[32] = src[38] + item.GlyphIdArray[33] = src[39] + item.GlyphIdArray[34] = src[40] + item.GlyphIdArray[35] = src[41] + item.GlyphIdArray[36] = src[42] + item.GlyphIdArray[37] = src[43] + item.GlyphIdArray[38] = src[44] + item.GlyphIdArray[39] = src[45] + item.GlyphIdArray[40] = src[46] + item.GlyphIdArray[41] = src[47] + item.GlyphIdArray[42] = src[48] + item.GlyphIdArray[43] = src[49] + item.GlyphIdArray[44] = src[50] + item.GlyphIdArray[45] = src[51] + item.GlyphIdArray[46] = src[52] + item.GlyphIdArray[47] = src[53] + item.GlyphIdArray[48] = src[54] + item.GlyphIdArray[49] = src[55] + item.GlyphIdArray[50] = src[56] + item.GlyphIdArray[51] = src[57] + item.GlyphIdArray[52] = src[58] + item.GlyphIdArray[53] = src[59] + item.GlyphIdArray[54] = src[60] + item.GlyphIdArray[55] = src[61] + item.GlyphIdArray[56] = src[62] + item.GlyphIdArray[57] = src[63] + item.GlyphIdArray[58] = src[64] + item.GlyphIdArray[59] = src[65] + item.GlyphIdArray[60] = src[66] + item.GlyphIdArray[61] = src[67] + item.GlyphIdArray[62] = src[68] + item.GlyphIdArray[63] = src[69] + item.GlyphIdArray[64] = src[70] + item.GlyphIdArray[65] = src[71] + item.GlyphIdArray[66] = src[72] + item.GlyphIdArray[67] = src[73] + item.GlyphIdArray[68] = src[74] + item.GlyphIdArray[69] = src[75] + item.GlyphIdArray[70] = src[76] + item.GlyphIdArray[71] = src[77] + item.GlyphIdArray[72] = src[78] + item.GlyphIdArray[73] = src[79] + item.GlyphIdArray[74] = src[80] + item.GlyphIdArray[75] = src[81] + item.GlyphIdArray[76] = src[82] + item.GlyphIdArray[77] = src[83] + item.GlyphIdArray[78] = src[84] + item.GlyphIdArray[79] = src[85] + item.GlyphIdArray[80] = src[86] + item.GlyphIdArray[81] = src[87] + item.GlyphIdArray[82] = src[88] + item.GlyphIdArray[83] = src[89] + item.GlyphIdArray[84] = src[90] + item.GlyphIdArray[85] = src[91] + item.GlyphIdArray[86] = src[92] + item.GlyphIdArray[87] = src[93] + item.GlyphIdArray[88] = src[94] + item.GlyphIdArray[89] = src[95] + item.GlyphIdArray[90] = src[96] + item.GlyphIdArray[91] = src[97] + item.GlyphIdArray[92] = src[98] + item.GlyphIdArray[93] = src[99] + item.GlyphIdArray[94] = src[100] + item.GlyphIdArray[95] = src[101] + item.GlyphIdArray[96] = src[102] + item.GlyphIdArray[97] = src[103] + item.GlyphIdArray[98] = src[104] + item.GlyphIdArray[99] = src[105] + item.GlyphIdArray[100] = src[106] + item.GlyphIdArray[101] = src[107] + item.GlyphIdArray[102] = src[108] + item.GlyphIdArray[103] = src[109] + item.GlyphIdArray[104] = src[110] + item.GlyphIdArray[105] = src[111] + item.GlyphIdArray[106] = src[112] + item.GlyphIdArray[107] = src[113] + item.GlyphIdArray[108] = src[114] + item.GlyphIdArray[109] = src[115] + item.GlyphIdArray[110] = src[116] + item.GlyphIdArray[111] = src[117] + item.GlyphIdArray[112] = src[118] + item.GlyphIdArray[113] = src[119] + item.GlyphIdArray[114] = src[120] + item.GlyphIdArray[115] = src[121] + item.GlyphIdArray[116] = src[122] + item.GlyphIdArray[117] = src[123] + item.GlyphIdArray[118] = src[124] + item.GlyphIdArray[119] = src[125] + item.GlyphIdArray[120] = src[126] + item.GlyphIdArray[121] = src[127] + item.GlyphIdArray[122] = src[128] + item.GlyphIdArray[123] = src[129] + item.GlyphIdArray[124] = src[130] + item.GlyphIdArray[125] = src[131] + item.GlyphIdArray[126] = src[132] + item.GlyphIdArray[127] = src[133] + item.GlyphIdArray[128] = src[134] + item.GlyphIdArray[129] = src[135] + item.GlyphIdArray[130] = src[136] + item.GlyphIdArray[131] = src[137] + item.GlyphIdArray[132] = src[138] + item.GlyphIdArray[133] = src[139] + item.GlyphIdArray[134] = src[140] + item.GlyphIdArray[135] = src[141] + item.GlyphIdArray[136] = src[142] + item.GlyphIdArray[137] = src[143] + item.GlyphIdArray[138] = src[144] + item.GlyphIdArray[139] = src[145] + item.GlyphIdArray[140] = src[146] + item.GlyphIdArray[141] = src[147] + item.GlyphIdArray[142] = src[148] + item.GlyphIdArray[143] = src[149] + item.GlyphIdArray[144] = src[150] + item.GlyphIdArray[145] = src[151] + item.GlyphIdArray[146] = src[152] + item.GlyphIdArray[147] = src[153] + item.GlyphIdArray[148] = src[154] + item.GlyphIdArray[149] = src[155] + item.GlyphIdArray[150] = src[156] + item.GlyphIdArray[151] = src[157] + item.GlyphIdArray[152] = src[158] + item.GlyphIdArray[153] = src[159] + item.GlyphIdArray[154] = src[160] + item.GlyphIdArray[155] = src[161] + item.GlyphIdArray[156] = src[162] + item.GlyphIdArray[157] = src[163] + item.GlyphIdArray[158] = src[164] + item.GlyphIdArray[159] = src[165] + item.GlyphIdArray[160] = src[166] + item.GlyphIdArray[161] = src[167] + item.GlyphIdArray[162] = src[168] + item.GlyphIdArray[163] = src[169] + item.GlyphIdArray[164] = src[170] + item.GlyphIdArray[165] = src[171] + item.GlyphIdArray[166] = src[172] + item.GlyphIdArray[167] = src[173] + item.GlyphIdArray[168] = src[174] + item.GlyphIdArray[169] = src[175] + item.GlyphIdArray[170] = src[176] + item.GlyphIdArray[171] = src[177] + item.GlyphIdArray[172] = src[178] + item.GlyphIdArray[173] = src[179] + item.GlyphIdArray[174] = src[180] + item.GlyphIdArray[175] = src[181] + item.GlyphIdArray[176] = src[182] + item.GlyphIdArray[177] = src[183] + item.GlyphIdArray[178] = src[184] + item.GlyphIdArray[179] = src[185] + item.GlyphIdArray[180] = src[186] + item.GlyphIdArray[181] = src[187] + item.GlyphIdArray[182] = src[188] + item.GlyphIdArray[183] = src[189] + item.GlyphIdArray[184] = src[190] + item.GlyphIdArray[185] = src[191] + item.GlyphIdArray[186] = src[192] + item.GlyphIdArray[187] = src[193] + item.GlyphIdArray[188] = src[194] + item.GlyphIdArray[189] = src[195] + item.GlyphIdArray[190] = src[196] + item.GlyphIdArray[191] = src[197] + item.GlyphIdArray[192] = src[198] + item.GlyphIdArray[193] = src[199] + item.GlyphIdArray[194] = src[200] + item.GlyphIdArray[195] = src[201] + item.GlyphIdArray[196] = src[202] + item.GlyphIdArray[197] = src[203] + item.GlyphIdArray[198] = src[204] + item.GlyphIdArray[199] = src[205] + item.GlyphIdArray[200] = src[206] + item.GlyphIdArray[201] = src[207] + item.GlyphIdArray[202] = src[208] + item.GlyphIdArray[203] = src[209] + item.GlyphIdArray[204] = src[210] + item.GlyphIdArray[205] = src[211] + item.GlyphIdArray[206] = src[212] + item.GlyphIdArray[207] = src[213] + item.GlyphIdArray[208] = src[214] + item.GlyphIdArray[209] = src[215] + item.GlyphIdArray[210] = src[216] + item.GlyphIdArray[211] = src[217] + item.GlyphIdArray[212] = src[218] + item.GlyphIdArray[213] = src[219] + item.GlyphIdArray[214] = src[220] + item.GlyphIdArray[215] = src[221] + item.GlyphIdArray[216] = src[222] + item.GlyphIdArray[217] = src[223] + item.GlyphIdArray[218] = src[224] + item.GlyphIdArray[219] = src[225] + item.GlyphIdArray[220] = src[226] + item.GlyphIdArray[221] = src[227] + item.GlyphIdArray[222] = src[228] + item.GlyphIdArray[223] = src[229] + item.GlyphIdArray[224] = src[230] + item.GlyphIdArray[225] = src[231] + item.GlyphIdArray[226] = src[232] + item.GlyphIdArray[227] = src[233] + item.GlyphIdArray[228] = src[234] + item.GlyphIdArray[229] = src[235] + item.GlyphIdArray[230] = src[236] + item.GlyphIdArray[231] = src[237] + item.GlyphIdArray[232] = src[238] + item.GlyphIdArray[233] = src[239] + item.GlyphIdArray[234] = src[240] + item.GlyphIdArray[235] = src[241] + item.GlyphIdArray[236] = src[242] + item.GlyphIdArray[237] = src[243] + item.GlyphIdArray[238] = src[244] + item.GlyphIdArray[239] = src[245] + item.GlyphIdArray[240] = src[246] + item.GlyphIdArray[241] = src[247] + item.GlyphIdArray[242] = src[248] + item.GlyphIdArray[243] = src[249] + item.GlyphIdArray[244] = src[250] + item.GlyphIdArray[245] = src[251] + item.GlyphIdArray[246] = src[252] + item.GlyphIdArray[247] = src[253] + item.GlyphIdArray[248] = src[254] + item.GlyphIdArray[249] = src[255] + item.GlyphIdArray[250] = src[256] + item.GlyphIdArray[251] = src[257] + item.GlyphIdArray[252] = src[258] + item.GlyphIdArray[253] = src[259] + item.GlyphIdArray[254] = src[260] + item.GlyphIdArray[255] = src[261] +} + +func ParseCmap(src []byte) (Cmap, int, error) { + var item Cmap + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading Cmap: "+"EOF: expected length: 4, got %d", L) + } + _ = src[3] // early bound checking + item.version = binary.BigEndian.Uint16(src[0:]) + item.numTables = binary.BigEndian.Uint16(src[2:]) + n += 4 + + { + arrayLength := int(item.numTables) + + offset := 4 + for i := 0; i < arrayLength; i++ { + elem, read, err := ParseEncodingRecord(src[offset:], src) + if err != nil { + return item, 0, fmt.Errorf("reading Cmap: %s", err) + } + item.Records = append(item.Records, elem) + offset += read + } + n = offset + } + return item, n, nil +} + +func ParseCmapSubtable(src []byte) (CmapSubtable, int, error) { + var item CmapSubtable + + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading CmapSubtable: "+"EOF: expected length: 2, got %d", L) + } + format := uint16(binary.BigEndian.Uint16(src[0:])) + var ( + read int + err error + ) + switch format { + case 0: + item, read, err = ParseCmapSubtable0(src[0:]) + case 10: + item, read, err = ParseCmapSubtable10(src[0:]) + case 12: + item, read, err = ParseCmapSubtable12(src[0:]) + case 13: + item, read, err = ParseCmapSubtable13(src[0:]) + case 14: + item, read, err = ParseCmapSubtable14(src[0:]) + case 2: + item, read, err = ParseCmapSubtable2(src[0:]) + case 4: + item, read, err = ParseCmapSubtable4(src[0:]) + case 6: + item, read, err = ParseCmapSubtable6(src[0:]) + default: + err = fmt.Errorf("unsupported CmapSubtable format %d", format) + } + if err != nil { + return item, 0, fmt.Errorf("reading CmapSubtable: %s", err) + } + + return item, read, nil +} + +func ParseCmapSubtable0(src []byte) (CmapSubtable0, int, error) { + var item CmapSubtable0 + n := 0 + if L := len(src); L < 262 { + return item, 0, fmt.Errorf("reading CmapSubtable0: "+"EOF: expected length: 262, got %d", L) + } + item.mustParse(src) + n += 262 + return item, n, nil +} + +func ParseCmapSubtable10(src []byte) (CmapSubtable10, int, error) { + var item CmapSubtable10 + n := 0 + if L := len(src); L < 20 { + return item, 0, fmt.Errorf("reading CmapSubtable10: "+"EOF: expected length: 20, got %d", L) + } + _ = src[19] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + item.reserved = binary.BigEndian.Uint16(src[2:]) + item.length = binary.BigEndian.Uint32(src[4:]) + item.language = binary.BigEndian.Uint32(src[8:]) + item.StartCharCode = binary.BigEndian.Uint32(src[12:]) + arrayLengthGlyphIdArray := int(binary.BigEndian.Uint32(src[16:])) + n += 20 + + { + + if L := len(src); L < 20+arrayLengthGlyphIdArray*2 { + return item, 0, fmt.Errorf("reading CmapSubtable10: "+"EOF: expected length: %d, got %d", 20+arrayLengthGlyphIdArray*2, L) + } + + item.GlyphIdArray = make([]uint16, arrayLengthGlyphIdArray) // allocation guarded by the previous check + for i := range item.GlyphIdArray { + item.GlyphIdArray[i] = binary.BigEndian.Uint16(src[20+i*2:]) + } + n += arrayLengthGlyphIdArray * 2 + } + return item, n, nil +} + +func ParseCmapSubtable12(src []byte) (CmapSubtable12, int, error) { + var item CmapSubtable12 + n := 0 + if L := len(src); L < 16 { + return item, 0, fmt.Errorf("reading CmapSubtable12: "+"EOF: expected length: 16, got %d", L) + } + _ = src[15] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + item.reserved = binary.BigEndian.Uint16(src[2:]) + item.length = binary.BigEndian.Uint32(src[4:]) + item.language = binary.BigEndian.Uint32(src[8:]) + arrayLengthGroups := int(binary.BigEndian.Uint32(src[12:])) + n += 16 + + { + + if L := len(src); L < 16+arrayLengthGroups*12 { + return item, 0, fmt.Errorf("reading CmapSubtable12: "+"EOF: expected length: %d, got %d", 16+arrayLengthGroups*12, L) + } + + item.Groups = make([]SequentialMapGroup, arrayLengthGroups) // allocation guarded by the previous check + for i := range item.Groups { + item.Groups[i].mustParse(src[16+i*12:]) + } + n += arrayLengthGroups * 12 + } + return item, n, nil +} + +func ParseCmapSubtable13(src []byte) (CmapSubtable13, int, error) { + var item CmapSubtable13 + n := 0 + if L := len(src); L < 16 { + return item, 0, fmt.Errorf("reading CmapSubtable13: "+"EOF: expected length: 16, got %d", L) + } + _ = src[15] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + item.reserved = binary.BigEndian.Uint16(src[2:]) + item.length = binary.BigEndian.Uint32(src[4:]) + item.language = binary.BigEndian.Uint32(src[8:]) + arrayLengthGroups := int(binary.BigEndian.Uint32(src[12:])) + n += 16 + + { + + if L := len(src); L < 16+arrayLengthGroups*12 { + return item, 0, fmt.Errorf("reading CmapSubtable13: "+"EOF: expected length: %d, got %d", 16+arrayLengthGroups*12, L) + } + + item.Groups = make([]SequentialMapGroup, arrayLengthGroups) // allocation guarded by the previous check + for i := range item.Groups { + item.Groups[i].mustParse(src[16+i*12:]) + } + n += arrayLengthGroups * 12 + } + return item, n, nil +} + +func ParseCmapSubtable14(src []byte) (CmapSubtable14, int, error) { + var item CmapSubtable14 + n := 0 + if L := len(src); L < 10 { + return item, 0, fmt.Errorf("reading CmapSubtable14: "+"EOF: expected length: 10, got %d", L) + } + _ = src[9] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + item.length = binary.BigEndian.Uint32(src[2:]) + arrayLengthVarSelectors := int(binary.BigEndian.Uint32(src[6:])) + n += 10 + + { + + offset := 10 + for i := 0; i < arrayLengthVarSelectors; i++ { + elem, read, err := ParseVariationSelector(src[offset:], src) + if err != nil { + return item, 0, fmt.Errorf("reading CmapSubtable14: %s", err) + } + item.VarSelectors = append(item.VarSelectors, elem) + offset += read + } + n = offset + } + return item, n, nil +} + +func ParseCmapSubtable2(src []byte) (CmapSubtable2, int, error) { + var item CmapSubtable2 + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading CmapSubtable2: "+"EOF: expected length: 2, got %d", L) + } + item.format = binary.BigEndian.Uint16(src[0:]) + n += 2 + + { + + item.rawData = src[2:] + n = len(src) + } + return item, n, nil +} + +func ParseCmapSubtable4(src []byte) (CmapSubtable4, int, error) { + var item CmapSubtable4 + n := 0 + if L := len(src); L < 14 { + return item, 0, fmt.Errorf("reading CmapSubtable4: "+"EOF: expected length: 14, got %d", L) + } + _ = src[13] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + item.length = binary.BigEndian.Uint16(src[2:]) + item.language = binary.BigEndian.Uint16(src[4:]) + item.segCountX2 = binary.BigEndian.Uint16(src[6:]) + item.searchRange = binary.BigEndian.Uint16(src[8:]) + item.entrySelector = binary.BigEndian.Uint16(src[10:]) + item.rangeShift = binary.BigEndian.Uint16(src[12:]) + n += 14 + + { + arrayLength := int(item.segCountX2 / 2) + + if L := len(src); L < 14+arrayLength*2 { + return item, 0, fmt.Errorf("reading CmapSubtable4: "+"EOF: expected length: %d, got %d", 14+arrayLength*2, L) + } + + item.EndCode = make([]uint16, arrayLength) // allocation guarded by the previous check + for i := range item.EndCode { + item.EndCode[i] = binary.BigEndian.Uint16(src[14+i*2:]) + } + n += arrayLength * 2 + } + if L := len(src); L < n+2 { + return item, 0, fmt.Errorf("reading CmapSubtable4: "+"EOF: expected length: n + 2, got %d", L) + } + item.reservedPad = binary.BigEndian.Uint16(src[n:]) + n += 2 + + { + arrayLength := int(item.segCountX2 / 2) + + if L := len(src); L < n+arrayLength*2 { + return item, 0, fmt.Errorf("reading CmapSubtable4: "+"EOF: expected length: %d, got %d", n+arrayLength*2, L) + } + + item.StartCode = make([]uint16, arrayLength) // allocation guarded by the previous check + for i := range item.StartCode { + item.StartCode[i] = binary.BigEndian.Uint16(src[n+i*2:]) + } + n += arrayLength * 2 + } + { + arrayLength := int(item.segCountX2 / 2) + + if L := len(src); L < n+arrayLength*2 { + return item, 0, fmt.Errorf("reading CmapSubtable4: "+"EOF: expected length: %d, got %d", n+arrayLength*2, L) + } + + item.IdDelta = make([]uint16, arrayLength) // allocation guarded by the previous check + for i := range item.IdDelta { + item.IdDelta[i] = binary.BigEndian.Uint16(src[n+i*2:]) + } + n += arrayLength * 2 + } + { + arrayLength := int(item.segCountX2 / 2) + + if L := len(src); L < n+arrayLength*2 { + return item, 0, fmt.Errorf("reading CmapSubtable4: "+"EOF: expected length: %d, got %d", n+arrayLength*2, L) + } + + item.IdRangeOffsets = make([]uint16, arrayLength) // allocation guarded by the previous check + for i := range item.IdRangeOffsets { + item.IdRangeOffsets[i] = binary.BigEndian.Uint16(src[n+i*2:]) + } + n += arrayLength * 2 + } + { + + item.GlyphIDArray = src[n:] + n = len(src) + } + return item, n, nil +} + +func ParseCmapSubtable6(src []byte) (CmapSubtable6, int, error) { + var item CmapSubtable6 + n := 0 + if L := len(src); L < 10 { + return item, 0, fmt.Errorf("reading CmapSubtable6: "+"EOF: expected length: 10, got %d", L) + } + _ = src[9] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + item.length = binary.BigEndian.Uint16(src[2:]) + item.language = binary.BigEndian.Uint16(src[4:]) + item.FirstCode = binary.BigEndian.Uint16(src[6:]) + arrayLengthGlyphIdArray := int(binary.BigEndian.Uint16(src[8:])) + n += 10 + + { + + if L := len(src); L < 10+arrayLengthGlyphIdArray*2 { + return item, 0, fmt.Errorf("reading CmapSubtable6: "+"EOF: expected length: %d, got %d", 10+arrayLengthGlyphIdArray*2, L) + } + + item.GlyphIdArray = make([]uint16, arrayLengthGlyphIdArray) // allocation guarded by the previous check + for i := range item.GlyphIdArray { + item.GlyphIdArray[i] = binary.BigEndian.Uint16(src[10+i*2:]) + } + n += arrayLengthGlyphIdArray * 2 + } + return item, n, nil +} + +func ParseDefaultUVSTable(src []byte) (DefaultUVSTable, int, error) { + var item DefaultUVSTable + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading DefaultUVSTable: "+"EOF: expected length: 4, got %d", L) + } + arrayLengthRanges := int(binary.BigEndian.Uint32(src[0:])) + n += 4 + + { + + if L := len(src); L < 4+arrayLengthRanges*4 { + return item, 0, fmt.Errorf("reading DefaultUVSTable: "+"EOF: expected length: %d, got %d", 4+arrayLengthRanges*4, L) + } + + item.Ranges = make([]UnicodeRange, arrayLengthRanges) // allocation guarded by the previous check + for i := range item.Ranges { + item.Ranges[i].mustParse(src[4+i*4:]) + } + n += arrayLengthRanges * 4 + } + return item, n, nil +} + +func ParseEncodingRecord(src []byte, parentSrc []byte) (EncodingRecord, int, error) { + var item EncodingRecord + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading EncodingRecord: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.PlatformID = PlatformID(binary.BigEndian.Uint16(src[0:])) + item.EncodingID = EncodingID(binary.BigEndian.Uint16(src[2:])) + offsetSubtable := int(binary.BigEndian.Uint32(src[4:])) + n += 8 + + { + + if offsetSubtable != 0 { // ignore null offset + if L := len(parentSrc); L < offsetSubtable { + return item, 0, fmt.Errorf("reading EncodingRecord: "+"EOF: expected length: %d, got %d", offsetSubtable, L) + } + + var ( + err error + read int + ) + item.Subtable, read, err = ParseCmapSubtable(parentSrc[offsetSubtable:]) + if err != nil { + return item, 0, fmt.Errorf("reading EncodingRecord: %s", err) + } + offsetSubtable += read + } + } + return item, n, nil +} + +func ParseUVSMappingTable(src []byte) (UVSMappingTable, int, error) { + var item UVSMappingTable + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading UVSMappingTable: "+"EOF: expected length: 4, got %d", L) + } + arrayLengthRanges := int(binary.BigEndian.Uint32(src[0:])) + n += 4 + + { + + if L := len(src); L < 4+arrayLengthRanges*5 { + return item, 0, fmt.Errorf("reading UVSMappingTable: "+"EOF: expected length: %d, got %d", 4+arrayLengthRanges*5, L) + } + + item.Ranges = make([]UvsMappingRecord, arrayLengthRanges) // allocation guarded by the previous check + for i := range item.Ranges { + item.Ranges[i].mustParse(src[4+i*5:]) + } + n += arrayLengthRanges * 5 + } + return item, n, nil +} + +func ParseVariationSelector(src []byte, parentSrc []byte) (VariationSelector, int, error) { + var item VariationSelector + n := 0 + if L := len(src); L < 11 { + return item, 0, fmt.Errorf("reading VariationSelector: "+"EOF: expected length: 11, got %d", L) + } + _ = src[10] // early bound checking + item.VarSelector[0] = src[0] + item.VarSelector[1] = src[1] + item.VarSelector[2] = src[2] + offsetDefaultUVS := int(binary.BigEndian.Uint32(src[3:])) + offsetNonDefaultUVS := int(binary.BigEndian.Uint32(src[7:])) + n += 11 + + { + + if offsetDefaultUVS != 0 { // ignore null offset + if L := len(parentSrc); L < offsetDefaultUVS { + return item, 0, fmt.Errorf("reading VariationSelector: "+"EOF: expected length: %d, got %d", offsetDefaultUVS, L) + } + + var err error + item.DefaultUVS, _, err = ParseDefaultUVSTable(parentSrc[offsetDefaultUVS:]) + if err != nil { + return item, 0, fmt.Errorf("reading VariationSelector: %s", err) + } + + } + } + { + + if offsetNonDefaultUVS != 0 { // ignore null offset + if L := len(parentSrc); L < offsetNonDefaultUVS { + return item, 0, fmt.Errorf("reading VariationSelector: "+"EOF: expected length: %d, got %d", offsetNonDefaultUVS, L) + } + + var err error + item.NonDefaultUVS, _, err = ParseUVSMappingTable(parentSrc[offsetNonDefaultUVS:]) + if err != nil { + return item, 0, fmt.Errorf("reading VariationSelector: %s", err) + } + + } + } + return item, n, nil +} + +func (item *SequentialMapGroup) mustParse(src []byte) { + _ = src[11] // early bound checking + item.StartCharCode = binary.BigEndian.Uint32(src[0:]) + item.EndCharCode = binary.BigEndian.Uint32(src[4:]) + item.StartGlyphID = binary.BigEndian.Uint32(src[8:]) +} + +func (item *UnicodeRange) mustParse(src []byte) { + _ = src[3] // early bound checking + item.StartUnicodeValue[0] = src[0] + item.StartUnicodeValue[1] = src[1] + item.StartUnicodeValue[2] = src[2] + item.AdditionalCount = src[3] +} + +func (item *UvsMappingRecord) mustParse(src []byte) { + _ = src[4] // early bound checking + item.UnicodeValue[0] = src[0] + item.UnicodeValue[1] = src[1] + item.UnicodeValue[2] = src[2] + item.GlyphID = binary.BigEndian.Uint16(src[3:]) +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/cmap_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/cmap_src.go new file mode 100644 index 0000000..6c6855e --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/cmap_src.go @@ -0,0 +1,132 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +// Cmap is the Character to Glyph Index Mapping table +// See https://learn.microsoft.com/en-us/typography/opentype/spec/cmap +type Cmap struct { + version uint16 // Table version number (0). + numTables uint16 // Number of encoding tables that follow. + Records []EncodingRecord `arrayCount:"ComputedField-numTables"` +} + +type EncodingRecord struct { + PlatformID PlatformID // Platform ID. + EncodingID EncodingID // Platform-specific encoding ID. + Subtable CmapSubtable `offsetSize:"Offset32" offsetRelativeTo:"Parent"` // Byte offset from beginning of table to the subtable for this encoding. +} + +// CmapSubtable is the union type for the various cmap formats +type CmapSubtable interface { + isCmapSubtable() +} + +func (CmapSubtable0) isCmapSubtable() {} +func (CmapSubtable2) isCmapSubtable() {} +func (CmapSubtable4) isCmapSubtable() {} +func (CmapSubtable6) isCmapSubtable() {} +func (CmapSubtable10) isCmapSubtable() {} +func (CmapSubtable12) isCmapSubtable() {} +func (CmapSubtable13) isCmapSubtable() {} +func (CmapSubtable14) isCmapSubtable() {} + +type CmapSubtable0 struct { + format uint16 `unionTag:"0"` // Format number is set to 0. + length uint16 // This is the length in bytes of the subtable. + language uint16 + GlyphIdArray [256]uint8 // An array that maps character codes to glyph index values. +} + +type CmapSubtable2 struct { + format uint16 `unionTag:"2"` // Format number is set to 2. + rawData []byte `arrayCount:"ToEnd"` +} + +type CmapSubtable4 struct { + format uint16 `unionTag:"4"` // Format number is set to 4. + length uint16 // This is the length in bytes of the subtable. + language uint16 + segCountX2 uint16 // 2 × segCount. + searchRange uint16 // Maximum power of 2 less than or equal to segCount, times 2 ((2**floor(log2(segCount))) * 2, where “**” is an exponentiation operator) + entrySelector uint16 // Log2 of the maximum power of 2 less than or equal to numTables (log2(searchRange/2), which is equal to floor(log2(segCount))) + rangeShift uint16 // segCount times 2, minus searchRange ((segCount * 2) - searchRange) + EndCode []uint16 `arrayCount:"ComputedField-segCountX2 / 2"` // [segCount]uint16 End characterCode for each segment, last=0xFFFF. + reservedPad uint16 // Set to 0. + StartCode []uint16 `arrayCount:"ComputedField-segCountX2 / 2"` // [segCount]uint16 Start character code for each segment. + IdDelta []uint16 `arrayCount:"ComputedField-segCountX2 / 2"` // [segCount]int16 Delta for all character codes in segment. + IdRangeOffsets []uint16 `arrayCount:"ComputedField-segCountX2 / 2"` // [segCount]uint16 Offsets into glyphIdArray or 0 + GlyphIDArray []byte `arrayCount:"ToEnd"` // glyphIdArray : uint16[] glyph index array (arbitrary length) +} + +type CmapSubtable6 struct { + format uint16 `unionTag:"6"` // Format number is set to 6. + length uint16 // This is the length in bytes of the subtable. + language uint16 + FirstCode uint16 // First character code of subrange. + GlyphIdArray []GlyphID `arrayCount:"FirstUint16"` // Array of glyph index values for character codes in the range. +} + +type CmapSubtable10 struct { + format uint16 `unionTag:"10"` // Subtable format; set to 10. + reserved uint16 // Reserved; set to 0 + length uint32 // Byte length of this subtable (including the header) + language uint32 + StartCharCode uint32 // First character code covered + GlyphIdArray []GlyphID `arrayCount:"FirstUint32"` // Array of glyph indices for the character codes covered +} + +type CmapSubtable12 struct { + format uint16 `unionTag:"12"` // Subtable format; set to 12. + reserved uint16 // Reserved; set to 0 + length uint32 // Byte length of this subtable (including the header) + language uint32 // For requirements on use of the language field, see “Use of the language field in 'cmap' subtables” in this document. + Groups []SequentialMapGroup `arrayCount:"FirstUint32"` // Array of SequentialMapGroup records. +} + +type SequentialMapGroup struct { + StartCharCode uint32 // First character code in this group + EndCharCode uint32 // Last character code in this group + StartGlyphID uint32 // Glyph index corresponding to the starting character code +} + +type CmapSubtable13 struct { + format uint16 `unionTag:"13"` // Subtable format; set to 13. + reserved uint16 // Reserved; set to 0 + length uint32 // Byte length of this subtable (including the header) + language uint32 // For requirements on use of the language field, see “Use of the language field in 'cmap' subtables” in this document. + Groups []SequentialMapGroup `arrayCount:"FirstUint32"` // Array of SequentialMapGroup records. +} + +type CmapSubtable14 struct { + format uint16 `unionTag:"14"` // Subtable format. Set to 14. + length uint32 // Byte length of this subtable (including this header) + VarSelectors []VariationSelector `arrayCount:"FirstUint32"` // [numVarSelectorRecords] Array of VariationSelector records. +} + +type VariationSelector struct { + VarSelector [3]byte // uint24 Variation selector + DefaultUVS DefaultUVSTable `offsetSize:"Offset32" offsetRelativeTo:"Parent"` // Offset from the start of the format 14 subtable to Default UVS Table. May be 0. + NonDefaultUVS UVSMappingTable `offsetSize:"Offset32" offsetRelativeTo:"Parent"` // Offset from the start of the format 14 subtable to Non-Default UVS Table. May be 0. +} + +// DefaultUVSTable is used in Cmap format 14 +// See https://learn.microsoft.com/en-us/typography/opentype/spec/cmap#default-uvs-table +type DefaultUVSTable struct { + Ranges []UnicodeRange `arrayCount:"FirstUint32"` +} + +type UnicodeRange struct { + StartUnicodeValue [3]byte // uint24 First value in this range + AdditionalCount uint8 // Number of additional values in this range +} + +// UVSMappingTable is used in Cmap format 14 +// See https://learn.microsoft.com/en-us/typography/opentype/spec/cmap#non-default-uvs-table +type UVSMappingTable struct { + Ranges []UvsMappingRecord `arrayCount:"FirstUint32"` +} + +type UvsMappingRecord struct { + UnicodeValue [3]byte // uint24 Base Unicode value of the UVS + GlyphID GlyphID // Glyph ID of the UVS +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs.go new file mode 100644 index 0000000..9e4366e --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs.go @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +type BitmapSubtable struct { + FirstGlyph GlyphID // First glyph ID of this range. + LastGlyph GlyphID // Last glyph ID of this range (inclusive). + IndexSubHeader +} + +// EBLC is the Embedded Bitmap Location Table +// See - https://learn.microsoft.com/fr-fr/typography/opentype/spec/eblc +type EBLC = CBLC + +// Bloc is the bitmap location table +// See - https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6bloc.html +type Bloc = CBLC diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_bitmap_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_bitmap_gen.go new file mode 100644 index 0000000..3d2fe1a --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_bitmap_gen.go @@ -0,0 +1,363 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from glyphs_bitmap_src.go. DO NOT EDIT + +func (item *BigGlyphMetrics) mustParse(src []byte) { + _ = src[7] // early bound checking + item.SmallGlyphMetrics.mustParse(src[0:]) + item.vertBearingX = int8(src[5]) + item.vertBearingY = int8(src[6]) + item.vertAdvance = src[7] +} + +func (item *BitmapSize) mustParse(src []byte) { + _ = src[47] // early bound checking + item.indexSubTableArrayOffset = Offset32(binary.BigEndian.Uint32(src[0:])) + item.indexTablesSize = binary.BigEndian.Uint32(src[4:]) + item.numberOfIndexSubTables = binary.BigEndian.Uint32(src[8:]) + item.colorRef = binary.BigEndian.Uint32(src[12:]) + item.Hori.mustParse(src[16:]) + item.Vert.mustParse(src[28:]) + item.startGlyphIndex = binary.BigEndian.Uint16(src[40:]) + item.endGlyphIndex = binary.BigEndian.Uint16(src[42:]) + item.PpemX = src[44] + item.PpemY = src[45] + item.bitDepth = src[46] + item.flags = int8(src[47]) +} + +func (item *GlyphIdOffsetPair) mustParse(src []byte) { + _ = src[3] // early bound checking + item.GlyphID = binary.BigEndian.Uint16(src[0:]) + item.SbitOffset = Offset16(binary.BigEndian.Uint16(src[2:])) +} + +func (item *IndexData2) mustParse(src []byte) { + _ = src[11] // early bound checking + item.ImageSize = binary.BigEndian.Uint32(src[0:]) + item.BigMetrics.mustParse(src[4:]) +} + +func (item *IndexSubTableHeader) mustParse(src []byte) { + _ = src[7] // early bound checking + item.FirstGlyph = binary.BigEndian.Uint16(src[0:]) + item.LastGlyph = binary.BigEndian.Uint16(src[2:]) + item.additionalOffsetToIndexSubtable = Offset32(binary.BigEndian.Uint32(src[4:])) +} + +func ParseBitmapData17(src []byte) (BitmapData17, int, error) { + var item BitmapData17 + n := 0 + if L := len(src); L < 9 { + return item, 0, fmt.Errorf("reading BitmapData17: "+"EOF: expected length: 9, got %d", L) + } + _ = src[8] // early bound checking + item.SmallGlyphMetrics.mustParse(src[0:]) + arrayLengthImage := int(binary.BigEndian.Uint32(src[5:])) + n += 9 + + { + + L := int(9 + arrayLengthImage) + if len(src) < L { + return item, 0, fmt.Errorf("reading BitmapData17: "+"EOF: expected length: %d, got %d", L, len(src)) + } + item.Image = src[9:L] + n = L + } + return item, n, nil +} + +func ParseBitmapData18(src []byte) (BitmapData18, int, error) { + var item BitmapData18 + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading BitmapData18: "+"EOF: expected length: 12, got %d", L) + } + _ = src[11] // early bound checking + item.BigGlyphMetrics.mustParse(src[0:]) + arrayLengthImage := int(binary.BigEndian.Uint32(src[8:])) + n += 12 + + { + + L := int(12 + arrayLengthImage) + if len(src) < L { + return item, 0, fmt.Errorf("reading BitmapData18: "+"EOF: expected length: %d, got %d", L, len(src)) + } + item.Image = src[12:L] + n = L + } + return item, n, nil +} + +func ParseBitmapData19(src []byte) (BitmapData19, int, error) { + var item BitmapData19 + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading BitmapData19: "+"EOF: expected length: 4, got %d", L) + } + arrayLengthImage := int(binary.BigEndian.Uint32(src[0:])) + n += 4 + + { + + L := int(4 + arrayLengthImage) + if len(src) < L { + return item, 0, fmt.Errorf("reading BitmapData19: "+"EOF: expected length: %d, got %d", L, len(src)) + } + item.Image = src[4:L] + n = L + } + return item, n, nil +} + +func ParseBitmapData2(src []byte) (BitmapData2, int, error) { + var item BitmapData2 + n := 0 + if L := len(src); L < 5 { + return item, 0, fmt.Errorf("reading BitmapData2: "+"EOF: expected length: 5, got %d", L) + } + item.SmallGlyphMetrics.mustParse(src[0:]) + n += 5 + + { + + item.Image = src[5:] + n = len(src) + } + return item, n, nil +} + +func ParseBitmapData5(src []byte) (BitmapData5, int, error) { + var item BitmapData5 + n := 0 + { + + item.Image = src[0:] + n = len(src) + } + return item, n, nil +} + +func ParseCBLC(src []byte) (CBLC, int, error) { + var item CBLC + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading CBLC: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.majorVersion = binary.BigEndian.Uint16(src[0:]) + item.minorVersion = binary.BigEndian.Uint16(src[2:]) + arrayLengthBitmapSizes := int(binary.BigEndian.Uint32(src[4:])) + n += 8 + + { + + if L := len(src); L < 8+arrayLengthBitmapSizes*48 { + return item, 0, fmt.Errorf("reading CBLC: "+"EOF: expected length: %d, got %d", 8+arrayLengthBitmapSizes*48, L) + } + + item.BitmapSizes = make([]BitmapSize, arrayLengthBitmapSizes) // allocation guarded by the previous check + for i := range item.BitmapSizes { + item.BitmapSizes[i].mustParse(src[8+i*48:]) + } + n += arrayLengthBitmapSizes * 48 + } + { + + err := item.parseIndexSubTables(src[:]) + if err != nil { + return item, 0, fmt.Errorf("reading CBLC: %s", err) + } + } + return item, n, nil +} + +func ParseIndexData1(src []byte, sbitOffsetsCount int) (IndexData1, int, error) { + var item IndexData1 + n := 0 + { + + if L := len(src); L < sbitOffsetsCount*4 { + return item, 0, fmt.Errorf("reading IndexData1: "+"EOF: expected length: %d, got %d", sbitOffsetsCount*4, L) + } + + item.SbitOffsets = make([]Offset32, sbitOffsetsCount) // allocation guarded by the previous check + for i := range item.SbitOffsets { + item.SbitOffsets[i] = Offset32(binary.BigEndian.Uint32(src[i*4:])) + } + n += sbitOffsetsCount * 4 + } + return item, n, nil +} + +func ParseIndexData2(src []byte) (IndexData2, int, error) { + var item IndexData2 + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading IndexData2: "+"EOF: expected length: 12, got %d", L) + } + item.mustParse(src) + n += 12 + return item, n, nil +} + +func ParseIndexData3(src []byte, sbitOffsetsCount int) (IndexData3, int, error) { + var item IndexData3 + n := 0 + { + + if L := len(src); L < sbitOffsetsCount*2 { + return item, 0, fmt.Errorf("reading IndexData3: "+"EOF: expected length: %d, got %d", sbitOffsetsCount*2, L) + } + + item.SbitOffsets = make([]Offset16, sbitOffsetsCount) // allocation guarded by the previous check + for i := range item.SbitOffsets { + item.SbitOffsets[i] = Offset16(binary.BigEndian.Uint16(src[i*2:])) + } + n += sbitOffsetsCount * 2 + } + return item, n, nil +} + +func ParseIndexData4(src []byte) (IndexData4, int, error) { + var item IndexData4 + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading IndexData4: "+"EOF: expected length: 4, got %d", L) + } + item.numGlyphs = binary.BigEndian.Uint32(src[0:]) + n += 4 + + { + arrayLength := int(item.numGlyphs + 1) + + if L := len(src); L < 4+arrayLength*4 { + return item, 0, fmt.Errorf("reading IndexData4: "+"EOF: expected length: %d, got %d", 4+arrayLength*4, L) + } + + item.GlyphArray = make([]GlyphIdOffsetPair, arrayLength) // allocation guarded by the previous check + for i := range item.GlyphArray { + item.GlyphArray[i].mustParse(src[4+i*4:]) + } + n += arrayLength * 4 + } + return item, n, nil +} + +func ParseIndexData5(src []byte) (IndexData5, int, error) { + var item IndexData5 + n := 0 + if L := len(src); L < 16 { + return item, 0, fmt.Errorf("reading IndexData5: "+"EOF: expected length: 16, got %d", L) + } + _ = src[15] // early bound checking + item.ImageSize = binary.BigEndian.Uint32(src[0:]) + item.BigMetrics.mustParse(src[4:]) + arrayLengthGlyphIdArray := int(binary.BigEndian.Uint32(src[12:])) + n += 16 + + { + + if L := len(src); L < 16+arrayLengthGlyphIdArray*2 { + return item, 0, fmt.Errorf("reading IndexData5: "+"EOF: expected length: %d, got %d", 16+arrayLengthGlyphIdArray*2, L) + } + + item.GlyphIdArray = make([]uint16, arrayLengthGlyphIdArray) // allocation guarded by the previous check + for i := range item.GlyphIdArray { + item.GlyphIdArray[i] = binary.BigEndian.Uint16(src[16+i*2:]) + } + n += arrayLengthGlyphIdArray * 2 + } + return item, n, nil +} + +func ParseIndexSubHeader(src []byte, sbitOffsetsCount int) (IndexSubHeader, int, error) { + var item IndexSubHeader + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading IndexSubHeader: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.indexFormat = indexVersion(binary.BigEndian.Uint16(src[0:])) + item.ImageFormat = binary.BigEndian.Uint16(src[2:]) + item.ImageDataOffset = Offset32(binary.BigEndian.Uint32(src[4:])) + n += 8 + + { + var ( + read int + err error + ) + switch item.indexFormat { + case indexVersion1: + item.IndexData, read, err = ParseIndexData1(src[8:], sbitOffsetsCount) + case indexVersion2: + item.IndexData, read, err = ParseIndexData2(src[8:]) + case indexVersion3: + item.IndexData, read, err = ParseIndexData3(src[8:], sbitOffsetsCount) + case indexVersion4: + item.IndexData, read, err = ParseIndexData4(src[8:]) + case indexVersion5: + item.IndexData, read, err = ParseIndexData5(src[8:]) + default: + err = fmt.Errorf("unsupported IndexDataVersion %d", item.indexFormat) + } + if err != nil { + return item, 0, fmt.Errorf("reading IndexSubHeader: %s", err) + } + n += read + } + return item, n, nil +} + +func ParseIndexSubTableArray(src []byte, subtablesCount int) (IndexSubTableArray, int, error) { + var item IndexSubTableArray + n := 0 + { + + if L := len(src); L < subtablesCount*8 { + return item, 0, fmt.Errorf("reading IndexSubTableArray: "+"EOF: expected length: %d, got %d", subtablesCount*8, L) + } + + item.Subtables = make([]IndexSubTableHeader, subtablesCount) // allocation guarded by the previous check + for i := range item.Subtables { + item.Subtables[i].mustParse(src[i*8:]) + } + n += subtablesCount * 8 + } + return item, n, nil +} + +func (item *SbitLineMetrics) mustParse(src []byte) { + _ = src[11] // early bound checking + item.Ascender = int8(src[0]) + item.Descender = int8(src[1]) + item.widthMax = src[2] + item.caretSlopeNumerator = int8(src[3]) + item.caretSlopeDenominator = int8(src[4]) + item.caretOffset = int8(src[5]) + item.minOriginSB = int8(src[6]) + item.minAdvanceSB = int8(src[7]) + item.MaxBeforeBL = int8(src[8]) + item.MinAfterBL = int8(src[9]) + item.pad1 = int8(src[10]) + item.pad2 = int8(src[11]) +} + +func (item *SmallGlyphMetrics) mustParse(src []byte) { + _ = src[4] // early bound checking + item.Height = src[0] + item.Width = src[1] + item.BearingX = int8(src[2]) + item.BearingY = int8(src[3]) + item.Advance = src[4] +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_bitmap_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_bitmap_src.go new file mode 100644 index 0000000..b2b548f --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_bitmap_src.go @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import "fmt" + +// CBLC is the Color Bitmap Location Table +// See - https://learn.microsoft.com/fr-fr/typography/opentype/spec/cblc +type CBLC struct { + majorVersion uint16 // Major version of the CBLC table, = 3. + minorVersion uint16 // Minor version of the CBLC table, = 0. + BitmapSizes []BitmapSize `arrayCount:"FirstUint32"` // BitmapSize records array. + IndexSubTables [][]BitmapSubtable `isOpaque:""` // with same length as [BitmapSizes] +} + +func (cb *CBLC) parseIndexSubTables(src []byte) error { + cb.IndexSubTables = make([][]BitmapSubtable, len(cb.BitmapSizes)) + for i, size := range cb.BitmapSizes { + start := int(size.indexSubTableArrayOffset) + if L := len(src); L < start { + return fmt.Errorf("EOF: expected length: %d, got %d", start, L) + } + subtables, _, err := ParseIndexSubTableArray(src[start:], int(size.numberOfIndexSubTables)) + if err != nil { + return err + } + sizeSubtables := make([]BitmapSubtable, len(subtables.Subtables)) + for j, subtable := range subtables.Subtables { + numGlyphs := int(subtable.LastGlyph) - int(subtable.FirstGlyph) + 1 + subtableStart := start + int(subtable.additionalOffsetToIndexSubtable) + + sizeSubtables[j].FirstGlyph = subtable.FirstGlyph + sizeSubtables[j].LastGlyph = subtable.LastGlyph + sizeSubtables[j].IndexSubHeader, _, err = ParseIndexSubHeader(src[subtableStart:], numGlyphs+1) + if err != nil { + return err + } + } + cb.IndexSubTables[i] = sizeSubtables + } + return nil +} + +type BitmapSize struct { + indexSubTableArrayOffset Offset32 // Offset to index subtable from beginning of CBLC. + indexTablesSize uint32 // Number of bytes in corresponding index subtables and array. + numberOfIndexSubTables uint32 // There is an index subtable for each range or format change. + colorRef uint32 // Not used; set to 0. + Hori SbitLineMetrics // Line metrics for text rendered horizontally. + Vert SbitLineMetrics // Line metrics for text rendered vertically. + startGlyphIndex uint16 // Lowest glyph index for this size. + endGlyphIndex uint16 // Highest glyph index for this size. + PpemX uint8 // Horizontal pixels per em. + PpemY uint8 // Vertical pixels per em. + bitDepth uint8 // In addtition to already defined bitDepth values 1, 2, 4, and 8 supported by existing implementations, the value of 32 is used to identify color bitmaps with 8 bit per pixel RGBA channels. + flags int8 // Vertical or horizontal (see the Bitmap Flags section of the EBLC table chapter). +} + +type SbitLineMetrics struct { + Ascender int8 + Descender int8 + widthMax uint8 + caretSlopeNumerator int8 + caretSlopeDenominator int8 + caretOffset int8 + minOriginSB int8 + minAdvanceSB int8 + MaxBeforeBL int8 + MinAfterBL int8 + pad1 int8 + pad2 int8 +} + +type IndexSubTableArray struct { + Subtables []IndexSubTableHeader +} + +type IndexSubTableHeader struct { + FirstGlyph GlyphID // First glyph ID of this range. + LastGlyph GlyphID // Last glyph ID of this range (inclusive). + additionalOffsetToIndexSubtable Offset32 // Add to indexSubTableArrayOffset to get offset from beginning of EBLC. +} + +type IndexSubHeader struct { + indexFormat indexVersion // Format of this IndexSubTable. + ImageFormat uint16 // Format of EBDT image data. + ImageDataOffset Offset32 // Offset to image data in EBDT table. + IndexData IndexData `unionField:"indexFormat"` +} + +type indexVersion uint16 + +const ( + indexVersion1 indexVersion = iota + 1 + indexVersion2 + indexVersion3 + indexVersion4 + indexVersion5 +) + +type IndexData interface { + isIndexData() +} + +func (IndexData1) isIndexData() {} +func (IndexData2) isIndexData() {} +func (IndexData3) isIndexData() {} +func (IndexData4) isIndexData() {} +func (IndexData5) isIndexData() {} + +type IndexData1 struct { + // sizeOfArray = (lastGlyph - firstGlyph + 1) + 1 + 1 pad if needed + // sbitOffsets[glyphIndex] + imageDataOffset = glyphData + SbitOffsets []Offset32 +} + +type IndexData2 struct { + ImageSize uint32 // All the glyphs are of the same size. + BigMetrics BigGlyphMetrics // All glyphs have the same metrics; glyph data may be compressed, byte-aligned, or bit-aligned. +} + +type IndexData3 struct { + // sizeOfArray = (lastGlyph - firstGlyph + 1) + 1 + 1 pad if needed + // sbitOffets[glyphIndex] + imageDataOffset = glyphData + SbitOffsets []Offset16 +} + +type IndexData4 struct { + numGlyphs uint32 // Array length. + GlyphArray []GlyphIdOffsetPair `arrayCount:"ComputedField-numGlyphs+1"` //[numGlyphs + 1] One per glyph. +} + +type GlyphIdOffsetPair struct { + GlyphID GlyphID // Glyph ID of glyph present. + SbitOffset Offset16 // Location in EBDT. +} + +type IndexData5 struct { + ImageSize uint32 // All glyphs have the same data size. + BigMetrics BigGlyphMetrics // All glyphs have the same metrics. + GlyphIdArray []GlyphID `arrayCount:"FirstUint32"` // [numGlyphs] One per glyph, sorted by glyph ID. +} + +// ------------------------- actual data : shared by EBDT / CBDT / BDAT ------------------------- +// for now, we simplify the implementation to two cases: +// - data, metrics (small) +// - data only + +type SmallGlyphMetrics struct { + Height uint8 // Number of rows of data. + Width uint8 // Number of columns of data. + BearingX int8 // Distance in pixels from the horizontal origin to the left edge of the bitmap. + BearingY int8 // Distance in pixels from the horizontal origin to the top edge of the bitmap. + Advance uint8 // Horizontal advance width in pixels. +} + +type BigGlyphMetrics struct { + SmallGlyphMetrics + vertBearingX int8 // Distance in pixels from the vertical origin to the left edge of the bitmap. + vertBearingY int8 // Distance in pixels from the vertical origin to the top edge of the bitmap. + vertAdvance uint8 // Vertical advance width in pixels. +} + +// Format 2: small metrics, bit-aligned data +type BitmapData2 struct { + SmallGlyphMetrics + Image []byte `arrayCount:"ToEnd"` +} + +// Format 5: metrics in CBLC table, bit-aligned image data only +type BitmapData5 struct { + Image []byte `arrayCount:"ToEnd"` +} + +// Format 17: small metrics, PNG image data +type BitmapData17 struct { + SmallGlyphMetrics + Image []byte `arrayCount:"FirstUint32"` +} + +// Format 18: big metrics, PNG image data +type BitmapData18 struct { + BigGlyphMetrics + Image []byte `arrayCount:"FirstUint32"` +} + +// Format 19: metrics in CBLC table, PNG image data +type BitmapData19 struct { + Image []byte `arrayCount:"FirstUint32"` +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_glyf_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_glyf_gen.go new file mode 100644 index 0000000..5ff7790 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_glyf_gen.go @@ -0,0 +1,135 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from glyphs_glyf_src.go. DO NOT EDIT + +func (item *CompositeGlyphPart) mustParse(src []byte) { + _ = src[23] // early bound checking + item.Flags = binary.BigEndian.Uint16(src[0:]) + item.GlyphIndex = binary.BigEndian.Uint16(src[2:]) + item.arg1 = binary.BigEndian.Uint16(src[4:]) + item.arg2 = binary.BigEndian.Uint16(src[6:]) + item.Scale[0] = float32(binary.BigEndian.Uint32(src[8:])) + item.Scale[1] = float32(binary.BigEndian.Uint32(src[12:])) + item.Scale[2] = float32(binary.BigEndian.Uint32(src[16:])) + item.Scale[3] = float32(binary.BigEndian.Uint32(src[20:])) +} + +func (item *GlyphContourPoint) mustParse(src []byte) { + _ = src[4] // early bound checking + item.Flag = src[0] + item.X = int16(binary.BigEndian.Uint16(src[1:])) + item.Y = int16(binary.BigEndian.Uint16(src[3:])) +} + +func ParseCompositeGlyph(src []byte) (CompositeGlyph, int, error) { + var item CompositeGlyph + n := 0 + { + + err := item.parseGlyphs(src[:]) + if err != nil { + return item, 0, fmt.Errorf("reading CompositeGlyph: %s", err) + } + } + { + + err := item.parseInstructions(src[:]) + if err != nil { + return item, 0, fmt.Errorf("reading CompositeGlyph: %s", err) + } + } + return item, n, nil +} + +func ParseCompositeGlyphPart(src []byte) (CompositeGlyphPart, int, error) { + var item CompositeGlyphPart + n := 0 + if L := len(src); L < 24 { + return item, 0, fmt.Errorf("reading CompositeGlyphPart: "+"EOF: expected length: 24, got %d", L) + } + item.mustParse(src) + n += 24 + return item, n, nil +} + +func ParseGlyph(src []byte) (Glyph, int, error) { + var item Glyph + n := 0 + if L := len(src); L < 10 { + return item, 0, fmt.Errorf("reading Glyph: "+"EOF: expected length: 10, got %d", L) + } + _ = src[9] // early bound checking + item.numberOfContours = int16(binary.BigEndian.Uint16(src[0:])) + item.XMin = int16(binary.BigEndian.Uint16(src[2:])) + item.YMin = int16(binary.BigEndian.Uint16(src[4:])) + item.XMax = int16(binary.BigEndian.Uint16(src[6:])) + item.YMax = int16(binary.BigEndian.Uint16(src[8:])) + n += 10 + + { + + err := item.parseData(src[10:]) + if err != nil { + return item, 0, fmt.Errorf("reading Glyph: %s", err) + } + } + return item, n, nil +} + +func ParseGlyphContourPoint(src []byte) (GlyphContourPoint, int, error) { + var item GlyphContourPoint + n := 0 + if L := len(src); L < 5 { + return item, 0, fmt.Errorf("reading GlyphContourPoint: "+"EOF: expected length: 5, got %d", L) + } + item.mustParse(src) + n += 5 + return item, n, nil +} + +func ParseSimpleGlyph(src []byte, endPtsOfContoursCount int) (SimpleGlyph, int, error) { + var item SimpleGlyph + n := 0 + { + + if L := len(src); L < endPtsOfContoursCount*2 { + return item, 0, fmt.Errorf("reading SimpleGlyph: "+"EOF: expected length: %d, got %d", endPtsOfContoursCount*2, L) + } + + item.EndPtsOfContours = make([]uint16, endPtsOfContoursCount) // allocation guarded by the previous check + for i := range item.EndPtsOfContours { + item.EndPtsOfContours[i] = binary.BigEndian.Uint16(src[i*2:]) + } + n += endPtsOfContoursCount * 2 + } + if L := len(src); L < n+2 { + return item, 0, fmt.Errorf("reading SimpleGlyph: "+"EOF: expected length: n + 2, got %d", L) + } + arrayLengthInstructions := int(binary.BigEndian.Uint16(src[n:])) + n += 2 + + { + + L := int(n + arrayLengthInstructions) + if len(src) < L { + return item, 0, fmt.Errorf("reading SimpleGlyph: "+"EOF: expected length: %d, got %d", L, len(src)) + } + item.Instructions = src[n:L] + n = L + } + { + + err := item.parsePoints(src[n:], endPtsOfContoursCount) + if err != nil { + return item, 0, fmt.Errorf("reading SimpleGlyph: %s", err) + } + } + return item, n, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_glyf_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_glyf_src.go new file mode 100644 index 0000000..1deb55e --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_glyf_src.go @@ -0,0 +1,350 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "errors" + "fmt" +) + +// shared with gvar, sbix, eblc +// return an error only if data is not long enough +func ParseLoca(src []byte, numGlyphs int, isLong bool) (out []uint32, err error) { + var size int + if isLong { + size = (numGlyphs + 1) * 4 + } else { + size = (numGlyphs + 1) * 2 + } + if L := len(src); L < size { + return nil, fmt.Errorf("reading Loca: EOF: expected length: %d, got %d", size, L) + } + out = make([]uint32, numGlyphs+1) + if isLong { + for i := range out { + out[i] = binary.BigEndian.Uint32(src[4*i:]) + } + } else { + for i := range out { + out[i] = 2 * uint32(binary.BigEndian.Uint16(src[2*i:])) // The actual local offset divided by 2 is stored. + } + } + return out, nil +} + +// Glyph Data +type Glyf []Glyph + +// ParseGlyf parses the 'glyf' table. +// locaOffsets has length numGlyphs + 1, and is returned by ParseLoca +func ParseGlyf(src []byte, locaOffsets []uint32) (Glyf, error) { + out := make(Glyf, len(locaOffsets)-1) + var err error + for i := range out { + start, end := locaOffsets[i], locaOffsets[i+1] + // If a glyph has no outline, then loca[n] = loca [n+1]. + if start == end { + continue + } + out[i], _, err = ParseGlyph(src[start:end]) + if err != nil { + return nil, err + } + } + return out, nil +} + +type Glyph struct { + numberOfContours int16 // If the number of contours is greater than or equal to zero, this is a simple glyph. If negative, this is a composite glyph — the value -1 should be used for composite glyphs. + XMin int16 // Minimum x for coordinate data. + YMin int16 // Minimum y for coordinate data. + XMax int16 // Maximum x for coordinate data. + YMax int16 // Maximum y for coordinate data. + Data GlyphData `isOpaque:"" subsliceStart:"AtCurrent"` +} + +func (gl *Glyph) parseData(src []byte) (err error) { + if gl.numberOfContours >= 0 { // simple glyph + gl.Data, _, err = ParseSimpleGlyph(src, int(gl.numberOfContours)) + } else { // composite glyph + gl.Data, _, err = ParseCompositeGlyph(src) + } + return err +} + +type GlyphData interface { + isGlyphData() +} + +func (SimpleGlyph) isGlyphData() {} +func (CompositeGlyph) isGlyphData() {} + +type SimpleGlyph struct { + EndPtsOfContours []uint16 // [numberOfContours] Array of point indices for the last point of each contour, in increasing numeric order. + Instructions []byte `arrayCount:"FirstUint16"` // [instructionLength] Array of instruction byte code for the glyph. + Points []GlyphContourPoint `isOpaque:"" subsliceStart:"AtCurrent"` +} + +type GlyphContourPoint struct { + Flag uint8 + X, Y int16 +} + +const ( + xShortVector = 0x02 + xIsSameOrPositiveXShortVector = 0x10 + yShortVector = 0x04 + yIsSameOrPositiveYShortVector = 0x20 +) + +func (sg *SimpleGlyph) parsePoints(src []byte, _ int) error { + if len(sg.EndPtsOfContours) == 0 { + return nil + } + + numPoints := int(sg.EndPtsOfContours[len(sg.EndPtsOfContours)-1]) + 1 + + const repeatFlag = 0x08 + + sg.Points = make([]GlyphContourPoint, numPoints) + + // read flags + // to avoid costly length check, we also precompute the expected data size for coordinates + var ( + coordinatesLengthX, coordinatesLengthY int + cursor int + L = len(src) + ) + for i := 0; i < numPoints; i++ { + if L <= cursor { + return errors.New("invalid simple glyph data flags (EOF)") + } + flag := src[cursor] + sg.Points[i].Flag = flag + cursor++ + + localLengthX, localLengthY := 0, 0 + if flag&xShortVector != 0 { + localLengthX = 1 + } else if flag&xIsSameOrPositiveXShortVector == 0 { + localLengthX = 2 + } + if flag&yShortVector != 0 { + localLengthY = 1 + } else if flag&yIsSameOrPositiveYShortVector == 0 { + localLengthY = 2 + } + + if flag&repeatFlag != 0 { + if L <= cursor { + return errors.New("invalid simple glyph data flags (EOF)") + } + repeatCount := int(src[cursor]) + cursor++ + if i+repeatCount+1 > numPoints { // gracefully handle out of bounds + repeatCount = numPoints - i - 1 + } + subSlice := sg.Points[i+1 : i+repeatCount+1] + for j := range subSlice { + subSlice[j].Flag = flag + } + i += repeatCount + localLengthX += repeatCount * localLengthX + localLengthY += repeatCount * localLengthY + } + + coordinatesLengthX += localLengthX + coordinatesLengthY += localLengthY + } + + src = src[cursor:] + if L, E := len(src), coordinatesLengthX+coordinatesLengthY; L < E { + return fmt.Errorf("EOF: expected length: %d, got %d", E, L) + } + + dataX, dataY := src[:coordinatesLengthX], src[coordinatesLengthX:coordinatesLengthX+coordinatesLengthY] + // read x and y coordinates + parseGlyphContourPoints(dataX, dataY, sg.Points) + + return nil +} + +// returns the position after the read and the relative coordinate +// the input slice has already been checked for length +func readContourPoint(flag byte, data []byte, pos int, shortFlag, sameFlag uint8) (int, int16) { + var v int16 + if flag&shortFlag != 0 { + val := data[pos] + pos++ + if flag&sameFlag != 0 { + v += int16(val) + } else { + v -= int16(val) + } + } else if flag&sameFlag == 0 { + val := binary.BigEndian.Uint16(data[pos:]) + pos += 2 + v += int16(val) + } + return pos, v +} + +// update the points in place +func parseGlyphContourPoints(dataX, dataY []byte, points []GlyphContourPoint) { + var ( + posX, posY int // position into data + vX, offsetX, vY, offsetY int16 // coordinates are relative to the previous + ) + for i, p := range points { + posX, offsetX = readContourPoint(p.Flag, dataX, posX, xShortVector, xIsSameOrPositiveXShortVector) + vX += offsetX + points[i].X = vX + + posY, offsetY = readContourPoint(p.Flag, dataY, posY, yShortVector, yIsSameOrPositiveYShortVector) + vY += offsetY + points[i].Y = vY + } +} + +type CompositeGlyph struct { + Glyphs []CompositeGlyphPart `isOpaque:""` + Instructions []byte `isOpaque:""` +} + +const arg1And2AreWords = 1 + +func (cg *CompositeGlyph) parseGlyphs(src []byte) error { + const ( + _ = 1 << iota + _ + _ + weHaveAScale + _ + moreComponents + weHaveAnXAndYScale + weHaveATwoByTwo + weHaveInstructions + ) + var flags uint16 + for do := true; do; do = flags&moreComponents != 0 { + var part CompositeGlyphPart + + if L := len(src); L < 4 { + return fmt.Errorf("EOF: expected length: %d, got %d", 4, L) + } + flags = binary.BigEndian.Uint16(src) + part.Flags = flags + part.GlyphIndex = GlyphID(binary.BigEndian.Uint16(src[2:])) + + if flags&arg1And2AreWords != 0 { // 16 bits + if L, E := len(src), 4+4; L < E { + return fmt.Errorf("EOF: expected length: %d, got %d", E, L) + } + part.arg1 = binary.BigEndian.Uint16(src[4:]) + part.arg2 = binary.BigEndian.Uint16(src[6:]) + src = src[8:] + } else { + if L, E := len(src), 4+2; L < E { + return fmt.Errorf("EOF: expected length: %d, got %d", E, L) + } + part.arg1 = uint16(src[4]) + part.arg2 = uint16(src[5]) + src = src[6:] + } + + part.Scale[0], part.Scale[3] = 1, 1 + if flags&weHaveAScale != 0 { + if L := len(src); L < 2 { + return fmt.Errorf("EOF: expected length: %d, got %d", 2, L) + } + part.Scale[0] = Float214FromUint(binary.BigEndian.Uint16(src)) + part.Scale[3] = part.Scale[0] + src = src[2:] + } else if flags&weHaveAnXAndYScale != 0 { + if L := len(src); L < 4 { + return fmt.Errorf("EOF: expected length: %d, got %d", 4, L) + } + part.Scale[0] = Float214FromUint(binary.BigEndian.Uint16(src)) + part.Scale[3] = Float214FromUint(binary.BigEndian.Uint16(src[2:])) + src = src[4:] + } else if flags&weHaveATwoByTwo != 0 { + if L := len(src); L < 8 { + return fmt.Errorf("EOF: expected length: %d, got %d", 8, L) + } + part.Scale[0] = Float214FromUint(binary.BigEndian.Uint16(src)) + part.Scale[1] = Float214FromUint(binary.BigEndian.Uint16(src[2:])) + part.Scale[2] = Float214FromUint(binary.BigEndian.Uint16(src[4:])) + part.Scale[3] = Float214FromUint(binary.BigEndian.Uint16(src[6:])) + src = src[8:] + } + + cg.Glyphs = append(cg.Glyphs, part) + } + + if flags&weHaveInstructions != 0 { + if L := len(src); L < 2 { + return fmt.Errorf("EOF: expected length: 2, got %d", L) + } + E := int(binary.BigEndian.Uint16(src)) + if L := len(src); L < E { + return fmt.Errorf("EOF: expected length: %d, got %d", E, len(src)) + } + cg.Instructions = src[0:E] + } + + return nil +} + +// already handled in parseGlyphs +func (cg *CompositeGlyph) parseInstructions(src []byte) error { return nil } + +type CompositeGlyphPart struct { + Flags uint16 + GlyphIndex GlyphID + + // raw value before interpretation: + // arg1 and arg2 may be either : + // - unsigned, when used as indices into the contour point list + // (see ArgsAsIndices) + // - signed, when used as translation in the transformation matrix + // (see ArgsAsTranslation) + arg1, arg2 uint16 + + // Scale is a matrix x, 01, 10, y ; default to identity + Scale [4]float32 +} + +func (c *CompositeGlyphPart) HasUseMyMetrics() bool { + const useMyMetrics = 0x0200 + return c.Flags&useMyMetrics != 0 +} + +// return true if arg1 and arg2 indicated an anchor point, +// not offsets +func (c *CompositeGlyphPart) IsAnchored() bool { + const argsAreXyValues = 0x0002 + return c.Flags&argsAreXyValues == 0 +} + +func (c *CompositeGlyphPart) IsScaledOffsets() bool { + const ( + scaledComponentOffset = 0x0800 + unscaledComponentOffset = 0x1000 + ) + return c.Flags&(scaledComponentOffset|unscaledComponentOffset) == scaledComponentOffset +} + +func (c *CompositeGlyphPart) ArgsAsTranslation() (int16, int16) { + // arg1 and arg2 are interpreted as signed integers here + // the conversion depends on the original size (8 or 16 bits) + if c.Flags&arg1And2AreWords != 0 { + return int16(c.arg1), int16(c.arg2) + } + return int16(int8(uint8(c.arg1))), int16(int8(uint8(c.arg2))) +} + +func (c *CompositeGlyphPart) ArgsAsIndices() (int, int) { + // arg1 and arg2 are interpreted as unsigned integers here + return int(c.arg1), int(c.arg2) +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_misc_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_misc_gen.go new file mode 100644 index 0000000..cf31e84 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_misc_gen.go @@ -0,0 +1,111 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from glyphs_misc_src.go. DO NOT EDIT + +func ParseSVG(src []byte) (SVG, int, error) { + var item SVG + n := 0 + if L := len(src); L < 10 { + return item, 0, fmt.Errorf("reading SVG: "+"EOF: expected length: 10, got %d", L) + } + _ = src[9] // early bound checking + item.version = binary.BigEndian.Uint16(src[0:]) + offsetSVGDocumentList := int(binary.BigEndian.Uint32(src[2:])) + item.reserved = binary.BigEndian.Uint32(src[6:]) + n += 10 + + { + + if offsetSVGDocumentList != 0 { // ignore null offset + if L := len(src); L < offsetSVGDocumentList { + return item, 0, fmt.Errorf("reading SVG: "+"EOF: expected length: %d, got %d", offsetSVGDocumentList, L) + } + + var err error + item.SVGDocumentList, _, err = ParseSVGDocumentList(src[offsetSVGDocumentList:]) + if err != nil { + return item, 0, fmt.Errorf("reading SVG: %s", err) + } + + } + } + return item, n, nil +} + +func ParseSVGDocumentList(src []byte) (SVGDocumentList, int, error) { + var item SVGDocumentList + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading SVGDocumentList: "+"EOF: expected length: 2, got %d", L) + } + arrayLengthDocumentRecords := int(binary.BigEndian.Uint16(src[0:])) + n += 2 + + { + + if L := len(src); L < 2+arrayLengthDocumentRecords*12 { + return item, 0, fmt.Errorf("reading SVGDocumentList: "+"EOF: expected length: %d, got %d", 2+arrayLengthDocumentRecords*12, L) + } + + item.DocumentRecords = make([]SVGDocumentRecord, arrayLengthDocumentRecords) // allocation guarded by the previous check + for i := range item.DocumentRecords { + item.DocumentRecords[i].mustParse(src[2+i*12:]) + } + n += arrayLengthDocumentRecords * 12 + } + { + + item.SVGRawData = src[0:] + n = len(src) + } + return item, n, nil +} + +func ParseVORG(src []byte) (VORG, int, error) { + var item VORG + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading VORG: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.majorVersion = binary.BigEndian.Uint16(src[0:]) + item.minorVersion = binary.BigEndian.Uint16(src[2:]) + item.DefaultVertOriginY = int16(binary.BigEndian.Uint16(src[4:])) + arrayLengthVertOriginYMetrics := int(binary.BigEndian.Uint16(src[6:])) + n += 8 + + { + + if L := len(src); L < 8+arrayLengthVertOriginYMetrics*4 { + return item, 0, fmt.Errorf("reading VORG: "+"EOF: expected length: %d, got %d", 8+arrayLengthVertOriginYMetrics*4, L) + } + + item.VertOriginYMetrics = make([]VertOriginYMetric, arrayLengthVertOriginYMetrics) // allocation guarded by the previous check + for i := range item.VertOriginYMetrics { + item.VertOriginYMetrics[i].mustParse(src[8+i*4:]) + } + n += arrayLengthVertOriginYMetrics * 4 + } + return item, n, nil +} + +func (item *SVGDocumentRecord) mustParse(src []byte) { + _ = src[11] // early bound checking + item.StartGlyphID = binary.BigEndian.Uint16(src[0:]) + item.EndGlyphID = binary.BigEndian.Uint16(src[2:]) + item.SvgDocOffset = Offset32(binary.BigEndian.Uint32(src[4:])) + item.SvgDocLength = binary.BigEndian.Uint32(src[8:]) +} + +func (item *VertOriginYMetric) mustParse(src []byte) { + _ = src[3] // early bound checking + item.GlyphIndex = binary.BigEndian.Uint16(src[0:]) + item.VertOriginY = int16(binary.BigEndian.Uint16(src[2:])) +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_misc_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_misc_src.go new file mode 100644 index 0000000..1933764 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_misc_src.go @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +// SVG is the SVG (Scalable Vector Graphics) table. +// See - https://learn.microsoft.com/fr-fr/typography/opentype/spec/svg +type SVG struct { + version uint16 // Table version (starting at 0). Set to 0. + SVGDocumentList SVGDocumentList `offsetSize:"Offset32"` // Offset to the SVG Document List, from the start of the SVG table. Must be non-zero. + reserved uint32 // Set to 0. +} + +type SVGDocumentList struct { + DocumentRecords []SVGDocumentRecord `arrayCount:"FirstUint16"` // [numEntries] Array of SVG document records. + SVGRawData []byte `subsliceStart:"AtStart" arrayCount:"ToEnd"` +} + +// Each SVG document record specifies a range of glyph IDs (from startGlyphID to endGlyphID, inclusive), and the location of its associated SVG document in the SVG table. +type SVGDocumentRecord struct { + StartGlyphID GlyphID // The first glyph ID for the range covered by this record. + EndGlyphID GlyphID // The last glyph ID for the range covered by this record. + SvgDocOffset Offset32 // Offset from the beginning of the SVGDocumentList to an SVG document. Must be non-zero. + SvgDocLength uint32 // Length of the SVG document data. Must be non-zero. +} + +// CFF is the Compact Font Format Table. +// Since it used its own format, quite different from the regular Opentype format, +// its interpretation is handled externally (see font/cff). +// See also https://learn.microsoft.com/fr-fr/typography/opentype/spec/cff +type CFF = []byte + +// VORG is the Vertical Origin Table +// See - https://learn.microsoft.com/fr-fr/typography/opentype/spec/vorg +type VORG struct { + majorVersion uint16 // Major version (starting at 1). Set to 1. + minorVersion uint16 // Minor version (starting at 0). Set to 0. + DefaultVertOriginY int16 // The y coordinate of a glyph’s vertical origin, in the font’s design coordinate system, to be used if no entry is present for the glyph in the vertOriginYMetrics array. + VertOriginYMetrics []VertOriginYMetric `arrayCount:"FirstUint16"` +} + +// YOrigin returns the vertical origin for [glyph]. +func (t *VORG) YOrigin(glyph GlyphID) int16 { + // binary search + for i, j := 0, len(t.VertOriginYMetrics); i < j; { + h := i + (j-i)/2 + entry := t.VertOriginYMetrics[h] + if glyph < entry.GlyphIndex { + j = h + } else if entry.GlyphIndex < glyph { + i = h + 1 + } else { + return entry.VertOriginY + } + } + return t.DefaultVertOriginY +} + +type VertOriginYMetric struct { + GlyphIndex GlyphID // Glyph index. + VertOriginY int16 // Y coordinate, in the font’s design coordinate system, of the vertical origin of glyph with index glyphIndex. +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_sbix_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_sbix_gen.go new file mode 100644 index 0000000..7dc38ce --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_sbix_gen.go @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from glyphs_sbix_src.go. DO NOT EDIT + +func ParseBitmapGlyphData(src []byte) (BitmapGlyphData, int, error) { + var item BitmapGlyphData + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading BitmapGlyphData: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.OriginOffsetX = int16(binary.BigEndian.Uint16(src[0:])) + item.OriginOffsetY = int16(binary.BigEndian.Uint16(src[2:])) + item.GraphicType = Tag(binary.BigEndian.Uint32(src[4:])) + n += 8 + + { + + item.Data = src[8:] + n = len(src) + } + return item, n, nil +} + +func ParseSbix(src []byte, numGlyphs int) (Sbix, int, error) { + var item Sbix + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading Sbix: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.version = binary.BigEndian.Uint16(src[0:]) + item.Flags = binary.BigEndian.Uint16(src[2:]) + arrayLengthStrikes := int(binary.BigEndian.Uint32(src[4:])) + n += 8 + + { + + if L := len(src); L < 8+arrayLengthStrikes*4 { + return item, 0, fmt.Errorf("reading Sbix: "+"EOF: expected length: %d, got %d", 8+arrayLengthStrikes*4, L) + } + + item.Strikes = make([]Strike, arrayLengthStrikes) // allocation guarded by the previous check + for i := range item.Strikes { + offset := int(binary.BigEndian.Uint32(src[8+i*4:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading Sbix: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.Strikes[i], _, err = ParseStrike(src[offset:], numGlyphs) + if err != nil { + return item, 0, fmt.Errorf("reading Sbix: %s", err) + } + } + n += arrayLengthStrikes * 4 + } + return item, n, nil +} + +func ParseStrike(src []byte, numGlyphs int) (Strike, int, error) { + var item Strike + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading Strike: "+"EOF: expected length: 4, got %d", L) + } + _ = src[3] // early bound checking + item.Ppem = binary.BigEndian.Uint16(src[0:]) + item.Ppi = binary.BigEndian.Uint16(src[2:]) + n += 4 + + { + + err := item.parseGlyphDatas(src[:], numGlyphs) + if err != nil { + return item, 0, fmt.Errorf("reading Strike: %s", err) + } + } + return item, n, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_sbix_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_sbix_src.go new file mode 100644 index 0000000..e6d2a95 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/glyphs_sbix_src.go @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "fmt" +) + +// Sbix is the Standard Bitmap Graphics Table +// See - https://learn.microsoft.com/fr-fr/typography/opentype/spec/sbix +type Sbix struct { + version uint16 // Table version number — set to 1 + // Bit 0: Set to 1. + // Bit 1: Draw outlines. + // Bits 2 to 15: reserved (set to 0). + Flags uint16 + Strikes []Strike `arrayCount:"FirstUint32" offsetsArray:"Offset32"` // [numStrikes] Offsets from the beginning of the 'sbix' table to data for each individual bitmap strike. +} + +// Strike stores one size of bitmap glyphs in the 'sbix' table. +// binarygen: argument=numGlyphs int +type Strike struct { + Ppem uint16 // The PPEM size for which this strike was designed. + Ppi uint16 // The device pixel density (in PPI) for which this strike was designed. (E.g., 96 PPI, 192 PPI.) + GlyphDatas []BitmapGlyphData `isOpaque:""` //[numGlyphs+1] Offset from the beginning of the strike data header to bitmap data for an individual glyph ID. +} + +func (st *Strike) parseGlyphDatas(src []byte, numGlyphs int) error { + const headerSize = 4 + offsets, err := ParseLoca(src[headerSize:], numGlyphs, true) + if err != nil { + return err + } + st.GlyphDatas = make([]BitmapGlyphData, numGlyphs) + for i := range st.GlyphDatas { + start, end := offsets[i], offsets[i+1] + if start == end { // no data + continue + } + + if start > end { + return fmt.Errorf("invalid strike offsets %d > %d", start, end) + } + + if L := len(src); L < int(end) { + return fmt.Errorf("EOF: expected length: %d, got %d", end, L) + } + + st.GlyphDatas[i], _, err = ParseBitmapGlyphData(src[start:end]) + if err != nil { + return err + } + } + return nil +} + +type BitmapGlyphData struct { + OriginOffsetX int16 // The horizontal (x-axis) position of the left edge of the bitmap graphic in relation to the glyph design space origin. + OriginOffsetY int16 // The vertical (y-axis) position of the bottom edge of the bitmap graphic in relation to the glyph design space origin. + GraphicType Tag // Indicates the format of the embedded graphic data: one of 'jpg ', 'png ' or 'tiff', or the special format 'dupe'. + Data []byte `arrayCount:"ToEnd"` // The actual embedded graphic data. The total length is inferred from sequential entries in the glyphDataOffsets array and the fixed size (8 bytes) of the preceding fields. +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/head_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/head_gen.go new file mode 100644 index 0000000..af61dea --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/head_gen.go @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from head_src.go. DO NOT EDIT + +func (item *Head) mustParse(src []byte) { + _ = src[53] // early bound checking + item.majorVersion = binary.BigEndian.Uint16(src[0:]) + item.minorVersion = binary.BigEndian.Uint16(src[2:]) + item.fontRevision = binary.BigEndian.Uint32(src[4:]) + item.checksumAdjustment = binary.BigEndian.Uint32(src[8:]) + item.magicNumber = binary.BigEndian.Uint32(src[12:]) + item.flags = binary.BigEndian.Uint16(src[16:]) + item.UnitsPerEm = binary.BigEndian.Uint16(src[18:]) + item.created = binary.BigEndian.Uint64(src[20:]) + item.modified = binary.BigEndian.Uint64(src[28:]) + item.XMin = int16(binary.BigEndian.Uint16(src[36:])) + item.YMin = int16(binary.BigEndian.Uint16(src[38:])) + item.XMax = int16(binary.BigEndian.Uint16(src[40:])) + item.YMax = int16(binary.BigEndian.Uint16(src[42:])) + item.MacStyle = binary.BigEndian.Uint16(src[44:]) + item.lowestRecPPEM = binary.BigEndian.Uint16(src[46:]) + item.fontDirectionHint = int16(binary.BigEndian.Uint16(src[48:])) + item.IndexToLocFormat = int16(binary.BigEndian.Uint16(src[50:])) + item.glyphDataFormat = int16(binary.BigEndian.Uint16(src[52:])) +} + +func ParseHead(src []byte) (Head, int, error) { + var item Head + n := 0 + if L := len(src); L < 54 { + return item, 0, fmt.Errorf("reading Head: "+"EOF: expected length: 54, got %d", L) + } + item.mustParse(src) + n += 54 + return item, n, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/head_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/head_src.go new file mode 100644 index 0000000..b84df29 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/head_src.go @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +// TableHead contains critical information about the rest of the font. +// https://learn.microsoft.com/en-us/typography/opentype/spec/head +// https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6head.html +// https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6bhed.html +type Head struct { + majorVersion uint16 + minorVersion uint16 + fontRevision uint32 + checksumAdjustment uint32 + magicNumber uint32 + flags uint16 + UnitsPerEm uint16 + created longdatetime + modified longdatetime + XMin int16 + YMin int16 + XMax int16 + YMax int16 + MacStyle uint16 + lowestRecPPEM uint16 + fontDirectionHint int16 + IndexToLocFormat int16 + glyphDataFormat int16 +} + +// Upem returns a sanitize version of the 'UnitsPerEm' field. +func (head *Head) Upem() uint16 { + if head.UnitsPerEm < 16 || head.UnitsPerEm > 16384 { + return 1000 + } + return head.UnitsPerEm +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/hhea_vhea_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/hhea_vhea_gen.go new file mode 100644 index 0000000..bdfa1df --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/hhea_vhea_gen.go @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from hhea_vhea_src.go. DO NOT EDIT + +func (item *Hhea) mustParse(src []byte) { + _ = src[35] // early bound checking + item.majorVersion = binary.BigEndian.Uint16(src[0:]) + item.minorVersion = binary.BigEndian.Uint16(src[2:]) + item.Ascender = int16(binary.BigEndian.Uint16(src[4:])) + item.Descender = int16(binary.BigEndian.Uint16(src[6:])) + item.LineGap = int16(binary.BigEndian.Uint16(src[8:])) + item.AdvanceMax = binary.BigEndian.Uint16(src[10:]) + item.MinFirstSideBearing = int16(binary.BigEndian.Uint16(src[12:])) + item.MinSecondSideBearing = int16(binary.BigEndian.Uint16(src[14:])) + item.MaxExtent = int16(binary.BigEndian.Uint16(src[16:])) + item.CaretSlopeRise = int16(binary.BigEndian.Uint16(src[18:])) + item.CaretSlopeRun = int16(binary.BigEndian.Uint16(src[20:])) + item.CaretOffset = int16(binary.BigEndian.Uint16(src[22:])) + item.reserved[0] = binary.BigEndian.Uint16(src[24:]) + item.reserved[1] = binary.BigEndian.Uint16(src[26:]) + item.reserved[2] = binary.BigEndian.Uint16(src[28:]) + item.reserved[3] = binary.BigEndian.Uint16(src[30:]) + item.metricDataformat = int16(binary.BigEndian.Uint16(src[32:])) + item.NumOfLongMetrics = binary.BigEndian.Uint16(src[34:]) +} + +func ParseHhea(src []byte) (Hhea, int, error) { + var item Hhea + n := 0 + if L := len(src); L < 36 { + return item, 0, fmt.Errorf("reading Hhea: "+"EOF: expected length: 36, got %d", L) + } + item.mustParse(src) + n += 36 + return item, n, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/hhea_vhea_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/hhea_vhea_src.go new file mode 100644 index 0000000..b1392e4 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/hhea_vhea_src.go @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +// https://learn.microsoft.com/en-us/typography/opentype/spec/hhea +type Hhea struct { + majorVersion uint16 + minorVersion uint16 + Ascender int16 + Descender int16 + LineGap int16 + AdvanceMax uint16 + MinFirstSideBearing int16 + MinSecondSideBearing int16 + MaxExtent int16 + CaretSlopeRise int16 + CaretSlopeRun int16 + CaretOffset int16 + reserved [4]uint16 + metricDataformat int16 + NumOfLongMetrics uint16 +} + +// https://learn.microsoft.com/en-us/typography/opentype/spec/vhea +type Vhea = Hhea diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/hmtx_vmtx_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/hmtx_vmtx_gen.go new file mode 100644 index 0000000..ec00258 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/hmtx_vmtx_gen.go @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from hmtx_vmtx_src.go. DO NOT EDIT + +func (item *LongHorMetric) mustParse(src []byte) { + _ = src[3] // early bound checking + item.AdvanceWidth = int16(binary.BigEndian.Uint16(src[0:])) + item.LeftSideBearing = int16(binary.BigEndian.Uint16(src[2:])) +} + +func ParseHmtx(src []byte, metricsCount int, leftSideBearingsCount int) (Hmtx, int, error) { + var item Hmtx + n := 0 + { + + if L := len(src); L < metricsCount*4 { + return item, 0, fmt.Errorf("reading Hmtx: "+"EOF: expected length: %d, got %d", metricsCount*4, L) + } + + item.Metrics = make([]LongHorMetric, metricsCount) // allocation guarded by the previous check + for i := range item.Metrics { + item.Metrics[i].mustParse(src[i*4:]) + } + n += metricsCount * 4 + } + { + + if L := len(src); L < n+leftSideBearingsCount*2 { + return item, 0, fmt.Errorf("reading Hmtx: "+"EOF: expected length: %d, got %d", n+leftSideBearingsCount*2, L) + } + + item.LeftSideBearings = make([]int16, leftSideBearingsCount) // allocation guarded by the previous check + for i := range item.LeftSideBearings { + item.LeftSideBearings[i] = int16(binary.BigEndian.Uint16(src[n+i*2:])) + } + n += leftSideBearingsCount * 2 + } + return item, n, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/hmtx_vmtx_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/hmtx_vmtx_src.go new file mode 100644 index 0000000..7591ea2 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/hmtx_vmtx_src.go @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +// https://learn.microsoft.com/en-us/typography/opentype/spec/hmtx +type Hmtx struct { + Metrics []LongHorMetric `arrayCount:""` + // avances are padded with the last value + // and side bearings are given + LeftSideBearings []int16 `arrayCount:""` +} + +func (table Hmtx) IsEmpty() bool { + return len(table.Metrics)+len(table.LeftSideBearings) == 0 +} + +func (table Hmtx) Advance(gid GlyphID) int16 { + LM, LS := len(table.Metrics), len(table.LeftSideBearings) + index := int(gid) + if index < LM { + return table.Metrics[index].AdvanceWidth + } else if index < LS+LM { // return the last value + return table.Metrics[len(table.Metrics)-1].AdvanceWidth + } + return 0 +} + +type LongHorMetric struct { + AdvanceWidth, LeftSideBearing int16 +} + +// https://learn.microsoft.com/en-us/typography/opentype/spec/vmtx +type Vmtx = Hmtx diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/kern.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/kern.go new file mode 100644 index 0000000..d3bc463 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/kern.go @@ -0,0 +1,101 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "errors" + "fmt" +) + +// Kern is the kern table. It has multiple header format, defined in Apple AAT and Microsoft OT +// specs, but the subtable data actually are the same. +// +// Microsoft (OT) format +// +// version uint16 : Table version number (0) +// nTables uint16 : Number of subtables in the kerning table. +// +// Apple (AAT) old format +// +// version uint16 : The version number of the kerning table (0x0001 for the current version). +// nTables uint16 : The number of subtables included in the kerning table. +// +// Apple (AAT) new format +// +// version uint32 : The version number of the kerning table (0x00010000 for the current version). +// nTables uint32 : The number of subtables included in the kerning table. +// +// See - https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6kern.html +// and - https://learn.microsoft.com/fr-fr/typography/opentype/spec/kern +type Kern struct { + version uint16 + Tables []KernSubtable +} + +// We apply the following logic: +// - read the first uint16 -> it's always the major version +// - if it's 0, we have a Miscrosoft table +// - if it's 1, we have an Apple table. We read the next uint16, +// to differentiate between the old and the new Apple format. +func ParseKern(src []byte) (Kern, int, error) { + if L := len(src); L < 4 { + return Kern{}, 0, fmt.Errorf("reading Kern: "+"EOF: expected length: 4, got %d", L) + } + + var numTables uint32 + + major := binary.BigEndian.Uint16(src) + switch major { + case 0: + numTables = uint32(binary.BigEndian.Uint16(src[2:])) + src = src[4:] + case 1: + nextUint16 := binary.BigEndian.Uint16(src[2:]) + if nextUint16 == 0 { + // either new format or old format with 0 subtables, the later being invalid (or at least useless) + if len(src) < 8 { + return Kern{}, 0, errors.New("invalid kern table version 1 (EOF)") + } + numTables = binary.BigEndian.Uint32(src[4:]) + src = src[8:] + } else { + // old format + numTables = uint32(nextUint16) + src = src[4:] + } + + default: + return Kern{}, 0, fmt.Errorf("unsupported kern table version: %d", major) + } + + out := make([]KernSubtable, numTables) + var ( + err error + nbRead int + isOT = major == 0 + ) + for i := range out { + if L := len(src); L < nbRead { + return Kern{}, 0, fmt.Errorf("reading Kern: "+"EOF: expected length: %d, got %d", nbRead, L) + } + src = src[nbRead:] + if isOT { + out[i], nbRead, err = ParseOTKernSubtableHeader(src) + } else { + out[i], nbRead, err = ParseAATKernSubtableHeader(src) + } + if err != nil { + return Kern{}, 0, err + } + } + + return Kern{ + version: major, + Tables: out, + }, 0, nil +} + +func (k AATKernSubtableHeader) Data() KernData { return k.data } + +func (k OTKernSubtableHeader) Data() KernData { return k.data } diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/kern_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/kern_gen.go new file mode 100644 index 0000000..21e9469 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/kern_gen.go @@ -0,0 +1,345 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from kern_src.go. DO NOT EDIT + +func ParseAATKernSubtableHeader(src []byte) (AATKernSubtableHeader, int, error) { + var item AATKernSubtableHeader + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading AATKernSubtableHeader: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.length = binary.BigEndian.Uint32(src[0:]) + item.Coverage = src[4] + item.version = kernSTVersion(src[5]) + item.TupleCount = binary.BigEndian.Uint16(src[6:]) + n += 8 + + { + var ( + read int + err error + ) + switch item.version { + case kernSTVersion0: + item.data, read, err = ParseKernData0(src[8:]) + case kernSTVersion1: + item.data, read, err = ParseKernData1(src[8:]) + case kernSTVersion2: + item.data, read, err = ParseKernData2(src[8:], src) + case kernSTVersion3: + item.data, read, err = ParseKernData3(src[8:]) + default: + err = fmt.Errorf("unsupported KernDataVersion %d", item.version) + } + if err != nil { + return item, 0, fmt.Errorf("reading AATKernSubtableHeader: %s", err) + } + n += read + } + var err error + n, err = item.parseEnd(src) + if err != nil { + return item, 0, fmt.Errorf("reading AATKernSubtableHeader: %s", err) + } + + return item, n, nil +} + +func ParseAATStateTable(src []byte) (AATStateTable, int, error) { + var item AATStateTable + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading AATStateTable: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.StateSize = binary.BigEndian.Uint16(src[0:]) + offsetClassTable := int(binary.BigEndian.Uint16(src[2:])) + item.stateArray = Offset16(binary.BigEndian.Uint16(src[4:])) + item.entryTable = Offset16(binary.BigEndian.Uint16(src[6:])) + n += 8 + + { + + if offsetClassTable != 0 { // ignore null offset + if L := len(src); L < offsetClassTable { + return item, 0, fmt.Errorf("reading AATStateTable: "+"EOF: expected length: %d, got %d", offsetClassTable, L) + } + + var err error + item.ClassTable, _, err = ParseClassTable(src[offsetClassTable:]) + if err != nil { + return item, 0, fmt.Errorf("reading AATStateTable: %s", err) + } + + } + } + { + + err := item.parseStates(src[:]) + if err != nil { + return item, 0, fmt.Errorf("reading AATStateTable: %s", err) + } + } + { + + read, err := item.parseEntries(src[:]) + if err != nil { + return item, 0, fmt.Errorf("reading AATStateTable: %s", err) + } + n = read + } + return item, n, nil +} + +func ParseClassTable(src []byte) (ClassTable, int, error) { + var item ClassTable + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading ClassTable: "+"EOF: expected length: 4, got %d", L) + } + _ = src[3] // early bound checking + item.StartGlyph = binary.BigEndian.Uint16(src[0:]) + arrayLengthValues := int(binary.BigEndian.Uint16(src[2:])) + n += 4 + + { + + L := int(4 + arrayLengthValues) + if len(src) < L { + return item, 0, fmt.Errorf("reading ClassTable: "+"EOF: expected length: %d, got %d", L, len(src)) + } + item.Values = src[4:L] + n = L + } + return item, n, nil +} + +func ParseKernData0(src []byte) (KernData0, int, error) { + var item KernData0 + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading KernData0: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.nPairs = binary.BigEndian.Uint16(src[0:]) + item.searchRange = binary.BigEndian.Uint16(src[2:]) + item.entrySelector = binary.BigEndian.Uint16(src[4:]) + item.rangeShift = binary.BigEndian.Uint16(src[6:]) + n += 8 + + { + arrayLength := int(item.nPairs) + + if L := len(src); L < 8+arrayLength*6 { + return item, 0, fmt.Errorf("reading KernData0: "+"EOF: expected length: %d, got %d", 8+arrayLength*6, L) + } + + item.Pairs = make([]Kernx0Record, arrayLength) // allocation guarded by the previous check + for i := range item.Pairs { + item.Pairs[i].mustParse(src[8+i*6:]) + } + n += arrayLength * 6 + } + return item, n, nil +} + +func ParseKernData1(src []byte) (KernData1, int, error) { + var item KernData1 + n := 0 + { + var ( + err error + read int + ) + item.AATStateTable, read, err = ParseAATStateTable(src[0:]) + if err != nil { + return item, 0, fmt.Errorf("reading KernData1: %s", err) + } + n += read + } + if L := len(src); L < n+2 { + return item, 0, fmt.Errorf("reading KernData1: "+"EOF: expected length: n + 2, got %d", L) + } + item.valueTable = binary.BigEndian.Uint16(src[n:]) + n += 2 + + { + + err := item.parseValues(src[:]) + if err != nil { + return item, 0, fmt.Errorf("reading KernData1: %s", err) + } + } + return item, n, nil +} + +func ParseKernData2(src []byte, parentSrc []byte) (KernData2, int, error) { + var item KernData2 + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading KernData2: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.rowWidth = binary.BigEndian.Uint16(src[0:]) + offsetLeft := int(binary.BigEndian.Uint16(src[2:])) + offsetRight := int(binary.BigEndian.Uint16(src[4:])) + item.KerningStart = Offset16(binary.BigEndian.Uint16(src[6:])) + n += 8 + + { + + if offsetLeft != 0 { // ignore null offset + if L := len(parentSrc); L < offsetLeft { + return item, 0, fmt.Errorf("reading KernData2: "+"EOF: expected length: %d, got %d", offsetLeft, L) + } + + var err error + item.Left, _, err = ParseAATLoopkup8Data(parentSrc[offsetLeft:]) + if err != nil { + return item, 0, fmt.Errorf("reading KernData2: %s", err) + } + + } + } + { + + if offsetRight != 0 { // ignore null offset + if L := len(parentSrc); L < offsetRight { + return item, 0, fmt.Errorf("reading KernData2: "+"EOF: expected length: %d, got %d", offsetRight, L) + } + + var err error + item.Right, _, err = ParseAATLoopkup8Data(parentSrc[offsetRight:]) + if err != nil { + return item, 0, fmt.Errorf("reading KernData2: %s", err) + } + + } + } + { + + err := item.parseKerningData(src[:], parentSrc) + if err != nil { + return item, 0, fmt.Errorf("reading KernData2: %s", err) + } + } + return item, n, nil +} + +func ParseKernData3(src []byte) (KernData3, int, error) { + var item KernData3 + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading KernData3: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.glyphCount = binary.BigEndian.Uint16(src[0:]) + item.kernValueCount = src[2] + item.leftClassCount = src[3] + item.RightClassCount = src[4] + item.flags = src[5] + n += 6 + + { + arrayLength := int(item.kernValueCount) + + if L := len(src); L < 6+arrayLength*2 { + return item, 0, fmt.Errorf("reading KernData3: "+"EOF: expected length: %d, got %d", 6+arrayLength*2, L) + } + + item.Kernings = make([]int16, arrayLength) // allocation guarded by the previous check + for i := range item.Kernings { + item.Kernings[i] = int16(binary.BigEndian.Uint16(src[6+i*2:])) + } + n += arrayLength * 2 + } + { + arrayLength := int(item.glyphCount) + + L := int(n + arrayLength) + if len(src) < L { + return item, 0, fmt.Errorf("reading KernData3: "+"EOF: expected length: %d, got %d", L, len(src)) + } + item.LeftClass = src[n:L] + n = L + } + { + arrayLength := int(item.glyphCount) + + L := int(n + arrayLength) + if len(src) < L { + return item, 0, fmt.Errorf("reading KernData3: "+"EOF: expected length: %d, got %d", L, len(src)) + } + item.RightClass = src[n:L] + n = L + } + { + arrayLength := int(item.nKernIndex()) + + L := int(n + arrayLength) + if len(src) < L { + return item, 0, fmt.Errorf("reading KernData3: "+"EOF: expected length: %d, got %d", L, len(src)) + } + item.KernIndex = src[n:L] + n = L + } + var err error + n, err = item.parseEnd(src) + if err != nil { + return item, 0, fmt.Errorf("reading KernData3: %s", err) + } + + return item, n, nil +} + +func ParseOTKernSubtableHeader(src []byte) (OTKernSubtableHeader, int, error) { + var item OTKernSubtableHeader + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading OTKernSubtableHeader: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.version = binary.BigEndian.Uint16(src[0:]) + item.length = binary.BigEndian.Uint16(src[2:]) + item.format = kernSTVersion(src[4]) + item.Coverage = src[5] + n += 6 + + { + var ( + read int + err error + ) + switch item.format { + case kernSTVersion0: + item.data, read, err = ParseKernData0(src[6:]) + case kernSTVersion1: + item.data, read, err = ParseKernData1(src[6:]) + case kernSTVersion2: + item.data, read, err = ParseKernData2(src[6:], src) + case kernSTVersion3: + item.data, read, err = ParseKernData3(src[6:]) + default: + err = fmt.Errorf("unsupported KernDataVersion %d", item.format) + } + if err != nil { + return item, 0, fmt.Errorf("reading OTKernSubtableHeader: %s", err) + } + n += read + } + var err error + n, err = item.parseEnd(src) + if err != nil { + return item, 0, fmt.Errorf("reading OTKernSubtableHeader: %s", err) + } + + return item, n, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/kern_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/kern_src.go new file mode 100644 index 0000000..c8ad9f4 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/kern_src.go @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "errors" + "fmt" +) + +type KernSubtable interface { + // Data returns the actual kerning data + Data() KernData +} + +type OTKernSubtableHeader struct { + version uint16 // Kern subtable version number + length uint16 // Length of the subtable, in bytes (including this header). + format kernSTVersion // What type of information is contained in this table. + Coverage byte // What type of information is contained in this table. + data KernData `unionField:"format"` +} + +// check and return the length +func (st *OTKernSubtableHeader) parseEnd(src []byte) (int, error) { + if L, E := len(src), int(st.length); L < E { + return 0, fmt.Errorf("EOF: expected length: %d, got %d", E, L) + } + return int(st.length), nil +} + +type AATKernSubtableHeader struct { + length uint32 // The length of this subtable in bytes, including this header. + Coverage byte // Circumstances under which this table is used. + version kernSTVersion + TupleCount uint16 // The tuple count. This value is only used with variation fonts and should be 0 for all other fonts. The subtable's tupleCount will be ignored if the 'kerx' table version is less than 4. + data KernData `unionField:"version"` +} + +// check and return the length +func (st *AATKernSubtableHeader) parseEnd(src []byte) (int, error) { + if L, E := len(src), int(st.length); L < E { + return 0, fmt.Errorf("EOF: expected length: %d, got %d", E, L) + } + return int(st.length), nil +} + +type KernData interface { + isKernData() +} + +func (KernData0) isKernData() {} +func (KernData1) isKernData() {} +func (KernData2) isKernData() {} +func (KernData3) isKernData() {} + +type kernSTVersion byte + +const ( + kernSTVersion0 kernSTVersion = iota + kernSTVersion1 + kernSTVersion2 + kernSTVersion3 +) + +type KernData0 struct { + nPairs uint16 // The number of kerning pairs in this subtable. + searchRange uint16 // The largest power of two less than or equal to the value of nPairs, multiplied by the size in bytes of an entry in the subtable. + entrySelector uint16 // This is calculated as log2 of the largest power of two less than or equal to the value of nPairs. This value indicates how many iterations of the search loop have to be made. For example, in a list of eight items, there would be three iterations of the loop. + rangeShift uint16 // The value of nPairs minus the largest power of two less than or equal to nPairs. This is multiplied b + Pairs []Kernx0Record `arrayCount:"ComputedField-nPairs"` +} + +type KernData1 struct { + AATStateTable + valueTable uint16 // Offset in bytes from the beginning of the subtable to the beginning of the kerning table. + Values []int16 `isOpaque:""` +} + +func (kd *KernData1) parseValues(src []byte) error { + valuesOffset := int(kd.valueTable) + // start by resolving offset -> index + for i := range kd.Entries { + entry := &kd.Entries[i] + offset := int(entry.Flags & Kern1Offset) + if offset == 0 || offset < valuesOffset { + binary.BigEndian.PutUint16(entry.data[:], 0xFFFF) + } else { + index := uint16((offset - valuesOffset) / 2) + binary.BigEndian.PutUint16(entry.data[:], index) + } + } + var err error + kd.Values, err = parseKernx1Values(src, kd.Entries, valuesOffset, 0) + return err +} + +type KernData2 struct { + rowWidth uint16 // The width, in bytes, of a row in the subtable. + Left AATLoopkup8Data `offsetSize:"Offset16" offsetRelativeTo:"Parent"` + Right AATLoopkup8Data `offsetSize:"Offset16" offsetRelativeTo:"Parent"` + KerningStart Offset16 // Offset from beginning of this subtable to the start of the kerning array. + KerningData []byte `isOpaque:"" offsetRelativeTo:"Parent"` // indexed by Left + Right +} + +func (kd *KernData2) parseKerningData(_ []byte, parentSrc []byte) error { + kd.KerningData = parentSrc + return nil +} + +type KernData3 struct { + glyphCount uint16 // The number of glyphs in this font. + kernValueCount uint8 // The number of kerning values. + leftClassCount uint8 // The number of left-hand classes. + RightClassCount uint8 // The number of right-hand classes. + flags uint8 // Set to zero (reserved for future use). + Kernings []int16 `arrayCount:"ComputedField-kernValueCount"` + LeftClass []uint8 `arrayCount:"ComputedField-glyphCount"` + RightClass []uint8 `arrayCount:"ComputedField-glyphCount"` + KernIndex []uint8 `arrayCount:"ComputedField-nKernIndex()"` +} + +func (kd *KernData3) nKernIndex() int { return int(kd.leftClassCount) * int(kd.RightClassCount) } + +// sanitize index and class values +func (kd *KernData3) parseEnd(_ []byte) (int, error) { + for _, index := range kd.KernIndex { + if index >= kd.kernValueCount { + return 0, errors.New("invalid kern subtable format 3 index value") + } + } + + for i := range kd.LeftClass { + if kd.LeftClass[i] >= kd.leftClassCount { + return 0, errors.New("invalid kern subtable format 3 left class value") + } + if kd.RightClass[i] >= kd.RightClassCount { + return 0, errors.New("invalid kern subtable format 3 right class value") + } + } + + return 0, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/maxp_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/maxp_gen.go new file mode 100644 index 0000000..7639dce --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/maxp_gen.go @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from maxp_src.go. DO NOT EDIT + +func ParseMaxp(src []byte) (Maxp, int, error) { + var item Maxp + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading Maxp: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.version = maxpVersion(binary.BigEndian.Uint32(src[0:])) + item.NumGlyphs = binary.BigEndian.Uint16(src[4:]) + n += 6 + + { + var ( + read int + err error + ) + switch item.version { + case maxpVersion05: + item.data, read, err = parseMaxpData05(src[6:]) + case maxpVersion1: + item.data, read, err = parseMaxpData1(src[6:]) + default: + err = fmt.Errorf("unsupported maxpDataVersion %d", item.version) + } + if err != nil { + return item, 0, fmt.Errorf("reading Maxp: %s", err) + } + n += read + } + return item, n, nil +} + +func (item *maxpData1) mustParse(src []byte) { + item.rawData[0] = binary.BigEndian.Uint16(src[0:]) + item.rawData[1] = binary.BigEndian.Uint16(src[2:]) + item.rawData[2] = binary.BigEndian.Uint16(src[4:]) + item.rawData[3] = binary.BigEndian.Uint16(src[6:]) + item.rawData[4] = binary.BigEndian.Uint16(src[8:]) + item.rawData[5] = binary.BigEndian.Uint16(src[10:]) + item.rawData[6] = binary.BigEndian.Uint16(src[12:]) + item.rawData[7] = binary.BigEndian.Uint16(src[14:]) + item.rawData[8] = binary.BigEndian.Uint16(src[16:]) + item.rawData[9] = binary.BigEndian.Uint16(src[18:]) + item.rawData[10] = binary.BigEndian.Uint16(src[20:]) + item.rawData[11] = binary.BigEndian.Uint16(src[22:]) + item.rawData[12] = binary.BigEndian.Uint16(src[24:]) +} + +func parseMaxpData05([]byte) (maxpData05, int, error) { + var item maxpData05 + n := 0 + return item, n, nil +} + +func parseMaxpData1(src []byte) (maxpData1, int, error) { + var item maxpData1 + n := 0 + if L := len(src); L < 26 { + return item, 0, fmt.Errorf("reading maxpData1: "+"EOF: expected length: 26, got %d", L) + } + item.mustParse(src) + n += 26 + return item, n, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/maxp_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/maxp_src.go new file mode 100644 index 0000000..4a28707 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/maxp_src.go @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +// https://learn.microsoft.com/en-us/typography/opentype/spec/Maxp +type Maxp struct { + version maxpVersion + NumGlyphs uint16 + data maxpData `unionField:"version"` +} + +type maxpVersion uint32 + +const ( + maxpVersion05 maxpVersion = 0x00005000 + maxpVersion1 maxpVersion = 0x00010000 +) + +type maxpData interface { + isMaxpVersion() +} + +func (maxpData05) isMaxpVersion() {} +func (maxpData1) isMaxpVersion() {} + +type maxpData05 struct{} + +type maxpData1 struct { + rawData [13]uint16 +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/name_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/name_gen.go new file mode 100644 index 0000000..a2220c4 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/name_gen.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from name_src.go. DO NOT EDIT + +func ParseName(src []byte) (Name, int, error) { + var item Name + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading Name: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.version = binary.BigEndian.Uint16(src[0:]) + item.count = binary.BigEndian.Uint16(src[2:]) + offsetStringData := int(binary.BigEndian.Uint16(src[4:])) + n += 6 + + { + + if offsetStringData != 0 { // ignore null offset + if L := len(src); L < offsetStringData { + return item, 0, fmt.Errorf("reading Name: "+"EOF: expected length: %d, got %d", offsetStringData, L) + } + + item.stringData = src[offsetStringData:] + } + } + { + arrayLength := int(item.count) + + if L := len(src); L < 6+arrayLength*12 { + return item, 0, fmt.Errorf("reading Name: "+"EOF: expected length: %d, got %d", 6+arrayLength*12, L) + } + + item.nameRecords = make([]nameRecord, arrayLength) // allocation guarded by the previous check + for i := range item.nameRecords { + item.nameRecords[i].mustParse(src[6+i*12:]) + } + n += arrayLength * 12 + } + return item, n, nil +} + +func (item *nameRecord) mustParse(src []byte) { + _ = src[11] // early bound checking + item.platformID = PlatformID(binary.BigEndian.Uint16(src[0:])) + item.encodingID = EncodingID(binary.BigEndian.Uint16(src[2:])) + item.languageID = LanguageID(binary.BigEndian.Uint16(src[4:])) + item.nameID = NameID(binary.BigEndian.Uint16(src[6:])) + item.length = binary.BigEndian.Uint16(src[8:]) + item.stringOffset = binary.BigEndian.Uint16(src[10:]) +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/name_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/name_src.go new file mode 100644 index 0000000..3a14443 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/name_src.go @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "unicode/utf16" +) + +const ( + PlatformUnicode PlatformID = iota + PlatformMac + PlatformIso // deprecated + PlatformMicrosoft + PlatformCustom + _ + _ + PlatformAdobe // artificial +) + +const ( + PEUnicodeDefault = EncodingID(0) + PEUnicodeBMP = EncodingID(3) + PEUnicodeFull = EncodingID(4) + PEUnicodeFull13 = EncodingID(6) + PEMacRoman = PEUnicodeDefault + PEMicrosoftSymbolCs = EncodingID(0) + PEMicrosoftUnicodeCs = EncodingID(1) + PEMicrosoftUcs4 = EncodingID(10) +) + +const ( + plMacEnglish = LanguageID(0) + plUnicodeDefault = LanguageID(0) + plMicrosoftEnglish = LanguageID(0x0409) +) + +// Naming table +// See https://learn.microsoft.com/en-us/typography/opentype/spec/name +type Name struct { + version uint16 + count uint16 + stringData []byte `offsetSize:"Offset16" arrayCount:"ToEnd"` + nameRecords []nameRecord `arrayCount:"ComputedField-count"` +} + +type nameRecord struct { + platformID PlatformID + encodingID EncodingID + languageID LanguageID + nameID NameID + length uint16 + stringOffset uint16 +} + +// selectRecord return the entry for `name` or nil if not found. +func (names Name) selectRecord(name NameID) *nameRecord { + var ( + foundAppleRoman = -1 + foundAppleEnglish = -1 + foundWin = -1 + foundUnicode = -1 + isEnglish = false + ) + + for n, rec := range names.nameRecords { + // According to the OpenType 1.3 specification, only Microsoft or + // Apple platform IDs might be used in the `name' table. The + // `Unicode' platform is reserved for the `cmap' table, and the + // `ISO' one is deprecated. + // + // However, the Apple TrueType specification doesn't say the same + // thing and goes to suggest that all Unicode `name' table entries + // should be coded in UTF-16. + if rec.nameID == name && rec.length > 0 { + switch rec.platformID { + case PlatformUnicode, PlatformIso: + // there is `languageID' to check there. We should use this + // field only as a last solution when nothing else is + // available. + foundUnicode = n + case PlatformMac: + // This is a bit special because some fonts will use either + // an English language id, or a Roman encoding id, to indicate + // the English version of its font name. + if rec.languageID == plMacEnglish { + foundAppleEnglish = n + } else if rec.encodingID == PEMacRoman { + foundAppleRoman = n + } + case PlatformMicrosoft: + // we only take a non-English name when there is nothing + // else available in the font + if foundWin == -1 || (rec.languageID&0x3FF) == 0x009 { + switch rec.encodingID { + case PEMicrosoftSymbolCs, PEMicrosoftUnicodeCs, PEMicrosoftUcs4: + isEnglish = (rec.languageID & 0x3FF) == 0x009 + foundWin = n + } + } + } + } + } + + foundApple := foundAppleRoman + if foundAppleEnglish >= 0 { + foundApple = foundAppleEnglish + } + + // some fonts contain invalid Unicode or Macintosh formatted entries; + // we will thus favor names encoded in Windows formats if available + // (provided it is an English name) + if foundWin >= 0 && !(foundApple >= 0 && !isEnglish) { + return &names.nameRecords[foundWin] + } else if foundApple >= 0 { + return &names.nameRecords[foundApple] + } else if foundUnicode >= 0 { + return &names.nameRecords[foundUnicode] + } + return nil +} + +// Name returns the entry at [name], encoded in UTF-8 when possible, +// or an empty string if not found +func (names Name) Name(name NameID) string { + if record := names.selectRecord(name); record != nil { + return names.decodeRecord(*record) + } + return "" +} + +// decode is a best-effort attempt to get an UTF-8 encoded version of +// Value. Only MicrosoftUnicode (3,1 ,X), MacRomain (1,0,X) and Unicode platform +// strings are supported. +func (names Name) decodeRecord(n nameRecord) string { + end := int(n.stringOffset) + int(n.length) + if end > len(names.stringData) { + // invalid record + return "" + } + value := names.stringData[n.stringOffset:end] + + if n.platformID == PlatformUnicode || (n.platformID == PlatformMicrosoft && + n.encodingID == PEMicrosoftUnicodeCs) { + return decodeUtf16(value) + } + + if n.platformID == PlatformMac && n.encodingID == PEMacRoman { + return DecodeMacintosh(value) + } + + // no encoding detected, hope for utf8 + return string(value) +} + +// decode a big ending, no BOM utf16 string +func decodeUtf16(b []byte) string { + ints := make([]uint16, len(b)/2) + for i := range ints { + ints[i] = binary.BigEndian.Uint16(b[2*i:]) + } + return string(utf16.Decode(ints)) +} + +// Support for the old macintosh encoding + +var macintoshEncoding = [256]rune{ + 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, 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, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 196, 197, 199, 201, 209, 214, 220, 225, 224, 226, 228, 227, 229, 231, 233, 232, 234, 235, 237, 236, 238, 239, 241, 243, 242, 244, 246, 245, 250, 249, 251, 252, 8224, 176, 162, 163, 167, 8226, 182, 223, 174, 169, 8482, 180, 168, 8800, 198, 216, 8734, 177, 8804, 8805, 165, 181, 8706, 8721, 8719, 960, 8747, 170, 186, 937, 230, 248, 191, 161, 172, 8730, 402, 8776, 8710, 171, 187, 8230, 160, 192, 195, 213, 338, 339, 8211, 8212, 8220, 8221, 8216, 8217, 247, 9674, 255, 376, 8260, 8364, + 8249, 8250, 64257, 64258, 8225, 183, 8218, 8222, 8240, 194, 202, 193, 203, 200, 205, 206, 207, 204, 211, 212, 63743, 210, 218, 219, 217, 305, 710, 732, 175, 728, 729, 730, 184, 733, 731, 711, +} + +// DecodeMacintoshByte returns the rune for the given byte +func DecodeMacintoshByte(b byte) rune { return macintoshEncoding[b] } + +// DecodeMacintosh decode a Macintosh encoded string +func DecodeMacintosh(encoded []byte) string { + out := make([]rune, len(encoded)) + for i, b := range encoded { + out[i] = macintoshEncoding[b] + } + return string(out) +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/os2_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/os2_gen.go new file mode 100644 index 0000000..d0f0154 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/os2_gen.go @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from os2_src.go. DO NOT EDIT + +func ParseOs2(src []byte) (Os2, int, error) { + var item Os2 + n := 0 + if L := len(src); L < 78 { + return item, 0, fmt.Errorf("reading Os2: "+"EOF: expected length: 78, got %d", L) + } + _ = src[77] // early bound checking + item.Version = binary.BigEndian.Uint16(src[0:]) + item.XAvgCharWidth = binary.BigEndian.Uint16(src[2:]) + item.USWeightClass = binary.BigEndian.Uint16(src[4:]) + item.USWidthClass = binary.BigEndian.Uint16(src[6:]) + item.fSType = binary.BigEndian.Uint16(src[8:]) + item.YSubscriptXSize = int16(binary.BigEndian.Uint16(src[10:])) + item.YSubscriptYSize = int16(binary.BigEndian.Uint16(src[12:])) + item.YSubscriptXOffset = int16(binary.BigEndian.Uint16(src[14:])) + item.YSubscriptYOffset = int16(binary.BigEndian.Uint16(src[16:])) + item.YSuperscriptXSize = int16(binary.BigEndian.Uint16(src[18:])) + item.YSuperscriptYSize = int16(binary.BigEndian.Uint16(src[20:])) + item.YSuperscriptXOffset = int16(binary.BigEndian.Uint16(src[22:])) + item.ySuperscriptYOffset = int16(binary.BigEndian.Uint16(src[24:])) + item.YStrikeoutSize = int16(binary.BigEndian.Uint16(src[26:])) + item.YStrikeoutPosition = int16(binary.BigEndian.Uint16(src[28:])) + item.sFamilyClass = int16(binary.BigEndian.Uint16(src[30:])) + item.panose[0] = src[32] + item.panose[1] = src[33] + item.panose[2] = src[34] + item.panose[3] = src[35] + item.panose[4] = src[36] + item.panose[5] = src[37] + item.panose[6] = src[38] + item.panose[7] = src[39] + item.panose[8] = src[40] + item.panose[9] = src[41] + item.ulCharRange[0] = binary.BigEndian.Uint32(src[42:]) + item.ulCharRange[1] = binary.BigEndian.Uint32(src[46:]) + item.ulCharRange[2] = binary.BigEndian.Uint32(src[50:]) + item.ulCharRange[3] = binary.BigEndian.Uint32(src[54:]) + item.achVendID = Tag(binary.BigEndian.Uint32(src[58:])) + item.FsSelection = binary.BigEndian.Uint16(src[62:]) + item.USFirstCharIndex = binary.BigEndian.Uint16(src[64:]) + item.USLastCharIndex = binary.BigEndian.Uint16(src[66:]) + item.STypoAscender = int16(binary.BigEndian.Uint16(src[68:])) + item.STypoDescender = int16(binary.BigEndian.Uint16(src[70:])) + item.STypoLineGap = int16(binary.BigEndian.Uint16(src[72:])) + item.usWinAscent = binary.BigEndian.Uint16(src[74:]) + item.usWinDescent = binary.BigEndian.Uint16(src[76:]) + n += 78 + + { + + item.HigherVersionData = src[78:] + n = len(src) + } + return item, n, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/os2_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/os2_src.go new file mode 100644 index 0000000..c28fcbd --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/os2_src.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +// OS/2 and Windows Metrics Table +// See https://learn.microsoft.com/en-us/typography/opentype/spec/os2 +type Os2 struct { + Version uint16 + XAvgCharWidth uint16 + USWeightClass uint16 + USWidthClass uint16 + fSType uint16 + YSubscriptXSize int16 + YSubscriptYSize int16 + YSubscriptXOffset int16 + YSubscriptYOffset int16 + YSuperscriptXSize int16 + YSuperscriptYSize int16 + YSuperscriptXOffset int16 + ySuperscriptYOffset int16 + YStrikeoutSize int16 + YStrikeoutPosition int16 + sFamilyClass int16 + panose [10]byte + ulCharRange [4]uint32 + achVendID Tag + FsSelection uint16 + USFirstCharIndex uint16 + USLastCharIndex uint16 + STypoAscender int16 + STypoDescender int16 + STypoLineGap int16 + usWinAscent uint16 + usWinDescent uint16 + HigherVersionData []byte `arrayCount:"ToEnd"` +} + +func (os *Os2) FontPage() FontPage { + if os.Version == 0 { + return FontPage(os.FsSelection & 0xFF00) + } + return FPNone +} + +// See https://docs.microsoft.com/en-us/typography/legacy/legacy_arabic_fonts +// https://github.com/Microsoft/Font-Validator/blob/520aaae/OTFontFileVal/val_OS2.cs#L644-L681 +type FontPage uint16 + +const ( + FPNone FontPage = 0 + FPHebrew FontPage = 0xB100 /* Hebrew Windows 3.1 font page */ + FPSimpArabic FontPage = 0xB200 /* Simplified Arabic Windows 3.1 font page */ + FPTradArabic FontPage = 0xB300 /* Traditional Arabic Windows 3.1 font page */ + FPOemArabic FontPage = 0xB400 /* OEM Arabic Windows 3.1 font page */ + FPSimpFarsi FontPage = 0xBA00 /* Simplified Farsi Windows 3.1 font page */ + FPTradFarsi FontPage = 0xBB00 /* Traditional Farsi Windows 3.1 font page */ + FPThai FontPage = 0xDE00 /* Thai Windows 3.1 font page */ +) diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_gdef_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_gdef_gen.go new file mode 100644 index 0000000..5753865 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_gdef_gen.go @@ -0,0 +1,582 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from ot_gdef_src.go. DO NOT EDIT + +func (item *CaretValue1) mustParse(src []byte) { + _ = src[3] // early bound checking + item.caretValueFormat = binary.BigEndian.Uint16(src[0:]) + item.Coordinate = int16(binary.BigEndian.Uint16(src[2:])) +} + +func (item *CaretValue2) mustParse(src []byte) { + _ = src[3] // early bound checking + item.caretValueFormat = binary.BigEndian.Uint16(src[0:]) + item.CaretValuePointIndex = binary.BigEndian.Uint16(src[2:]) +} + +func (item *ClassRangeRecord) mustParse(src []byte) { + _ = src[5] // early bound checking + item.StartGlyphID = binary.BigEndian.Uint16(src[0:]) + item.EndGlyphID = binary.BigEndian.Uint16(src[2:]) + item.Class = binary.BigEndian.Uint16(src[4:]) +} + +func ParseAttachList(src []byte) (AttachList, int, error) { + var item AttachList + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading AttachList: "+"EOF: expected length: 4, got %d", L) + } + _ = src[3] // early bound checking + offsetCoverage := int(binary.BigEndian.Uint16(src[0:])) + arrayLengthAttachPoints := int(binary.BigEndian.Uint16(src[2:])) + n += 4 + + { + + if offsetCoverage != 0 { // ignore null offset + if L := len(src); L < offsetCoverage { + return item, 0, fmt.Errorf("reading AttachList: "+"EOF: expected length: %d, got %d", offsetCoverage, L) + } + + var ( + err error + read int + ) + item.Coverage, read, err = ParseCoverage(src[offsetCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading AttachList: %s", err) + } + offsetCoverage += read + } + } + { + + if L := len(src); L < 4+arrayLengthAttachPoints*2 { + return item, 0, fmt.Errorf("reading AttachList: "+"EOF: expected length: %d, got %d", 4+arrayLengthAttachPoints*2, L) + } + + item.AttachPoints = make([]AttachPoint, arrayLengthAttachPoints) // allocation guarded by the previous check + for i := range item.AttachPoints { + offset := int(binary.BigEndian.Uint16(src[4+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading AttachList: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.AttachPoints[i], _, err = ParseAttachPoint(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading AttachList: %s", err) + } + } + n += arrayLengthAttachPoints * 2 + } + return item, n, nil +} + +func ParseAttachPoint(src []byte) (AttachPoint, int, error) { + var item AttachPoint + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading AttachPoint: "+"EOF: expected length: 2, got %d", L) + } + arrayLengthPointIndices := int(binary.BigEndian.Uint16(src[0:])) + n += 2 + + { + + if L := len(src); L < 2+arrayLengthPointIndices*2 { + return item, 0, fmt.Errorf("reading AttachPoint: "+"EOF: expected length: %d, got %d", 2+arrayLengthPointIndices*2, L) + } + + item.PointIndices = make([]uint16, arrayLengthPointIndices) // allocation guarded by the previous check + for i := range item.PointIndices { + item.PointIndices[i] = binary.BigEndian.Uint16(src[2+i*2:]) + } + n += arrayLengthPointIndices * 2 + } + return item, n, nil +} + +func ParseCaretValue(src []byte) (CaretValue, int, error) { + var item CaretValue + + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading CaretValue: "+"EOF: expected length: 2, got %d", L) + } + format := uint16(binary.BigEndian.Uint16(src[0:])) + var ( + read int + err error + ) + switch format { + case 1: + item, read, err = ParseCaretValue1(src[0:]) + case 2: + item, read, err = ParseCaretValue2(src[0:]) + case 3: + item, read, err = ParseCaretValue3(src[0:]) + default: + err = fmt.Errorf("unsupported CaretValue format %d", format) + } + if err != nil { + return item, 0, fmt.Errorf("reading CaretValue: %s", err) + } + + return item, read, nil +} + +func ParseCaretValue1(src []byte) (CaretValue1, int, error) { + var item CaretValue1 + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading CaretValue1: "+"EOF: expected length: 4, got %d", L) + } + item.mustParse(src) + n += 4 + return item, n, nil +} + +func ParseCaretValue2(src []byte) (CaretValue2, int, error) { + var item CaretValue2 + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading CaretValue2: "+"EOF: expected length: 4, got %d", L) + } + item.mustParse(src) + n += 4 + return item, n, nil +} + +func ParseCaretValue3(src []byte) (CaretValue3, int, error) { + var item CaretValue3 + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading CaretValue3: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.caretValueFormat = binary.BigEndian.Uint16(src[0:]) + item.Coordinate = int16(binary.BigEndian.Uint16(src[2:])) + item.deviceOffset = Offset16(binary.BigEndian.Uint16(src[4:])) + n += 6 + + { + + err := item.parseDevice(src[:]) + if err != nil { + return item, 0, fmt.Errorf("reading CaretValue3: %s", err) + } + } + return item, n, nil +} + +func ParseClassDef(src []byte) (ClassDef, int, error) { + var item ClassDef + + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading ClassDef: "+"EOF: expected length: 2, got %d", L) + } + format := uint16(binary.BigEndian.Uint16(src[0:])) + var ( + read int + err error + ) + switch format { + case 1: + item, read, err = ParseClassDef1(src[0:]) + case 2: + item, read, err = ParseClassDef2(src[0:]) + default: + err = fmt.Errorf("unsupported ClassDef format %d", format) + } + if err != nil { + return item, 0, fmt.Errorf("reading ClassDef: %s", err) + } + + return item, read, nil +} + +func ParseClassDef1(src []byte) (ClassDef1, int, error) { + var item ClassDef1 + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading ClassDef1: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + item.StartGlyphID = binary.BigEndian.Uint16(src[2:]) + arrayLengthClassValueArray := int(binary.BigEndian.Uint16(src[4:])) + n += 6 + + { + + if L := len(src); L < 6+arrayLengthClassValueArray*2 { + return item, 0, fmt.Errorf("reading ClassDef1: "+"EOF: expected length: %d, got %d", 6+arrayLengthClassValueArray*2, L) + } + + item.ClassValueArray = make([]uint16, arrayLengthClassValueArray) // allocation guarded by the previous check + for i := range item.ClassValueArray { + item.ClassValueArray[i] = binary.BigEndian.Uint16(src[6+i*2:]) + } + n += arrayLengthClassValueArray * 2 + } + return item, n, nil +} + +func ParseClassDef2(src []byte) (ClassDef2, int, error) { + var item ClassDef2 + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading ClassDef2: "+"EOF: expected length: 4, got %d", L) + } + _ = src[3] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + arrayLengthClassRangeRecords := int(binary.BigEndian.Uint16(src[2:])) + n += 4 + + { + + if L := len(src); L < 4+arrayLengthClassRangeRecords*6 { + return item, 0, fmt.Errorf("reading ClassDef2: "+"EOF: expected length: %d, got %d", 4+arrayLengthClassRangeRecords*6, L) + } + + item.ClassRangeRecords = make([]ClassRangeRecord, arrayLengthClassRangeRecords) // allocation guarded by the previous check + for i := range item.ClassRangeRecords { + item.ClassRangeRecords[i].mustParse(src[4+i*6:]) + } + n += arrayLengthClassRangeRecords * 6 + } + return item, n, nil +} + +func ParseCoverage(src []byte) (Coverage, int, error) { + var item Coverage + + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading Coverage: "+"EOF: expected length: 2, got %d", L) + } + format := uint16(binary.BigEndian.Uint16(src[0:])) + var ( + read int + err error + ) + switch format { + case 1: + item, read, err = ParseCoverage1(src[0:]) + case 2: + item, read, err = ParseCoverage2(src[0:]) + default: + err = fmt.Errorf("unsupported Coverage format %d", format) + } + if err != nil { + return item, 0, fmt.Errorf("reading Coverage: %s", err) + } + + return item, read, nil +} + +func ParseCoverage1(src []byte) (Coverage1, int, error) { + var item Coverage1 + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading Coverage1: "+"EOF: expected length: 4, got %d", L) + } + _ = src[3] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + arrayLengthGlyphs := int(binary.BigEndian.Uint16(src[2:])) + n += 4 + + { + + if L := len(src); L < 4+arrayLengthGlyphs*2 { + return item, 0, fmt.Errorf("reading Coverage1: "+"EOF: expected length: %d, got %d", 4+arrayLengthGlyphs*2, L) + } + + item.Glyphs = make([]uint16, arrayLengthGlyphs) // allocation guarded by the previous check + for i := range item.Glyphs { + item.Glyphs[i] = binary.BigEndian.Uint16(src[4+i*2:]) + } + n += arrayLengthGlyphs * 2 + } + return item, n, nil +} + +func ParseCoverage2(src []byte) (Coverage2, int, error) { + var item Coverage2 + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading Coverage2: "+"EOF: expected length: 4, got %d", L) + } + _ = src[3] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + arrayLengthRanges := int(binary.BigEndian.Uint16(src[2:])) + n += 4 + + { + + if L := len(src); L < 4+arrayLengthRanges*6 { + return item, 0, fmt.Errorf("reading Coverage2: "+"EOF: expected length: %d, got %d", 4+arrayLengthRanges*6, L) + } + + item.Ranges = make([]RangeRecord, arrayLengthRanges) // allocation guarded by the previous check + for i := range item.Ranges { + item.Ranges[i].mustParse(src[4+i*6:]) + } + n += arrayLengthRanges * 6 + } + return item, n, nil +} + +func ParseGDEF(src []byte) (GDEF, int, error) { + var item GDEF + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading GDEF: "+"EOF: expected length: 12, got %d", L) + } + _ = src[11] // early bound checking + item.majorVersion = binary.BigEndian.Uint16(src[0:]) + item.minorVersion = binary.BigEndian.Uint16(src[2:]) + offsetGlyphClassDef := int(binary.BigEndian.Uint16(src[4:])) + offsetAttachList := int(binary.BigEndian.Uint16(src[6:])) + offsetLigCaretList := int(binary.BigEndian.Uint16(src[8:])) + offsetMarkAttachClass := int(binary.BigEndian.Uint16(src[10:])) + n += 12 + + { + + if offsetGlyphClassDef != 0 { // ignore null offset + if L := len(src); L < offsetGlyphClassDef { + return item, 0, fmt.Errorf("reading GDEF: "+"EOF: expected length: %d, got %d", offsetGlyphClassDef, L) + } + + var ( + err error + read int + ) + item.GlyphClassDef, read, err = ParseClassDef(src[offsetGlyphClassDef:]) + if err != nil { + return item, 0, fmt.Errorf("reading GDEF: %s", err) + } + offsetGlyphClassDef += read + } + } + { + + if offsetAttachList != 0 { // ignore null offset + if L := len(src); L < offsetAttachList { + return item, 0, fmt.Errorf("reading GDEF: "+"EOF: expected length: %d, got %d", offsetAttachList, L) + } + + var err error + item.AttachList, _, err = ParseAttachList(src[offsetAttachList:]) + if err != nil { + return item, 0, fmt.Errorf("reading GDEF: %s", err) + } + + } + } + { + + if offsetLigCaretList != 0 { // ignore null offset + if L := len(src); L < offsetLigCaretList { + return item, 0, fmt.Errorf("reading GDEF: "+"EOF: expected length: %d, got %d", offsetLigCaretList, L) + } + + var err error + item.LigCaretList, _, err = ParseLigCaretList(src[offsetLigCaretList:]) + if err != nil { + return item, 0, fmt.Errorf("reading GDEF: %s", err) + } + + } + } + { + + if offsetMarkAttachClass != 0 { // ignore null offset + if L := len(src); L < offsetMarkAttachClass { + return item, 0, fmt.Errorf("reading GDEF: "+"EOF: expected length: %d, got %d", offsetMarkAttachClass, L) + } + + var ( + err error + read int + ) + item.MarkAttachClass, read, err = ParseClassDef(src[offsetMarkAttachClass:]) + if err != nil { + return item, 0, fmt.Errorf("reading GDEF: %s", err) + } + offsetMarkAttachClass += read + } + } + { + + err := item.parseMarkGlyphSetsDef(src[:]) + if err != nil { + return item, 0, fmt.Errorf("reading GDEF: %s", err) + } + } + { + + read, err := item.parseItemVarStore(src[:]) + if err != nil { + return item, 0, fmt.Errorf("reading GDEF: %s", err) + } + n = read + } + return item, n, nil +} + +func ParseLigCaretList(src []byte) (LigCaretList, int, error) { + var item LigCaretList + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading LigCaretList: "+"EOF: expected length: 4, got %d", L) + } + _ = src[3] // early bound checking + offsetCoverage := int(binary.BigEndian.Uint16(src[0:])) + arrayLengthLigGlyphs := int(binary.BigEndian.Uint16(src[2:])) + n += 4 + + { + + if offsetCoverage != 0 { // ignore null offset + if L := len(src); L < offsetCoverage { + return item, 0, fmt.Errorf("reading LigCaretList: "+"EOF: expected length: %d, got %d", offsetCoverage, L) + } + + var ( + err error + read int + ) + item.Coverage, read, err = ParseCoverage(src[offsetCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading LigCaretList: %s", err) + } + offsetCoverage += read + } + } + { + + if L := len(src); L < 4+arrayLengthLigGlyphs*2 { + return item, 0, fmt.Errorf("reading LigCaretList: "+"EOF: expected length: %d, got %d", 4+arrayLengthLigGlyphs*2, L) + } + + item.LigGlyphs = make([]LigGlyph, arrayLengthLigGlyphs) // allocation guarded by the previous check + for i := range item.LigGlyphs { + offset := int(binary.BigEndian.Uint16(src[4+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading LigCaretList: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.LigGlyphs[i], _, err = ParseLigGlyph(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading LigCaretList: %s", err) + } + } + n += arrayLengthLigGlyphs * 2 + } + return item, n, nil +} + +func ParseLigGlyph(src []byte) (LigGlyph, int, error) { + var item LigGlyph + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading LigGlyph: "+"EOF: expected length: 2, got %d", L) + } + arrayLengthCaretValues := int(binary.BigEndian.Uint16(src[0:])) + n += 2 + + { + + if L := len(src); L < 2+arrayLengthCaretValues*2 { + return item, 0, fmt.Errorf("reading LigGlyph: "+"EOF: expected length: %d, got %d", 2+arrayLengthCaretValues*2, L) + } + + item.CaretValues = make([]CaretValue, arrayLengthCaretValues) // allocation guarded by the previous check + for i := range item.CaretValues { + offset := int(binary.BigEndian.Uint16(src[2+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading LigGlyph: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.CaretValues[i], _, err = ParseCaretValue(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading LigGlyph: %s", err) + } + } + n += arrayLengthCaretValues * 2 + } + return item, n, nil +} + +func ParseMarkGlyphSets(src []byte) (MarkGlyphSets, int, error) { + var item MarkGlyphSets + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading MarkGlyphSets: "+"EOF: expected length: 4, got %d", L) + } + _ = src[3] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + arrayLengthCoverages := int(binary.BigEndian.Uint16(src[2:])) + n += 4 + + { + + if L := len(src); L < 4+arrayLengthCoverages*4 { + return item, 0, fmt.Errorf("reading MarkGlyphSets: "+"EOF: expected length: %d, got %d", 4+arrayLengthCoverages*4, L) + } + + item.Coverages = make([]Coverage, arrayLengthCoverages) // allocation guarded by the previous check + for i := range item.Coverages { + offset := int(binary.BigEndian.Uint32(src[4+i*4:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading MarkGlyphSets: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.Coverages[i], _, err = ParseCoverage(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading MarkGlyphSets: %s", err) + } + } + n += arrayLengthCoverages * 4 + } + return item, n, nil +} + +func (item *RangeRecord) mustParse(src []byte) { + _ = src[5] // early bound checking + item.StartGlyphID = binary.BigEndian.Uint16(src[0:]) + item.EndGlyphID = binary.BigEndian.Uint16(src[2:]) + item.StartCoverageIndex = binary.BigEndian.Uint16(src[4:]) +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_gdef_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_gdef_src.go new file mode 100644 index 0000000..8816b23 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_gdef_src.go @@ -0,0 +1,111 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +type GDEF struct { + majorVersion uint16 // Major version of the GDEF table, = 1 + minorVersion uint16 // Minor version of the GDEF table, = 0, 2, 3 + GlyphClassDef ClassDef `offsetSize:"Offset16"` // Offset to class definition table for glyph type, from beginning of GDEF header (may be NULL) + AttachList AttachList `offsetSize:"Offset16"` // Offset to attachment point list table, from beginning of GDEF header (may be NULL) + LigCaretList LigCaretList `offsetSize:"Offset16"` // Offset to ligature caret list table, from beginning of GDEF header (may be NULL) + MarkAttachClass ClassDef `offsetSize:"Offset16"` // Offset to class definition table for mark attachment type, from beginning of GDEF header (may be NULL) + + MarkGlyphSetsDef MarkGlyphSets `isOpaque:""` // Offset to the table of mark glyph set definitions, from beginning of GDEF header (may be NULL) + ItemVarStore ItemVarStore `isOpaque:""` // Offset to the Item Variation Store table, from beginning of GDEF header (may be NULL) +} + +func (gdef *GDEF) parseMarkGlyphSetsDef(src []byte) error { + const headerSize = 12 + if gdef.minorVersion < 2 { + return nil + } + if L := len(src); L < headerSize+2 { + return fmt.Errorf("EOF: expected length: %d, got %d", headerSize+2, L) + } + offset := binary.BigEndian.Uint16(src[headerSize:]) + if offset != 0 { + var err error + gdef.MarkGlyphSetsDef, _, err = ParseMarkGlyphSets(src[offset:]) + if err != nil { + return err + } + } + return nil +} + +func (gdef *GDEF) parseItemVarStore(src []byte) (int, error) { + const headerSize = 12 + 2 + if gdef.minorVersion < 3 { + return 0, nil + } + if L := len(src); L < headerSize+4 { + return 0, fmt.Errorf("EOF: expected length: %d, got %d", headerSize+4, L) + } + offset := binary.BigEndian.Uint32(src[headerSize:]) + if offset != 0 { + var err error + gdef.ItemVarStore, _, err = ParseItemVarStore(src[offset:]) + if err != nil { + return 0, err + } + } + return headerSize + 4, nil +} + +type AttachList struct { + Coverage Coverage `offsetSize:"Offset16"` // Offset to Coverage table - from beginning of AttachList table + AttachPoints []AttachPoint `arrayCount:"FirstUint16" offsetsArray:"Offset16"` // [glyphCount] Array of offsets to AttachPoint tables-from beginning of AttachList table-in Coverage Index order +} + +type AttachPoint struct { + PointIndices []uint16 `arrayCount:"FirstUint16"` // [pointCount] Array of contour point indices -in increasing numerical order +} + +type LigCaretList struct { + Coverage Coverage `offsetSize:"Offset16"` // Offset to Coverage table - from beginning of LigCaretList table + LigGlyphs []LigGlyph `arrayCount:"FirstUint16" offsetsArray:"Offset16"` // [ligGlyphCount] Array of offsets to LigGlyph tables, from beginning of LigCaretList table —in Coverage Index order +} + +type LigGlyph struct { + CaretValues []CaretValue `arrayCount:"FirstUint16" offsetsArray:"Offset16"` // [caretCount] Array of offsets to CaretValue tables, from beginning of LigGlyph table — in increasing coordinate order +} + +type CaretValue interface { + isCaretValue() +} + +func (CaretValue1) isCaretValue() {} +func (CaretValue2) isCaretValue() {} +func (CaretValue3) isCaretValue() {} + +type CaretValue1 struct { + caretValueFormat uint16 `unionTag:"1"` // Format identifier: format = 1 + Coordinate int16 // X or Y value, in design units +} + +type CaretValue2 struct { + caretValueFormat uint16 `unionTag:"2"` // Format identifier: format = 2 + CaretValuePointIndex uint16 // Contour point index on glyph +} + +type CaretValue3 struct { + caretValueFormat uint16 `unionTag:"3"` // Format identifier: format = 3 + Coordinate int16 // X or Y value, in design units + deviceOffset Offset16 // Offset to Device table (non-variable font) / Variation Index table (variable font) for X or Y value-from beginning of CaretValue table + Device DeviceTable `isOpaque:""` +} + +func (cv *CaretValue3) parseDevice(src []byte) (err error) { + cv.Device, err = parseDeviceTable(src, uint16(cv.deviceOffset)) + return err +} + +type MarkGlyphSets struct { + format uint16 // Format identifier == 1 + Coverages []Coverage `arrayCount:"FirstUint16" offsetsArray:"Offset32"` // [markGlyphSetCount] Array of offsets to mark glyph set coverage tables, from the start of the MarkGlyphSets table. +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_gpos_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_gpos_gen.go new file mode 100644 index 0000000..9d56a00 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_gpos_gen.go @@ -0,0 +1,1772 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +//lint:file-ignore SA4006 The code generator is not smart enough to remove unused variables. + +// Code generated by binarygen from ot_gpos_src.go. DO NOT EDIT + +func (item *AnchorFormat1) mustParse(src []byte) { + _ = src[5] // early bound checking + item.anchorFormat = binary.BigEndian.Uint16(src[0:]) + item.XCoordinate = int16(binary.BigEndian.Uint16(src[2:])) + item.YCoordinate = int16(binary.BigEndian.Uint16(src[4:])) +} + +func (item *AnchorFormat2) mustParse(src []byte) { + _ = src[7] // early bound checking + item.anchorFormat = binary.BigEndian.Uint16(src[0:]) + item.XCoordinate = int16(binary.BigEndian.Uint16(src[2:])) + item.YCoordinate = int16(binary.BigEndian.Uint16(src[4:])) + item.AnchorPoint = binary.BigEndian.Uint16(src[6:]) +} + +func (item *DeviceTableHeader) mustParse(src []byte) { + _ = src[5] // early bound checking + item.first = binary.BigEndian.Uint16(src[0:]) + item.second = binary.BigEndian.Uint16(src[2:]) + item.deltaFormat = binary.BigEndian.Uint16(src[4:]) +} + +func (item *MarkRecord) mustParse(src []byte) { + _ = src[3] // early bound checking + item.MarkClass = binary.BigEndian.Uint16(src[0:]) + item.markAnchorOffset = Offset16(binary.BigEndian.Uint16(src[2:])) +} + +func ParseAnchor(src []byte) (Anchor, int, error) { + var item Anchor + + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading Anchor: "+"EOF: expected length: 2, got %d", L) + } + format := uint16(binary.BigEndian.Uint16(src[0:])) + var ( + read int + err error + ) + switch format { + case 1: + item, read, err = ParseAnchorFormat1(src[0:]) + case 2: + item, read, err = ParseAnchorFormat2(src[0:]) + case 3: + item, read, err = ParseAnchorFormat3(src[0:]) + default: + err = fmt.Errorf("unsupported Anchor format %d", format) + } + if err != nil { + return item, 0, fmt.Errorf("reading Anchor: %s", err) + } + + return item, read, nil +} + +func ParseAnchorFormat1(src []byte) (AnchorFormat1, int, error) { + var item AnchorFormat1 + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading AnchorFormat1: "+"EOF: expected length: 6, got %d", L) + } + item.mustParse(src) + n += 6 + return item, n, nil +} + +func ParseAnchorFormat2(src []byte) (AnchorFormat2, int, error) { + var item AnchorFormat2 + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading AnchorFormat2: "+"EOF: expected length: 8, got %d", L) + } + item.mustParse(src) + n += 8 + return item, n, nil +} + +func ParseAnchorFormat3(src []byte) (AnchorFormat3, int, error) { + var item AnchorFormat3 + n := 0 + if L := len(src); L < 10 { + return item, 0, fmt.Errorf("reading AnchorFormat3: "+"EOF: expected length: 10, got %d", L) + } + _ = src[9] // early bound checking + item.anchorFormat = binary.BigEndian.Uint16(src[0:]) + item.XCoordinate = int16(binary.BigEndian.Uint16(src[2:])) + item.YCoordinate = int16(binary.BigEndian.Uint16(src[4:])) + item.xDeviceOffset = Offset16(binary.BigEndian.Uint16(src[6:])) + item.yDeviceOffset = Offset16(binary.BigEndian.Uint16(src[8:])) + n += 10 + + { + + err := item.parseXDevice(src[:]) + if err != nil { + return item, 0, fmt.Errorf("reading AnchorFormat3: %s", err) + } + } + { + + err := item.parseYDevice(src[:]) + if err != nil { + return item, 0, fmt.Errorf("reading AnchorFormat3: %s", err) + } + } + return item, n, nil +} + +func ParseBaseArray(src []byte, offsetsCount int) (BaseArray, int, error) { + var item BaseArray + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading BaseArray: "+"EOF: expected length: 2, got %d", L) + } + arrayLengthBaseRecords := int(binary.BigEndian.Uint16(src[0:])) + n += 2 + + { + + offset := 2 + for i := 0; i < arrayLengthBaseRecords; i++ { + elem, read, err := parseAnchorOffsets(src[offset:], offsetsCount) + if err != nil { + return item, 0, fmt.Errorf("reading BaseArray: %s", err) + } + item.baseRecords = append(item.baseRecords, elem) + offset += read + } + n = offset + } + { + + item.data = src[0:] + n = len(src) + } + return item, n, nil +} + +func ParseChainedContextualPos(src []byte) (ChainedContextualPos, int, error) { + var item ChainedContextualPos + n := 0 + { + var ( + err error + read int + ) + item.Data, read, err = ParseChainedContextualPosITF(src[0:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualPos: %s", err) + } + n += read + } + return item, n, nil +} + +func ParseChainedContextualPos1(src []byte) (ChainedContextualPos1, int, error) { + var item ChainedContextualPos1 + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading ChainedContextualPos1: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + offsetCoverage := int(binary.BigEndian.Uint16(src[2:])) + arrayLengthChainedSeqRuleSet := int(binary.BigEndian.Uint16(src[4:])) + n += 6 + + { + + if offsetCoverage != 0 { // ignore null offset + if L := len(src); L < offsetCoverage { + return item, 0, fmt.Errorf("reading ChainedContextualPos1: "+"EOF: expected length: %d, got %d", offsetCoverage, L) + } + + var ( + err error + read int + ) + item.coverage, read, err = ParseCoverage(src[offsetCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualPos1: %s", err) + } + offsetCoverage += read + } + } + { + + if L := len(src); L < 6+arrayLengthChainedSeqRuleSet*2 { + return item, 0, fmt.Errorf("reading ChainedContextualPos1: "+"EOF: expected length: %d, got %d", 6+arrayLengthChainedSeqRuleSet*2, L) + } + + item.ChainedSeqRuleSet = make([]ChainedSequenceRuleSet, arrayLengthChainedSeqRuleSet) // allocation guarded by the previous check + for i := range item.ChainedSeqRuleSet { + offset := int(binary.BigEndian.Uint16(src[6+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading ChainedContextualPos1: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.ChainedSeqRuleSet[i], _, err = ParseChainedSequenceRuleSet(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualPos1: %s", err) + } + } + n += arrayLengthChainedSeqRuleSet * 2 + } + return item, n, nil +} + +func ParseChainedContextualPos2(src []byte) (ChainedContextualPos2, int, error) { + var item ChainedContextualPos2 + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading ChainedContextualPos2: "+"EOF: expected length: 12, got %d", L) + } + _ = src[11] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + offsetCoverage := int(binary.BigEndian.Uint16(src[2:])) + offsetBacktrackClassDef := int(binary.BigEndian.Uint16(src[4:])) + offsetInputClassDef := int(binary.BigEndian.Uint16(src[6:])) + offsetLookaheadClassDef := int(binary.BigEndian.Uint16(src[8:])) + arrayLengthChainedClassSeqRuleSet := int(binary.BigEndian.Uint16(src[10:])) + n += 12 + + { + + if offsetCoverage != 0 { // ignore null offset + if L := len(src); L < offsetCoverage { + return item, 0, fmt.Errorf("reading ChainedContextualPos2: "+"EOF: expected length: %d, got %d", offsetCoverage, L) + } + + var ( + err error + read int + ) + item.coverage, read, err = ParseCoverage(src[offsetCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualPos2: %s", err) + } + offsetCoverage += read + } + } + { + + if offsetBacktrackClassDef != 0 { // ignore null offset + if L := len(src); L < offsetBacktrackClassDef { + return item, 0, fmt.Errorf("reading ChainedContextualPos2: "+"EOF: expected length: %d, got %d", offsetBacktrackClassDef, L) + } + + var ( + err error + read int + ) + item.BacktrackClassDef, read, err = ParseClassDef(src[offsetBacktrackClassDef:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualPos2: %s", err) + } + offsetBacktrackClassDef += read + } + } + { + + if offsetInputClassDef != 0 { // ignore null offset + if L := len(src); L < offsetInputClassDef { + return item, 0, fmt.Errorf("reading ChainedContextualPos2: "+"EOF: expected length: %d, got %d", offsetInputClassDef, L) + } + + var ( + err error + read int + ) + item.InputClassDef, read, err = ParseClassDef(src[offsetInputClassDef:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualPos2: %s", err) + } + offsetInputClassDef += read + } + } + { + + if offsetLookaheadClassDef != 0 { // ignore null offset + if L := len(src); L < offsetLookaheadClassDef { + return item, 0, fmt.Errorf("reading ChainedContextualPos2: "+"EOF: expected length: %d, got %d", offsetLookaheadClassDef, L) + } + + var ( + err error + read int + ) + item.LookaheadClassDef, read, err = ParseClassDef(src[offsetLookaheadClassDef:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualPos2: %s", err) + } + offsetLookaheadClassDef += read + } + } + { + + if L := len(src); L < 12+arrayLengthChainedClassSeqRuleSet*2 { + return item, 0, fmt.Errorf("reading ChainedContextualPos2: "+"EOF: expected length: %d, got %d", 12+arrayLengthChainedClassSeqRuleSet*2, L) + } + + item.ChainedClassSeqRuleSet = make([]ChainedSequenceRuleSet, arrayLengthChainedClassSeqRuleSet) // allocation guarded by the previous check + for i := range item.ChainedClassSeqRuleSet { + offset := int(binary.BigEndian.Uint16(src[12+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading ChainedContextualPos2: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.ChainedClassSeqRuleSet[i], _, err = ParseChainedSequenceRuleSet(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualPos2: %s", err) + } + } + n += arrayLengthChainedClassSeqRuleSet * 2 + } + return item, n, nil +} + +func ParseChainedContextualPos3(src []byte) (ChainedContextualPos3, int, error) { + var item ChainedContextualPos3 + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading ChainedContextualPos3: "+"EOF: expected length: 4, got %d", L) + } + _ = src[3] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + arrayLengthBacktrackCoverages := int(binary.BigEndian.Uint16(src[2:])) + n += 4 + + { + + if L := len(src); L < 4+arrayLengthBacktrackCoverages*2 { + return item, 0, fmt.Errorf("reading ChainedContextualPos3: "+"EOF: expected length: %d, got %d", 4+arrayLengthBacktrackCoverages*2, L) + } + + item.BacktrackCoverages = make([]Coverage, arrayLengthBacktrackCoverages) // allocation guarded by the previous check + for i := range item.BacktrackCoverages { + offset := int(binary.BigEndian.Uint16(src[4+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading ChainedContextualPos3: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.BacktrackCoverages[i], _, err = ParseCoverage(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualPos3: %s", err) + } + } + n += arrayLengthBacktrackCoverages * 2 + } + if L := len(src); L < n+2 { + return item, 0, fmt.Errorf("reading ChainedContextualPos3: "+"EOF: expected length: n + 2, got %d", L) + } + arrayLengthInputCoverages := int(binary.BigEndian.Uint16(src[n:])) + n += 2 + + { + + if L := len(src); L < n+arrayLengthInputCoverages*2 { + return item, 0, fmt.Errorf("reading ChainedContextualPos3: "+"EOF: expected length: %d, got %d", n+arrayLengthInputCoverages*2, L) + } + + item.InputCoverages = make([]Coverage, arrayLengthInputCoverages) // allocation guarded by the previous check + for i := range item.InputCoverages { + offset := int(binary.BigEndian.Uint16(src[n+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading ChainedContextualPos3: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.InputCoverages[i], _, err = ParseCoverage(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualPos3: %s", err) + } + } + n += arrayLengthInputCoverages * 2 + } + if L := len(src); L < n+2 { + return item, 0, fmt.Errorf("reading ChainedContextualPos3: "+"EOF: expected length: n + 2, got %d", L) + } + arrayLengthLookaheadCoverages := int(binary.BigEndian.Uint16(src[n:])) + n += 2 + + { + + if L := len(src); L < n+arrayLengthLookaheadCoverages*2 { + return item, 0, fmt.Errorf("reading ChainedContextualPos3: "+"EOF: expected length: %d, got %d", n+arrayLengthLookaheadCoverages*2, L) + } + + item.LookaheadCoverages = make([]Coverage, arrayLengthLookaheadCoverages) // allocation guarded by the previous check + for i := range item.LookaheadCoverages { + offset := int(binary.BigEndian.Uint16(src[n+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading ChainedContextualPos3: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.LookaheadCoverages[i], _, err = ParseCoverage(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualPos3: %s", err) + } + } + n += arrayLengthLookaheadCoverages * 2 + } + if L := len(src); L < n+2 { + return item, 0, fmt.Errorf("reading ChainedContextualPos3: "+"EOF: expected length: n + 2, got %d", L) + } + arrayLengthSeqLookupRecords := int(binary.BigEndian.Uint16(src[n:])) + n += 2 + + { + + if L := len(src); L < n+arrayLengthSeqLookupRecords*4 { + return item, 0, fmt.Errorf("reading ChainedContextualPos3: "+"EOF: expected length: %d, got %d", n+arrayLengthSeqLookupRecords*4, L) + } + + item.SeqLookupRecords = make([]SequenceLookupRecord, arrayLengthSeqLookupRecords) // allocation guarded by the previous check + for i := range item.SeqLookupRecords { + item.SeqLookupRecords[i].mustParse(src[n+i*4:]) + } + n += arrayLengthSeqLookupRecords * 4 + } + return item, n, nil +} + +func ParseChainedContextualPosITF(src []byte) (ChainedContextualPosITF, int, error) { + var item ChainedContextualPosITF + + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading ChainedContextualPosITF: "+"EOF: expected length: 2, got %d", L) + } + format := uint16(binary.BigEndian.Uint16(src[0:])) + var ( + read int + err error + ) + switch format { + case 1: + item, read, err = ParseChainedContextualPos1(src[0:]) + case 2: + item, read, err = ParseChainedContextualPos2(src[0:]) + case 3: + item, read, err = ParseChainedContextualPos3(src[0:]) + default: + err = fmt.Errorf("unsupported ChainedContextualPosITF format %d", format) + } + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualPosITF: %s", err) + } + + return item, read, nil +} + +func ParseChainedSequenceRule(src []byte) (ChainedSequenceRule, int, error) { + var item ChainedSequenceRule + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading ChainedSequenceRule: "+"EOF: expected length: 2, got %d", L) + } + arrayLengthBacktrackSequence := int(binary.BigEndian.Uint16(src[0:])) + n += 2 + + { + + if L := len(src); L < 2+arrayLengthBacktrackSequence*2 { + return item, 0, fmt.Errorf("reading ChainedSequenceRule: "+"EOF: expected length: %d, got %d", 2+arrayLengthBacktrackSequence*2, L) + } + + item.BacktrackSequence = make([]uint16, arrayLengthBacktrackSequence) // allocation guarded by the previous check + for i := range item.BacktrackSequence { + item.BacktrackSequence[i] = binary.BigEndian.Uint16(src[2+i*2:]) + } + n += arrayLengthBacktrackSequence * 2 + } + if L := len(src); L < n+2 { + return item, 0, fmt.Errorf("reading ChainedSequenceRule: "+"EOF: expected length: n + 2, got %d", L) + } + item.inputGlyphCount = binary.BigEndian.Uint16(src[n:]) + n += 2 + + { + arrayLength := int(item.inputGlyphCount - 1) + + if L := len(src); L < n+arrayLength*2 { + return item, 0, fmt.Errorf("reading ChainedSequenceRule: "+"EOF: expected length: %d, got %d", n+arrayLength*2, L) + } + + item.InputSequence = make([]uint16, arrayLength) // allocation guarded by the previous check + for i := range item.InputSequence { + item.InputSequence[i] = binary.BigEndian.Uint16(src[n+i*2:]) + } + n += arrayLength * 2 + } + if L := len(src); L < n+2 { + return item, 0, fmt.Errorf("reading ChainedSequenceRule: "+"EOF: expected length: n + 2, got %d", L) + } + arrayLengthLookaheadSequence := int(binary.BigEndian.Uint16(src[n:])) + n += 2 + + { + + if L := len(src); L < n+arrayLengthLookaheadSequence*2 { + return item, 0, fmt.Errorf("reading ChainedSequenceRule: "+"EOF: expected length: %d, got %d", n+arrayLengthLookaheadSequence*2, L) + } + + item.LookaheadSequence = make([]uint16, arrayLengthLookaheadSequence) // allocation guarded by the previous check + for i := range item.LookaheadSequence { + item.LookaheadSequence[i] = binary.BigEndian.Uint16(src[n+i*2:]) + } + n += arrayLengthLookaheadSequence * 2 + } + if L := len(src); L < n+2 { + return item, 0, fmt.Errorf("reading ChainedSequenceRule: "+"EOF: expected length: n + 2, got %d", L) + } + arrayLengthSeqLookupRecords := int(binary.BigEndian.Uint16(src[n:])) + n += 2 + + { + + if L := len(src); L < n+arrayLengthSeqLookupRecords*4 { + return item, 0, fmt.Errorf("reading ChainedSequenceRule: "+"EOF: expected length: %d, got %d", n+arrayLengthSeqLookupRecords*4, L) + } + + item.SeqLookupRecords = make([]SequenceLookupRecord, arrayLengthSeqLookupRecords) // allocation guarded by the previous check + for i := range item.SeqLookupRecords { + item.SeqLookupRecords[i].mustParse(src[n+i*4:]) + } + n += arrayLengthSeqLookupRecords * 4 + } + return item, n, nil +} + +func ParseChainedSequenceRuleSet(src []byte) (ChainedSequenceRuleSet, int, error) { + var item ChainedSequenceRuleSet + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading ChainedSequenceRuleSet: "+"EOF: expected length: 2, got %d", L) + } + arrayLengthChainedSeqRules := int(binary.BigEndian.Uint16(src[0:])) + n += 2 + + { + + if L := len(src); L < 2+arrayLengthChainedSeqRules*2 { + return item, 0, fmt.Errorf("reading ChainedSequenceRuleSet: "+"EOF: expected length: %d, got %d", 2+arrayLengthChainedSeqRules*2, L) + } + + item.ChainedSeqRules = make([]ChainedSequenceRule, arrayLengthChainedSeqRules) // allocation guarded by the previous check + for i := range item.ChainedSeqRules { + offset := int(binary.BigEndian.Uint16(src[2+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading ChainedSequenceRuleSet: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.ChainedSeqRules[i], _, err = ParseChainedSequenceRule(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedSequenceRuleSet: %s", err) + } + } + n += arrayLengthChainedSeqRules * 2 + } + return item, n, nil +} + +func ParseContextualPos(src []byte) (ContextualPos, int, error) { + var item ContextualPos + n := 0 + { + var ( + err error + read int + ) + item.Data, read, err = ParseContextualPosITF(src[0:]) + if err != nil { + return item, 0, fmt.Errorf("reading ContextualPos: %s", err) + } + n += read + } + return item, n, nil +} + +func ParseContextualPos1(src []byte) (ContextualPos1, int, error) { + var item ContextualPos1 + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading ContextualPos1: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + offsetCoverage := int(binary.BigEndian.Uint16(src[2:])) + arrayLengthSeqRuleSet := int(binary.BigEndian.Uint16(src[4:])) + n += 6 + + { + + if offsetCoverage != 0 { // ignore null offset + if L := len(src); L < offsetCoverage { + return item, 0, fmt.Errorf("reading ContextualPos1: "+"EOF: expected length: %d, got %d", offsetCoverage, L) + } + + var ( + err error + read int + ) + item.coverage, read, err = ParseCoverage(src[offsetCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading ContextualPos1: %s", err) + } + offsetCoverage += read + } + } + { + + if L := len(src); L < 6+arrayLengthSeqRuleSet*2 { + return item, 0, fmt.Errorf("reading ContextualPos1: "+"EOF: expected length: %d, got %d", 6+arrayLengthSeqRuleSet*2, L) + } + + item.SeqRuleSet = make([]SequenceRuleSet, arrayLengthSeqRuleSet) // allocation guarded by the previous check + for i := range item.SeqRuleSet { + offset := int(binary.BigEndian.Uint16(src[6+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading ContextualPos1: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.SeqRuleSet[i], _, err = ParseSequenceRuleSet(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading ContextualPos1: %s", err) + } + } + n += arrayLengthSeqRuleSet * 2 + } + return item, n, nil +} + +func ParseContextualPos2(src []byte) (ContextualPos2, int, error) { + var item ContextualPos2 + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading ContextualPos2: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + offsetCoverage := int(binary.BigEndian.Uint16(src[2:])) + offsetClassDef := int(binary.BigEndian.Uint16(src[4:])) + arrayLengthClassSeqRuleSet := int(binary.BigEndian.Uint16(src[6:])) + n += 8 + + { + + if offsetCoverage != 0 { // ignore null offset + if L := len(src); L < offsetCoverage { + return item, 0, fmt.Errorf("reading ContextualPos2: "+"EOF: expected length: %d, got %d", offsetCoverage, L) + } + + var ( + err error + read int + ) + item.coverage, read, err = ParseCoverage(src[offsetCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading ContextualPos2: %s", err) + } + offsetCoverage += read + } + } + { + + if offsetClassDef != 0 { // ignore null offset + if L := len(src); L < offsetClassDef { + return item, 0, fmt.Errorf("reading ContextualPos2: "+"EOF: expected length: %d, got %d", offsetClassDef, L) + } + + var ( + err error + read int + ) + item.ClassDef, read, err = ParseClassDef(src[offsetClassDef:]) + if err != nil { + return item, 0, fmt.Errorf("reading ContextualPos2: %s", err) + } + offsetClassDef += read + } + } + { + + if L := len(src); L < 8+arrayLengthClassSeqRuleSet*2 { + return item, 0, fmt.Errorf("reading ContextualPos2: "+"EOF: expected length: %d, got %d", 8+arrayLengthClassSeqRuleSet*2, L) + } + + item.ClassSeqRuleSet = make([]SequenceRuleSet, arrayLengthClassSeqRuleSet) // allocation guarded by the previous check + for i := range item.ClassSeqRuleSet { + offset := int(binary.BigEndian.Uint16(src[8+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading ContextualPos2: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.ClassSeqRuleSet[i], _, err = ParseSequenceRuleSet(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading ContextualPos2: %s", err) + } + } + n += arrayLengthClassSeqRuleSet * 2 + } + return item, n, nil +} + +func ParseContextualPos3(src []byte) (ContextualPos3, int, error) { + var item ContextualPos3 + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading ContextualPos3: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + item.glyphCount = binary.BigEndian.Uint16(src[2:]) + item.seqLookupCount = binary.BigEndian.Uint16(src[4:]) + n += 6 + + { + arrayLength := int(item.glyphCount) + + if L := len(src); L < 6+arrayLength*2 { + return item, 0, fmt.Errorf("reading ContextualPos3: "+"EOF: expected length: %d, got %d", 6+arrayLength*2, L) + } + + item.Coverages = make([]Coverage, arrayLength) // allocation guarded by the previous check + for i := range item.Coverages { + offset := int(binary.BigEndian.Uint16(src[6+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading ContextualPos3: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.Coverages[i], _, err = ParseCoverage(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading ContextualPos3: %s", err) + } + } + n += arrayLength * 2 + } + { + arrayLength := int(item.seqLookupCount) + + if L := len(src); L < n+arrayLength*4 { + return item, 0, fmt.Errorf("reading ContextualPos3: "+"EOF: expected length: %d, got %d", n+arrayLength*4, L) + } + + item.SeqLookupRecords = make([]SequenceLookupRecord, arrayLength) // allocation guarded by the previous check + for i := range item.SeqLookupRecords { + item.SeqLookupRecords[i].mustParse(src[n+i*4:]) + } + n += arrayLength * 4 + } + return item, n, nil +} + +func ParseContextualPosITF(src []byte) (ContextualPosITF, int, error) { + var item ContextualPosITF + + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading ContextualPosITF: "+"EOF: expected length: 2, got %d", L) + } + format := uint16(binary.BigEndian.Uint16(src[0:])) + var ( + read int + err error + ) + switch format { + case 1: + item, read, err = ParseContextualPos1(src[0:]) + case 2: + item, read, err = ParseContextualPos2(src[0:]) + case 3: + item, read, err = ParseContextualPos3(src[0:]) + default: + err = fmt.Errorf("unsupported ContextualPosITF format %d", format) + } + if err != nil { + return item, 0, fmt.Errorf("reading ContextualPosITF: %s", err) + } + + return item, read, nil +} + +func ParseCursivePos(src []byte) (CursivePos, int, error) { + var item CursivePos + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading CursivePos: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.posFormat = binary.BigEndian.Uint16(src[0:]) + offsetCoverage := int(binary.BigEndian.Uint16(src[2:])) + arrayLengthEntryExitRecords := int(binary.BigEndian.Uint16(src[4:])) + n += 6 + + { + + if offsetCoverage != 0 { // ignore null offset + if L := len(src); L < offsetCoverage { + return item, 0, fmt.Errorf("reading CursivePos: "+"EOF: expected length: %d, got %d", offsetCoverage, L) + } + + var ( + err error + read int + ) + item.coverage, read, err = ParseCoverage(src[offsetCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading CursivePos: %s", err) + } + offsetCoverage += read + } + } + { + + if L := len(src); L < 6+arrayLengthEntryExitRecords*4 { + return item, 0, fmt.Errorf("reading CursivePos: "+"EOF: expected length: %d, got %d", 6+arrayLengthEntryExitRecords*4, L) + } + + item.entryExitRecords = make([]entryExitRecord, arrayLengthEntryExitRecords) // allocation guarded by the previous check + for i := range item.entryExitRecords { + item.entryExitRecords[i].mustParse(src[6+i*4:]) + } + n += arrayLengthEntryExitRecords * 4 + } + { + + err := item.parseEntryExits(src[:]) + if err != nil { + return item, 0, fmt.Errorf("reading CursivePos: %s", err) + } + } + return item, n, nil +} + +func ParseDeviceTableHeader(src []byte) (DeviceTableHeader, int, error) { + var item DeviceTableHeader + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading DeviceTableHeader: "+"EOF: expected length: 6, got %d", L) + } + item.mustParse(src) + n += 6 + return item, n, nil +} + +func ParseEntryExit(src []byte) (EntryExit, int, error) { + var item EntryExit + n := 0 + { + var ( + err error + read int + ) + item.EntryAnchor, read, err = ParseAnchor(src[0:]) + if err != nil { + return item, 0, fmt.Errorf("reading EntryExit: %s", err) + } + n += read + } + { + var ( + err error + read int + ) + item.ExitAnchor, read, err = ParseAnchor(src[n:]) + if err != nil { + return item, 0, fmt.Errorf("reading EntryExit: %s", err) + } + n += read + } + return item, n, nil +} + +func ParseExtensionPos(src []byte) (ExtensionPos, int, error) { + var item ExtensionPos + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading ExtensionPos: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.substFormat = binary.BigEndian.Uint16(src[0:]) + item.ExtensionLookupType = binary.BigEndian.Uint16(src[2:]) + item.ExtensionOffset = Offset32(binary.BigEndian.Uint32(src[4:])) + n += 8 + + { + + item.RawData = src[0:] + n = len(src) + } + return item, n, nil +} + +func ParseLigatureArray(src []byte, offsetsCount int) (LigatureArray, int, error) { + var item LigatureArray + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading LigatureArray: "+"EOF: expected length: 2, got %d", L) + } + arrayLengthLigatureAttachs := int(binary.BigEndian.Uint16(src[0:])) + n += 2 + + { + + if L := len(src); L < 2+arrayLengthLigatureAttachs*2 { + return item, 0, fmt.Errorf("reading LigatureArray: "+"EOF: expected length: %d, got %d", 2+arrayLengthLigatureAttachs*2, L) + } + + item.LigatureAttachs = make([]LigatureAttach, arrayLengthLigatureAttachs) // allocation guarded by the previous check + for i := range item.LigatureAttachs { + offset := int(binary.BigEndian.Uint16(src[2+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading LigatureArray: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.LigatureAttachs[i], _, err = ParseLigatureAttach(src[offset:], offsetsCount) + if err != nil { + return item, 0, fmt.Errorf("reading LigatureArray: %s", err) + } + } + n += arrayLengthLigatureAttachs * 2 + } + return item, n, nil +} + +func ParseLigatureAttach(src []byte, offsetsCount int) (LigatureAttach, int, error) { + var item LigatureAttach + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading LigatureAttach: "+"EOF: expected length: 2, got %d", L) + } + arrayLengthComponentRecords := int(binary.BigEndian.Uint16(src[0:])) + n += 2 + + { + + offset := 2 + for i := 0; i < arrayLengthComponentRecords; i++ { + elem, read, err := parseAnchorOffsets(src[offset:], offsetsCount) + if err != nil { + return item, 0, fmt.Errorf("reading LigatureAttach: %s", err) + } + item.componentRecords = append(item.componentRecords, elem) + offset += read + } + n = offset + } + { + + item.data = src[0:] + n = len(src) + } + return item, n, nil +} + +func ParseMark2Array(src []byte, offsetsCount int) (Mark2Array, int, error) { + var item Mark2Array + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading Mark2Array: "+"EOF: expected length: 2, got %d", L) + } + arrayLengthMark2Records := int(binary.BigEndian.Uint16(src[0:])) + n += 2 + + { + + offset := 2 + for i := 0; i < arrayLengthMark2Records; i++ { + elem, read, err := parseAnchorOffsets(src[offset:], offsetsCount) + if err != nil { + return item, 0, fmt.Errorf("reading Mark2Array: %s", err) + } + item.mark2Records = append(item.mark2Records, elem) + offset += read + } + n = offset + } + { + + item.data = src[0:] + n = len(src) + } + return item, n, nil +} + +func ParseMarkArray(src []byte) (MarkArray, int, error) { + var item MarkArray + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading MarkArray: "+"EOF: expected length: 2, got %d", L) + } + arrayLengthMarkRecords := int(binary.BigEndian.Uint16(src[0:])) + n += 2 + + { + + if L := len(src); L < 2+arrayLengthMarkRecords*4 { + return item, 0, fmt.Errorf("reading MarkArray: "+"EOF: expected length: %d, got %d", 2+arrayLengthMarkRecords*4, L) + } + + item.MarkRecords = make([]MarkRecord, arrayLengthMarkRecords) // allocation guarded by the previous check + for i := range item.MarkRecords { + item.MarkRecords[i].mustParse(src[2+i*4:]) + } + n += arrayLengthMarkRecords * 4 + } + { + + err := item.parseMarkAnchors(src[:]) + if err != nil { + return item, 0, fmt.Errorf("reading MarkArray: %s", err) + } + } + return item, n, nil +} + +func ParseMarkBasePos(src []byte) (MarkBasePos, int, error) { + var item MarkBasePos + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading MarkBasePos: "+"EOF: expected length: 12, got %d", L) + } + _ = src[11] // early bound checking + item.posFormat = binary.BigEndian.Uint16(src[0:]) + offsetMarkCoverage := int(binary.BigEndian.Uint16(src[2:])) + offsetBaseCoverage := int(binary.BigEndian.Uint16(src[4:])) + item.markClassCount = binary.BigEndian.Uint16(src[6:]) + offsetMarkArray := int(binary.BigEndian.Uint16(src[8:])) + offsetBaseArray := int(binary.BigEndian.Uint16(src[10:])) + n += 12 + + { + + if offsetMarkCoverage != 0 { // ignore null offset + if L := len(src); L < offsetMarkCoverage { + return item, 0, fmt.Errorf("reading MarkBasePos: "+"EOF: expected length: %d, got %d", offsetMarkCoverage, L) + } + + var ( + err error + read int + ) + item.markCoverage, read, err = ParseCoverage(src[offsetMarkCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading MarkBasePos: %s", err) + } + offsetMarkCoverage += read + } + } + { + + if offsetBaseCoverage != 0 { // ignore null offset + if L := len(src); L < offsetBaseCoverage { + return item, 0, fmt.Errorf("reading MarkBasePos: "+"EOF: expected length: %d, got %d", offsetBaseCoverage, L) + } + + var ( + err error + read int + ) + item.BaseCoverage, read, err = ParseCoverage(src[offsetBaseCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading MarkBasePos: %s", err) + } + offsetBaseCoverage += read + } + } + { + + if offsetMarkArray != 0 { // ignore null offset + if L := len(src); L < offsetMarkArray { + return item, 0, fmt.Errorf("reading MarkBasePos: "+"EOF: expected length: %d, got %d", offsetMarkArray, L) + } + + var err error + item.MarkArray, _, err = ParseMarkArray(src[offsetMarkArray:]) + if err != nil { + return item, 0, fmt.Errorf("reading MarkBasePos: %s", err) + } + + } + } + { + + if offsetBaseArray != 0 { // ignore null offset + if L := len(src); L < offsetBaseArray { + return item, 0, fmt.Errorf("reading MarkBasePos: "+"EOF: expected length: %d, got %d", offsetBaseArray, L) + } + + var err error + item.BaseArray, _, err = ParseBaseArray(src[offsetBaseArray:], int(item.markClassCount)) + if err != nil { + return item, 0, fmt.Errorf("reading MarkBasePos: %s", err) + } + + } + } + return item, n, nil +} + +func ParseMarkLigPos(src []byte) (MarkLigPos, int, error) { + var item MarkLigPos + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading MarkLigPos: "+"EOF: expected length: 12, got %d", L) + } + _ = src[11] // early bound checking + item.posFormat = binary.BigEndian.Uint16(src[0:]) + offsetMarkCoverage := int(binary.BigEndian.Uint16(src[2:])) + offsetLigatureCoverage := int(binary.BigEndian.Uint16(src[4:])) + item.MarkClassCount = binary.BigEndian.Uint16(src[6:]) + offsetMarkArray := int(binary.BigEndian.Uint16(src[8:])) + offsetLigatureArray := int(binary.BigEndian.Uint16(src[10:])) + n += 12 + + { + + if offsetMarkCoverage != 0 { // ignore null offset + if L := len(src); L < offsetMarkCoverage { + return item, 0, fmt.Errorf("reading MarkLigPos: "+"EOF: expected length: %d, got %d", offsetMarkCoverage, L) + } + + var ( + err error + read int + ) + item.MarkCoverage, read, err = ParseCoverage(src[offsetMarkCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading MarkLigPos: %s", err) + } + offsetMarkCoverage += read + } + } + { + + if offsetLigatureCoverage != 0 { // ignore null offset + if L := len(src); L < offsetLigatureCoverage { + return item, 0, fmt.Errorf("reading MarkLigPos: "+"EOF: expected length: %d, got %d", offsetLigatureCoverage, L) + } + + var ( + err error + read int + ) + item.LigatureCoverage, read, err = ParseCoverage(src[offsetLigatureCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading MarkLigPos: %s", err) + } + offsetLigatureCoverage += read + } + } + { + + if offsetMarkArray != 0 { // ignore null offset + if L := len(src); L < offsetMarkArray { + return item, 0, fmt.Errorf("reading MarkLigPos: "+"EOF: expected length: %d, got %d", offsetMarkArray, L) + } + + var err error + item.MarkArray, _, err = ParseMarkArray(src[offsetMarkArray:]) + if err != nil { + return item, 0, fmt.Errorf("reading MarkLigPos: %s", err) + } + + } + } + { + + if offsetLigatureArray != 0 { // ignore null offset + if L := len(src); L < offsetLigatureArray { + return item, 0, fmt.Errorf("reading MarkLigPos: "+"EOF: expected length: %d, got %d", offsetLigatureArray, L) + } + + var err error + item.LigatureArray, _, err = ParseLigatureArray(src[offsetLigatureArray:], int(item.MarkClassCount)) + if err != nil { + return item, 0, fmt.Errorf("reading MarkLigPos: %s", err) + } + + } + } + return item, n, nil +} + +func ParseMarkMarkPos(src []byte) (MarkMarkPos, int, error) { + var item MarkMarkPos + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading MarkMarkPos: "+"EOF: expected length: 12, got %d", L) + } + _ = src[11] // early bound checking + item.PosFormat = binary.BigEndian.Uint16(src[0:]) + offsetMark1Coverage := int(binary.BigEndian.Uint16(src[2:])) + offsetMark2Coverage := int(binary.BigEndian.Uint16(src[4:])) + item.MarkClassCount = binary.BigEndian.Uint16(src[6:]) + offsetMark1Array := int(binary.BigEndian.Uint16(src[8:])) + offsetMark2Array := int(binary.BigEndian.Uint16(src[10:])) + n += 12 + + { + + if offsetMark1Coverage != 0 { // ignore null offset + if L := len(src); L < offsetMark1Coverage { + return item, 0, fmt.Errorf("reading MarkMarkPos: "+"EOF: expected length: %d, got %d", offsetMark1Coverage, L) + } + + var ( + err error + read int + ) + item.Mark1Coverage, read, err = ParseCoverage(src[offsetMark1Coverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading MarkMarkPos: %s", err) + } + offsetMark1Coverage += read + } + } + { + + if offsetMark2Coverage != 0 { // ignore null offset + if L := len(src); L < offsetMark2Coverage { + return item, 0, fmt.Errorf("reading MarkMarkPos: "+"EOF: expected length: %d, got %d", offsetMark2Coverage, L) + } + + var ( + err error + read int + ) + item.Mark2Coverage, read, err = ParseCoverage(src[offsetMark2Coverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading MarkMarkPos: %s", err) + } + offsetMark2Coverage += read + } + } + { + + if offsetMark1Array != 0 { // ignore null offset + if L := len(src); L < offsetMark1Array { + return item, 0, fmt.Errorf("reading MarkMarkPos: "+"EOF: expected length: %d, got %d", offsetMark1Array, L) + } + + var err error + item.Mark1Array, _, err = ParseMarkArray(src[offsetMark1Array:]) + if err != nil { + return item, 0, fmt.Errorf("reading MarkMarkPos: %s", err) + } + + } + } + { + + if offsetMark2Array != 0 { // ignore null offset + if L := len(src); L < offsetMark2Array { + return item, 0, fmt.Errorf("reading MarkMarkPos: "+"EOF: expected length: %d, got %d", offsetMark2Array, L) + } + + var err error + item.Mark2Array, _, err = ParseMark2Array(src[offsetMark2Array:], int(item.MarkClassCount)) + if err != nil { + return item, 0, fmt.Errorf("reading MarkMarkPos: %s", err) + } + + } + } + return item, n, nil +} + +func ParsePairPos(src []byte) (PairPos, int, error) { + var item PairPos + n := 0 + { + var ( + err error + read int + ) + item.Data, read, err = ParsePairPosData(src[0:]) + if err != nil { + return item, 0, fmt.Errorf("reading PairPos: %s", err) + } + n += read + } + return item, n, nil +} + +func ParsePairPosData(src []byte) (PairPosData, int, error) { + var item PairPosData + + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading PairPosData: "+"EOF: expected length: 2, got %d", L) + } + format := uint16(binary.BigEndian.Uint16(src[0:])) + var ( + read int + err error + ) + switch format { + case 1: + item, read, err = ParsePairPosData1(src[0:]) + case 2: + item, read, err = ParsePairPosData2(src[0:]) + default: + err = fmt.Errorf("unsupported PairPosData format %d", format) + } + if err != nil { + return item, 0, fmt.Errorf("reading PairPosData: %s", err) + } + + return item, read, nil +} + +func ParsePairPosData1(src []byte) (PairPosData1, int, error) { + var item PairPosData1 + n := 0 + if L := len(src); L < 10 { + return item, 0, fmt.Errorf("reading PairPosData1: "+"EOF: expected length: 10, got %d", L) + } + _ = src[9] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + offsetCoverage := int(binary.BigEndian.Uint16(src[2:])) + item.ValueFormat1 = ValueFormat(binary.BigEndian.Uint16(src[4:])) + item.ValueFormat2 = ValueFormat(binary.BigEndian.Uint16(src[6:])) + arrayLengthPairSets := int(binary.BigEndian.Uint16(src[8:])) + n += 10 + + { + + if offsetCoverage != 0 { // ignore null offset + if L := len(src); L < offsetCoverage { + return item, 0, fmt.Errorf("reading PairPosData1: "+"EOF: expected length: %d, got %d", offsetCoverage, L) + } + + var ( + err error + read int + ) + item.coverage, read, err = ParseCoverage(src[offsetCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading PairPosData1: %s", err) + } + offsetCoverage += read + } + } + { + + if L := len(src); L < 10+arrayLengthPairSets*2 { + return item, 0, fmt.Errorf("reading PairPosData1: "+"EOF: expected length: %d, got %d", 10+arrayLengthPairSets*2, L) + } + + item.PairSets = make([]PairSet, arrayLengthPairSets) // allocation guarded by the previous check + for i := range item.PairSets { + offset := int(binary.BigEndian.Uint16(src[10+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading PairPosData1: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.PairSets[i], _, err = ParsePairSet(src[offset:], ValueFormat(item.ValueFormat1), ValueFormat(item.ValueFormat2)) + if err != nil { + return item, 0, fmt.Errorf("reading PairPosData1: %s", err) + } + } + n += arrayLengthPairSets * 2 + } + return item, n, nil +} + +func ParsePairPosData2(src []byte) (PairPosData2, int, error) { + var item PairPosData2 + n := 0 + if L := len(src); L < 16 { + return item, 0, fmt.Errorf("reading PairPosData2: "+"EOF: expected length: 16, got %d", L) + } + _ = src[15] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + offsetCoverage := int(binary.BigEndian.Uint16(src[2:])) + item.ValueFormat1 = ValueFormat(binary.BigEndian.Uint16(src[4:])) + item.ValueFormat2 = ValueFormat(binary.BigEndian.Uint16(src[6:])) + offsetClassDef1 := int(binary.BigEndian.Uint16(src[8:])) + offsetClassDef2 := int(binary.BigEndian.Uint16(src[10:])) + item.class1Count = binary.BigEndian.Uint16(src[12:]) + item.class2Count = binary.BigEndian.Uint16(src[14:]) + n += 16 + + { + + if offsetCoverage != 0 { // ignore null offset + if L := len(src); L < offsetCoverage { + return item, 0, fmt.Errorf("reading PairPosData2: "+"EOF: expected length: %d, got %d", offsetCoverage, L) + } + + var ( + err error + read int + ) + item.coverage, read, err = ParseCoverage(src[offsetCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading PairPosData2: %s", err) + } + offsetCoverage += read + } + } + { + + if offsetClassDef1 != 0 { // ignore null offset + if L := len(src); L < offsetClassDef1 { + return item, 0, fmt.Errorf("reading PairPosData2: "+"EOF: expected length: %d, got %d", offsetClassDef1, L) + } + + var ( + err error + read int + ) + item.ClassDef1, read, err = ParseClassDef(src[offsetClassDef1:]) + if err != nil { + return item, 0, fmt.Errorf("reading PairPosData2: %s", err) + } + offsetClassDef1 += read + } + } + { + + if offsetClassDef2 != 0 { // ignore null offset + if L := len(src); L < offsetClassDef2 { + return item, 0, fmt.Errorf("reading PairPosData2: "+"EOF: expected length: %d, got %d", offsetClassDef2, L) + } + + var ( + err error + read int + ) + item.ClassDef2, read, err = ParseClassDef(src[offsetClassDef2:]) + if err != nil { + return item, 0, fmt.Errorf("reading PairPosData2: %s", err) + } + offsetClassDef2 += read + } + } + { + + item.classData = src[0:] + } + return item, n, nil +} + +func ParsePairSet(src []byte, valueFormat1 ValueFormat, valueFormat2 ValueFormat) (PairSet, int, error) { + var item PairSet + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading PairSet: "+"EOF: expected length: 2, got %d", L) + } + item.pairValueCount = binary.BigEndian.Uint16(src[0:]) + n += 2 + + { + + err := item.parseData(src[:], valueFormat1, valueFormat2) + if err != nil { + return item, 0, fmt.Errorf("reading PairSet: %s", err) + } + } + return item, n, nil +} + +func ParseSequenceRule(src []byte) (SequenceRule, int, error) { + var item SequenceRule + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading SequenceRule: "+"EOF: expected length: 4, got %d", L) + } + _ = src[3] // early bound checking + item.glyphCount = binary.BigEndian.Uint16(src[0:]) + item.seqLookupCount = binary.BigEndian.Uint16(src[2:]) + n += 4 + + { + arrayLength := int(item.glyphCount - 1) + + if L := len(src); L < 4+arrayLength*2 { + return item, 0, fmt.Errorf("reading SequenceRule: "+"EOF: expected length: %d, got %d", 4+arrayLength*2, L) + } + + item.InputSequence = make([]uint16, arrayLength) // allocation guarded by the previous check + for i := range item.InputSequence { + item.InputSequence[i] = binary.BigEndian.Uint16(src[4+i*2:]) + } + n += arrayLength * 2 + } + { + arrayLength := int(item.seqLookupCount) + + if L := len(src); L < n+arrayLength*4 { + return item, 0, fmt.Errorf("reading SequenceRule: "+"EOF: expected length: %d, got %d", n+arrayLength*4, L) + } + + item.SeqLookupRecords = make([]SequenceLookupRecord, arrayLength) // allocation guarded by the previous check + for i := range item.SeqLookupRecords { + item.SeqLookupRecords[i].mustParse(src[n+i*4:]) + } + n += arrayLength * 4 + } + return item, n, nil +} + +func ParseSequenceRuleSet(src []byte) (SequenceRuleSet, int, error) { + var item SequenceRuleSet + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading SequenceRuleSet: "+"EOF: expected length: 2, got %d", L) + } + arrayLengthSeqRule := int(binary.BigEndian.Uint16(src[0:])) + n += 2 + + { + + if L := len(src); L < 2+arrayLengthSeqRule*2 { + return item, 0, fmt.Errorf("reading SequenceRuleSet: "+"EOF: expected length: %d, got %d", 2+arrayLengthSeqRule*2, L) + } + + item.SeqRule = make([]SequenceRule, arrayLengthSeqRule) // allocation guarded by the previous check + for i := range item.SeqRule { + offset := int(binary.BigEndian.Uint16(src[2+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading SequenceRuleSet: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.SeqRule[i], _, err = ParseSequenceRule(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading SequenceRuleSet: %s", err) + } + } + n += arrayLengthSeqRule * 2 + } + return item, n, nil +} + +func ParseSinglePos(src []byte) (SinglePos, int, error) { + var item SinglePos + n := 0 + { + var ( + err error + read int + ) + item.Data, read, err = ParseSinglePosData(src[0:]) + if err != nil { + return item, 0, fmt.Errorf("reading SinglePos: %s", err) + } + n += read + } + return item, n, nil +} + +func ParseSinglePosData(src []byte) (SinglePosData, int, error) { + var item SinglePosData + + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading SinglePosData: "+"EOF: expected length: 2, got %d", L) + } + format := uint16(binary.BigEndian.Uint16(src[0:])) + var ( + read int + err error + ) + switch format { + case 1: + item, read, err = ParseSinglePosData1(src[0:]) + case 2: + item, read, err = ParseSinglePosData2(src[0:]) + default: + err = fmt.Errorf("unsupported SinglePosData format %d", format) + } + if err != nil { + return item, 0, fmt.Errorf("reading SinglePosData: %s", err) + } + + return item, read, nil +} + +func ParseSinglePosData1(src []byte) (SinglePosData1, int, error) { + var item SinglePosData1 + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading SinglePosData1: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + offsetCoverage := int(binary.BigEndian.Uint16(src[2:])) + item.ValueFormat = ValueFormat(binary.BigEndian.Uint16(src[4:])) + n += 6 + + { + + if offsetCoverage != 0 { // ignore null offset + if L := len(src); L < offsetCoverage { + return item, 0, fmt.Errorf("reading SinglePosData1: "+"EOF: expected length: %d, got %d", offsetCoverage, L) + } + + var ( + err error + read int + ) + item.coverage, read, err = ParseCoverage(src[offsetCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading SinglePosData1: %s", err) + } + offsetCoverage += read + } + } + { + + err := item.parseValueRecord(src[:]) + if err != nil { + return item, 0, fmt.Errorf("reading SinglePosData1: %s", err) + } + } + return item, n, nil +} + +func ParseSinglePosData2(src []byte) (SinglePosData2, int, error) { + var item SinglePosData2 + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading SinglePosData2: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + offsetCoverage := int(binary.BigEndian.Uint16(src[2:])) + item.ValueFormat = ValueFormat(binary.BigEndian.Uint16(src[4:])) + item.valueCount = binary.BigEndian.Uint16(src[6:]) + n += 8 + + { + + if offsetCoverage != 0 { // ignore null offset + if L := len(src); L < offsetCoverage { + return item, 0, fmt.Errorf("reading SinglePosData2: "+"EOF: expected length: %d, got %d", offsetCoverage, L) + } + + var ( + err error + read int + ) + item.coverage, read, err = ParseCoverage(src[offsetCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading SinglePosData2: %s", err) + } + offsetCoverage += read + } + } + { + + err := item.parseValueRecords(src[:]) + if err != nil { + return item, 0, fmt.Errorf("reading SinglePosData2: %s", err) + } + } + return item, n, nil +} + +func (item *SequenceLookupRecord) mustParse(src []byte) { + _ = src[3] // early bound checking + item.SequenceIndex = binary.BigEndian.Uint16(src[0:]) + item.LookupListIndex = binary.BigEndian.Uint16(src[2:]) +} + +func (item *entryExitRecord) mustParse(src []byte) { + _ = src[3] // early bound checking + item.entryAnchorOffset = Offset16(binary.BigEndian.Uint16(src[0:])) + item.exitAnchorOffset = Offset16(binary.BigEndian.Uint16(src[2:])) +} + +func parseAnchorOffsets(src []byte, offsetsCount int) (anchorOffsets, int, error) { + var item anchorOffsets + n := 0 + { + + if L := len(src); L < offsetsCount*2 { + return item, 0, fmt.Errorf("reading anchorOffsets: "+"EOF: expected length: %d, got %d", offsetsCount*2, L) + } + + item.offsets = make([]Offset16, offsetsCount) // allocation guarded by the previous check + for i := range item.offsets { + item.offsets[i] = Offset16(binary.BigEndian.Uint16(src[i*2:])) + } + n += offsetsCount * 2 + } + return item, n, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_gpos_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_gpos_src.go new file mode 100644 index 0000000..1f3ff8b --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_gpos_src.go @@ -0,0 +1,276 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "fmt" +) + +type SinglePos struct { + Data SinglePosData +} + +type SinglePosData interface { + isSinglePosData() + + Cov() Coverage +} + +func (SinglePosData1) isSinglePosData() {} +func (SinglePosData2) isSinglePosData() {} + +type SinglePosData1 struct { + format uint16 `unionTag:"1"` + coverage Coverage `offsetSize:"Offset16"` // Offset to Coverage table, from beginning of SinglePos subtable. + ValueFormat ValueFormat // Defines the types of data in the ValueRecord. + ValueRecord ValueRecord `isOpaque:""` // Defines positioning value(s) — applied to all glyphs in the Coverage table. +} + +func (sp *SinglePosData1) parseValueRecord(src []byte) (err error) { + sp.ValueRecord, _, err = parseValueRecord(sp.ValueFormat, src, 6) + return err +} + +type SinglePosData2 struct { + format uint16 `unionTag:"2"` + coverage Coverage `offsetSize:"Offset16"` // Offset to Coverage table, from beginning of SinglePos subtable. + ValueFormat ValueFormat // Defines the types of data in the ValueRecords. + valueCount uint16 // Number of ValueRecords — must equal glyphCount in the Coverage table. + ValueRecords []ValueRecord `isOpaque:""` //[valueCount] Array of ValueRecords — positioning values applied to glyphs. +} + +func (sp *SinglePosData2) parseValueRecords(src []byte) (err error) { + offset := 8 + sp.ValueRecords = make([]ValueRecord, sp.valueCount) + for i := range sp.ValueRecords { + sp.ValueRecords[i], offset, err = parseValueRecord(sp.ValueFormat, src, offset) + if err != nil { + return err + } + } + + return err +} + +type PairPos struct { + Data PairPosData +} + +type PairPosData interface { + isPairPosData() + + Cov() Coverage +} + +func (PairPosData1) isPairPosData() {} +func (PairPosData2) isPairPosData() {} + +type PairPosData1 struct { + format uint16 `unionTag:"1"` + coverage Coverage `offsetSize:"Offset16"` // Offset to Coverage table, from beginning of PairPos subtable. + + ValueFormat1 ValueFormat // Defines the types of data in valueRecord1 — for the first glyph in the pair (may be zero). + ValueFormat2 ValueFormat // Defines the types of data in valueRecord2 — for the second glyph in the pair (may be zero). + PairSets []PairSet `arrayCount:"FirstUint16" offsetsArray:"Offset16" arguments:"valueFormat1=.ValueFormat1, valueFormat2=.ValueFormat2"` //[pairSetCount] Array of offsets to PairSet tables. Offsets are from beginning of PairPos subtable, ordered by Coverage Index. +} + +// binarygen: argument=valueFormat1 ValueFormat +// binarygen: argument=valueFormat2 ValueFormat +type PairSet struct { + pairValueCount uint16 // Number of PairValueRecords + // we store the compressed form to avoid wasting to much memory + data pairValueRecords `isOpaque:""` +} + +func (ps *PairSet) parseData(src []byte, fmt1, fmt2 ValueFormat) error { + recNbUint16 := 1 + fmt1.size() + fmt2.size() // in uint16 + if exp := 2 + recNbUint16*2*int(ps.pairValueCount); len(src) < exp { // + return fmt.Errorf("EOF: expected length: %d, got %d", exp, len(src)) + } + ps.data = pairValueRecords{data: src, fmt1: fmt1, fmt2: fmt2} + return nil +} + +type PairPosData2 struct { + format uint16 `unionTag:"2"` + coverage Coverage `offsetSize:"Offset16"` // Offset to Coverage table, from beginning of PairPos subtable. + + ValueFormat1 ValueFormat // Defines the types of data in valueRecord1 — for the first glyph in the pair (may be zero). + ValueFormat2 ValueFormat // Defines the types of data in valueRecord2 — for the second glyph in the pair (may be zero). + + ClassDef1 ClassDef `offsetSize:"Offset16"` // Offset to ClassDef table, from beginning of PairPos subtable — for the first glyph of the pair. + ClassDef2 ClassDef `offsetSize:"Offset16"` // Offset to ClassDef table, from beginning of PairPos subtable — for the second glyph of the pair. + class1Count uint16 // Number of classes in classDef1 table — includes Class 0. + class2Count uint16 // Number of classes in classDef2 table — includes Class 0. + + classData []byte `subsliceStart:"AtStart" arrayCount:"ToEnd"` +} + +// Record returns the record for the given classes, which must come from ClassDef1 +// and ClassDef2 +func (pp *PairPosData2) Record(class1, class2 uint16) Class2Record { + const headerSize = 16 // including posFormat and coverageOffset + size2 := (pp.ValueFormat1.size() + pp.ValueFormat2.size()) * 2 + size1 := int(pp.class2Count) * size2 + offset := headerSize + size1*int(class1) + size2*int(class2) + v1, newOffset, _ := parseValueRecord(pp.ValueFormat1, pp.classData, offset) + v2, _, _ := parseValueRecord(pp.ValueFormat2, pp.classData, newOffset) + return Class2Record{v1, v2} +} + +// DeviceTableHeader is the common header for DeviceTable +// See https://learn.microsoft.com/fr-fr/typography/opentype/spec/chapter2#device-and-variationindex-tables +type DeviceTableHeader struct { + first uint16 + second uint16 + deltaFormat uint16 // Format of deltaValue array data +} + +type Anchor interface { + isAnchor() +} + +type EntryExit struct { + EntryAnchor Anchor + ExitAnchor Anchor +} + +type CursivePos struct { + posFormat uint16 // Format identifier: format = 1 + coverage Coverage `offsetSize:"Offset16"` // Offset to Coverage table, from beginning of CursivePos subtable. + entryExitRecords []entryExitRecord `arrayCount:"FirstUint16"` //[entryExitCount] Array of EntryExit records, in Coverage index order. + EntryExits []EntryExit `isOpaque:""` +} + +type entryExitRecord struct { + entryAnchorOffset Offset16 // Offset to entryAnchor table, from beginning of CursivePos subtable (may be NULL). + exitAnchorOffset Offset16 // Offset to exitAnchor table, from beginning of CursivePos subtable (may be NULL). +} + +func (cp *CursivePos) parseEntryExits(src []byte) error { + cp.EntryExits = make([]EntryExit, len(cp.entryExitRecords)) + var err error + for i, rec := range cp.entryExitRecords { + if rec.entryAnchorOffset != 0 { + if L := len(src); L < int(rec.entryAnchorOffset) { + return fmt.Errorf("EOF: expected length: %d, got %d", rec.entryAnchorOffset, L) + } + cp.EntryExits[i].EntryAnchor, _, err = ParseAnchor(src[rec.entryAnchorOffset:]) + if err != nil { + return err + } + } + if rec.exitAnchorOffset != 0 { + if L := len(src); L < int(rec.exitAnchorOffset) { + return fmt.Errorf("EOF: expected length: %d, got %d", rec.exitAnchorOffset, L) + } + cp.EntryExits[i].ExitAnchor, _, err = ParseAnchor(src[rec.exitAnchorOffset:]) + if err != nil { + return err + } + } + } + return nil +} + +type MarkBasePos struct { + posFormat uint16 // Format identifier: format = 1 + markCoverage Coverage `offsetSize:"Offset16"` // Offset to markCoverage table, from beginning of MarkBasePos subtable. + BaseCoverage Coverage `offsetSize:"Offset16"` // Offset to baseCoverage table, from beginning of MarkBasePos subtable. + markClassCount uint16 // Number of classes defined for marks + MarkArray MarkArray `offsetSize:"Offset16"` // Offset to MarkArray table, from beginning of MarkBasePos subtable. + BaseArray BaseArray `offsetSize:"Offset16" arguments:"offsetsCount=.markClassCount"` // Offset to BaseArray table, from beginning of MarkBasePos subtable. +} + +type BaseArray struct { + baseRecords []anchorOffsets `arrayCount:"FirstUint16"` // [markClassCount] Array of offsets (one per mark class) to Anchor tables. Offsets are from beginning of BaseArray table, ordered by class (offsets may be NULL). + data []byte `arrayCount:"ToEnd" subsliceStart:"AtStart"` +} + +func (ba BaseArray) Anchors() AnchorMatrix { return AnchorMatrix{ba.baseRecords, ba.data} } + +type anchorOffsets struct { + offsets []Offset16 // Array of offsets to Anchor tables, with external length +} + +type MarkLigPos struct { + posFormat uint16 // Format identifier: format = 1 + MarkCoverage Coverage `offsetSize:"Offset16"` // Offset to markCoverage table, from beginning of MarkLigPos subtable. + LigatureCoverage Coverage `offsetSize:"Offset16"` // Offset to ligatureCoverage table, from beginning of MarkLigPos subtable. + MarkClassCount uint16 // Number of defined mark classes + MarkArray MarkArray `offsetSize:"Offset16"` // Offset to MarkArray table, from beginning of MarkLigPos subtable. + LigatureArray LigatureArray `offsetSize:"Offset16" arguments:"offsetsCount=.MarkClassCount"` // Offset to LigatureArray table, from beginning of MarkLigPos subtable. +} + +type LigatureArray struct { + LigatureAttachs []LigatureAttach `arrayCount:"FirstUint16" offsetsArray:"Offset16"` // [ligatureCount] Array of offsets to LigatureAttach tables. Offsets are from beginning of LigatureArray table, ordered by ligatureCoverage index. +} + +type LigatureAttach struct { + // [componentCount] Array of Component records, ordered in writing direction. + // Each element is an array of offsets (one per class, length = [markClassCount]) to Anchor tables. Offsets are from beginning of LigatureAttach table, ordered by class (offsets may be NULL). + componentRecords []anchorOffsets `arrayCount:"FirstUint16"` + data []byte `arrayCount:"ToEnd" subsliceStart:"AtStart"` +} + +func (la LigatureAttach) Anchors() AnchorMatrix { return AnchorMatrix{la.componentRecords, la.data} } + +type MarkMarkPos struct { + PosFormat uint16 // Format identifier: format = 1 + Mark1Coverage Coverage `offsetSize:"Offset16"` // Offset to Combining Mark Coverage table, from beginning of MarkMarkPos subtable. + Mark2Coverage Coverage `offsetSize:"Offset16"` // Offset to Base Mark Coverage table, from beginning of MarkMarkPos subtable. + MarkClassCount uint16 // Number of Combining Mark classes defined + Mark1Array MarkArray `offsetSize:"Offset16"` // Offset to MarkArray table for mark1, from beginning of MarkMarkPos subtable. + Mark2Array Mark2Array `offsetSize:"Offset16" arguments:"offsetsCount=.MarkClassCount"` // Offset to Mark2Array table for mark2, from beginning of MarkMarkPos subtable. +} + +type Mark2Array struct { + // [mark2Count] Array of Mark2Records, in Coverage order. + // Each element if an array of offsets (one per class, length = [markClassCount]) to Anchor tables. Offsets are from beginning of Mark2Array table, in class order (offsets may be NULL). + mark2Records []anchorOffsets `arrayCount:"FirstUint16"` + data []byte `arrayCount:"ToEnd" subsliceStart:"AtStart"` +} + +func (ma Mark2Array) Anchors() AnchorMatrix { return AnchorMatrix{ma.mark2Records, ma.data} } + +type ContextualPos struct { + Data ContextualPosITF +} + +type ContextualPosITF interface { + isContextualPosITF() + + Cov() Coverage +} + +type ( + ContextualPos1 SequenceContextFormat1 + ContextualPos2 SequenceContextFormat2 + ContextualPos3 SequenceContextFormat3 +) + +func (ContextualPos1) isContextualPosITF() {} +func (ContextualPos2) isContextualPosITF() {} +func (ContextualPos3) isContextualPosITF() {} + +type ChainedContextualPos struct { + Data ChainedContextualPosITF +} + +type ChainedContextualPosITF interface { + isChainedContextualPosITF() + + Cov() Coverage +} + +type ( + ChainedContextualPos1 ChainedSequenceContextFormat1 + ChainedContextualPos2 ChainedSequenceContextFormat2 + ChainedContextualPos3 ChainedSequenceContextFormat3 +) + +func (ChainedContextualPos1) isChainedContextualPosITF() {} +func (ChainedContextualPos2) isChainedContextualPosITF() {} +func (ChainedContextualPos3) isChainedContextualPosITF() {} + +type ExtensionPos Extension diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_gsub_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_gsub_gen.go new file mode 100644 index 0000000..c320e93 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_gsub_gen.go @@ -0,0 +1,1129 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from ot_gsub_src.go. DO NOT EDIT + +func ParseAlternateSet(src []byte) (AlternateSet, int, error) { + var item AlternateSet + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading AlternateSet: "+"EOF: expected length: 2, got %d", L) + } + arrayLengthAlternateGlyphIDs := int(binary.BigEndian.Uint16(src[0:])) + n += 2 + + { + + if L := len(src); L < 2+arrayLengthAlternateGlyphIDs*2 { + return item, 0, fmt.Errorf("reading AlternateSet: "+"EOF: expected length: %d, got %d", 2+arrayLengthAlternateGlyphIDs*2, L) + } + + item.AlternateGlyphIDs = make([]uint16, arrayLengthAlternateGlyphIDs) // allocation guarded by the previous check + for i := range item.AlternateGlyphIDs { + item.AlternateGlyphIDs[i] = binary.BigEndian.Uint16(src[2+i*2:]) + } + n += arrayLengthAlternateGlyphIDs * 2 + } + return item, n, nil +} + +func ParseAlternateSubs(src []byte) (AlternateSubs, int, error) { + var item AlternateSubs + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading AlternateSubs: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.substFormat = binary.BigEndian.Uint16(src[0:]) + offsetCoverage := int(binary.BigEndian.Uint16(src[2:])) + arrayLengthAlternateSets := int(binary.BigEndian.Uint16(src[4:])) + n += 6 + + { + + if offsetCoverage != 0 { // ignore null offset + if L := len(src); L < offsetCoverage { + return item, 0, fmt.Errorf("reading AlternateSubs: "+"EOF: expected length: %d, got %d", offsetCoverage, L) + } + + var ( + err error + read int + ) + item.Coverage, read, err = ParseCoverage(src[offsetCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading AlternateSubs: %s", err) + } + offsetCoverage += read + } + } + { + + if L := len(src); L < 6+arrayLengthAlternateSets*2 { + return item, 0, fmt.Errorf("reading AlternateSubs: "+"EOF: expected length: %d, got %d", 6+arrayLengthAlternateSets*2, L) + } + + item.AlternateSets = make([]AlternateSet, arrayLengthAlternateSets) // allocation guarded by the previous check + for i := range item.AlternateSets { + offset := int(binary.BigEndian.Uint16(src[6+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading AlternateSubs: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.AlternateSets[i], _, err = ParseAlternateSet(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading AlternateSubs: %s", err) + } + } + n += arrayLengthAlternateSets * 2 + } + return item, n, nil +} + +func ParseChainedContextualSubs(src []byte) (ChainedContextualSubs, int, error) { + var item ChainedContextualSubs + n := 0 + { + var ( + err error + read int + ) + item.Data, read, err = ParseChainedContextualSubsITF(src[0:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualSubs: %s", err) + } + n += read + } + return item, n, nil +} + +func ParseChainedContextualSubs1(src []byte) (ChainedContextualSubs1, int, error) { + var item ChainedContextualSubs1 + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading ChainedContextualSubs1: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + offsetCoverage := int(binary.BigEndian.Uint16(src[2:])) + arrayLengthChainedSeqRuleSet := int(binary.BigEndian.Uint16(src[4:])) + n += 6 + + { + + if offsetCoverage != 0 { // ignore null offset + if L := len(src); L < offsetCoverage { + return item, 0, fmt.Errorf("reading ChainedContextualSubs1: "+"EOF: expected length: %d, got %d", offsetCoverage, L) + } + + var ( + err error + read int + ) + item.coverage, read, err = ParseCoverage(src[offsetCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualSubs1: %s", err) + } + offsetCoverage += read + } + } + { + + if L := len(src); L < 6+arrayLengthChainedSeqRuleSet*2 { + return item, 0, fmt.Errorf("reading ChainedContextualSubs1: "+"EOF: expected length: %d, got %d", 6+arrayLengthChainedSeqRuleSet*2, L) + } + + item.ChainedSeqRuleSet = make([]ChainedSequenceRuleSet, arrayLengthChainedSeqRuleSet) // allocation guarded by the previous check + for i := range item.ChainedSeqRuleSet { + offset := int(binary.BigEndian.Uint16(src[6+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading ChainedContextualSubs1: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.ChainedSeqRuleSet[i], _, err = ParseChainedSequenceRuleSet(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualSubs1: %s", err) + } + } + n += arrayLengthChainedSeqRuleSet * 2 + } + return item, n, nil +} + +func ParseChainedContextualSubs2(src []byte) (ChainedContextualSubs2, int, error) { + var item ChainedContextualSubs2 + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading ChainedContextualSubs2: "+"EOF: expected length: 12, got %d", L) + } + _ = src[11] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + offsetCoverage := int(binary.BigEndian.Uint16(src[2:])) + offsetBacktrackClassDef := int(binary.BigEndian.Uint16(src[4:])) + offsetInputClassDef := int(binary.BigEndian.Uint16(src[6:])) + offsetLookaheadClassDef := int(binary.BigEndian.Uint16(src[8:])) + arrayLengthChainedClassSeqRuleSet := int(binary.BigEndian.Uint16(src[10:])) + n += 12 + + { + + if offsetCoverage != 0 { // ignore null offset + if L := len(src); L < offsetCoverage { + return item, 0, fmt.Errorf("reading ChainedContextualSubs2: "+"EOF: expected length: %d, got %d", offsetCoverage, L) + } + + var ( + err error + read int + ) + item.coverage, read, err = ParseCoverage(src[offsetCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualSubs2: %s", err) + } + offsetCoverage += read + } + } + { + + if offsetBacktrackClassDef != 0 { // ignore null offset + if L := len(src); L < offsetBacktrackClassDef { + return item, 0, fmt.Errorf("reading ChainedContextualSubs2: "+"EOF: expected length: %d, got %d", offsetBacktrackClassDef, L) + } + + var ( + err error + read int + ) + item.BacktrackClassDef, read, err = ParseClassDef(src[offsetBacktrackClassDef:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualSubs2: %s", err) + } + offsetBacktrackClassDef += read + } + } + { + + if offsetInputClassDef != 0 { // ignore null offset + if L := len(src); L < offsetInputClassDef { + return item, 0, fmt.Errorf("reading ChainedContextualSubs2: "+"EOF: expected length: %d, got %d", offsetInputClassDef, L) + } + + var ( + err error + read int + ) + item.InputClassDef, read, err = ParseClassDef(src[offsetInputClassDef:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualSubs2: %s", err) + } + offsetInputClassDef += read + } + } + { + + if offsetLookaheadClassDef != 0 { // ignore null offset + if L := len(src); L < offsetLookaheadClassDef { + return item, 0, fmt.Errorf("reading ChainedContextualSubs2: "+"EOF: expected length: %d, got %d", offsetLookaheadClassDef, L) + } + + var ( + err error + read int + ) + item.LookaheadClassDef, read, err = ParseClassDef(src[offsetLookaheadClassDef:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualSubs2: %s", err) + } + offsetLookaheadClassDef += read + } + } + { + + if L := len(src); L < 12+arrayLengthChainedClassSeqRuleSet*2 { + return item, 0, fmt.Errorf("reading ChainedContextualSubs2: "+"EOF: expected length: %d, got %d", 12+arrayLengthChainedClassSeqRuleSet*2, L) + } + + item.ChainedClassSeqRuleSet = make([]ChainedSequenceRuleSet, arrayLengthChainedClassSeqRuleSet) // allocation guarded by the previous check + for i := range item.ChainedClassSeqRuleSet { + offset := int(binary.BigEndian.Uint16(src[12+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading ChainedContextualSubs2: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.ChainedClassSeqRuleSet[i], _, err = ParseChainedSequenceRuleSet(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualSubs2: %s", err) + } + } + n += arrayLengthChainedClassSeqRuleSet * 2 + } + return item, n, nil +} + +func ParseChainedContextualSubs3(src []byte) (ChainedContextualSubs3, int, error) { + var item ChainedContextualSubs3 + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading ChainedContextualSubs3: "+"EOF: expected length: 4, got %d", L) + } + _ = src[3] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + arrayLengthBacktrackCoverages := int(binary.BigEndian.Uint16(src[2:])) + n += 4 + + { + + if L := len(src); L < 4+arrayLengthBacktrackCoverages*2 { + return item, 0, fmt.Errorf("reading ChainedContextualSubs3: "+"EOF: expected length: %d, got %d", 4+arrayLengthBacktrackCoverages*2, L) + } + + item.BacktrackCoverages = make([]Coverage, arrayLengthBacktrackCoverages) // allocation guarded by the previous check + for i := range item.BacktrackCoverages { + offset := int(binary.BigEndian.Uint16(src[4+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading ChainedContextualSubs3: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.BacktrackCoverages[i], _, err = ParseCoverage(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualSubs3: %s", err) + } + } + n += arrayLengthBacktrackCoverages * 2 + } + if L := len(src); L < n+2 { + return item, 0, fmt.Errorf("reading ChainedContextualSubs3: "+"EOF: expected length: n + 2, got %d", L) + } + arrayLengthInputCoverages := int(binary.BigEndian.Uint16(src[n:])) + n += 2 + + { + + if L := len(src); L < n+arrayLengthInputCoverages*2 { + return item, 0, fmt.Errorf("reading ChainedContextualSubs3: "+"EOF: expected length: %d, got %d", n+arrayLengthInputCoverages*2, L) + } + + item.InputCoverages = make([]Coverage, arrayLengthInputCoverages) // allocation guarded by the previous check + for i := range item.InputCoverages { + offset := int(binary.BigEndian.Uint16(src[n+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading ChainedContextualSubs3: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.InputCoverages[i], _, err = ParseCoverage(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualSubs3: %s", err) + } + } + n += arrayLengthInputCoverages * 2 + } + if L := len(src); L < n+2 { + return item, 0, fmt.Errorf("reading ChainedContextualSubs3: "+"EOF: expected length: n + 2, got %d", L) + } + arrayLengthLookaheadCoverages := int(binary.BigEndian.Uint16(src[n:])) + n += 2 + + { + + if L := len(src); L < n+arrayLengthLookaheadCoverages*2 { + return item, 0, fmt.Errorf("reading ChainedContextualSubs3: "+"EOF: expected length: %d, got %d", n+arrayLengthLookaheadCoverages*2, L) + } + + item.LookaheadCoverages = make([]Coverage, arrayLengthLookaheadCoverages) // allocation guarded by the previous check + for i := range item.LookaheadCoverages { + offset := int(binary.BigEndian.Uint16(src[n+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading ChainedContextualSubs3: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.LookaheadCoverages[i], _, err = ParseCoverage(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualSubs3: %s", err) + } + } + n += arrayLengthLookaheadCoverages * 2 + } + if L := len(src); L < n+2 { + return item, 0, fmt.Errorf("reading ChainedContextualSubs3: "+"EOF: expected length: n + 2, got %d", L) + } + arrayLengthSeqLookupRecords := int(binary.BigEndian.Uint16(src[n:])) + n += 2 + + { + + if L := len(src); L < n+arrayLengthSeqLookupRecords*4 { + return item, 0, fmt.Errorf("reading ChainedContextualSubs3: "+"EOF: expected length: %d, got %d", n+arrayLengthSeqLookupRecords*4, L) + } + + item.SeqLookupRecords = make([]SequenceLookupRecord, arrayLengthSeqLookupRecords) // allocation guarded by the previous check + for i := range item.SeqLookupRecords { + item.SeqLookupRecords[i].mustParse(src[n+i*4:]) + } + n += arrayLengthSeqLookupRecords * 4 + } + return item, n, nil +} + +func ParseChainedContextualSubsITF(src []byte) (ChainedContextualSubsITF, int, error) { + var item ChainedContextualSubsITF + + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading ChainedContextualSubsITF: "+"EOF: expected length: 2, got %d", L) + } + format := uint16(binary.BigEndian.Uint16(src[0:])) + var ( + read int + err error + ) + switch format { + case 1: + item, read, err = ParseChainedContextualSubs1(src[0:]) + case 2: + item, read, err = ParseChainedContextualSubs2(src[0:]) + case 3: + item, read, err = ParseChainedContextualSubs3(src[0:]) + default: + err = fmt.Errorf("unsupported ChainedContextualSubsITF format %d", format) + } + if err != nil { + return item, 0, fmt.Errorf("reading ChainedContextualSubsITF: %s", err) + } + + return item, read, nil +} + +func ParseContextualSubs(src []byte) (ContextualSubs, int, error) { + var item ContextualSubs + n := 0 + { + var ( + err error + read int + ) + item.Data, read, err = ParseContextualSubsITF(src[0:]) + if err != nil { + return item, 0, fmt.Errorf("reading ContextualSubs: %s", err) + } + n += read + } + return item, n, nil +} + +func ParseContextualSubs1(src []byte) (ContextualSubs1, int, error) { + var item ContextualSubs1 + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading ContextualSubs1: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + offsetCoverage := int(binary.BigEndian.Uint16(src[2:])) + arrayLengthSeqRuleSet := int(binary.BigEndian.Uint16(src[4:])) + n += 6 + + { + + if offsetCoverage != 0 { // ignore null offset + if L := len(src); L < offsetCoverage { + return item, 0, fmt.Errorf("reading ContextualSubs1: "+"EOF: expected length: %d, got %d", offsetCoverage, L) + } + + var ( + err error + read int + ) + item.coverage, read, err = ParseCoverage(src[offsetCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading ContextualSubs1: %s", err) + } + offsetCoverage += read + } + } + { + + if L := len(src); L < 6+arrayLengthSeqRuleSet*2 { + return item, 0, fmt.Errorf("reading ContextualSubs1: "+"EOF: expected length: %d, got %d", 6+arrayLengthSeqRuleSet*2, L) + } + + item.SeqRuleSet = make([]SequenceRuleSet, arrayLengthSeqRuleSet) // allocation guarded by the previous check + for i := range item.SeqRuleSet { + offset := int(binary.BigEndian.Uint16(src[6+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading ContextualSubs1: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.SeqRuleSet[i], _, err = ParseSequenceRuleSet(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading ContextualSubs1: %s", err) + } + } + n += arrayLengthSeqRuleSet * 2 + } + return item, n, nil +} + +func ParseContextualSubs2(src []byte) (ContextualSubs2, int, error) { + var item ContextualSubs2 + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading ContextualSubs2: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + offsetCoverage := int(binary.BigEndian.Uint16(src[2:])) + offsetClassDef := int(binary.BigEndian.Uint16(src[4:])) + arrayLengthClassSeqRuleSet := int(binary.BigEndian.Uint16(src[6:])) + n += 8 + + { + + if offsetCoverage != 0 { // ignore null offset + if L := len(src); L < offsetCoverage { + return item, 0, fmt.Errorf("reading ContextualSubs2: "+"EOF: expected length: %d, got %d", offsetCoverage, L) + } + + var ( + err error + read int + ) + item.coverage, read, err = ParseCoverage(src[offsetCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading ContextualSubs2: %s", err) + } + offsetCoverage += read + } + } + { + + if offsetClassDef != 0 { // ignore null offset + if L := len(src); L < offsetClassDef { + return item, 0, fmt.Errorf("reading ContextualSubs2: "+"EOF: expected length: %d, got %d", offsetClassDef, L) + } + + var ( + err error + read int + ) + item.ClassDef, read, err = ParseClassDef(src[offsetClassDef:]) + if err != nil { + return item, 0, fmt.Errorf("reading ContextualSubs2: %s", err) + } + offsetClassDef += read + } + } + { + + if L := len(src); L < 8+arrayLengthClassSeqRuleSet*2 { + return item, 0, fmt.Errorf("reading ContextualSubs2: "+"EOF: expected length: %d, got %d", 8+arrayLengthClassSeqRuleSet*2, L) + } + + item.ClassSeqRuleSet = make([]SequenceRuleSet, arrayLengthClassSeqRuleSet) // allocation guarded by the previous check + for i := range item.ClassSeqRuleSet { + offset := int(binary.BigEndian.Uint16(src[8+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading ContextualSubs2: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.ClassSeqRuleSet[i], _, err = ParseSequenceRuleSet(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading ContextualSubs2: %s", err) + } + } + n += arrayLengthClassSeqRuleSet * 2 + } + return item, n, nil +} + +func ParseContextualSubs3(src []byte) (ContextualSubs3, int, error) { + var item ContextualSubs3 + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading ContextualSubs3: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + item.glyphCount = binary.BigEndian.Uint16(src[2:]) + item.seqLookupCount = binary.BigEndian.Uint16(src[4:]) + n += 6 + + { + arrayLength := int(item.glyphCount) + + if L := len(src); L < 6+arrayLength*2 { + return item, 0, fmt.Errorf("reading ContextualSubs3: "+"EOF: expected length: %d, got %d", 6+arrayLength*2, L) + } + + item.Coverages = make([]Coverage, arrayLength) // allocation guarded by the previous check + for i := range item.Coverages { + offset := int(binary.BigEndian.Uint16(src[6+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading ContextualSubs3: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.Coverages[i], _, err = ParseCoverage(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading ContextualSubs3: %s", err) + } + } + n += arrayLength * 2 + } + { + arrayLength := int(item.seqLookupCount) + + if L := len(src); L < n+arrayLength*4 { + return item, 0, fmt.Errorf("reading ContextualSubs3: "+"EOF: expected length: %d, got %d", n+arrayLength*4, L) + } + + item.SeqLookupRecords = make([]SequenceLookupRecord, arrayLength) // allocation guarded by the previous check + for i := range item.SeqLookupRecords { + item.SeqLookupRecords[i].mustParse(src[n+i*4:]) + } + n += arrayLength * 4 + } + return item, n, nil +} + +func ParseContextualSubsITF(src []byte) (ContextualSubsITF, int, error) { + var item ContextualSubsITF + + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading ContextualSubsITF: "+"EOF: expected length: 2, got %d", L) + } + format := uint16(binary.BigEndian.Uint16(src[0:])) + var ( + read int + err error + ) + switch format { + case 1: + item, read, err = ParseContextualSubs1(src[0:]) + case 2: + item, read, err = ParseContextualSubs2(src[0:]) + case 3: + item, read, err = ParseContextualSubs3(src[0:]) + default: + err = fmt.Errorf("unsupported ContextualSubsITF format %d", format) + } + if err != nil { + return item, 0, fmt.Errorf("reading ContextualSubsITF: %s", err) + } + + return item, read, nil +} + +func ParseExtensionSubs(src []byte) (ExtensionSubs, int, error) { + var item ExtensionSubs + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading ExtensionSubs: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.substFormat = binary.BigEndian.Uint16(src[0:]) + item.ExtensionLookupType = binary.BigEndian.Uint16(src[2:]) + item.ExtensionOffset = Offset32(binary.BigEndian.Uint32(src[4:])) + n += 8 + + { + + item.RawData = src[0:] + n = len(src) + } + return item, n, nil +} + +func ParseLigature(src []byte) (Ligature, int, error) { + var item Ligature + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading Ligature: "+"EOF: expected length: 4, got %d", L) + } + _ = src[3] // early bound checking + item.LigatureGlyph = binary.BigEndian.Uint16(src[0:]) + item.componentCount = binary.BigEndian.Uint16(src[2:]) + n += 4 + + { + arrayLength := int(item.componentCount - 1) + + if L := len(src); L < 4+arrayLength*2 { + return item, 0, fmt.Errorf("reading Ligature: "+"EOF: expected length: %d, got %d", 4+arrayLength*2, L) + } + + item.ComponentGlyphIDs = make([]uint16, arrayLength) // allocation guarded by the previous check + for i := range item.ComponentGlyphIDs { + item.ComponentGlyphIDs[i] = binary.BigEndian.Uint16(src[4+i*2:]) + } + n += arrayLength * 2 + } + return item, n, nil +} + +func ParseLigatureSet(src []byte) (LigatureSet, int, error) { + var item LigatureSet + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading LigatureSet: "+"EOF: expected length: 2, got %d", L) + } + arrayLengthLigatures := int(binary.BigEndian.Uint16(src[0:])) + n += 2 + + { + + if L := len(src); L < 2+arrayLengthLigatures*2 { + return item, 0, fmt.Errorf("reading LigatureSet: "+"EOF: expected length: %d, got %d", 2+arrayLengthLigatures*2, L) + } + + item.Ligatures = make([]Ligature, arrayLengthLigatures) // allocation guarded by the previous check + for i := range item.Ligatures { + offset := int(binary.BigEndian.Uint16(src[2+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading LigatureSet: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.Ligatures[i], _, err = ParseLigature(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading LigatureSet: %s", err) + } + } + n += arrayLengthLigatures * 2 + } + return item, n, nil +} + +func ParseLigatureSubs(src []byte) (LigatureSubs, int, error) { + var item LigatureSubs + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading LigatureSubs: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.substFormat = binary.BigEndian.Uint16(src[0:]) + offsetCoverage := int(binary.BigEndian.Uint16(src[2:])) + arrayLengthLigatureSets := int(binary.BigEndian.Uint16(src[4:])) + n += 6 + + { + + if offsetCoverage != 0 { // ignore null offset + if L := len(src); L < offsetCoverage { + return item, 0, fmt.Errorf("reading LigatureSubs: "+"EOF: expected length: %d, got %d", offsetCoverage, L) + } + + var ( + err error + read int + ) + item.Coverage, read, err = ParseCoverage(src[offsetCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading LigatureSubs: %s", err) + } + offsetCoverage += read + } + } + { + + if L := len(src); L < 6+arrayLengthLigatureSets*2 { + return item, 0, fmt.Errorf("reading LigatureSubs: "+"EOF: expected length: %d, got %d", 6+arrayLengthLigatureSets*2, L) + } + + item.LigatureSets = make([]LigatureSet, arrayLengthLigatureSets) // allocation guarded by the previous check + for i := range item.LigatureSets { + offset := int(binary.BigEndian.Uint16(src[6+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading LigatureSubs: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.LigatureSets[i], _, err = ParseLigatureSet(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading LigatureSubs: %s", err) + } + } + n += arrayLengthLigatureSets * 2 + } + return item, n, nil +} + +func ParseMultipleSubs(src []byte) (MultipleSubs, int, error) { + var item MultipleSubs + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading MultipleSubs: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.substFormat = binary.BigEndian.Uint16(src[0:]) + offsetCoverage := int(binary.BigEndian.Uint16(src[2:])) + arrayLengthSequences := int(binary.BigEndian.Uint16(src[4:])) + n += 6 + + { + + if offsetCoverage != 0 { // ignore null offset + if L := len(src); L < offsetCoverage { + return item, 0, fmt.Errorf("reading MultipleSubs: "+"EOF: expected length: %d, got %d", offsetCoverage, L) + } + + var ( + err error + read int + ) + item.Coverage, read, err = ParseCoverage(src[offsetCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading MultipleSubs: %s", err) + } + offsetCoverage += read + } + } + { + + if L := len(src); L < 6+arrayLengthSequences*2 { + return item, 0, fmt.Errorf("reading MultipleSubs: "+"EOF: expected length: %d, got %d", 6+arrayLengthSequences*2, L) + } + + item.Sequences = make([]Sequence, arrayLengthSequences) // allocation guarded by the previous check + for i := range item.Sequences { + offset := int(binary.BigEndian.Uint16(src[6+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading MultipleSubs: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.Sequences[i], _, err = ParseSequence(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading MultipleSubs: %s", err) + } + } + n += arrayLengthSequences * 2 + } + return item, n, nil +} + +func ParseReverseChainSingleSubs(src []byte) (ReverseChainSingleSubs, int, error) { + var item ReverseChainSingleSubs + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading ReverseChainSingleSubs: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.substFormat = binary.BigEndian.Uint16(src[0:]) + offsetCoverage := int(binary.BigEndian.Uint16(src[2:])) + arrayLengthBacktrackCoverages := int(binary.BigEndian.Uint16(src[4:])) + n += 6 + + { + + if offsetCoverage != 0 { // ignore null offset + if L := len(src); L < offsetCoverage { + return item, 0, fmt.Errorf("reading ReverseChainSingleSubs: "+"EOF: expected length: %d, got %d", offsetCoverage, L) + } + + var ( + err error + read int + ) + item.coverage, read, err = ParseCoverage(src[offsetCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading ReverseChainSingleSubs: %s", err) + } + offsetCoverage += read + } + } + { + + if L := len(src); L < 6+arrayLengthBacktrackCoverages*2 { + return item, 0, fmt.Errorf("reading ReverseChainSingleSubs: "+"EOF: expected length: %d, got %d", 6+arrayLengthBacktrackCoverages*2, L) + } + + item.BacktrackCoverages = make([]Coverage, arrayLengthBacktrackCoverages) // allocation guarded by the previous check + for i := range item.BacktrackCoverages { + offset := int(binary.BigEndian.Uint16(src[6+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading ReverseChainSingleSubs: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.BacktrackCoverages[i], _, err = ParseCoverage(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading ReverseChainSingleSubs: %s", err) + } + } + n += arrayLengthBacktrackCoverages * 2 + } + if L := len(src); L < n+2 { + return item, 0, fmt.Errorf("reading ReverseChainSingleSubs: "+"EOF: expected length: n + 2, got %d", L) + } + arrayLengthLookaheadCoverages := int(binary.BigEndian.Uint16(src[n:])) + n += 2 + + { + + if L := len(src); L < n+arrayLengthLookaheadCoverages*2 { + return item, 0, fmt.Errorf("reading ReverseChainSingleSubs: "+"EOF: expected length: %d, got %d", n+arrayLengthLookaheadCoverages*2, L) + } + + item.LookaheadCoverages = make([]Coverage, arrayLengthLookaheadCoverages) // allocation guarded by the previous check + for i := range item.LookaheadCoverages { + offset := int(binary.BigEndian.Uint16(src[n+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading ReverseChainSingleSubs: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.LookaheadCoverages[i], _, err = ParseCoverage(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading ReverseChainSingleSubs: %s", err) + } + } + n += arrayLengthLookaheadCoverages * 2 + } + if L := len(src); L < n+2 { + return item, 0, fmt.Errorf("reading ReverseChainSingleSubs: "+"EOF: expected length: n + 2, got %d", L) + } + arrayLengthSubstituteGlyphIDs := int(binary.BigEndian.Uint16(src[n:])) + n += 2 + + { + + if L := len(src); L < n+arrayLengthSubstituteGlyphIDs*2 { + return item, 0, fmt.Errorf("reading ReverseChainSingleSubs: "+"EOF: expected length: %d, got %d", n+arrayLengthSubstituteGlyphIDs*2, L) + } + + item.SubstituteGlyphIDs = make([]uint16, arrayLengthSubstituteGlyphIDs) // allocation guarded by the previous check + for i := range item.SubstituteGlyphIDs { + item.SubstituteGlyphIDs[i] = binary.BigEndian.Uint16(src[n+i*2:]) + } + n += arrayLengthSubstituteGlyphIDs * 2 + } + return item, n, nil +} + +func ParseSequence(src []byte) (Sequence, int, error) { + var item Sequence + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading Sequence: "+"EOF: expected length: 2, got %d", L) + } + arrayLengthSubstituteGlyphIDs := int(binary.BigEndian.Uint16(src[0:])) + n += 2 + + { + + if L := len(src); L < 2+arrayLengthSubstituteGlyphIDs*2 { + return item, 0, fmt.Errorf("reading Sequence: "+"EOF: expected length: %d, got %d", 2+arrayLengthSubstituteGlyphIDs*2, L) + } + + item.SubstituteGlyphIDs = make([]uint16, arrayLengthSubstituteGlyphIDs) // allocation guarded by the previous check + for i := range item.SubstituteGlyphIDs { + item.SubstituteGlyphIDs[i] = binary.BigEndian.Uint16(src[2+i*2:]) + } + n += arrayLengthSubstituteGlyphIDs * 2 + } + return item, n, nil +} + +func ParseSingleSubs(src []byte) (SingleSubs, int, error) { + var item SingleSubs + n := 0 + { + var ( + err error + read int + ) + item.Data, read, err = ParseSingleSubstData(src[0:]) + if err != nil { + return item, 0, fmt.Errorf("reading SingleSubs: %s", err) + } + n += read + } + return item, n, nil +} + +func ParseSingleSubstData(src []byte) (SingleSubstData, int, error) { + var item SingleSubstData + + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading SingleSubstData: "+"EOF: expected length: 2, got %d", L) + } + format := uint16(binary.BigEndian.Uint16(src[0:])) + var ( + read int + err error + ) + switch format { + case 1: + item, read, err = ParseSingleSubstData1(src[0:]) + case 2: + item, read, err = ParseSingleSubstData2(src[0:]) + default: + err = fmt.Errorf("unsupported SingleSubstData format %d", format) + } + if err != nil { + return item, 0, fmt.Errorf("reading SingleSubstData: %s", err) + } + + return item, read, nil +} + +func ParseSingleSubstData1(src []byte) (SingleSubstData1, int, error) { + var item SingleSubstData1 + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading SingleSubstData1: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + offsetCoverage := int(binary.BigEndian.Uint16(src[2:])) + item.DeltaGlyphID = int16(binary.BigEndian.Uint16(src[4:])) + n += 6 + + { + + if offsetCoverage != 0 { // ignore null offset + if L := len(src); L < offsetCoverage { + return item, 0, fmt.Errorf("reading SingleSubstData1: "+"EOF: expected length: %d, got %d", offsetCoverage, L) + } + + var ( + err error + read int + ) + item.Coverage, read, err = ParseCoverage(src[offsetCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading SingleSubstData1: %s", err) + } + offsetCoverage += read + } + } + return item, n, nil +} + +func ParseSingleSubstData2(src []byte) (SingleSubstData2, int, error) { + var item SingleSubstData2 + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading SingleSubstData2: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + offsetCoverage := int(binary.BigEndian.Uint16(src[2:])) + arrayLengthSubstituteGlyphIDs := int(binary.BigEndian.Uint16(src[4:])) + n += 6 + + { + + if offsetCoverage != 0 { // ignore null offset + if L := len(src); L < offsetCoverage { + return item, 0, fmt.Errorf("reading SingleSubstData2: "+"EOF: expected length: %d, got %d", offsetCoverage, L) + } + + var ( + err error + read int + ) + item.Coverage, read, err = ParseCoverage(src[offsetCoverage:]) + if err != nil { + return item, 0, fmt.Errorf("reading SingleSubstData2: %s", err) + } + offsetCoverage += read + } + } + { + + if L := len(src); L < 6+arrayLengthSubstituteGlyphIDs*2 { + return item, 0, fmt.Errorf("reading SingleSubstData2: "+"EOF: expected length: %d, got %d", 6+arrayLengthSubstituteGlyphIDs*2, L) + } + + item.SubstituteGlyphIDs = make([]uint16, arrayLengthSubstituteGlyphIDs) // allocation guarded by the previous check + for i := range item.SubstituteGlyphIDs { + item.SubstituteGlyphIDs[i] = binary.BigEndian.Uint16(src[6+i*2:]) + } + n += arrayLengthSubstituteGlyphIDs * 2 + } + return item, n, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_gsub_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_gsub_src.go new file mode 100644 index 0000000..5e78d80 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_gsub_src.go @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +type SingleSubs struct { + Data SingleSubstData +} + +type SingleSubstData interface { + isSingleSubstData() + + Cov() Coverage +} + +func (SingleSubstData1) isSingleSubstData() {} +func (SingleSubstData2) isSingleSubstData() {} + +type SingleSubstData1 struct { + format uint16 `unionTag:"1"` + Coverage Coverage `offsetSize:"Offset16"` // Offset to Coverage table, from beginning of substitution subtable + DeltaGlyphID int16 // Add to original glyph ID to get substitute glyph ID +} + +type SingleSubstData2 struct { + format uint16 `unionTag:"2"` + Coverage Coverage `offsetSize:"Offset16"` // Offset to Coverage table, from beginning of substitution subtable + SubstituteGlyphIDs []GlyphID `arrayCount:"FirstUint16"` //[glyphCount] Array of substitute glyph IDs — ordered by Coverage index +} + +type MultipleSubs struct { + substFormat uint16 // Format identifier: format = 1 + Coverage Coverage `offsetSize:"Offset16"` // Offset to Coverage table, from beginning of substitution subtable + Sequences []Sequence `arrayCount:"FirstUint16" offsetsArray:"Offset16"` + //[sequenceCount] Array of offsets to Sequence tables. Offsets are from beginning of substitution subtable, ordered by Coverage index +} + +type Sequence struct { + SubstituteGlyphIDs []GlyphID `arrayCount:"FirstUint16"` // [glyphCount] String of glyph IDs to substitute +} + +type AlternateSubs struct { + substFormat uint16 // Format identifier: format = 1 + Coverage Coverage `offsetSize:"Offset16"` // Offset to Coverage table, from beginning of substitution subtable + AlternateSets []AlternateSet `arrayCount:"FirstUint16" offsetsArray:"Offset16"` +} + +type AlternateSet struct { + AlternateGlyphIDs []GlyphID `arrayCount:"FirstUint16"` // Array of alternate glyph IDs, in arbitrary order +} + +type LigatureSubs struct { + substFormat uint16 // Format identifier: format = 1 + Coverage Coverage `offsetSize:"Offset16"` // Offset to Coverage table, from beginning of substitution subtable + LigatureSets []LigatureSet `arrayCount:"FirstUint16" offsetsArray:"Offset16"` //[ligatureSetCount] Array of offsets to LigatureSet tables. Offsets are from beginning of substitution subtable, ordered by Coverage index +} + +// All ligatures beginning with the same glyph +type LigatureSet struct { + Ligatures []Ligature `arrayCount:"FirstUint16" offsetsArray:"Offset16"` // [LigatureCount] Array of offsets to Ligature tables. Offsets are from beginning of LigatureSet table, ordered by preference. +} + +// Glyph components for one ligature +type Ligature struct { + LigatureGlyph GlyphID // glyph ID of ligature to substitute + componentCount uint16 // Number of components in the ligature + ComponentGlyphIDs []GlyphID `arrayCount:"ComputedField-componentCount-1"` // [componentCount - 1] Array of component glyph IDs — start with the second component, ordered in writing direction +} + +type ContextualSubs struct { + Data ContextualSubsITF +} + +type ContextualSubsITF interface { + isContextualSubsITF() + + Cov() Coverage +} + +type ( + ContextualSubs1 SequenceContextFormat1 + ContextualSubs2 SequenceContextFormat2 + ContextualSubs3 SequenceContextFormat3 +) + +func (ContextualSubs1) isContextualSubsITF() {} +func (ContextualSubs2) isContextualSubsITF() {} +func (ContextualSubs3) isContextualSubsITF() {} + +type ChainedContextualSubs struct { + Data ChainedContextualSubsITF +} + +type ChainedContextualSubsITF interface { + isChainedContextualSubsITF() + + Cov() Coverage +} + +type ( + ChainedContextualSubs1 ChainedSequenceContextFormat1 + ChainedContextualSubs2 ChainedSequenceContextFormat2 + ChainedContextualSubs3 ChainedSequenceContextFormat3 +) + +func (ChainedContextualSubs1) isChainedContextualSubsITF() {} +func (ChainedContextualSubs2) isChainedContextualSubsITF() {} +func (ChainedContextualSubs3) isChainedContextualSubsITF() {} + +type ExtensionSubs Extension + +type ReverseChainSingleSubs struct { + substFormat uint16 // Format identifier: format = 1 + coverage Coverage `offsetSize:"Offset16"` // Offset to Coverage table, from beginning of substitution subtable. + BacktrackCoverages []Coverage `arrayCount:"FirstUint16" offsetsArray:"Offset16"` //[backtrackGlyphCount] Array of offsets to coverage tables in backtrack sequence, in glyph sequence order. + LookaheadCoverages []Coverage `arrayCount:"FirstUint16" offsetsArray:"Offset16"` //[lookaheadGlyphCount] Array of offsets to coverage tables in lookahead sequence, in glyph sequence order. + SubstituteGlyphIDs []GlyphID `arrayCount:"FirstUint16"` //[glyphCount] Array of substitute glyph IDs — ordered by Coverage index. +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_layout.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_layout.go new file mode 100644 index 0000000..ea146ff --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_layout.go @@ -0,0 +1,814 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "errors" + "fmt" + "math/bits" +) + +// The following are types shared by GSUB and GPOS tables + +// Coverage specifies all the glyphs affected by a substitution or +// positioning operation described in a subtable. +// Conceptually is it a []GlyphIndex, with an Index method, +// but it may be implemented for efficiently. +// See https://learn.microsoft.com/typography/opentype/spec/chapter2#lookup-table +type Coverage interface { + isCov() + + // Index returns the index of the provided glyph, or + // `false` if the glyph is not covered by this lookup. + // Note: this method is injective: two distincts, covered glyphs are mapped + // to distincts indices. + Index(GlyphID) (int, bool) + + // Len return the number of glyphs covered. + // It is 0 for empty coverages. + // For non empty Coverages, it is also 1 + (maximum index returned) + Len() int +} + +func (Coverage1) isCov() {} +func (Coverage2) isCov() {} + +type Coverage1 struct { + format uint16 `unionTag:"1"` + Glyphs []GlyphID `arrayCount:"FirstUint16"` +} + +type Coverage2 struct { + format uint16 `unionTag:"2"` + Ranges []RangeRecord `arrayCount:"FirstUint16"` +} + +type RangeRecord struct { + StartGlyphID GlyphID // First glyph ID in the range + EndGlyphID GlyphID // Last glyph ID in the range + StartCoverageIndex uint16 // Coverage Index of first glyph ID in range +} + +// ClassDef stores a value for a set of GlyphIDs. +// Conceptually it is a map[GlyphID]uint16, but it may +// be implemented more efficiently. +type ClassDef interface { + isClassDef() + Class(gi GlyphID) (uint16, bool) + + // Extent returns the maximum class ID + 1. This is the length + // required for an array to be indexed by the class values. + Extent() int +} + +func (ClassDef1) isClassDef() {} +func (ClassDef2) isClassDef() {} + +type ClassDef1 struct { + format uint16 `unionTag:"1"` + StartGlyphID GlyphID // First glyph ID of the classValueArray + ClassValueArray []uint16 `arrayCount:"FirstUint16"` //[glyphCount] Array of Class Values — one per glyph ID +} + +type ClassDef2 struct { + format uint16 `unionTag:"2"` + ClassRangeRecords []ClassRangeRecord `arrayCount:"FirstUint16"` //[glyphCount] Array of Class Values — one per glyph ID +} + +type ClassRangeRecord struct { + StartGlyphID GlyphID // First glyph ID in the range + EndGlyphID GlyphID // Last glyph ID in the range + Class uint16 // Applied to all glyphs in the range +} + +// Lookups + +type SequenceLookupRecord struct { + SequenceIndex uint16 // Index (zero-based) into the input glyph sequence + LookupListIndex uint16 // Index (zero-based) into the LookupList +} + +type SequenceContextFormat1 struct { + format uint16 `unionTag:"1"` + coverage Coverage `offsetSize:"Offset16"` // Offset to Coverage table, from beginning of SequenceContextFormat1 table + SeqRuleSet []SequenceRuleSet `arrayCount:"FirstUint16" offsetsArray:"Offset16"` //[seqRuleSetCount] Array of offsets to SequenceRuleSet tables, from beginning of SequenceContextFormat1 table (offsets may be NULL) +} + +func (sc *SequenceContextFormat1) sanitize(lookupCount uint16) error { + for _, set := range sc.SeqRuleSet { + for _, rule := range set.SeqRule { + if err := rule.sanitize(lookupCount); err != nil { + return err + } + } + } + return nil +} + +type SequenceRuleSet struct { + SeqRule []SequenceRule `arrayCount:"FirstUint16" offsetsArray:"Offset16"` // Array of offsets to SequenceRule tables, from beginning of the SequenceRuleSet table +} + +type SequenceRule struct { + glyphCount uint16 // Number of glyphs in the input glyph sequence + seqLookupCount uint16 // Number of SequenceLookupRecords + InputSequence []GlyphID `arrayCount:"ComputedField-glyphCount-1"` //[glyphCount - 1] Array of input glyph IDs—starting with the second glyph + SeqLookupRecords []SequenceLookupRecord `arrayCount:"ComputedField-seqLookupCount"` //[seqLookupCount] Array of Sequence lookup records +} + +func (sr *SequenceRule) sanitize(lookupCount uint16) error { + for _, rec := range sr.SeqLookupRecords { + if rec.SequenceIndex >= sr.glyphCount { + return fmt.Errorf("invalid sequence lookup table (input index %d >= %d)", rec.SequenceIndex, sr.glyphCount) + } + if rec.LookupListIndex >= lookupCount { + return fmt.Errorf("invalid sequence lookup table (lookup index %d >= %d)", rec.LookupListIndex, lookupCount) + } + } + return nil +} + +type SequenceContextFormat2 struct { + format uint16 `unionTag:"2"` + coverage Coverage `offsetSize:"Offset16"` // Offset to Coverage table, from beginning of SequenceContextFormat2 table + ClassDef ClassDef `offsetSize:"Offset16"` // Offset to ClassDef table, from beginning of SequenceContextFormat2 table + ClassSeqRuleSet []ClassSequenceRuleSet `arrayCount:"FirstUint16" offsetsArray:"Offset16"` //[classSeqRuleSetCount] Array of offsets to ClassSequenceRuleSet tables, from beginning of SequenceContextFormat2 table (may be NULL) +} + +// ClassSequenceRuleSet has the same binary format as SequenceRuleSet, +// and using the same type simplifies later processing. +type ClassSequenceRuleSet = SequenceRuleSet + +type SequenceContextFormat3 struct { + format uint16 `unionTag:"3"` + glyphCount uint16 // Number of glyphs in the input sequence + seqLookupCount uint16 // Number of SequenceLookupRecords + Coverages []Coverage `arrayCount:"ComputedField-glyphCount" offsetsArray:"Offset16"` //[glyphCount] Array of offsets to Coverage tables, from beginning of SequenceContextFormat3 subtable + SeqLookupRecords []SequenceLookupRecord `arrayCount:"ComputedField-seqLookupCount"` //[seqLookupCount] Array of SequenceLookupRecords +} + +type ChainedSequenceContextFormat1 struct { + format uint16 `unionTag:"1"` + coverage Coverage `offsetSize:"Offset16"` // Offset to Coverage table, from beginning of ChainSequenceContextFormat1 table + ChainedSeqRuleSet []ChainedSequenceRuleSet `arrayCount:"FirstUint16" offsetsArray:"Offset16"` //[chainedSeqRuleSetCount] Array of offsets to ChainedSeqRuleSet tables, from beginning of ChainedSequenceContextFormat1 table (may be NULL) +} + +type ChainedSequenceRuleSet struct { + ChainedSeqRules []ChainedSequenceRule `arrayCount:"FirstUint16" offsetsArray:"Offset16"` // Array of offsets to SequenceRule tables, from beginning of the SequenceRuleSet table +} + +type ChainedSequenceRule struct { + BacktrackSequence []GlyphID `arrayCount:"FirstUint16"` //[backtrackGlyphCount] Array of backtrack glyph IDs + inputGlyphCount uint16 // Number of glyphs in the input sequence + InputSequence []GlyphID `arrayCount:"ComputedField-inputGlyphCount-1"` //[inputGlyphCount - 1] Array of input glyph IDs—start with second glyph + LookaheadSequence []GlyphID `arrayCount:"FirstUint16"` //[lookaheadGlyphCount] Array of lookahead glyph IDs + SeqLookupRecords []SequenceLookupRecord `arrayCount:"FirstUint16"` //[seqLookupCount] Array of SequenceLookupRecords +} + +type ChainedSequenceContextFormat2 struct { + format uint16 `unionTag:"2"` + coverage Coverage `offsetSize:"Offset16"` // Offset to Coverage table, from beginning of ChainedSequenceContextFormat2 table + BacktrackClassDef ClassDef `offsetSize:"Offset16"` // Offset to ClassDef table containing backtrack sequence context, from beginning of ChainedSequenceContextFormat2 table + InputClassDef ClassDef `offsetSize:"Offset16"` // Offset to ClassDef table containing input sequence context, from beginning of ChainedSequenceContextFormat2 table + LookaheadClassDef ClassDef `offsetSize:"Offset16"` // Offset to ClassDef table containing lookahead sequence context, from beginning of ChainedSequenceContextFormat2 table + ChainedClassSeqRuleSet []ChainedClassSequenceRuleSet `arrayCount:"FirstUint16" offsetsArray:"Offset16"` //[chainedClassSeqRuleSetCount] Array of offsets to ChainedClassSequenceRuleSet tables, from beginning of ChainedSequenceContextFormat2 table (may be NULL) +} + +// ChainedClassSequenceRuleSet has the same binary format as ChainedSequenceRuleSet, +// and using the same type simplifies later processing. +type ChainedClassSequenceRuleSet = ChainedSequenceRuleSet + +type ChainedSequenceContextFormat3 struct { + format uint16 `unionTag:"3"` + BacktrackCoverages []Coverage `arrayCount:"FirstUint16" offsetsArray:"Offset16"` //[backtrackGlyphCount] Array of offsets to coverage tables for the backtrack sequence + InputCoverages []Coverage `arrayCount:"FirstUint16" offsetsArray:"Offset16"` //[inputGlyphCount] Array of offsets to coverage tables for the input sequence + LookaheadCoverages []Coverage `arrayCount:"FirstUint16" offsetsArray:"Offset16"` //[lookaheadGlyphCount] Array of offsets to coverage tables for the lookahead sequence + SeqLookupRecords []SequenceLookupRecord `arrayCount:"FirstUint16"` //[seqLookupCount] Array of SequenceLookupRecords +} + +type Extension struct { + substFormat uint16 // Format identifier. Set to 1. + ExtensionLookupType uint16 // Lookup type of subtable referenced by extensionOffset (that is, the extension subtable). + ExtensionOffset Offset32 // Offset to the extension subtable, of lookup type extensionLookupType, relative to the start of the ExtensionSubstFormat1 subtable. + RawData []byte `subsliceStart:"AtStart" arrayCount:"ToEnd"` +} + +// GSUB is the Glyph Substitution (GSUB) table. +// It provides data for substition of glyphs for appropriate rendering of scripts, +// such as cursively-connecting forms in Arabic script, +// or for advanced typographic effects, such as ligatures. +// See https://learn.microsoft.com/fr-fr/typography/opentype/spec/gsub +type GSUB Layout + +// GSUBLookup is one lookup subtable data +type GSUBLookup interface { + isGSUBLookup() + + // Coverage returns the coverage of the lookup subtable. + // For ContextualSubs3 and ChainedContextualSubs3, its the coverage of the first input. + Cov() Coverage +} + +func (SingleSubs) isGSUBLookup() {} +func (MultipleSubs) isGSUBLookup() {} +func (AlternateSubs) isGSUBLookup() {} +func (LigatureSubs) isGSUBLookup() {} +func (ContextualSubs) isGSUBLookup() {} +func (ChainedContextualSubs) isGSUBLookup() {} +func (ExtensionSubs) isGSUBLookup() {} +func (ReverseChainSingleSubs) isGSUBLookup() {} + +func (ms MultipleSubs) Sanitize() error { + if exp, got := ms.Coverage.Len(), len(ms.Sequences); exp != got { + return fmt.Errorf("GSUB: invalid MultipleSubs sequences count (%d != %d)", exp, got) + } + return nil +} + +func (ls LigatureSubs) Sanitize() error { + if exp, got := ls.Coverage.Len(), len(ls.LigatureSets); exp != got { + return fmt.Errorf("GSUB: invalid LigatureSubs sets count (%d != %d)", exp, got) + } + return nil +} + +func (cs ContextualSubs) Sanitize(lookupCount uint16) error { + if f1, isFormat1 := cs.Data.(ContextualSubs1); isFormat1 { + return (*SequenceContextFormat1)(&f1).sanitize(lookupCount) + } + return nil +} + +func (rs ReverseChainSingleSubs) Sanitize() error { + if exp, got := rs.coverage.Len(), len(rs.SubstituteGlyphIDs); exp != got { + return fmt.Errorf("GSUB: invalid ReverseChainSingleSubs glyphs count (%d != %d)", exp, got) + } + return nil +} + +func (ext ExtensionSubs) Resolve() (GSUBLookup, error) { + if L, E := len(ext.RawData), int(ext.ExtensionOffset); L < E { + return nil, fmt.Errorf("EOF: expected length: %d, got %d", E, L) + } + lk, err := parseGSUBLookup(ext.RawData[ext.ExtensionOffset:], ext.ExtensionLookupType) + if err != nil { + return nil, err + } + if _, isExt := lk.(ExtensionSubs); isExt { + return nil, errors.New("invalid extension substitution table") + } + return lk, nil +} + +func parseGSUBLookup(src []byte, lookupType uint16) (out GSUBLookup, err error) { + switch lookupType { + case 1: // Single (format 1.1 1.2) Replace one glyph with one glyph + out, _, err = ParseSingleSubs(src) + case 2: // Multiple (format 2.1) Replace one glyph with more than one glyph + out, _, err = ParseMultipleSubs(src) + case 3: // Alternate (format 3.1) Replace one glyph with one of many glyphs + out, _, err = ParseAlternateSubs(src) + case 4: // Ligature (format 4.1) Replace multiple glyphs with one glyph + out, _, err = ParseLigatureSubs(src) + case 5: // Context (format 5.1 5.2 5.3) Replace one or more glyphs in context + out, _, err = ParseContextualSubs(src) + case 6: // Chaining Context (format 6.1 6.2 6.3) Replace one or more glyphs in chained context + out, _, err = ParseChainedContextualSubs(src) + case 7: // Extension Substitution (format 7.1) Extension mechanism for other substitutions + out, _, err = ParseExtensionSubs(src) + case 8: // Reverse chaining context single (format 8.1) + out, _, err = ParseReverseChainSingleSubs(src) + default: + err = fmt.Errorf("invalid GSUB Loopkup type %d", lookupType) + } + return out, err +} + +// AsGSUBLookups returns the GSUB lookup subtables. +func (lk Lookup) AsGSUBLookups() ([]GSUBLookup, error) { + var err error + out := make([]GSUBLookup, len(lk.subtableOffsets)) + for i, offset := range lk.subtableOffsets { + if L := len(lk.rawData); L < int(offset) { + return nil, fmt.Errorf("EOF: expected length: %d, got %d", offset, L) + } + out[i], err = parseGSUBLookup(lk.rawData[offset:], lk.lookupType) + if err != nil { + return nil, err + } + } + + return out, nil +} + +// ------------------------ GPOS common data structures ------------------------ + +// GPOS is the Glyph Positioning (GPOS) table. +// It provides precise control over glyph placement +// for sophisticated text layout and rendering in each script +// and language system that a font supports. +// See https://learn.microsoft.com/fr-fr/typography/opentype/spec/gpos +type GPOS Layout + +type GPOSLookup interface { + isGPOSLookup() + + // Coverage returns the coverage of the lookup subtable. + // For ContextualPos3 and ChainedContextualPos3, its the coverage of the first input. + Cov() Coverage +} + +func (SinglePos) isGPOSLookup() {} +func (PairPos) isGPOSLookup() {} +func (CursivePos) isGPOSLookup() {} +func (MarkBasePos) isGPOSLookup() {} +func (MarkLigPos) isGPOSLookup() {} +func (MarkMarkPos) isGPOSLookup() {} +func (ContextualPos) isGPOSLookup() {} +func (ChainedContextualPos) isGPOSLookup() {} +func (ExtensionPos) isGPOSLookup() {} + +func (sp *SinglePos) Sanitize() error { + if f2, isFormat2 := sp.Data.(SinglePosData2); isFormat2 { + if exp, got := f2.coverage.Len(), len(f2.ValueRecords); exp != got { + return fmt.Errorf("GPOS: invalid SinglePos values count (%d != %d)", exp, got) + } + } + return nil +} + +func (pp *PairPos) Sanitize() error { + if f1, isFormat1 := pp.Data.(PairPosData1); isFormat1 { + // there are fonts with to much PairSets : accept it + if exp, got := f1.coverage.Len(), len(f1.PairSets); exp > got { + return fmt.Errorf("GPOS: invalid PairPos1 sets count (%d > %d)", exp, got) + } + } else if f2, isFormat2 := pp.Data.(PairPosData2); isFormat2 { + if exp, got := f2.ClassDef1.Extent(), int(f2.class1Count); exp != got { + return fmt.Errorf("GPOS: invalid PairPos2 class1 count (%d != %d)", exp, got) + } + if exp, got := f2.ClassDef2.Extent(), int(f2.class2Count); exp != got { + return fmt.Errorf("GPOS: invalid PairPos2 class2 count (%d != %d)", exp, got) + } + } + return nil +} + +func (mp *MarkBasePos) Sanitize() error { + if exp, got := mp.markCoverage.Len(), len(mp.MarkArray.MarkRecords); exp != got { + return fmt.Errorf("GPOS: invalid MarkBasePos marks count (%d != %d)", exp, got) + } + if exp, got := mp.BaseCoverage.Len(), len(mp.BaseArray.baseRecords); exp != got { + return fmt.Errorf("GPOS: invalid MarkBasePos marks count (%d != %d)", exp, got) + } + if err := mp.BaseArray.Anchors().sanitizeOffsets(); err != nil { + return err + } + + return nil +} + +func (mp *MarkLigPos) Sanitize() error { + if exp, got := mp.MarkCoverage.Len(), len(mp.MarkArray.MarkAnchors); exp != got { + return fmt.Errorf("GPOS: invalid MarkBasePos marks count (%d != %d)", exp, got) + } + if exp, got := mp.LigatureCoverage.Len(), len(mp.LigatureArray.LigatureAttachs); exp != got { + return fmt.Errorf("GPOS: invalid MarkBasePos marks count (%d != %d)", exp, got) + } + + return nil +} + +func (cs *ContextualPos) Sanitize(lookupCount uint16) error { + if f1, isFormat1 := cs.Data.(ContextualPos1); isFormat1 { + return (*SequenceContextFormat1)(&f1).sanitize(lookupCount) + } + return nil +} + +func (ext ExtensionPos) Resolve() (GPOSLookup, error) { + if L, E := len(ext.RawData), int(ext.ExtensionOffset); L < E { + return nil, fmt.Errorf("EOF: expected length: %d, got %d", E, L) + } + lk, err := parseGPOSLookup(ext.RawData[ext.ExtensionOffset:], ext.ExtensionLookupType) + if err != nil { + return nil, err + } + if _, isExt := lk.(ExtensionPos); isExt { + return nil, errors.New("invalid extension positioning table") + } + return lk, nil +} + +func parseGPOSLookup(src []byte, lookupType uint16) (out GPOSLookup, err error) { + switch lookupType { + case 1: // Single adjustment Adjust position of a single glyph + out, _, err = ParseSinglePos(src) + case 2: // Pair adjustment Adjust position of a pair of glyphs + out, _, err = ParsePairPos(src) + case 3: // Cursive attachment Attach cursive glyphs + out, _, err = ParseCursivePos(src) + case 4: // MarkToBase attachment Attach a combining mark to a base glyph + out, _, err = ParseMarkBasePos(src) + case 5: // MarkToLigature attachment Attach a combining mark to a ligature + out, _, err = ParseMarkLigPos(src) + case 6: // MarkToMark attachment Attach a combining mark to another mark + out, _, err = ParseMarkMarkPos(src) + case 7: // Context positioning Position one or more glyphs in context + out, _, err = ParseContextualPos(src) + case 8: // Chained Context positioning Position one or more glyphs in chained context + out, _, err = ParseChainedContextualPos(src) + case 9: // Extension positioning Extension mechanism for other positionings + out, _, err = ParseExtensionPos(src) + default: + err = fmt.Errorf("invalid GPOS Loopkup type %d", lookupType) + } + return out, err +} + +// AsGPOSLookups returns the GPOS lookup subtables +func (lk Lookup) AsGPOSLookups() ([]GPOSLookup, error) { + var err error + out := make([]GPOSLookup, len(lk.subtableOffsets)) + for i, offset := range lk.subtableOffsets { + if L := len(lk.rawData); L < int(offset) { + return nil, fmt.Errorf("EOF: expected length: %d, got %d", offset, L) + } + out[i], err = parseGPOSLookup(lk.rawData[offset:], lk.lookupType) + if err != nil { + return nil, err + } + } + + return out, nil +} + +// ValueFormat is a mask indicating which field +// are set in a GPOS [ValueRecord]. +// It is often shared between many records. +type ValueFormat uint16 + +// number of fields present +func (f ValueFormat) size() int { return bits.OnesCount16(uint16(f)) } + +const ( + XPlacement ValueFormat = 1 << iota // Includes horizontal adjustment for placement + YPlacement // Includes vertical adjustment for placement + XAdvance // Includes horizontal adjustment for advance + YAdvance // Includes vertical adjustment for advance + XPlaDevice // Includes horizontal Device table for placement + YPlaDevice // Includes vertical Device table for placement + XAdvDevice // Includes horizontal Device table for advance + YAdvDevice // Includes vertical Device table for advance + + // Mask for having any Device table + Devices = XPlaDevice | YPlaDevice | XAdvDevice | YAdvDevice +) + +// ValueRecord has optional fields +type ValueRecord struct { + XPlacement int16 // Horizontal adjustment for placement, in design units. + YPlacement int16 // Vertical adjustment for placement, in design units. + XAdvance int16 // Horizontal adjustment for advance, in design units — only used for horizontal layout. + YAdvance int16 // Vertical adjustment for advance, in design units — only used for vertical layout. + XPlaDevice DeviceTable // Offset to Device table (non-variable font) / VariationIndex table (variable font) for horizontal placement, from beginning of the immediate parent table (SinglePos or PairPosFormat2 lookup subtable, PairSet table within a PairPosFormat1 lookup subtable) — may be NULL. + YPlaDevice DeviceTable // Offset to Device table (non-variable font) / VariationIndex table (variable font) for vertical placement, from beginning of the immediate parent table (SinglePos or PairPosFormat2 lookup subtable, PairSet table within a PairPosFormat1 lookup subtable) — may be NULL. + XAdvDevice DeviceTable // Offset to Device table (non-variable font) / VariationIndex table (variable font) for horizontal advance, from beginning of the immediate parent table (SinglePos or PairPosFormat2 lookup subtable, PairSet table within a PairPosFormat1 lookup subtable) — may be NULL. + YAdvDevice DeviceTable // Offset to Device table (non-variable font) / VariationIndex table (variable font) for vertical advance, from beginning of the immediate parent table (SinglePos or PairPosFormat2 lookup subtable, PairSet table within a PairPosFormat1 lookup su +} + +// [data] must start at the immediate parent table, [offset] indicating +// the start of the record in it. +// Returns [offset] + the number of bytes read from [offset] +// Note that a [format] with value 0, is supported, resulting in a no-op +func parseValueRecord(format ValueFormat, data []byte, offset int) (out ValueRecord, _ int, err error) { + if L := len(data); L < offset { + return out, 0, fmt.Errorf("EOF: expected length: %d, got %d", offset, L) + } + + size := format.size() // number of fields present + if size == 0 { // return early + return out, offset, nil + } + // start by parsing the list of values + values, err := ParseUint16s(data[offset:], size) + if err != nil { + return out, 0, fmt.Errorf("invalid value record: %s", err) + } + // follow the order + cursor := 0 + if format&XPlacement != 0 { + out.XPlacement = int16(values[cursor]) + cursor++ + } + if format&YPlacement != 0 { + out.YPlacement = int16(values[cursor]) + cursor++ + } + if format&XAdvance != 0 { + out.XAdvance = int16(values[cursor]) + cursor++ + } + if format&YAdvance != 0 { + out.YAdvance = int16(values[cursor]) + cursor++ + } + if format&XPlaDevice != 0 { + if devOffset := values[cursor]; devOffset != 0 { + out.XPlaDevice, err = parseDeviceTable(data, devOffset) + if err != nil { + return out, 0, err + } + } + cursor++ + } + if format&YPlaDevice != 0 { + if devOffset := values[cursor]; devOffset != 0 { + out.YPlaDevice, err = parseDeviceTable(data, devOffset) + if err != nil { + return out, 0, err + } + } + cursor++ + } + if format&XAdvDevice != 0 { + if devOffset := values[cursor]; devOffset != 0 { + out.XAdvDevice, err = parseDeviceTable(data, devOffset) + if err != nil { + return out, 0, err + } + } + cursor++ + } + if format&YAdvDevice != 0 { + if devOffset := values[cursor]; devOffset != 0 { + out.YAdvDevice, err = parseDeviceTable(data, devOffset) + if err != nil { + return out, 0, err + } + } + cursor++ // useless actually + } + return out, offset + 2*size, err +} + +type pairValueRecords struct { + data []byte // start with the item count + fmt1, fmt2 ValueFormat +} + +// panic if index is out of range +func (ps pairValueRecords) get(index int) (out PairValueRecord, err error) { + recLen := 1 + ps.fmt1.size() + ps.fmt2.size() + offset := 2 + 2*index*recLen + + out.SecondGlyph = GlyphID(binary.BigEndian.Uint16(ps.data[offset:])) + v1, newOffset, err := parseValueRecord(ps.fmt1, ps.data, offset+2) + if err != nil { + return out, fmt.Errorf("invalid pair set table: %s", err) + } + v2, _, err := parseValueRecord(ps.fmt2, ps.data, newOffset) + if err != nil { + return out, fmt.Errorf("invalid pair set table: %s", err) + } + out.ValueRecord1 = v1 + out.ValueRecord2 = v2 + return out, nil +} + +// DeviceTable is either an DeviceHinting for standard fonts, +// or a DeviceVariation for variable fonts. +type DeviceTable interface { + isDevice() +} + +func (DeviceHinting) isDevice() {} +func (DeviceVariation) isDevice() {} + +type DeviceHinting struct { + // with length endSize - startSize + 1 + Values []int8 + // correction range, in ppem + StartSize, EndSize uint16 +} + +type DeviceVariation VariationStoreIndex + +func parseDeviceTable(src []byte, offset uint16) (DeviceTable, error) { + if L := len(src); L < int(offset)+6 { + return nil, fmt.Errorf("EOF: expected length: %d, got %d", offset+6, L) + } + var header DeviceTableHeader + header.mustParse(src[offset:]) + + switch format := header.deltaFormat; format { + case 1, 2, 3: + var out DeviceHinting + + out.StartSize, out.EndSize = header.first, header.second + if out.EndSize < out.StartSize { + return nil, errors.New("invalid positionning device subtable") + } + + nbPerUint16 := 16 / (1 << format) // 8, 4 or 2 + outLength := int(out.EndSize - out.StartSize + 1) + var count int + if outLength%nbPerUint16 == 0 { + count = outLength / nbPerUint16 + } else { + // add padding + count = outLength/nbPerUint16 + 1 + } + uint16s, err := ParseUint16s(src[offset+6:], count) + if err != nil { + return nil, err + } + out.Values = make([]int8, count*nbPerUint16) // handle rounding error by reslicing after + switch format { + case 1: + for i, u := range uint16s { + uint16As2Bits(out.Values[i*8:], u) + } + case 2: + for i, u := range uint16s { + uint16As4Bits(out.Values[i*4:], u) + } + case 3: + for i, u := range uint16s { + uint16As8Bits(out.Values[i*2:], u) + } + } + out.Values = out.Values[:outLength] + return out, nil + case 0x8000: + return DeviceVariation{DeltaSetOuter: header.first, DeltaSetInner: header.second}, nil + default: + return nil, fmt.Errorf("unsupported positionning device subtable: %d", format) + } +} + +type PairValueRecord struct { + SecondGlyph GlyphID // Glyph ID of second glyph in the pair (first glyph is listed in the Coverage table). + ValueRecord1 ValueRecord // Positioning data for the first glyph in the pair. + ValueRecord2 ValueRecord // Positioning data for the second glyph in the pair. +} + +type Class1Record []Class2Record //[class2Count] Array of Class2 records, ordered by classes in classDef2. + +type Class2Record struct { + ValueRecord1 ValueRecord // Positioning for first glyph — empty if valueFormat1 = 0. + ValueRecord2 ValueRecord // Positioning for second glyph — empty if valueFormat2 = 0. +} + +func (AnchorFormat1) isAnchor() {} +func (AnchorFormat2) isAnchor() {} +func (AnchorFormat3) isAnchor() {} + +type AnchorFormat1 struct { + anchorFormat uint16 `unionTag:"1"` + XCoordinate int16 // Horizontal value, in design units + YCoordinate int16 // Vertical value, in design units +} + +type AnchorFormat2 struct { + anchorFormat uint16 `unionTag:"2"` + XCoordinate int16 // Horizontal value, in design units + YCoordinate int16 // Vertical value, in design units + AnchorPoint uint16 // Index to glyph contour point +} + +type AnchorFormat3 struct { + anchorFormat uint16 `unionTag:"3"` + XCoordinate int16 // Horizontal value, in design units + YCoordinate int16 // Vertical value, in design units + xDeviceOffset Offset16 // Offset to Device table (non-variable font) / VariationIndex table (variable font) for X coordinate, from beginning of Anchor table (may be NULL) + yDeviceOffset Offset16 // Offset to Device table (non-variable font) / VariationIndex table (variable font) for Y coordinate, from beginning of Anchor table (may be NULL) + XDevice DeviceTable `isOpaque:""` // Offset to Device table (non-variable font) / VariationIndex table (variable font) for X coordinate, from beginning of Anchor table (may be NULL) + YDevice DeviceTable `isOpaque:""` // Offset to Device table (non-variable font) / VariationIndex table (variable font) for Y coordinate, from beginning of Anchor table (may be NULL) +} + +func (af *AnchorFormat3) parseXDevice(src []byte) error { + if af.xDeviceOffset == 0 { + return nil + } + var err error + af.XDevice, err = parseDeviceTable(src, uint16(af.xDeviceOffset)) + return err +} + +func (af *AnchorFormat3) parseYDevice(src []byte) error { + if af.yDeviceOffset == 0 { + return nil + } + var err error + af.YDevice, err = parseDeviceTable(src, uint16(af.yDeviceOffset)) + return err +} + +// AnchorMatrix is a compact representation of a [][]Anchor +type AnchorMatrix struct { + records []anchorOffsets + data []byte +} + +func (am AnchorMatrix) Len() int { return len(am.records) } + +func (am AnchorMatrix) sanitizeOffsets() error { + for _, list := range am.records { + for _, offset := range list.offsets { + if offset == 0 { + continue + } + if L := len(am.data); L < int(offset) { + return fmt.Errorf("EOF: expected length: %d, got %d", offset, L) + } + } + } + return nil +} + +func (am AnchorMatrix) Anchor(index, class int) Anchor { + if len(am.records) < index { + return nil + } + offsets := am.records[index].offsets + if len(offsets) < class { + return nil + } + offset := offsets[class] + if offset == 0 { + return nil + } + anchor, _, _ := ParseAnchor(am.data[offset:]) // offset is sanitized + return anchor +} + +type MarkArray struct { + MarkRecords []MarkRecord `arrayCount:"FirstUint16"` //[markCount] Array of MarkRecords, ordered by corresponding glyphs in the associated mark Coverage table. + MarkAnchors []Anchor `isOpaque:""` // with same length as MarkRecords +} + +func (ma *MarkArray) parseMarkAnchors(src []byte) error { + ma.MarkAnchors = make([]Anchor, len(ma.MarkRecords)) + var err error + for i, rec := range ma.MarkRecords { + if L := len(src); L < int(rec.markAnchorOffset) { + return fmt.Errorf("EOF: expected length: %d, got %d", rec.markAnchorOffset, L) + } + ma.MarkAnchors[i], _, err = ParseAnchor(src[rec.markAnchorOffset:]) + if err != nil { + return err + } + } + return nil +} + +type MarkRecord struct { + MarkClass uint16 // Class defined for the associated mark. + markAnchorOffset Offset16 // Offset to Anchor table, from beginning of MarkArray table. +} + +// ------------------------------ parsing helpers ------------------------------ + +// write 8 elements +func uint16As2Bits(dst []int8, u uint16) { + const mask = 0xFE // 11111110 + dst[0] = int8((0-uint8(u>>15&1))&mask | uint8(u>>14&1)) + dst[1] = int8((0-uint8(u>>13&1))&mask | uint8(u>>12&1)) + dst[2] = int8((0-uint8(u>>11&1))&mask | uint8(u>>10&1)) + dst[3] = int8((0-uint8(u>>9&1))&mask | uint8(u>>8&1)) + dst[4] = int8((0-uint8(u>>7&1))&mask | uint8(u>>6&1)) + dst[5] = int8((0-uint8(u>>5&1))&mask | uint8(u>>4&1)) + dst[6] = int8((0-uint8(u>>3&1))&mask | uint8(u>>2&1)) + dst[7] = int8((0-uint8(u>>1&1))&mask | uint8(u>>0&1)) +} + +// write 4 elements +func uint16As4Bits(dst []int8, u uint16) { + const mask = 0xF8 // 11111000 + + dst[0] = int8((0-uint8(u>>15&1))&mask | uint8(u>>12&0x07)) + dst[1] = int8((0-uint8(u>>11&1))&mask | uint8(u>>8&0x07)) + dst[2] = int8((0-uint8(u>>7&1))&mask | uint8(u>>4&0x07)) + dst[3] = int8((0-uint8(u>>3&1))&mask | uint8(u>>0&0x07)) +} + +// write 2 elements +func uint16As8Bits(dst []int8, u uint16) { + dst[0] = int8(u >> 8) + dst[1] = int8(u) +} + +// ParseUint16s interprets data as a (big endian) uint16 slice. +// It returns an error if [data] is not long enough for the given [count]. +func ParseUint16s(src []byte, count int) ([]uint16, error) { + if L := len(src); L < 2*count { + return nil, fmt.Errorf("EOF: expected length: %d, got %d", 2*count, L) + } + out := make([]uint16, count) + for i := range out { + out[i] = binary.BigEndian.Uint16(src[2*i:]) + } + return out, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_layout_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_layout_gen.go new file mode 100644 index 0000000..e6ae680 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_layout_gen.go @@ -0,0 +1,513 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from ot_layout_src.go. DO NOT EDIT + +func (item *ConditionFormat1) mustParse(src []byte) { + _ = src[7] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + item.AxisIndex = binary.BigEndian.Uint16(src[2:]) + item.FilterRangeMinValue = Coord(binary.BigEndian.Uint16(src[4:])) + item.FilterRangeMaxValue = Coord(binary.BigEndian.Uint16(src[6:])) +} + +func ParseConditionFormat1(src []byte) (ConditionFormat1, int, error) { + var item ConditionFormat1 + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading ConditionFormat1: "+"EOF: expected length: 8, got %d", L) + } + item.mustParse(src) + n += 8 + return item, n, nil +} + +func ParseConditionSet(src []byte) (ConditionSet, int, error) { + var item ConditionSet + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading ConditionSet: "+"EOF: expected length: 2, got %d", L) + } + arrayLengthConditions := int(binary.BigEndian.Uint16(src[0:])) + n += 2 + + { + + if L := len(src); L < 2+arrayLengthConditions*4 { + return item, 0, fmt.Errorf("reading ConditionSet: "+"EOF: expected length: %d, got %d", 2+arrayLengthConditions*4, L) + } + + item.Conditions = make([]ConditionFormat1, arrayLengthConditions) // allocation guarded by the previous check + for i := range item.Conditions { + offset := int(binary.BigEndian.Uint32(src[2+i*4:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading ConditionSet: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.Conditions[i], _, err = ParseConditionFormat1(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading ConditionSet: %s", err) + } + } + n += arrayLengthConditions * 4 + } + return item, n, nil +} + +func ParseFeature(src []byte) (Feature, int, error) { + var item Feature + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading Feature: "+"EOF: expected length: 4, got %d", L) + } + _ = src[3] // early bound checking + item.featureParamsOffset = binary.BigEndian.Uint16(src[0:]) + arrayLengthLookupListIndices := int(binary.BigEndian.Uint16(src[2:])) + n += 4 + + { + + if L := len(src); L < 4+arrayLengthLookupListIndices*2 { + return item, 0, fmt.Errorf("reading Feature: "+"EOF: expected length: %d, got %d", 4+arrayLengthLookupListIndices*2, L) + } + + item.LookupListIndices = make([]uint16, arrayLengthLookupListIndices) // allocation guarded by the previous check + for i := range item.LookupListIndices { + item.LookupListIndices[i] = binary.BigEndian.Uint16(src[4+i*2:]) + } + n += arrayLengthLookupListIndices * 2 + } + return item, n, nil +} + +func ParseFeatureList(src []byte) (FeatureList, int, error) { + var item FeatureList + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading FeatureList: "+"EOF: expected length: 2, got %d", L) + } + arrayLengthRecords := int(binary.BigEndian.Uint16(src[0:])) + n += 2 + + { + + if L := len(src); L < 2+arrayLengthRecords*6 { + return item, 0, fmt.Errorf("reading FeatureList: "+"EOF: expected length: %d, got %d", 2+arrayLengthRecords*6, L) + } + + item.Records = make([]TagOffsetRecord, arrayLengthRecords) // allocation guarded by the previous check + for i := range item.Records { + item.Records[i].mustParse(src[2+i*6:]) + } + n += arrayLengthRecords * 6 + } + { + + err := item.parseFeatures(src[:]) + if err != nil { + return item, 0, fmt.Errorf("reading FeatureList: %s", err) + } + } + return item, n, nil +} + +func ParseFeatureTableSubstitution(src []byte) (FeatureTableSubstitution, int, error) { + var item FeatureTableSubstitution + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading FeatureTableSubstitution: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.majorVersion = binary.BigEndian.Uint16(src[0:]) + item.minorVersion = binary.BigEndian.Uint16(src[2:]) + arrayLengthSubstitutions := int(binary.BigEndian.Uint16(src[4:])) + n += 6 + + { + + offset := 6 + for i := 0; i < arrayLengthSubstitutions; i++ { + elem, read, err := ParseFeatureTableSubstitutionRecord(src[offset:], src) + if err != nil { + return item, 0, fmt.Errorf("reading FeatureTableSubstitution: %s", err) + } + item.Substitutions = append(item.Substitutions, elem) + offset += read + } + n = offset + } + return item, n, nil +} + +func ParseFeatureTableSubstitutionRecord(src []byte, parentSrc []byte) (FeatureTableSubstitutionRecord, int, error) { + var item FeatureTableSubstitutionRecord + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading FeatureTableSubstitutionRecord: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.FeatureIndex = binary.BigEndian.Uint16(src[0:]) + offsetAlternateFeature := int(binary.BigEndian.Uint32(src[2:])) + n += 6 + + { + + if offsetAlternateFeature != 0 { // ignore null offset + if L := len(parentSrc); L < offsetAlternateFeature { + return item, 0, fmt.Errorf("reading FeatureTableSubstitutionRecord: "+"EOF: expected length: %d, got %d", offsetAlternateFeature, L) + } + + var err error + item.AlternateFeature, _, err = ParseFeature(parentSrc[offsetAlternateFeature:]) + if err != nil { + return item, 0, fmt.Errorf("reading FeatureTableSubstitutionRecord: %s", err) + } + + } + } + return item, n, nil +} + +func ParseFeatureVariation(src []byte) (FeatureVariation, int, error) { + var item FeatureVariation + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading FeatureVariation: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.majorVersion = binary.BigEndian.Uint16(src[0:]) + item.minorVersion = binary.BigEndian.Uint16(src[2:]) + arrayLengthFeatureVariationRecords := int(binary.BigEndian.Uint32(src[4:])) + n += 8 + + { + + offset := 8 + for i := 0; i < arrayLengthFeatureVariationRecords; i++ { + elem, read, err := ParseFeatureVariationRecord(src[offset:], src) + if err != nil { + return item, 0, fmt.Errorf("reading FeatureVariation: %s", err) + } + item.FeatureVariationRecords = append(item.FeatureVariationRecords, elem) + offset += read + } + n = offset + } + return item, n, nil +} + +func ParseFeatureVariationRecord(src []byte, parentSrc []byte) (FeatureVariationRecord, int, error) { + var item FeatureVariationRecord + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading FeatureVariationRecord: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + offsetConditionSet := int(binary.BigEndian.Uint32(src[0:])) + offsetSubstitutions := int(binary.BigEndian.Uint32(src[4:])) + n += 8 + + { + + if offsetConditionSet != 0 { // ignore null offset + if L := len(parentSrc); L < offsetConditionSet { + return item, 0, fmt.Errorf("reading FeatureVariationRecord: "+"EOF: expected length: %d, got %d", offsetConditionSet, L) + } + + var err error + item.ConditionSet, _, err = ParseConditionSet(parentSrc[offsetConditionSet:]) + if err != nil { + return item, 0, fmt.Errorf("reading FeatureVariationRecord: %s", err) + } + + } + } + { + + if offsetSubstitutions != 0 { // ignore null offset + if L := len(parentSrc); L < offsetSubstitutions { + return item, 0, fmt.Errorf("reading FeatureVariationRecord: "+"EOF: expected length: %d, got %d", offsetSubstitutions, L) + } + + var err error + item.Substitutions, _, err = ParseFeatureTableSubstitution(parentSrc[offsetSubstitutions:]) + if err != nil { + return item, 0, fmt.Errorf("reading FeatureVariationRecord: %s", err) + } + + } + } + return item, n, nil +} + +func ParseLangSys(src []byte) (LangSys, int, error) { + var item LangSys + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading LangSys: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.lookupOrderOffset = binary.BigEndian.Uint16(src[0:]) + item.RequiredFeatureIndex = binary.BigEndian.Uint16(src[2:]) + arrayLengthFeatureIndices := int(binary.BigEndian.Uint16(src[4:])) + n += 6 + + { + + if L := len(src); L < 6+arrayLengthFeatureIndices*2 { + return item, 0, fmt.Errorf("reading LangSys: "+"EOF: expected length: %d, got %d", 6+arrayLengthFeatureIndices*2, L) + } + + item.FeatureIndices = make([]uint16, arrayLengthFeatureIndices) // allocation guarded by the previous check + for i := range item.FeatureIndices { + item.FeatureIndices[i] = binary.BigEndian.Uint16(src[6+i*2:]) + } + n += arrayLengthFeatureIndices * 2 + } + return item, n, nil +} + +func ParseLayout(src []byte) (Layout, int, error) { + var item Layout + n := 0 + if L := len(src); L < 10 { + return item, 0, fmt.Errorf("reading Layout: "+"EOF: expected length: 10, got %d", L) + } + _ = src[9] // early bound checking + item.majorVersion = binary.BigEndian.Uint16(src[0:]) + item.minorVersion = binary.BigEndian.Uint16(src[2:]) + offsetScriptList := int(binary.BigEndian.Uint16(src[4:])) + offsetFeatureList := int(binary.BigEndian.Uint16(src[6:])) + offsetLookupList := int(binary.BigEndian.Uint16(src[8:])) + n += 10 + + { + + if offsetScriptList != 0 { // ignore null offset + if L := len(src); L < offsetScriptList { + return item, 0, fmt.Errorf("reading Layout: "+"EOF: expected length: %d, got %d", offsetScriptList, L) + } + + var err error + item.ScriptList, _, err = ParseScriptList(src[offsetScriptList:]) + if err != nil { + return item, 0, fmt.Errorf("reading Layout: %s", err) + } + + } + } + { + + if offsetFeatureList != 0 { // ignore null offset + if L := len(src); L < offsetFeatureList { + return item, 0, fmt.Errorf("reading Layout: "+"EOF: expected length: %d, got %d", offsetFeatureList, L) + } + + var err error + item.FeatureList, _, err = ParseFeatureList(src[offsetFeatureList:]) + if err != nil { + return item, 0, fmt.Errorf("reading Layout: %s", err) + } + + } + } + { + + if offsetLookupList != 0 { // ignore null offset + if L := len(src); L < offsetLookupList { + return item, 0, fmt.Errorf("reading Layout: "+"EOF: expected length: %d, got %d", offsetLookupList, L) + } + + var err error + item.LookupList, _, err = parseLookupList(src[offsetLookupList:]) + if err != nil { + return item, 0, fmt.Errorf("reading Layout: %s", err) + } + + } + } + { + + read, err := item.parseFeatureVariations(src[:]) + if err != nil { + return item, 0, fmt.Errorf("reading Layout: %s", err) + } + n = read + } + return item, n, nil +} + +func ParseLookup(src []byte) (Lookup, int, error) { + var item Lookup + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading Lookup: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.lookupType = binary.BigEndian.Uint16(src[0:]) + item.LookupFlag = binary.BigEndian.Uint16(src[2:]) + arrayLengthSubtableOffsets := int(binary.BigEndian.Uint16(src[4:])) + n += 6 + + { + + if L := len(src); L < 6+arrayLengthSubtableOffsets*2 { + return item, 0, fmt.Errorf("reading Lookup: "+"EOF: expected length: %d, got %d", 6+arrayLengthSubtableOffsets*2, L) + } + + item.subtableOffsets = make([]Offset16, arrayLengthSubtableOffsets) // allocation guarded by the previous check + for i := range item.subtableOffsets { + item.subtableOffsets[i] = Offset16(binary.BigEndian.Uint16(src[6+i*2:])) + } + n += arrayLengthSubtableOffsets * 2 + } + if L := len(src); L < n+2 { + return item, 0, fmt.Errorf("reading Lookup: "+"EOF: expected length: n + 2, got %d", L) + } + item.MarkFilteringSet = binary.BigEndian.Uint16(src[n:]) + n += 2 + + { + + item.rawData = src[0:] + n = len(src) + } + return item, n, nil +} + +func ParseScript(src []byte) (Script, int, error) { + var item Script + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading Script: "+"EOF: expected length: 4, got %d", L) + } + _ = src[3] // early bound checking + offsetDefaultLangSys := int(binary.BigEndian.Uint16(src[0:])) + arrayLengthLangSysRecords := int(binary.BigEndian.Uint16(src[2:])) + n += 4 + + { + + if offsetDefaultLangSys != 0 { // ignore null offset + if L := len(src); L < offsetDefaultLangSys { + return item, 0, fmt.Errorf("reading Script: "+"EOF: expected length: %d, got %d", offsetDefaultLangSys, L) + } + + var tmpDefaultLangSys LangSys + var err error + tmpDefaultLangSys, _, err = ParseLangSys(src[offsetDefaultLangSys:]) + if err != nil { + return item, 0, fmt.Errorf("reading Script: %s", err) + } + + item.DefaultLangSys = &tmpDefaultLangSys + } + } + { + + if L := len(src); L < 4+arrayLengthLangSysRecords*6 { + return item, 0, fmt.Errorf("reading Script: "+"EOF: expected length: %d, got %d", 4+arrayLengthLangSysRecords*6, L) + } + + item.LangSysRecords = make([]TagOffsetRecord, arrayLengthLangSysRecords) // allocation guarded by the previous check + for i := range item.LangSysRecords { + item.LangSysRecords[i].mustParse(src[4+i*6:]) + } + n += arrayLengthLangSysRecords * 6 + } + { + + err := item.parseLangSys(src[:]) + if err != nil { + return item, 0, fmt.Errorf("reading Script: %s", err) + } + } + return item, n, nil +} + +func ParseScriptList(src []byte) (ScriptList, int, error) { + var item ScriptList + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading ScriptList: "+"EOF: expected length: 2, got %d", L) + } + arrayLengthRecords := int(binary.BigEndian.Uint16(src[0:])) + n += 2 + + { + + if L := len(src); L < 2+arrayLengthRecords*6 { + return item, 0, fmt.Errorf("reading ScriptList: "+"EOF: expected length: %d, got %d", 2+arrayLengthRecords*6, L) + } + + item.Records = make([]TagOffsetRecord, arrayLengthRecords) // allocation guarded by the previous check + for i := range item.Records { + item.Records[i].mustParse(src[2+i*6:]) + } + n += arrayLengthRecords * 6 + } + { + + err := item.parseScripts(src[:]) + if err != nil { + return item, 0, fmt.Errorf("reading ScriptList: %s", err) + } + } + return item, n, nil +} + +func (item *TagOffsetRecord) mustParse(src []byte) { + _ = src[5] // early bound checking + item.Tag = Tag(binary.BigEndian.Uint32(src[0:])) + item.Offset = binary.BigEndian.Uint16(src[4:]) +} + +func parseLookupList(src []byte) (lookupList, int, error) { + var item lookupList + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading lookupList: "+"EOF: expected length: 2, got %d", L) + } + arrayLengthLookups := int(binary.BigEndian.Uint16(src[0:])) + n += 2 + + { + + if L := len(src); L < 2+arrayLengthLookups*2 { + return item, 0, fmt.Errorf("reading lookupList: "+"EOF: expected length: %d, got %d", 2+arrayLengthLookups*2, L) + } + + item.Lookups = make([]Lookup, arrayLengthLookups) // allocation guarded by the previous check + for i := range item.Lookups { + offset := int(binary.BigEndian.Uint16(src[2+i*2:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading lookupList: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.Lookups[i], _, err = ParseLookup(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading lookupList: %s", err) + } + } + n += arrayLengthLookups * 2 + } + return item, n, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_layout_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_layout_src.go new file mode 100644 index 0000000..e97ad99 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_layout_src.go @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Layout represents the common layout table used by GPOS and GSUB. +// The Features field contains all the features for this layout. However, +// the script and language determines which feature is used. +// +// See https://learn.microsoft.com/typography/opentype/spec/chapter2#organization +// See https://learn.microsoft.com/typography/opentype/spec/gpos +// See https://www.microsoft.com/typography/otspec/GSUB.htm +type Layout struct { + majorVersion uint16 // Major version of the GPOS table, = 1 + minorVersion uint16 // Minor version of the GPOS table, = 0 or 1 + ScriptList ScriptList `offsetSize:"Offset16"` // Offset to ScriptList table, from beginning of GPOS table + FeatureList FeatureList `offsetSize:"Offset16"` // Offset to FeatureList table, from beginning of GPOS table + LookupList lookupList `offsetSize:"Offset16"` // Offset to LookupList table, from beginning of GPOS table + FeatureVariations *FeatureVariation `isOpaque:""` // Offset to FeatureVariations table, from beginning of GPOS table (may be NULL) +} + +func (lt *Layout) parseFeatureVariations(src []byte) (int, error) { + const layoutHeaderSize = 2 + 2 + 2 + 2 + 2 + if lt.minorVersion != 1 { + return 0, nil + } + if L := len(src); L < layoutHeaderSize+4 { + return 0, fmt.Errorf("reading Layout: EOF: expected length: 4, got %d", L) + } + offset := binary.BigEndian.Uint32(src[layoutHeaderSize:]) + if offset == 0 { + return 4, nil + } + if L := len(src); L < int(offset) { + return 0, fmt.Errorf("reading Layout: EOF: expected length: %d, got %d", offset, L) + } + fv, _, err := ParseFeatureVariation(src[offset:]) + if err != nil { + return 0, err + } + lt.FeatureVariations = &fv + + return 4, nil +} + +type TagOffsetRecord struct { + Tag Tag // 4-byte script tag identifier + Offset uint16 // Offset to object from beginning of list +} + +type ScriptList struct { + Records []TagOffsetRecord `arrayCount:"FirstUint16"` // Array of ScriptRecords, listed alphabetically by script tag + Scripts []Script `isOpaque:""` +} + +func (sl *ScriptList) parseScripts(src []byte) error { + sl.Scripts = make([]Script, len(sl.Records)) + for i, rec := range sl.Records { + var err error + if L := len(src); L < int(rec.Offset) { + return fmt.Errorf("EOF: expected length: %d, got %d", rec.Offset, L) + } + sl.Scripts[i], _, err = ParseScript(src[rec.Offset:]) + if err != nil { + return err + } + } + return nil +} + +type Script struct { + DefaultLangSys *LangSys `offsetSize:"Offset16"` // Offset to default LangSys table, from beginning of Script table — may be NULL + LangSysRecords []TagOffsetRecord `arrayCount:"FirstUint16"` // [langSysCount] Array of LangSysRecords, listed alphabetically by LangSys tag + LangSys []LangSys `isOpaque:""` // same length as langSysRecords +} + +func (sc *Script) parseLangSys(src []byte) error { + sc.LangSys = make([]LangSys, len(sc.LangSysRecords)) + for i, rec := range sc.LangSysRecords { + var err error + if L := len(src); L < int(rec.Offset) { + return fmt.Errorf("EOF: expected length: %d, got %d", rec.Offset, L) + } + sc.LangSys[i], _, err = ParseLangSys(src[rec.Offset:]) + if err != nil { + return err + } + } + return nil +} + +type LangSys struct { + lookupOrderOffset uint16 // = NULL (reserved for an offset to a reordering table) + RequiredFeatureIndex uint16 // Index of a feature required for this language system; if no required features = 0xFFFF + FeatureIndices []uint16 `arrayCount:"FirstUint16"` // [featureIndexCount] Array of indices into the FeatureList, in arbitrary order +} + +type FeatureList struct { + Records []TagOffsetRecord `arrayCount:"FirstUint16"` // Array of FeatureRecords — zero-based (first feature has FeatureIndex = 0), listed alphabetically by feature tag + Features []Feature `isOpaque:""` +} + +func (fl *FeatureList) parseFeatures(src []byte) error { + fl.Features = make([]Feature, len(fl.Records)) + for i, rec := range fl.Records { + var err error + if L := len(src); L < int(rec.Offset) { + return fmt.Errorf("EOF: expected length: %d, got %d", rec.Offset, L) + } + fl.Features[i], _, err = ParseFeature(src[rec.Offset:]) + if err != nil { + return err + } + } + return nil +} + +type Feature struct { + featureParamsOffset uint16 // Offset from start of Feature table to FeatureParams table, if defined for the feature and present, else NULL + LookupListIndices []uint16 `arrayCount:"FirstUint16"` // [lookupIndexCount] Array of indices into the LookupList — zero-based (first lookup is LookupListIndex = 0) +} + +type lookupList struct { + Lookups []Lookup `arrayCount:"FirstUint16" offsetsArray:"Offset16"` // Array of offsets to Lookup tables, from beginning of LookupList — zero based (first lookup is Lookup index = 0) +} + +// Lookup is the common format for GSUB and GPOS lookups +type Lookup struct { + lookupType uint16 // Different enumerations for GSUB and GPOS + LookupFlag uint16 // Lookup qualifiers + subtableOffsets []Offset16 `arrayCount:"FirstUint16"` // [subTableCount] Array of offsets to lookup subtables, from beginning of Lookup table + MarkFilteringSet uint16 // Index (base 0) into GDEF mark glyph sets structure. This field is only present if the USE_MARK_FILTERING_SET lookup flag is set. + rawData []byte `subsliceStart:"AtStart" arrayCount:"ToEnd"` +} + +type FeatureVariation struct { + majorVersion uint16 // Major version of the FeatureVariations table — set to 1. + minorVersion uint16 // Minor version of the FeatureVariations table — set to 0. + FeatureVariationRecords []FeatureVariationRecord `arrayCount:"FirstUint32"` //[featureVariationRecordCount] Array of feature variation records. +} + +type FeatureVariationRecord struct { + ConditionSet ConditionSet `offsetSize:"Offset32" offsetRelativeTo:"Parent"` // Offset to a condition set table, from beginning of FeatureVariations table. + Substitutions FeatureTableSubstitution `offsetSize:"Offset32" offsetRelativeTo:"Parent"` // Offset to a feature table substitution table, from beginning of the FeatureVariations table. +} + +type ConditionSet struct { + // uint16 conditionCount Number of Conditions for this condition set. + Conditions []ConditionFormat1 `arrayCount:"FirstUint16" offsetsArray:"Offset32"` // [conditionCount] Array of offsets to condition tables, from beginning of the ConditionSet table. +} + +type ConditionFormat1 struct { + format uint16 // Format, = 1 + AxisIndex uint16 // Index (zero-based) for the variation axis within the 'fvar' table. + FilterRangeMinValue Coord // Minimum value of the font variation instances that satisfy this condition. + FilterRangeMaxValue Coord // Maximum value of the font variation instances that satisfy this condition. +} + +type FeatureTableSubstitution struct { + majorVersion uint16 // Major version of the feature table substitution table — set to 1 + minorVersion uint16 // Minor version of the feature table substitution table — set to 0. + Substitutions []FeatureTableSubstitutionRecord `arrayCount:"FirstUint16"` // [substitutionCount] Array of feature table substitution records. +} + +type FeatureTableSubstitutionRecord struct { + FeatureIndex uint16 // The feature table index to match. + AlternateFeature Feature `offsetSize:"Offset32" offsetRelativeTo:"Parent"` // Offset to an alternate feature table, from start of the FeatureTableSubstitution table. +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_properties.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_properties.go new file mode 100644 index 0000000..25c8635 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/ot_properties.go @@ -0,0 +1,315 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "sort" +) + +func (c Coverage1) Index(gi GlyphID) (int, bool) { + num := len(c.Glyphs) + idx := sort.Search(num, func(i int) bool { return gi <= c.Glyphs[i] }) + if idx < num && c.Glyphs[idx] == gi { + return idx, true + } + return 0, false +} + +func (cl Coverage1) Len() int { return len(cl.Glyphs) } + +func (c Coverage2) Index(gi GlyphID) (int, bool) { + num := len(c.Ranges) + if num == 0 { + return 0, false + } + + idx := sort.Search(num, func(i int) bool { return gi <= c.Ranges[i].StartGlyphID }) + // idx either points to a matching start, or to the next range (or idx==num) + // e.g. with the range example from above: 130 points to 130-135 range, 133 points to 137-137 range + + // check if gi is the start of a range, but only if sort.Search returned a valid result + if idx < num { + if rang := c.Ranges[idx]; gi == rang.StartGlyphID { + return int(rang.StartCoverageIndex), true + } + } + // check if gi is in previous range + if idx > 0 { + idx-- + if rang := c.Ranges[idx]; gi >= rang.StartGlyphID && gi <= rang.EndGlyphID { + return int(rang.StartCoverageIndex) + int(gi-rang.StartGlyphID), true + } + } + + return 0, false +} + +func (cr Coverage2) Len() int { + size := 0 + for _, r := range cr.Ranges { + size += int(r.EndGlyphID - r.StartGlyphID + 1) + } + return size +} + +func (cl ClassDef1) Class(gi GlyphID) (uint16, bool) { + if gi < cl.StartGlyphID || gi >= cl.StartGlyphID+GlyphID(len(cl.ClassValueArray)) { + return 0, false + } + return cl.ClassValueArray[gi-cl.StartGlyphID], true +} + +func (cl ClassDef1) Extent() int { + max := uint16(0) + for _, cid := range cl.ClassValueArray { + if cid >= max { + max = cid + } + } + return int(max) + 1 +} + +func (cl ClassDef2) Class(g GlyphID) (uint16, bool) { + // 'adapted' from golang/x/image/font/sfnt + c := cl.ClassRangeRecords + num := len(c) + if num == 0 { + return 0, false + } + + // classRange is an array of startGlyphID, endGlyphID and target class ID. + // Ranges are non-overlapping. + // E.g. 130, 135, 1 137, 137, 5 etc + + idx := sort.Search(num, func(i int) bool { return g <= c[i].StartGlyphID }) + // idx either points to a matching start, or to the next range (or idx==num) + // e.g. with the range example from above: 130 points to 130-135 range, 133 points to 137-137 range + + // check if gi is the start of a range, but only if sort.Search returned a valid result + if idx < num { + if class := c[idx]; g == c[idx].StartGlyphID { + return class.Class, true + } + } + // check if gi is in previous range + if idx > 0 { + idx-- + if class := c[idx]; g >= class.StartGlyphID && g <= class.EndGlyphID { + return class.Class, true + } + } + + return 0, false +} + +func (cl ClassDef2) Extent() int { + max := uint16(0) + for _, r := range cl.ClassRangeRecords { + if r.Class >= max { + max = r.Class + } + } + return int(max) + 1 +} + +// ------------------------------------ layout getters ------------------------------------ + +// FindLanguage looks for [language] and return its index into the [LangSys] slice, +// or -1 if the tag is not found. +func (sc Script) FindLanguage(language Tag) int { + // LangSys is sorted: binary search + low, high := 0, len(sc.LangSysRecords) + for low < high { + mid := low + (high-low)/2 // avoid overflow when computing mid + p := sc.LangSysRecords[mid].Tag + if language < p { + high = mid + } else if language > p { + low = mid + 1 + } else { + return mid + } + } + return -1 +} + +// GetLangSys return the language at [index]. It [index] is out of range (for example with 0xFFFF), +// it returns [DefaultLangSys] (which may be empty) +func (sc Script) GetLangSys(index uint16) LangSys { + if int(index) >= len(sc.LangSys) { + if sc.DefaultLangSys != nil { + return *sc.DefaultLangSys + } + return LangSys{RequiredFeatureIndex: 0xFFFF} + } + return sc.LangSys[index] +} + +// --------------------------------------- gsub --------------------------------------- + +func (d SingleSubstData1) Cov() Coverage { return d.Coverage } +func (d SingleSubstData2) Cov() Coverage { return d.Coverage } + +func (cs ContextualSubs1) Cov() Coverage { return cs.coverage } +func (cs ContextualSubs2) Cov() Coverage { return cs.coverage } +func (cs ContextualSubs3) Cov() Coverage { + if len(cs.Coverages) == 0 { // return an empty, valid Coverage + return Coverage1{} + } + return cs.Coverages[0] +} + +func (cc ChainedContextualSubs1) Cov() Coverage { return cc.coverage } +func (cc ChainedContextualSubs2) Cov() Coverage { return cc.coverage } +func (cc ChainedContextualSubs3) Cov() Coverage { + if len(cc.InputCoverages) == 0 { // return an empty, valid Coverage + return Coverage1{} + } + return cc.InputCoverages[0] +} + +func (lk SingleSubs) Cov() Coverage { return lk.Data.Cov() } +func (lk MultipleSubs) Cov() Coverage { return lk.Coverage } +func (lk AlternateSubs) Cov() Coverage { return lk.Coverage } +func (lk LigatureSubs) Cov() Coverage { return lk.Coverage } +func (lk ContextualSubs) Cov() Coverage { return lk.Data.Cov() } +func (lk ChainedContextualSubs) Cov() Coverage { return lk.Data.Cov() } +func (lk ExtensionSubs) Cov() Coverage { return nil } // not used anyway +func (lk ReverseChainSingleSubs) Cov() Coverage { return lk.coverage } + +// --------------------------------------- gpos --------------------------------------- + +func (d SinglePosData1) Cov() Coverage { return d.coverage } +func (d SinglePosData2) Cov() Coverage { return d.coverage } + +func (d PairPosData1) Cov() Coverage { return d.coverage } +func (d PairPosData2) Cov() Coverage { return d.coverage } + +func (cs ContextualPos1) Cov() Coverage { return cs.coverage } +func (cs ContextualPos2) Cov() Coverage { return cs.coverage } +func (cs ContextualPos3) Cov() Coverage { + if len(cs.Coverages) == 0 { // return an empty, valid Coverage + return Coverage1{} + } + return cs.Coverages[0] +} + +func (cc ChainedContextualPos1) Cov() Coverage { return cc.coverage } +func (cc ChainedContextualPos2) Cov() Coverage { return cc.coverage } +func (cc ChainedContextualPos3) Cov() Coverage { + if len(cc.InputCoverages) == 0 { // return an empty, valid Coverage + return Coverage1{} + } + return cc.InputCoverages[0] +} + +func (lk SinglePos) Cov() Coverage { return lk.Data.Cov() } +func (lk PairPos) Cov() Coverage { return lk.Data.Cov() } +func (lk CursivePos) Cov() Coverage { return lk.coverage } +func (lk MarkBasePos) Cov() Coverage { return lk.markCoverage } +func (lk MarkLigPos) Cov() Coverage { return lk.MarkCoverage } +func (lk MarkMarkPos) Cov() Coverage { return lk.Mark1Coverage } +func (lk ContextualPos) Cov() Coverage { return lk.Data.Cov() } +func (lk ChainedContextualPos) Cov() Coverage { return lk.Data.Cov() } +func (lk ExtensionPos) Cov() Coverage { return nil } // not used anyway + +// FindGlyph performs a binary search in the list, returning the record for `secondGlyph`, +// or `nil` if not found. +func (ps PairSet) FindGlyph(secondGlyph GlyphID) (PairValueRecord, bool) { + low, high := 0, int(ps.pairValueCount) + for low < high { + mid := low + (high-low)/2 // avoid overflow when computing mid + rec, err := ps.data.get(mid) + if err != nil { // argh... + return PairValueRecord{}, false + } + p := rec.SecondGlyph + if secondGlyph < p { + high = mid + } else if secondGlyph > p { + low = mid + 1 + } else { + return rec, true + } + } + return PairValueRecord{}, false +} + +// GetDelta returns the hint for the given `ppem`, scaled by `scale`. +// It returns 0 for out of range `ppem` values. +func (dev DeviceHinting) GetDelta(ppem uint16, scale int32) int32 { + if ppem == 0 { + return 0 + } + + if ppem < dev.StartSize || ppem > dev.EndSize { + return 0 + } + + pixels := dev.Values[ppem-dev.StartSize] + + return int32(pixels) * (scale / int32(ppem)) +} + +// -------------------------------------- gdef -------------------------------------- + +// GlyphProps is a 16-bit integer where the lower 8-bit have bits representing +// glyph class, and high 8-bit the mark attachment type (if any). +type GlyphProps = uint16 + +const ( + GPBaseGlyph GlyphProps = 1 << (iota + 1) + GPLigature + GPMark +) + +// GlyphProps return a summary of the glyph properties. +func (gd *GDEF) GlyphProps(glyph GlyphID) GlyphProps { + klass, _ := gd.GlyphClassDef.Class(glyph) + switch klass { + case 1: + return GPBaseGlyph + case 2: + return GPLigature + case 3: + var klass uint16 // it is actually a byte + if gd.MarkAttachClass != nil { + klass, _ = gd.MarkAttachClass.Class(glyph) + } + return GPMark | GlyphProps(klass)<<8 + default: + return 0 + } +} + +// -------------------------------------- var -------------------------------------- + +// GetDelta uses the variation [store] and the selected instance coordinates [coords] +// to compute the value at [index]. +func (store ItemVarStore) GetDelta(index VariationStoreIndex, coords []Coord) float32 { + if int(index.DeltaSetOuter) >= len(store.ItemVariationDatas) { + return 0 + } + varData := store.ItemVariationDatas[index.DeltaSetOuter] + if int(index.DeltaSetInner) >= len(varData.DeltaSets) { + return 0 + } + deltaSet := varData.DeltaSets[index.DeltaSetInner] + var delta float32 + for i, regionIndex := range varData.RegionIndexes { + region := store.VariationRegionList.VariationRegions[regionIndex] + v := region.Evaluate(coords) + delta += float32(deltaSet[i]) * v + } + return delta +} + +// Evaluate returns the scalar factor of the region +func (vr VariationRegion) Evaluate(coords []Coord) float32 { + v := float32(1) + for axis, coord := range coords { + factor := vr.RegionAxes[axis].evaluate(coord) + v *= factor + } + return v +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/post_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/post_gen.go new file mode 100644 index 0000000..477fe43 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/post_gen.go @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from post_src.go. DO NOT EDIT + +func ParsePost(src []byte) (Post, int, error) { + var item Post + n := 0 + if L := len(src); L < 32 { + return item, 0, fmt.Errorf("reading Post: "+"EOF: expected length: 32, got %d", L) + } + _ = src[31] // early bound checking + item.version = postVersion(binary.BigEndian.Uint32(src[0:])) + item.italicAngle = binary.BigEndian.Uint32(src[4:]) + item.UnderlinePosition = int16(binary.BigEndian.Uint16(src[8:])) + item.UnderlineThickness = int16(binary.BigEndian.Uint16(src[10:])) + item.IsFixedPitch = binary.BigEndian.Uint32(src[12:]) + item.memoryUsage[0] = binary.BigEndian.Uint32(src[16:]) + item.memoryUsage[1] = binary.BigEndian.Uint32(src[20:]) + item.memoryUsage[2] = binary.BigEndian.Uint32(src[24:]) + item.memoryUsage[3] = binary.BigEndian.Uint32(src[28:]) + n += 32 + + { + var ( + read int + err error + ) + switch item.version { + case postVersion10: + item.Names, read, err = ParsePostNames10(src[32:]) + case postVersion20: + item.Names, read, err = ParsePostNames20(src[32:]) + case postVersion30: + item.Names, read, err = ParsePostNames30(src[32:]) + default: + err = fmt.Errorf("unsupported PostNamesVersion %d", item.version) + } + if err != nil { + return item, 0, fmt.Errorf("reading Post: %s", err) + } + n += read + } + return item, n, nil +} + +func ParsePostNames10([]byte) (PostNames10, int, error) { + var item PostNames10 + n := 0 + return item, n, nil +} + +func ParsePostNames20(src []byte) (PostNames20, int, error) { + var item PostNames20 + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading PostNames20: "+"EOF: expected length: 2, got %d", L) + } + arrayLengthGlyphNameIndexes := int(binary.BigEndian.Uint16(src[0:])) + n += 2 + + { + + if L := len(src); L < 2+arrayLengthGlyphNameIndexes*2 { + return item, 0, fmt.Errorf("reading PostNames20: "+"EOF: expected length: %d, got %d", 2+arrayLengthGlyphNameIndexes*2, L) + } + + item.GlyphNameIndexes = make([]uint16, arrayLengthGlyphNameIndexes) // allocation guarded by the previous check + for i := range item.GlyphNameIndexes { + item.GlyphNameIndexes[i] = binary.BigEndian.Uint16(src[2+i*2:]) + } + n += arrayLengthGlyphNameIndexes * 2 + } + { + + item.StringData = src[n:] + n = len(src) + } + return item, n, nil +} + +func ParsePostNames30([]byte) (PostNames30, int, error) { + var item PostNames30 + n := 0 + return item, n, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/post_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/post_src.go new file mode 100644 index 0000000..30094cd --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/post_src.go @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +// PostScript table +// See https://learn.microsoft.com/en-us/typography/opentype/spec/post +type Post struct { + version postVersion + italicAngle uint32 + // UnderlinePosition is the suggested distance of the top of the + // underline from the baseline (negative values indicate below baseline). + UnderlinePosition int16 + // Suggested values for the underline thickness. + UnderlineThickness int16 + // IsFixedPitch indicates that the font is not proportionally spaced + // (i.e. monospaced). + IsFixedPitch uint32 + memoryUsage [4]uint32 + Names PostNames `unionField:"version"` +} + +type PostNames interface { + isPostNames() +} + +func (PostNames10) isPostNames() {} +func (PostNames20) isPostNames() {} +func (PostNames30) isPostNames() {} + +type postVersion uint32 + +const ( + postVersion10 postVersion = 0x00010000 + postVersion20 postVersion = 0x00020000 + postVersion30 postVersion = 0x00030000 +) + +type PostNames10 struct{} + +type PostNames20 struct { + GlyphNameIndexes []uint16 `arrayCount:"FirstUint16"` // size numGlyph + StringData []byte `arrayCount:"ToEnd"` +} + +type PostNames30 PostNames10 diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/tables.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/tables.go new file mode 100644 index 0000000..4ee8d73 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/tables.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import "github.com/go-text/typesetting/font/opentype" + +//go:generate ../../../typesetting-utils/generators/binarygen/cmd/generator . _src.go + +type GlyphID = uint16 + +// NameID is the ID for entries in the font table. +type NameID uint16 + +type Tag = opentype.Tag + +// Float1616 is a float32, represented in +// fixed 16.16 format in font files. +type Float1616 = float32 + +func Float1616FromUint(v uint32) Float1616 { + // value are actually signed integers + return Float1616(int32(v)) / (1 << 16) +} + +func Float1616ToUint(f Float1616) uint32 { + return uint32(int32(f * (1 << 16))) +} + +func Float214FromUint(v uint16) float32 { + // value are actually signed integers + return float32(int16(v)) / (1 << 14) +} + +// Coord is real number in [-1;1], stored as a fixed 2.14 integer +type Coord int16 + +func NewCoord(c float64) Coord { + return Coord(c * (1 << 14)) +} + +// Number of seconds since 12:00 midnight that started January 1st 1904 in GMT/UTC time zone. +type longdatetime = uint64 + +// PlatformID represents the platform id for entries in the name table. +type PlatformID uint16 + +// EncodingID represents the platform specific id for entries in the name table. +// The most common values are provided as constants. +type EncodingID uint16 + +// LanguageID represents the language used by an entry in the name table +type LanguageID uint16 + +// Offset16 is an offset into the input byte slice +type Offset16 uint16 + +// Offset32 is an offset into the input byte slice +type Offset32 uint32 diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/xvar_gen.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/xvar_gen.go new file mode 100644 index 0000000..ea35afa --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/xvar_gen.go @@ -0,0 +1,628 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "fmt" +) + +// Code generated by binarygen from xvar_src.go. DO NOT EDIT + +func (item *AxisValueMap) mustParse(src []byte) { + _ = src[3] // early bound checking + item.FromCoordinate = Coord(binary.BigEndian.Uint16(src[0:])) + item.ToCoordinate = Coord(binary.BigEndian.Uint16(src[2:])) +} + +func ParseAvar(src []byte) (Avar, int, error) { + var item Avar + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading Avar: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.majorVersion = binary.BigEndian.Uint16(src[0:]) + item.minorVersion = binary.BigEndian.Uint16(src[2:]) + item.reserved = binary.BigEndian.Uint16(src[4:]) + arrayLengthAxisSegmentMaps := int(binary.BigEndian.Uint16(src[6:])) + n += 8 + + { + + offset := 8 + for i := 0; i < arrayLengthAxisSegmentMaps; i++ { + elem, read, err := ParseSegmentMaps(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading Avar: %s", err) + } + item.AxisSegmentMaps = append(item.AxisSegmentMaps, elem) + offset += read + } + n = offset + } + return item, n, nil +} + +func ParseDeltaSetMapping(src []byte) (DeltaSetMapping, int, error) { + var item DeltaSetMapping + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading DeltaSetMapping: "+"EOF: expected length: 2, got %d", L) + } + _ = src[1] // early bound checking + item.format = src[0] + item.entryFormat = src[1] + n += 2 + + { + + err := item.parseMap(src[2:]) + if err != nil { + return item, 0, fmt.Errorf("reading DeltaSetMapping: %s", err) + } + } + return item, n, nil +} + +func ParseFvar(src []byte) (Fvar, int, error) { + var item Fvar + n := 0 + if L := len(src); L < 16 { + return item, 0, fmt.Errorf("reading Fvar: "+"EOF: expected length: 16, got %d", L) + } + _ = src[15] // early bound checking + item.majorVersion = binary.BigEndian.Uint16(src[0:]) + item.minorVersion = binary.BigEndian.Uint16(src[2:]) + item.axesArrayOffset = Offset16(binary.BigEndian.Uint16(src[4:])) + item.reserved = binary.BigEndian.Uint16(src[6:]) + item.axisCount = binary.BigEndian.Uint16(src[8:]) + item.axisSize = binary.BigEndian.Uint16(src[10:]) + item.instanceCount = binary.BigEndian.Uint16(src[12:]) + item.instanceSize = binary.BigEndian.Uint16(src[14:]) + n += 16 + + { + + err := item.parseFvarRecords(src[:]) + if err != nil { + return item, 0, fmt.Errorf("reading Fvar: %s", err) + } + } + return item, n, nil +} + +func ParseFvarRecords(src []byte, axisCount int, instanceCount int, instanceSize int) (FvarRecords, int, error) { + var item FvarRecords + n := 0 + { + + if L := len(src); L < axisCount*20 { + return item, 0, fmt.Errorf("reading FvarRecords: "+"EOF: expected length: %d, got %d", axisCount*20, L) + } + + item.Axis = make([]VariationAxisRecord, axisCount) // allocation guarded by the previous check + for i := range item.Axis { + item.Axis[i].mustParse(src[i*20:]) + } + n += axisCount * 20 + } + { + + err := item.parseInstances(src[n:], axisCount, instanceCount, instanceSize) + if err != nil { + return item, 0, fmt.Errorf("reading FvarRecords: %s", err) + } + } + return item, n, nil +} + +func ParseGlyphVariationData(src []byte, axisCount int) (GlyphVariationData, int, error) { + var item GlyphVariationData + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading GlyphVariationData: "+"EOF: expected length: 4, got %d", L) + } + _ = src[3] // early bound checking + item.tupleVariationCount = binary.BigEndian.Uint16(src[0:]) + offsetSerializedData := int(binary.BigEndian.Uint16(src[2:])) + n += 4 + + { + + if offsetSerializedData != 0 { // ignore null offset + if L := len(src); L < offsetSerializedData { + return item, 0, fmt.Errorf("reading GlyphVariationData: "+"EOF: expected length: %d, got %d", offsetSerializedData, L) + } + + item.SerializedData = src[offsetSerializedData:] + } + } + { + arrayLength := int(item.tupleVariationCount & 0x0FFF) + + offset := 4 + for i := 0; i < arrayLength; i++ { + elem, read, err := ParseTupleVariationHeader(src[offset:], axisCount) + if err != nil { + return item, 0, fmt.Errorf("reading GlyphVariationData: %s", err) + } + item.TupleVariationHeaders = append(item.TupleVariationHeaders, elem) + offset += read + } + n = offset + } + return item, n, nil +} + +func ParseGvar(src []byte) (Gvar, int, error) { + var item Gvar + n := 0 + if L := len(src); L < 20 { + return item, 0, fmt.Errorf("reading Gvar: "+"EOF: expected length: 20, got %d", L) + } + _ = src[19] // early bound checking + item.majorVersion = binary.BigEndian.Uint16(src[0:]) + item.minorVersion = binary.BigEndian.Uint16(src[2:]) + item.axisCount = binary.BigEndian.Uint16(src[4:]) + item.sharedTupleCount = binary.BigEndian.Uint16(src[6:]) + offsetSharedTuples := int(binary.BigEndian.Uint32(src[8:])) + item.glyphCount = binary.BigEndian.Uint16(src[12:]) + item.flags = binary.BigEndian.Uint16(src[14:]) + item.glyphVariationDataArrayOffset = Offset32(binary.BigEndian.Uint32(src[16:])) + n += 20 + + { + + if offsetSharedTuples != 0 { // ignore null offset + if L := len(src); L < offsetSharedTuples { + return item, 0, fmt.Errorf("reading Gvar: "+"EOF: expected length: %d, got %d", offsetSharedTuples, L) + } + + var err error + item.SharedTuples, _, err = ParseSharedTuples(src[offsetSharedTuples:], int(item.sharedTupleCount), int(item.axisCount)) + if err != nil { + return item, 0, fmt.Errorf("reading Gvar: %s", err) + } + + } + } + { + + err := item.parseGlyphVariationDataOffsets(src[20:]) + if err != nil { + return item, 0, fmt.Errorf("reading Gvar: %s", err) + } + } + { + + err := item.parseGlyphVariationDatas(src[:]) + if err != nil { + return item, 0, fmt.Errorf("reading Gvar: %s", err) + } + } + return item, n, nil +} + +func ParseHVAR(src []byte) (HVAR, int, error) { + var item HVAR + n := 0 + if L := len(src); L < 20 { + return item, 0, fmt.Errorf("reading HVAR: "+"EOF: expected length: 20, got %d", L) + } + _ = src[19] // early bound checking + item.majorVersion = binary.BigEndian.Uint16(src[0:]) + item.minorVersion = binary.BigEndian.Uint16(src[2:]) + offsetItemVariationStore := int(binary.BigEndian.Uint32(src[4:])) + offsetAdvanceWidthMapping := int(binary.BigEndian.Uint32(src[8:])) + offsetLsbMapping := int(binary.BigEndian.Uint32(src[12:])) + offsetRsbMapping := int(binary.BigEndian.Uint32(src[16:])) + n += 20 + + { + + if offsetItemVariationStore != 0 { // ignore null offset + if L := len(src); L < offsetItemVariationStore { + return item, 0, fmt.Errorf("reading HVAR: "+"EOF: expected length: %d, got %d", offsetItemVariationStore, L) + } + + var err error + item.ItemVariationStore, _, err = ParseItemVarStore(src[offsetItemVariationStore:]) + if err != nil { + return item, 0, fmt.Errorf("reading HVAR: %s", err) + } + + } + } + { + + if offsetAdvanceWidthMapping != 0 { // ignore null offset + if L := len(src); L < offsetAdvanceWidthMapping { + return item, 0, fmt.Errorf("reading HVAR: "+"EOF: expected length: %d, got %d", offsetAdvanceWidthMapping, L) + } + + var err error + item.AdvanceWidthMapping, _, err = ParseDeltaSetMapping(src[offsetAdvanceWidthMapping:]) + if err != nil { + return item, 0, fmt.Errorf("reading HVAR: %s", err) + } + + } + } + { + + if offsetLsbMapping != 0 { // ignore null offset + if L := len(src); L < offsetLsbMapping { + return item, 0, fmt.Errorf("reading HVAR: "+"EOF: expected length: %d, got %d", offsetLsbMapping, L) + } + + var tmpLsbMapping DeltaSetMapping + var err error + tmpLsbMapping, _, err = ParseDeltaSetMapping(src[offsetLsbMapping:]) + if err != nil { + return item, 0, fmt.Errorf("reading HVAR: %s", err) + } + + item.LsbMapping = &tmpLsbMapping + } + } + { + + if offsetRsbMapping != 0 { // ignore null offset + if L := len(src); L < offsetRsbMapping { + return item, 0, fmt.Errorf("reading HVAR: "+"EOF: expected length: %d, got %d", offsetRsbMapping, L) + } + + var tmpRsbMapping DeltaSetMapping + var err error + tmpRsbMapping, _, err = ParseDeltaSetMapping(src[offsetRsbMapping:]) + if err != nil { + return item, 0, fmt.Errorf("reading HVAR: %s", err) + } + + item.RsbMapping = &tmpRsbMapping + } + } + return item, n, nil +} + +func ParseInstanceRecord(src []byte, coordinatesCount int) (InstanceRecord, int, error) { + var item InstanceRecord + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading InstanceRecord: "+"EOF: expected length: 4, got %d", L) + } + _ = src[3] // early bound checking + item.SubfamilyNameID = binary.BigEndian.Uint16(src[0:]) + item.flags = binary.BigEndian.Uint16(src[2:]) + n += 4 + + { + + if L := len(src); L < 4+coordinatesCount*4 { + return item, 0, fmt.Errorf("reading InstanceRecord: "+"EOF: expected length: %d, got %d", 4+coordinatesCount*4, L) + } + + item.Coordinates = make([]float32, coordinatesCount) // allocation guarded by the previous check + for i := range item.Coordinates { + item.Coordinates[i] = Float1616FromUint(binary.BigEndian.Uint32(src[4+i*4:])) + } + n += coordinatesCount * 4 + } + { + + read, err := item.parsePostScriptNameID(src[n:], coordinatesCount) + if err != nil { + return item, 0, fmt.Errorf("reading InstanceRecord: %s", err) + } + n += read + } + return item, n, nil +} + +func ParseItemVarStore(src []byte) (ItemVarStore, int, error) { + var item ItemVarStore + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading ItemVarStore: "+"EOF: expected length: 8, got %d", L) + } + _ = src[7] // early bound checking + item.format = binary.BigEndian.Uint16(src[0:]) + offsetVariationRegionList := int(binary.BigEndian.Uint32(src[2:])) + arrayLengthItemVariationDatas := int(binary.BigEndian.Uint16(src[6:])) + n += 8 + + { + + if offsetVariationRegionList != 0 { // ignore null offset + if L := len(src); L < offsetVariationRegionList { + return item, 0, fmt.Errorf("reading ItemVarStore: "+"EOF: expected length: %d, got %d", offsetVariationRegionList, L) + } + + var err error + item.VariationRegionList, _, err = ParseVariationRegionList(src[offsetVariationRegionList:]) + if err != nil { + return item, 0, fmt.Errorf("reading ItemVarStore: %s", err) + } + + } + } + { + + if L := len(src); L < 8+arrayLengthItemVariationDatas*4 { + return item, 0, fmt.Errorf("reading ItemVarStore: "+"EOF: expected length: %d, got %d", 8+arrayLengthItemVariationDatas*4, L) + } + + item.ItemVariationDatas = make([]ItemVariationData, arrayLengthItemVariationDatas) // allocation guarded by the previous check + for i := range item.ItemVariationDatas { + offset := int(binary.BigEndian.Uint32(src[8+i*4:])) + // ignore null offsets + if offset == 0 { + continue + } + + if L := len(src); L < offset { + return item, 0, fmt.Errorf("reading ItemVarStore: "+"EOF: expected length: %d, got %d", offset, L) + } + + var err error + item.ItemVariationDatas[i], _, err = ParseItemVariationData(src[offset:]) + if err != nil { + return item, 0, fmt.Errorf("reading ItemVarStore: %s", err) + } + } + n += arrayLengthItemVariationDatas * 4 + } + return item, n, nil +} + +func ParseItemVariationData(src []byte) (ItemVariationData, int, error) { + var item ItemVariationData + n := 0 + if L := len(src); L < 6 { + return item, 0, fmt.Errorf("reading ItemVariationData: "+"EOF: expected length: 6, got %d", L) + } + _ = src[5] // early bound checking + item.itemCount = binary.BigEndian.Uint16(src[0:]) + item.wordDeltaCount = binary.BigEndian.Uint16(src[2:]) + item.regionIndexCount = binary.BigEndian.Uint16(src[4:]) + n += 6 + + { + arrayLength := int(item.regionIndexCount) + + if L := len(src); L < 6+arrayLength*2 { + return item, 0, fmt.Errorf("reading ItemVariationData: "+"EOF: expected length: %d, got %d", 6+arrayLength*2, L) + } + + item.RegionIndexes = make([]uint16, arrayLength) // allocation guarded by the previous check + for i := range item.RegionIndexes { + item.RegionIndexes[i] = binary.BigEndian.Uint16(src[6+i*2:]) + } + n += arrayLength * 2 + } + { + + err := item.parseDeltaSets(src[n:]) + if err != nil { + return item, 0, fmt.Errorf("reading ItemVariationData: %s", err) + } + } + return item, n, nil +} + +func ParseMVAR(src []byte) (MVAR, int, error) { + var item MVAR + n := 0 + if L := len(src); L < 12 { + return item, 0, fmt.Errorf("reading MVAR: "+"EOF: expected length: 12, got %d", L) + } + _ = src[11] // early bound checking + item.majorVersion = binary.BigEndian.Uint16(src[0:]) + item.minorVersion = binary.BigEndian.Uint16(src[2:]) + item.reserved = binary.BigEndian.Uint16(src[4:]) + item.valueRecordSize = binary.BigEndian.Uint16(src[6:]) + item.valueRecordCount = binary.BigEndian.Uint16(src[8:]) + offsetItemVariationStore := int(binary.BigEndian.Uint16(src[10:])) + n += 12 + + { + + if offsetItemVariationStore != 0 { // ignore null offset + if L := len(src); L < offsetItemVariationStore { + return item, 0, fmt.Errorf("reading MVAR: "+"EOF: expected length: %d, got %d", offsetItemVariationStore, L) + } + + var err error + item.ItemVariationStore, _, err = ParseItemVarStore(src[offsetItemVariationStore:]) + if err != nil { + return item, 0, fmt.Errorf("reading MVAR: %s", err) + } + + } + } + { + + err := item.parseValueRecords(src[12:]) + if err != nil { + return item, 0, fmt.Errorf("reading MVAR: %s", err) + } + } + return item, n, nil +} + +func ParseSegmentMaps(src []byte) (SegmentMaps, int, error) { + var item SegmentMaps + n := 0 + if L := len(src); L < 2 { + return item, 0, fmt.Errorf("reading SegmentMaps: "+"EOF: expected length: 2, got %d", L) + } + arrayLengthAxisValueMaps := int(binary.BigEndian.Uint16(src[0:])) + n += 2 + + { + + if L := len(src); L < 2+arrayLengthAxisValueMaps*4 { + return item, 0, fmt.Errorf("reading SegmentMaps: "+"EOF: expected length: %d, got %d", 2+arrayLengthAxisValueMaps*4, L) + } + + item.AxisValueMaps = make([]AxisValueMap, arrayLengthAxisValueMaps) // allocation guarded by the previous check + for i := range item.AxisValueMaps { + item.AxisValueMaps[i].mustParse(src[2+i*4:]) + } + n += arrayLengthAxisValueMaps * 4 + } + return item, n, nil +} + +func ParseSharedTuples(src []byte, sharedTuplesCount int, valuesCount int) (SharedTuples, int, error) { + var item SharedTuples + n := 0 + { + + offset := 0 + for i := 0; i < sharedTuplesCount; i++ { + elem, read, err := ParseTuple(src[offset:], valuesCount) + if err != nil { + return item, 0, fmt.Errorf("reading SharedTuples: %s", err) + } + item.SharedTuples = append(item.SharedTuples, elem) + offset += read + } + n = offset + } + return item, n, nil +} + +func ParseTuple(src []byte, valuesCount int) (Tuple, int, error) { + var item Tuple + n := 0 + { + + if L := len(src); L < valuesCount*2 { + return item, 0, fmt.Errorf("reading Tuple: "+"EOF: expected length: %d, got %d", valuesCount*2, L) + } + + item.Values = make([]Coord, valuesCount) // allocation guarded by the previous check + for i := range item.Values { + item.Values[i] = Coord(binary.BigEndian.Uint16(src[i*2:])) + } + n += valuesCount * 2 + } + return item, n, nil +} + +func ParseTupleVariationHeader(src []byte, axisCount int) (TupleVariationHeader, int, error) { + var item TupleVariationHeader + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading TupleVariationHeader: "+"EOF: expected length: 4, got %d", L) + } + _ = src[3] // early bound checking + item.VariationDataSize = binary.BigEndian.Uint16(src[0:]) + item.tupleIndex = binary.BigEndian.Uint16(src[2:]) + n += 4 + + { + + read, err := item.parsePeakTuple(src[4:], axisCount) + if err != nil { + return item, 0, fmt.Errorf("reading TupleVariationHeader: %s", err) + } + n += read + } + { + + read, err := item.parseIntermediateTuples(src[n:], axisCount) + if err != nil { + return item, 0, fmt.Errorf("reading TupleVariationHeader: %s", err) + } + n += read + } + return item, n, nil +} + +func ParseVarValueRecord(src []byte) (VarValueRecord, int, error) { + var item VarValueRecord + n := 0 + if L := len(src); L < 8 { + return item, 0, fmt.Errorf("reading VarValueRecord: "+"EOF: expected length: 8, got %d", L) + } + item.mustParse(src) + n += 8 + return item, n, nil +} + +func ParseVariationRegion(src []byte, regionAxesCount int) (VariationRegion, int, error) { + var item VariationRegion + n := 0 + { + + if L := len(src); L < regionAxesCount*6 { + return item, 0, fmt.Errorf("reading VariationRegion: "+"EOF: expected length: %d, got %d", regionAxesCount*6, L) + } + + item.RegionAxes = make([]RegionAxisCoordinates, regionAxesCount) // allocation guarded by the previous check + for i := range item.RegionAxes { + item.RegionAxes[i].mustParse(src[i*6:]) + } + n += regionAxesCount * 6 + } + return item, n, nil +} + +func ParseVariationRegionList(src []byte) (VariationRegionList, int, error) { + var item VariationRegionList + n := 0 + if L := len(src); L < 4 { + return item, 0, fmt.Errorf("reading VariationRegionList: "+"EOF: expected length: 4, got %d", L) + } + _ = src[3] // early bound checking + item.axisCount = binary.BigEndian.Uint16(src[0:]) + arrayLengthVariationRegions := int(binary.BigEndian.Uint16(src[2:])) + n += 4 + + { + + offset := 4 + for i := 0; i < arrayLengthVariationRegions; i++ { + elem, read, err := ParseVariationRegion(src[offset:], int(item.axisCount)) + if err != nil { + return item, 0, fmt.Errorf("reading VariationRegionList: %s", err) + } + item.VariationRegions = append(item.VariationRegions, elem) + offset += read + } + n = offset + } + return item, n, nil +} + +func (item *RegionAxisCoordinates) mustParse(src []byte) { + _ = src[5] // early bound checking + item.StartCoord = Coord(binary.BigEndian.Uint16(src[0:])) + item.PeakCoord = Coord(binary.BigEndian.Uint16(src[2:])) + item.EndCoord = Coord(binary.BigEndian.Uint16(src[4:])) +} + +func (item *VarValueRecord) mustParse(src []byte) { + _ = src[7] // early bound checking + item.ValueTag = Tag(binary.BigEndian.Uint32(src[0:])) + item.Index.mustParse(src[4:]) +} + +func (item *VariationAxisRecord) mustParse(src []byte) { + _ = src[19] // early bound checking + item.Tag = Tag(binary.BigEndian.Uint32(src[0:])) + item.Minimum = Float1616FromUint(binary.BigEndian.Uint32(src[4:])) + item.Default = Float1616FromUint(binary.BigEndian.Uint32(src[8:])) + item.Maximum = Float1616FromUint(binary.BigEndian.Uint32(src[12:])) + item.flags = binary.BigEndian.Uint16(src[16:]) + item.strid = NameID(binary.BigEndian.Uint16(src[18:])) +} + +func (item *VariationStoreIndex) mustParse(src []byte) { + _ = src[3] // early bound checking + item.DeltaSetOuter = binary.BigEndian.Uint16(src[0:]) + item.DeltaSetInner = binary.BigEndian.Uint16(src[2:]) +} diff --git a/vendor/github.com/go-text/typesetting/font/opentype/tables/xvar_src.go b/vendor/github.com/go-text/typesetting/font/opentype/tables/xvar_src.go new file mode 100644 index 0000000..a0cf29c --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/opentype/tables/xvar_src.go @@ -0,0 +1,426 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package tables + +import ( + "encoding/binary" + "errors" + "fmt" +) + +// ------------------------------------ fvar ------------------------------------ + +// Fvar is the Font Variations Table. +// See - https://learn.microsoft.com/fr-fr/typography/opentype/spec/fvar +type Fvar struct { + majorVersion uint16 // Major version number of the font variations table — set to 1. + minorVersion uint16 // Minor version number of the font variations table — set to 0. + axesArrayOffset Offset16 // Offset in bytes from the beginning of the table to the start of the VariationAxisRecord array. + reserved uint16 // This field is permanently reserved. Set to 2. + axisCount uint16 // The number of variation axes in the font (the number of records in the axes array). + axisSize uint16 // The size in bytes of each VariationAxisRecord — set to 20 (0x0014) for this version. + instanceCount uint16 // The number of named instances defined in the font (the number of records in the instances array). + instanceSize uint16 // The size in bytes of each InstanceRecord — set to either axisCount * sizeof(Fixed) + 4, or to axisCount * sizeof(Fixed) + 6. + FvarRecords `isOpaque:""` +} + +func (fv *Fvar) parseFvarRecords(src []byte) (err error) { + if L := len(src); L < int(fv.axesArrayOffset) { + return fmt.Errorf("EOF: expected length: %d, got %d", fv.axesArrayOffset, L) + } + fv.FvarRecords, _, err = ParseFvarRecords(src[fv.axesArrayOffset:], int(fv.axisCount), int(fv.instanceCount), int(fv.axisCount)) + return +} + +// binarygen: argument=instanceCount int +// binarygen: argument=instanceSize int +type FvarRecords struct { + Axis []VariationAxisRecord + Instances []InstanceRecord `isOpaque:"" subsliceStart:"AtCurrent"` +} + +func (fvr *FvarRecords) parseInstances(src []byte, axisCount, instanceCount, instanceSize int) error { + if L := len(src); L < instanceCount*instanceSize { + return fmt.Errorf("EOF: expected length: %d, got %d", instanceCount*instanceSize, L) + } + fvr.Instances = make([]InstanceRecord, instanceCount) + for i := range fvr.Instances { + var err error + fvr.Instances[i], _, err = ParseInstanceRecord(src[instanceSize*i:], axisCount) + if err != nil { + return err + } + } + return nil +} + +type VariationAxisRecord struct { + Tag Tag // Tag identifying the design variation for the axis. + Minimum Float1616 // mininum value on the variation axis that the font covers + Default Float1616 // default position on the axis + Maximum Float1616 // maximum value on the variation axis that the font covers + flags uint16 // Axis qualifiers — see details below. + strid NameID // name entry in the font's ‘name’ table +} + +type InstanceRecord struct { + SubfamilyNameID uint16 // The name ID for entries in the 'name' table that provide subfamily names for this instance. + flags uint16 // Reserved for future use — set to 0. + Coordinates []Float1616 // [axisCount] The coordinates array for this instance. + PostScriptNameID uint16 `isOpaque:"" subsliceStart:"AtCurrent"` // Optional. The name ID for entries in the 'name' table that provide PostScript names for this instance. +} + +func (ir *InstanceRecord) parsePostScriptNameID(src []byte, _ int) (int, error) { + if len(src) >= 2 { + ir.PostScriptNameID = binary.BigEndian.Uint16(src) + return 2, nil + } + return 0, nil +} + +type ItemVarStore struct { + format uint16 // Format — set to 1 + VariationRegionList VariationRegionList `offsetSize:"Offset32"` // Offset in bytes from the start of the item variation store to the variation region list. + ItemVariationDatas []ItemVariationData `arrayCount:"FirstUint16" offsetsArray:"Offset32"` // [itemVariationDataCount] Offsets in bytes from the start of the item variation store to each item variation data subtable. +} + +// AxisCount returns the number of axis found in the +// var store, which must be the same as the one in the 'fvar' table. +// It returns -1 if the store is empty +func (vs *ItemVarStore) AxisCount() int { + if vs.format == 0 { + return -1 + } + return int(vs.VariationRegionList.axisCount) +} + +type VariationRegionList struct { + axisCount uint16 // The number of variation axes for this font. This must be the same number as axisCount in the 'fvar' table. + VariationRegions []VariationRegion `arrayCount:"FirstUint16" arguments:"regionAxesCount=.axisCount"` // [regionCount] Array of variation regions. +} + +type VariationRegion struct { + // Array of region axis coordinates records, in the order of axes given in the 'fvar' table. + // Each RegionAxisCoordinates record provides coordinate values for a region along a single axis: + RegionAxes []RegionAxisCoordinates // [axisCount] +} + +type RegionAxisCoordinates struct { + StartCoord Coord // The region start coordinate value for the current axis. + PeakCoord Coord // The region peak coordinate value for the current axis. + EndCoord Coord // The region end coordinate value for the current axis. +} + +// evaluate returns the factor corresponding to the given [coord], +// interpolating between start and end. +func (reg RegionAxisCoordinates) evaluate(coord Coord) float32 { + start, peak, end := reg.StartCoord, reg.PeakCoord, reg.EndCoord + if peak == 0 || coord == peak { + return 1. + } + + if coord <= start || end <= coord { + return 0. + } + + // Interpolate + if coord < peak { + return float32(coord-start) / float32(peak-start) + } + return float32(end-coord) / float32(end-peak) +} + +type ItemVariationData struct { + itemCount uint16 // The number of delta sets for distinct items. + wordDeltaCount uint16 // A packed field: the high bit is a flag—see details below. + regionIndexCount uint16 // The number of variation regions referenced. + RegionIndexes []uint16 `arrayCount:"ComputedField-regionIndexCount"` //[regionIndexCount] Array of indices into the variation region list for the regions referenced by this item variation data table. + DeltaSets [][]int16 `isOpaque:"" subsliceStart:"AtCurrent"` //[itemCount] Delta-set rows. +} + +func (ivd *ItemVariationData) parseDeltaSets(src []byte) error { + const ( + LONG_WORDS = 0x8000 // Flag indicating that “word” deltas are long (int32) + WORD_DELTA_COUNT_MASK = 0x7FFF // Count of “word” delt + ) + if ivd.wordDeltaCount&LONG_WORDS != 0 { + return errors.New("LONG_WORDS not implemented in DeltaSets") + } + itemCount := int(ivd.itemCount) + shortDeltaCount := int(WORD_DELTA_COUNT_MASK & ivd.wordDeltaCount) + regionIndexCount := int(ivd.regionIndexCount) + + rowLength := shortDeltaCount + regionIndexCount + if L := len(src); L < itemCount*rowLength { + return fmt.Errorf("EOF: expected length: %d, got %d", itemCount*rowLength, L) + } + if shortDeltaCount > regionIndexCount { + return errors.New("invalid item variation data subtable") + } + ivd.DeltaSets = make([][]int16, itemCount) + for i := range ivd.DeltaSets { + vi := make([]int16, regionIndexCount) + j := 0 + for ; j < shortDeltaCount; j++ { + vi[j] = int16(binary.BigEndian.Uint16(src[2*j:])) + } + for ; j < regionIndexCount; j++ { + vi[j] = int16(int8(src[shortDeltaCount+j])) + } + ivd.DeltaSets[i] = vi + src = src[rowLength:] + } + return nil +} + +// ------------------------------------ GVAR ------------------------------------ + +// See - https://learn.microsoft.com/fr-fr/typography/opentype/spec/gvar +type Gvar struct { + majorVersion uint16 // Major version number of the glyph variations table — set to 1. + minorVersion uint16 // Minor version number of the glyph variations table — set to 0. + axisCount uint16 // The number of variation axes for this font. This must be the same number as axisCount in the 'fvar' table. + sharedTupleCount uint16 // The number of shared tuple records. Shared tuple records can be referenced within glyph variation data tables for multiple glyphs, as opposed to other tuple records stored directly within a glyph variation data table. + SharedTuples `offsetSize:"Offset32" arguments:"sharedTuplesCount=.sharedTupleCount,valuesCount=.axisCount"` // Offset from the start of this table to the shared tuple records. + glyphCount uint16 // The number of glyphs in this font. This must match the number of glyphs stored elsewhere in the font. + flags uint16 // Bit-field that gives the format of the offset array that follows. If bit 0 is clear, the offsets are uint16; if bit 0 is set, the offsets are uint32. + glyphVariationDataArrayOffset Offset32 // Offset from the start of this table to the array of GlyphVariationData tables. + glyphVariationDataOffsets []uint32 `isOpaque:"" subsliceStart:"AtCurrent"` // [glyphCount + 1]Offset16 or Offset32 Offsets from the start of the GlyphVariationData array to each GlyphVariationData table. + GlyphVariationDatas []GlyphVariationData `isOpaque:""` +} + +func (gv *Gvar) parseGlyphVariationDataOffsets(src []byte) error { + var err error + gv.glyphVariationDataOffsets, err = ParseLoca(src, int(gv.glyphCount), gv.flags&1 != 0) + return err +} + +func (gv *Gvar) parseGlyphVariationDatas(src []byte) error { + gv.GlyphVariationDatas = make([]GlyphVariationData, gv.glyphCount) + startArray := uint32(gv.glyphVariationDataArrayOffset) + for i := range gv.GlyphVariationDatas { + start, end := int(startArray+gv.glyphVariationDataOffsets[i]), int(startArray+gv.glyphVariationDataOffsets[i+1]) + if start == end { + continue + } + + if start > end { + return fmt.Errorf("invalid offsets %d > %d", start, end) + } + + if L := len(src); L < end { + return fmt.Errorf("EOF: expected length: %d, got %d", end, L) + } + + var err error + gv.GlyphVariationDatas[i], _, err = ParseGlyphVariationData(src[start:end], int(gv.axisCount)) + if err != nil { + return err + } + } + return nil +} + +type SharedTuples struct { + SharedTuples []Tuple // [sharedTupleCount] Array of tuple records shared across all glyph variation data tables. +} + +type Tuple struct { + Values []Coord // [axisCount] Coordinate array specifying a position within the font’s variation space. The number of elements must match the axisCount specified in the 'fvar' table. +} + +type GlyphVariationData struct { + tupleVariationCount uint16 // A packed field. The high 4 bits are flags, and the low 12 bits are the number of tuple variation tables for this glyph. The number of tuple variation tables can be any number between 1 and 4095. + SerializedData []byte `offsetSize:"Offset16" arrayCount:"ToEnd"` // Offset from the start of the GlyphVariationData table to the serialized data + TupleVariationHeaders []TupleVariationHeader `arrayCount:"ComputedField-tupleVariationCount&0x0FFF"` //[tupleCount] Array of tuple variation headers. +} + +// HasSharedPointNumbers returns true if the 'sharedPointNumbers' is on. +func (gv *GlyphVariationData) HasSharedPointNumbers() bool { + const sharedPointNumbers = 0x8000 + return gv.tupleVariationCount&sharedPointNumbers != 0 +} + +// binarygen: argument=axisCount int +type TupleVariationHeader struct { + VariationDataSize uint16 // The size in bytes of the serialized data for this tuple variation table. + tupleIndex uint16 // A packed field. The high 4 bits are flags (see below). The low 12 bits are an index into a shared tuple records array. + // Peak tuple record for this tuple variation table — optional, determined by flags in the tupleIndex value. + // Note that this must always be included in the 'cvar' table. + PeakTuple Tuple `isOpaque:"" subsliceStart:"AtCurrent"` + IntermediateTuples [2]Tuple `isOpaque:"" subsliceStart:"AtCurrent"` // Intermediate start/end tuple record for this tuple variation table — optional, determined by flags in the tupleIndex value. +} + +func (tv *TupleVariationHeader) parsePeakTuple(src []byte, axisCount int) (read int, err error) { + const embeddedPeakTuple = 0x8000 + if hasPeak := tv.tupleIndex&embeddedPeakTuple != 0; hasPeak { + tv.PeakTuple, read, err = ParseTuple(src, axisCount) + if err != nil { + return 0, err + } + } + return +} + +func (tv *TupleVariationHeader) parseIntermediateTuples(src []byte, axisCount int) (read int, err error) { + const intermediateRegion = 0x4000 + if hasRegions := tv.tupleIndex&intermediateRegion != 0; hasRegions { + tv.IntermediateTuples[0], read, err = ParseTuple(src, axisCount) + if err != nil { + return 0, err + } + tv.IntermediateTuples[1], _, err = ParseTuple(src[read:], axisCount) + read *= 2 + } + return +} + +// HasPrivatePointNumbers returns true if the flag 'privatePointNumbers' is on +func (t *TupleVariationHeader) HasPrivatePointNumbers() bool { + const privatePointNumbers = 0x2000 + return t.tupleIndex&privatePointNumbers != 0 +} + +// Index returns the tuple index, after masking +func (t *TupleVariationHeader) Index() uint16 { + const TupleIndexMask = 0x0FFF + return t.tupleIndex & TupleIndexMask +} + +// ---------------------------------- HVAR/VVAR ---------------------------------- + +// See - https://learn.microsoft.com/fr-fr/typography/opentype/spec/hvar +type HVAR struct { + majorVersion uint16 // Major version number of the horizontal metrics variations table — set to 1. + minorVersion uint16 // Minor version number of the horizontal metrics variations table — set to 0. + ItemVariationStore ItemVarStore `offsetSize:"Offset32"` // Offset in bytes from the start of this table to the item variation store table. + AdvanceWidthMapping DeltaSetMapping `offsetSize:"Offset32"` // Offset in bytes from the start of this table to the delta-set index mapping for advance widths (may be NULL). + LsbMapping *DeltaSetMapping `offsetSize:"Offset32"` // Offset in bytes from the start of this table to the delta-set index mapping for left side bearings (may be NULL). + RsbMapping *DeltaSetMapping `offsetSize:"Offset32"` // Offset in bytes from the start of this table to the delta-set index mapping for right side bearings (may be NULL). +} + +// VariationStoreIndex reference an item in the variation store +type VariationStoreIndex struct { + DeltaSetOuter, DeltaSetInner uint16 +} + +type DeltaSetMapping struct { + format uint8 // DeltaSetIndexMap format: 0 or 1 + entryFormat uint8 // A packed field that describes the compressed representation of delta-set indices. See details below. + // uint16 or uint32 mapCount : The number of mapping entries. + Map []VariationStoreIndex `isOpaque:"" subsliceStart:"AtCurrent"` +} + +// Index returns the [VariationStoreIndex] for the given index. +func (m DeltaSetMapping) Index(glyph GlyphID) VariationStoreIndex { + // If a mapping table is not provided, glyph indices are used as implicit delta-set indices. + // [...] the delta-set outer-level index is zero, and the glyph ID is used as the inner-level index. + if len(m.Map) == 0 { + return VariationStoreIndex{DeltaSetInner: uint16(glyph)} + } + + // If a given glyph ID is greater than mapCount - 1, then the last entry is used. + if int(glyph) >= len(m.Map) { + glyph = GlyphID(len(m.Map) - 1) + } + + return m.Map[glyph] +} + +func (ds *DeltaSetMapping) parseMap(src []byte) error { + var mapCount int + switch ds.format { + case 0: + if L := len(src); L < 2 { + return fmt.Errorf("EOF: expected length: %d, got %d", 2, L) + } + mapCount = int(binary.BigEndian.Uint16(src)) + src = src[2:] + case 1: + if L := len(src); L < 4 { + return fmt.Errorf("EOF: expected length: %d, got %d", 4, L) + } + mapCount = int(binary.BigEndian.Uint32(src)) + src = src[4:] + default: + return fmt.Errorf("unsupported DeltaSetMapping format %d", ds.format) + } + + const ( + INNER_INDEX_BIT_COUNT_MASK = 0x0F // Mask for the low 4 bits, which give the count of bits minus one that are used in each entry for the inner-level index. + MAP_ENTRY_SIZE_MASK = 0x30 // Mask for bits that indicate the size in bytes minus one of each entry. + ) + innerBitSize := ds.entryFormat&INNER_INDEX_BIT_COUNT_MASK + 1 + entrySize := int((ds.entryFormat&MAP_ENTRY_SIZE_MASK)>>4 + 1) + if entrySize > 4 || len(src) < entrySize*mapCount { + return fmt.Errorf("invalid delta-set mapping (length %d, entrySize %d, mapCount %d)", len(src), entrySize, mapCount) + } + ds.Map = make([]VariationStoreIndex, mapCount) + for i := range ds.Map { + var v uint32 + for _, b := range src[entrySize*i : entrySize*(i+1)] { // 1 to 4 bytes + v = v<<8 + uint32(b) + } + ds.Map[i].DeltaSetOuter = uint16(v >> innerBitSize) + ds.Map[i].DeltaSetInner = uint16(v & (1<= ttfHeaderSize +func writeTTFHeader(nTables int, out []byte) { + log2 := math.Floor(math.Log2(float64(nTables))) + // Maximum power of 2 less than or equal to numTables, times 16 ((2**floor(log2(numTables))) * 16, where “**” is an exponentiation operator). + searchRange := math.Pow(2, log2) * 16 + // Log2 of the maximum power of 2 less than or equal to numTables (log2(searchRange/16), which is equal to floor(log2(numTables))). + entrySelector := log2 + // numTables times 16, minus searchRange ((numTables * 16) - searchRange). + rangeShift := nTables*16 - int(searchRange) + + binary.BigEndian.PutUint32(out[:], uint32(TrueType)) + binary.BigEndian.PutUint16(out[4:], uint16(nTables)) + binary.BigEndian.PutUint16(out[6:], uint16(searchRange)) + binary.BigEndian.PutUint16(out[8:], uint16(entrySelector)) + binary.BigEndian.PutUint16(out[10:], uint16(rangeShift)) +} + +func checksum(table []byte) uint32 { + // "To accommodate data with a length that is not a multiple of four, + // the above algorithm must be modified to treat the data as though + // it contains zero padding to a length that is a multiple of four." + if r := len(table) % 4; r != 0 { + table = append(table, make([]byte, r)...) + } + + var sum uint32 + for i := 0; i < len(table)/4; i++ { + sum += binary.BigEndian.Uint32(table[i*4:]) + } + + return sum +} diff --git a/vendor/github.com/go-text/typesetting/font/os2.go b/vendor/github.com/go-text/typesetting/font/os2.go new file mode 100644 index 0000000..bde606b --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/os2.go @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package font + +import ( + "encoding/binary" + "errors" + + "github.com/go-text/typesetting/font/opentype/tables" +) + +type os2 struct { + version uint16 + xAvgCharWidth uint16 + + *os2Desc + + useTypoMetrics bool // true if the field sTypoAscender, sTypoDescender and sTypoLineGap are valid. + + ySubscriptXSize float32 + ySubscriptYSize float32 + ySubscriptXOffset float32 + ySubscriptYOffset float32 + ySuperscriptXSize float32 + ySuperscriptYSize float32 + ySuperscriptXOffset float32 + yStrikeoutSize float32 + yStrikeoutPosition float32 + sTypoAscender float32 + sTypoDescender float32 + sTypoLineGap float32 + sxHeigh float32 + sCapHeight float32 +} + +func newOs2(os tables.Os2) (os2, error) { + out := os2{ + version: os.Version, + xAvgCharWidth: os.XAvgCharWidth, + os2Desc: newOS2Desc(os), + ySubscriptXSize: float32(os.YSubscriptXSize), + ySubscriptYSize: float32(os.YSubscriptYSize), + ySubscriptXOffset: float32(os.YSubscriptXOffset), + ySubscriptYOffset: float32(os.YSubscriptYOffset), + ySuperscriptXSize: float32(os.YSuperscriptXSize), + ySuperscriptYSize: float32(os.YSuperscriptYSize), + ySuperscriptXOffset: float32(os.YSuperscriptXOffset), + yStrikeoutSize: float32(os.YStrikeoutSize), + yStrikeoutPosition: float32(os.YStrikeoutPosition), + sTypoAscender: float32(os.STypoAscender), + sTypoDescender: float32(os.STypoDescender), + sTypoLineGap: float32(os.STypoLineGap), + } + // add addition info for version >= 2 + if os.Version >= 2 { + if len(os.HigherVersionData) < 12 { + return os2{}, errors.New("invalid table os2") + } + out.sxHeigh = float32(binary.BigEndian.Uint16(os.HigherVersionData[8:])) + out.sCapHeight = float32(binary.BigEndian.Uint16(os.HigherVersionData[10:])) + } + + const useTypoMetrics = 1 << 7 + use := os.FsSelection&useTypoMetrics != 0 + hasData := os.USWeightClass != 0 || os.USWidthClass != 0 || os.USFirstCharIndex != 0 || os.USLastCharIndex != 0 + out.useTypoMetrics = use && hasData + + return out, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/ot_layout.go b/vendor/github.com/go-text/typesetting/font/ot_layout.go new file mode 100644 index 0000000..d3d3732 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/ot_layout.go @@ -0,0 +1,255 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package font + +import "github.com/go-text/typesetting/font/opentype/tables" + +// shared between GSUB and GPOS +type Layout struct { + Scripts []Script + Features []Feature + FeatureVariations []tables.FeatureVariationRecord +} + +func newLayout(table tables.Layout) Layout { + fCount := len(table.FeatureList.Features) + out := Layout{ + Scripts: make([]Script, len(table.ScriptList.Scripts)), + Features: make([]Feature, fCount), + } + for i, s := range table.ScriptList.Scripts { + if langSys := s.DefaultLangSys; langSys != nil { + sanitizeLangSys(langSys, fCount) + } + for i := range s.LangSys { + sanitizeLangSys(&s.LangSys[i], fCount) + } + out.Scripts[i] = Script{ + Script: s, + Tag: table.ScriptList.Records[i].Tag, + } + } + for i, f := range table.FeatureList.Features { + out.Features[i] = Feature{ + Feature: f, + Tag: table.FeatureList.Records[i].Tag, + } + } + if table.FeatureVariations != nil { + out.FeatureVariations = table.FeatureVariations.FeatureVariationRecords + } + return out +} + +func sanitizeLangSys(langSys *tables.LangSys, featuresCount int) { + if int(langSys.RequiredFeatureIndex) >= featuresCount { + // invalid index : replace it by the sentinel value + langSys.RequiredFeatureIndex = 0xFFFF + } +} + +type Script struct { + tables.Script + Tag Tag +} + +type Feature struct { + tables.Feature + Tag Tag +} + +// FindScript looks for [script] and return its index into the Scripts slice, +// or -1 if the tag is not found. +func (la *Layout) FindScript(script Tag) int { + // Scripts is sorted: binary search + low, high := 0, len(la.Scripts) + for low < high { + mid := low + (high-low)/2 // avoid overflow when computing mid + p := la.Scripts[mid].Tag + if script < p { + high = mid + } else if script > p { + low = mid + 1 + } else { + return mid + } + } + return -1 +} + +// FindVariationIndex returns the first feature variation matching +// the specified variation coordinates, as an index in the +// `FeatureVariations` field. +// It returns `-1` if not found. +func (la *Layout) FindVariationIndex(coords []VarCoord) int { + for i, record := range la.FeatureVariations { + if evaluateVarRec(record, coords) { + return i + } + } + return -1 +} + +// returns `true` if the feature is concerned by the `coords` +func evaluateVarRec(fv tables.FeatureVariationRecord, coords []VarCoord) bool { + for _, c := range fv.ConditionSet.Conditions { + if !evaluateCondition(c, coords) { + return false + } + } + return true +} + +// returns `true` if `coords` match the condition `c` +func evaluateCondition(c tables.ConditionFormat1, coords []VarCoord) bool { + var coord VarCoord + if int(c.AxisIndex) < len(coords) { + coord = coords[c.AxisIndex] + } + return c.FilterRangeMinValue <= coord && coord <= c.FilterRangeMaxValue +} + +// FindFeatureIndex fetches the index for a given feature tag in the GSUB or GPOS table. +// Returns false if not found +func (la *Layout) FindFeatureIndex(featureTag Tag) (uint16, bool) { + for i, feat := range la.Features { // i fits in uint16 + if featureTag == feat.Tag { + return uint16(i), true + } + } + return 0, false +} + +// ---------------------------------- GSUB ---------------------------------- + +type GSUB struct { + Layout + Lookups []GSUBLookup +} + +type LookupOptions struct { + // Lookup qualifiers. + Flag uint16 + // Index (base 0) into GDEF mark glyph sets structure, + // meaningfull only if UseMarkFilteringSet is set. + MarkFilteringSet uint16 +} + +const UseMarkFilteringSet = 1 << 4 + +// Props returns a 32-bit integer where the lower 16-bit is `Flag` and +// the higher 16-bit is `MarkFilteringSet` if the lookup uses one. +func (lo LookupOptions) Props() uint32 { + flag := uint32(lo.Flag) + if lo.Flag&UseMarkFilteringSet != 0 { + flag |= uint32(lo.MarkFilteringSet) << 16 + } + return flag +} + +type GSUBLookup struct { + LookupOptions + Subtables []tables.GSUBLookup +} + +func newGSUB(table tables.Layout) (GSUB, error) { + out := GSUB{ + Layout: newLayout(table), + Lookups: make([]GSUBLookup, len(table.LookupList.Lookups)), + } + for i, lk := range table.LookupList.Lookups { + subtables, err := lk.AsGSUBLookups() + if err != nil { + return GSUB{}, err + } + for j, subtable := range subtables { + // start by resolving extension + if ext, isExt := subtable.(tables.ExtensionSubs); isExt { + subtables[j], err = ext.Resolve() + if err != nil { + return GSUB{}, err + } + } + + // sanitize each lookup + switch subtable := subtable.(type) { + case tables.MultipleSubs: + err = subtable.Sanitize() + case tables.LigatureSubs: + err = subtable.Sanitize() + case tables.ContextualSubs: + err = subtable.Sanitize(uint16(len(out.Lookups))) + case tables.ReverseChainSingleSubs: + err = subtable.Sanitize() + } + if err != nil { + return GSUB{}, err + } + } + out.Lookups[i] = GSUBLookup{ + LookupOptions: LookupOptions{ + Flag: lk.LookupFlag, + MarkFilteringSet: lk.MarkFilteringSet, + }, + Subtables: subtables, + } + } + return out, nil +} + +type GPOS struct { + Layout + Lookups []GPOSLookup +} + +type GPOSLookup struct { + LookupOptions + Subtables []tables.GPOSLookup +} + +func newGPOS(table tables.Layout) (GPOS, error) { + out := GPOS{ + Layout: newLayout(table), + Lookups: make([]GPOSLookup, len(table.LookupList.Lookups)), + } + for i, lk := range table.LookupList.Lookups { + subtables, err := lk.AsGPOSLookups() + if err != nil { + return GPOS{}, err + } + for j, subtable := range subtables { + // start by resolving extension + if ext, isExt := subtable.(tables.ExtensionPos); isExt { + subtables[j], err = ext.Resolve() + if err != nil { + return GPOS{}, err + } + } + + // sanitize each lookup + switch subtable := subtable.(type) { + case tables.SinglePos: + err = subtable.Sanitize() + case tables.PairPos: + err = subtable.Sanitize() + case tables.MarkBasePos: + err = subtable.Sanitize() + case tables.MarkLigPos: + err = subtable.Sanitize() + case tables.ContextualPos: + err = subtable.Sanitize(uint16(len(out.Lookups))) + } + if err != nil { + return GPOS{}, err + } + } + out.Lookups[i] = GPOSLookup{ + LookupOptions: LookupOptions{ + Flag: lk.LookupFlag, + MarkFilteringSet: lk.MarkFilteringSet, + }, + Subtables: subtables, + } + } + return out, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/post.go b/vendor/github.com/go-text/typesetting/font/post.go new file mode 100644 index 0000000..82c0ed5 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/post.go @@ -0,0 +1,380 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package font + +import ( + "errors" + "fmt" + + "github.com/go-text/typesetting/font/opentype/tables" +) + +const numBuiltInPostNames = len(builtInPostNames) + +// names is the built-in post table names listed at +// https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html +var builtInPostNames = [...]string{ + ".notdef", + ".null", + "nonmarkingreturn", + "space", + "exclam", + "quotedbl", + "numbersign", + "dollar", + "percent", + "ampersand", + "quotesingle", + "parenleft", + "parenright", + "asterisk", + "plus", + "comma", + "hyphen", + "period", + "slash", + "zero", + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", + "colon", + "semicolon", + "less", + "equal", + "greater", + "question", + "at", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + "bracketleft", + "backslash", + "bracketright", + "asciicircum", + "underscore", + "grave", + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "braceleft", + "bar", + "braceright", + "asciitilde", + "Adieresis", + "Aring", + "Ccedilla", + "Eacute", + "Ntilde", + "Odieresis", + "Udieresis", + "aacute", + "agrave", + "acircumflex", + "adieresis", + "atilde", + "aring", + "ccedilla", + "eacute", + "egrave", + "ecircumflex", + "edieresis", + "iacute", + "igrave", + "icircumflex", + "idieresis", + "ntilde", + "oacute", + "ograve", + "ocircumflex", + "odieresis", + "otilde", + "uacute", + "ugrave", + "ucircumflex", + "udieresis", + "dagger", + "degree", + "cent", + "sterling", + "section", + "bullet", + "paragraph", + "germandbls", + "registered", + "copyright", + "trademark", + "acute", + "dieresis", + "notequal", + "AE", + "Oslash", + "infinity", + "plusminus", + "lessequal", + "greaterequal", + "yen", + "mu", + "partialdiff", + "summation", + "product", + "pi", + "integral", + "ordfeminine", + "ordmasculine", + "Omega", + "ae", + "oslash", + "questiondown", + "exclamdown", + "logicalnot", + "radical", + "florin", + "approxequal", + "Delta", + "guillemotleft", + "guillemotright", + "ellipsis", + "nonbreakingspace", + "Agrave", + "Atilde", + "Otilde", + "OE", + "oe", + "endash", + "emdash", + "quotedblleft", + "quotedblright", + "quoteleft", + "quoteright", + "divide", + "lozenge", + "ydieresis", + "Ydieresis", + "fraction", + "currency", + "guilsinglleft", + "guilsinglright", + "fi", + "fl", + "daggerdbl", + "periodcentered", + "quotesinglbase", + "quotedblbase", + "perthousand", + "Acircumflex", + "Ecircumflex", + "Aacute", + "Edieresis", + "Egrave", + "Iacute", + "Icircumflex", + "Idieresis", + "Igrave", + "Oacute", + "Ocircumflex", + "apple", + "Ograve", + "Uacute", + "Ucircumflex", + "Ugrave", + "dotlessi", + "circumflex", + "tilde", + "macron", + "breve", + "dotaccent", + "ring", + "cedilla", + "hungarumlaut", + "ogonek", + "caron", + "Lslash", + "lslash", + "Scaron", + "scaron", + "Zcaron", + "zcaron", + "brokenbar", + "Eth", + "eth", + "Yacute", + "yacute", + "Thorn", + "thorn", + "minus", + "multiply", + "onesuperior", + "twosuperior", + "threesuperior", + "onehalf", + "onequarter", + "threequarters", + "franc", + "Gbreve", + "gbreve", + "Idotaccent", + "Scedilla", + "scedilla", + "Cacute", + "cacute", + "Ccaron", + "ccaron", + "dcroat", +} + +type post struct { + // suggested distance of the top of the + // underline from the baseline (negative values indicate below baseline). + underlinePosition float32 + // suggested values for the underline thickness. + underlineThickness float32 + + names postGlyphNames + + isFixedPitch bool +} + +func newPost(pst tables.Post) (post, error) { + out := post{ + underlinePosition: float32(pst.UnderlinePosition), + underlineThickness: float32(pst.UnderlineThickness), + isFixedPitch: pst.IsFixedPitch != 0, + } + switch names := pst.Names.(type) { + case tables.PostNames10: + out.names = postNames10or30{} + case tables.PostNames20: + var err error + out.names, err = newPostNames20(names) + if err != nil { + return out, err + } + case tables.PostNames30: + // no-op, do not use the post name tables + } + return out, nil +} + +// postGlyphNames stores the names of a 'post' table. +type postGlyphNames interface { + // GlyphName return the postscript name of a + // glyph, or an empty string if it not found + glyphName(x GID) string +} + +type postNames10or30 struct{} + +func (p postNames10or30) glyphName(x GID) string { + if int(x) >= numBuiltInPostNames { + return "" + } + // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html + return builtInPostNames[x] +} + +type postNames20 struct { + glyphNameIndexes []uint16 // size numGlyph + names []string +} + +func (p postNames20) glyphName(x GID) string { + if int(x) >= len(p.glyphNameIndexes) { + return "" + } + u := int(p.glyphNameIndexes[x]) + if u < numBuiltInPostNames { + return builtInPostNames[u] + } + u -= numBuiltInPostNames + return p.names[u] +} + +func newPostNames20(names tables.PostNames20) (postNames20, error) { + out := postNames20{glyphNameIndexes: names.GlyphNameIndexes} + // we check at parse time that all the indexes are valid: + // we find the maximum + var maxIndex uint16 + for _, u := range names.GlyphNameIndexes { + // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html + // says that "32768 through 65535 are reserved for future use". + if u > 32767 { + return postNames20{}, errors.New("invalid index in Postscript names table format 20") + } + if u > maxIndex { + maxIndex = u + } + } + + // read all the string data until the end of the table + // quoting the spec + // "Strings are in Pascal string format, meaning that the first byte of + // a given string is a length: the number of characters in that string. + // The length byte is not included; for example, a length byte of 8 indicates + // that the 8 bytes following the length byte comprise the string character data." + for i := 0; i < len(names.StringData); { + length := int(names.StringData[i]) // read the length + E, L := i+1+length, len(names.StringData) + if L < E { + return postNames20{}, fmt.Errorf("invalid Postscript names tables format 20: EOF: expected %d, got %d", E, L) + } + out.names = append(out.names, string(names.StringData[i+1:E])) + i = E + } + + if int(maxIndex) >= numBuiltInPostNames && len(out.names) < (int(maxIndex)-numBuiltInPostNames) { + return postNames20{}, errors.New("invalid index in Postscript names table format 20") + } + return out, nil +} diff --git a/vendor/github.com/go-text/typesetting/font/renderer.go b/vendor/github.com/go-text/typesetting/font/renderer.go new file mode 100644 index 0000000..171bae4 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/renderer.go @@ -0,0 +1,433 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package font + +import ( + "bytes" + "compress/gzip" + "errors" + "fmt" + "io" + + ot "github.com/go-text/typesetting/font/opentype" +) + +var ( + errEmptySbixTable = errors.New("empty 'sbix' table") + errEmptyBitmapTable = errors.New("empty bitmap table") +) + +type ( + Segment = ot.Segment + SegmentPoint = ot.SegmentPoint +) + +// GlyphData describe how to draw a glyph. +// It is either an GlyphOutline, GlyphSVG or GlyphBitmap. +type GlyphData interface { + isGlyphData() +} + +func (GlyphOutline) isGlyphData() {} +func (GlyphSVG) isGlyphData() {} +func (GlyphBitmap) isGlyphData() {} + +// GlyphOutline exposes the path to draw for +// vector glyph. +// Coordinates are expressed in fonts units. +type GlyphOutline struct { + Segments []Segment +} + +// Sideways updates the coordinates of the outline by applying +// a 90° clockwise rotation, and adding [yOffset] afterwards. +// +// When used for vertical text, pass +// -Glyph.YOffset, converted in font units, as [yOffset] +// (a positive value to lift the glyph up). +func (o GlyphOutline) Sideways(yOffset float32) { + for i := range o.Segments { + target := o.Segments[i].Args[:] + target[0].X, target[0].Y = target[0].Y, -target[0].X+yOffset + target[1].X, target[1].Y = target[1].Y, -target[1].X+yOffset + target[2].X, target[2].Y = target[2].Y, -target[2].X+yOffset + } +} + +// GlyphSVG is an SVG description for the glyph, +// as found in Opentype SVG table. +type GlyphSVG struct { + // The SVG image content, decompressed if needed. + // The actual glyph description is an SVG element + // with id="glyph" (as in id="glyph12"), + // and several glyphs may share the same Source + Source []byte + + // According to the specification, a fallback outline + // should be specified for each SVG glyphs + Outline GlyphOutline +} + +type GlyphBitmap struct { + // The actual image content, whose interpretation depends + // on the Format field. + Data []byte + Format BitmapFormat + Width, Height int // number of columns and rows + + // Outline may be specified to be drawn with bitmap + Outline *GlyphOutline +} + +// BitmapFormat identifies the format on the glyph +// raw data. Across the various font files, many formats +// may be encountered : black and white bitmaps, PNG, TIFF, JPG. +type BitmapFormat uint8 + +const ( + _ BitmapFormat = iota + // The [GlyphBitmap.Data] slice stores a black or white (0/1) + // bit image, whose length L satisfies + // L * 8 >= [GlyphBitmap.Width] * [GlyphBitmap.Height] + BlackAndWhite + // The [GlyphBitmap.Data] slice stores a PNG encoded image + PNG + // The [GlyphBitmap.Data] slice stores a JPG encoded image + JPG + // The [GlyphBitmap.Data] slice stores a TIFF encoded image + TIFF +) + +// BitmapSize expose the size of bitmap glyphs. +// One font may contain several sizes. +type BitmapSize struct { + Height, Width uint16 + XPpem, YPpem uint16 +} + +// GlyphData returns the glyph content for [gid], or nil if +// not found. +func (f *Face) GlyphData(gid GID) GlyphData { + // since outline may be specified for SVG and bitmaps, check it at the end + outB, err := f.sbix.glyphData(gID(gid), f.xPpem, f.yPpem) + if err == nil { + outline, ok := f.outlineGlyphData(gID(gid)) + if ok { + outB.Outline = &outline + } + return outB + } + + outB, err = f.bitmap.glyphData(gID(gid), f.xPpem, f.yPpem) + if err == nil { + outline, ok := f.outlineGlyphData(gID(gid)) + if ok { + outB.Outline = &outline + } + return outB + } + + outS, ok := f.svg.glyphData(gID(gid)) + if ok { + // Spec : + // For every SVG glyph description, there must be a corresponding TrueType, + // CFF or CFF2 glyph description in the font. + outS.Outline, _ = f.outlineGlyphData(gID(gid)) + return outS + } + + if out, ok := f.outlineGlyphData(gID(gid)); ok { + return out + } + + return nil +} + +func (sb sbix) glyphData(gid gID, xPpem, yPpem uint16) (GlyphBitmap, error) { + st := sb.chooseStrike(xPpem, yPpem) + if st == nil { + return GlyphBitmap{}, errEmptySbixTable + } + + glyph := strikeGlyph(st, gid, 0) + if glyph.GraphicType == 0 { + return GlyphBitmap{}, fmt.Errorf("no glyph %d in 'sbix' table for resolution (%d, %d)", gid, xPpem, yPpem) + } + + out := GlyphBitmap{Data: glyph.Data} + var err error + out.Width, out.Height, out.Format, err = decodeBitmapConfig(glyph) + + return out, err +} + +func (bt bitmap) glyphData(gid gID, xPpem, yPpem uint16) (GlyphBitmap, error) { + st := bt.chooseStrike(xPpem, yPpem) + if st == nil || st.ppemX == 0 || st.ppemY == 0 { + return GlyphBitmap{}, errEmptyBitmapTable + } + + subtable := st.findTable(gid) + if subtable == nil { + return GlyphBitmap{}, fmt.Errorf("no glyph %d in bitmap table for resolution (%d, %d)", gid, xPpem, yPpem) + } + + glyph := subtable.image(gid) + if glyph == nil { + return GlyphBitmap{}, fmt.Errorf("no glyph %d in bitmap table for resolution (%d, %d)", gid, xPpem, yPpem) + } + + out := GlyphBitmap{ + Data: glyph.image, + Width: int(glyph.metrics.Width), + Height: int(glyph.metrics.Height), + } + switch subtable.imageFormat { + case 17, 18, 19: // PNG + out.Format = PNG + case 2, 5: + out.Format = BlackAndWhite + // ensure data length + L := out.Width * out.Height // in bits + if len(out.Data)*8 < L { + return GlyphBitmap{}, fmt.Errorf("EOF in glyph bitmap: expected %d, got %d", L, len(out.Data)*8) + } + default: + return GlyphBitmap{}, fmt.Errorf("unsupported format %d in bitmap table", subtable.imageFormat) + } + + return out, nil +} + +// look for data in 'glyf', 'CFF ' and 'CFF2' tables +func (f *Face) outlineGlyphData(gid gID) (GlyphOutline, bool) { + out, err := f.glyphDataFromCFF1(gid) + if err == nil { + return out, true + } + + out, err = f.glyphDataFromCFF2(gid) + if err == nil { + return out, true + } + + out, err = f.glyphDataFromGlyf(gid) + if err == nil { + return out, true + } + + return GlyphOutline{}, false +} + +func (s svg) glyphData(gid gID) (GlyphSVG, bool) { + data, ok := s.rawGlyphData(gid) + if !ok { + return GlyphSVG{}, false + } + + // un-compress if needed + if r, err := gzip.NewReader(bytes.NewReader(data)); err == nil { + var buf bytes.Buffer + if _, err := io.Copy(&buf, r); err == nil { + data = buf.Bytes() + } + } + + return GlyphSVG{Source: data}, true +} + +// this file converts from font format for glyph outlines to +// segments that rasterizer will consume +// +// adapted from snft/truetype.go + +func midPoint(p, q SegmentPoint) SegmentPoint { + return SegmentPoint{ + X: (p.X + q.X) / 2, + Y: (p.Y + q.Y) / 2, + } +} + +// build the segments from the resolved contour points +func buildSegments(points []contourPoint) []Segment { + if len(points) == 0 { + return nil + } + + var ( + firstOnCurveValid, firstOffCurveValid, lastOffCurveValid bool + firstOnCurve, firstOffCurve, lastOffCurve SegmentPoint + ) + + out := make([]Segment, 0, len(points)+2) + + for _, point := range points { + p := point.SegmentPoint + if !firstOnCurveValid { + if point.isOnCurve { + firstOnCurve = p + firstOnCurveValid = true + out = append(out, Segment{ + Op: ot.SegmentOpMoveTo, + Args: [3]SegmentPoint{p}, + }) + } else if !firstOffCurveValid { + firstOffCurve = p + firstOffCurveValid = true + + if !point.isEndPoint { + continue + } + } else { + firstOnCurve = midPoint(firstOffCurve, p) + firstOnCurveValid = true + lastOffCurve = p + lastOffCurveValid = true + out = append(out, Segment{ + Op: ot.SegmentOpMoveTo, + Args: [3]SegmentPoint{firstOnCurve}, + }) + } + } else if !lastOffCurveValid { + if !point.isOnCurve { + lastOffCurve = p + lastOffCurveValid = true + + if !point.isEndPoint { + continue + } + } else { + out = append(out, Segment{ + Op: ot.SegmentOpLineTo, + Args: [3]SegmentPoint{p}, + }) + } + } else { + if !point.isOnCurve { + out = append(out, Segment{ + Op: ot.SegmentOpQuadTo, + Args: [3]SegmentPoint{ + lastOffCurve, + midPoint(lastOffCurve, p), + }, + }) + lastOffCurve = p + lastOffCurveValid = true + } else { + out = append(out, Segment{ + Op: ot.SegmentOpQuadTo, + Args: [3]SegmentPoint{lastOffCurve, p}, + }) + lastOffCurveValid = false + } + } + + if point.isEndPoint { + // closing the contour + switch { + case !firstOffCurveValid && !lastOffCurveValid: + out = append(out, Segment{ + Op: ot.SegmentOpLineTo, + Args: [3]SegmentPoint{firstOnCurve}, + }) + case !firstOffCurveValid && lastOffCurveValid: + out = append(out, Segment{ + Op: ot.SegmentOpQuadTo, + Args: [3]SegmentPoint{lastOffCurve, firstOnCurve}, + }) + case firstOffCurveValid && !lastOffCurveValid: + out = append(out, Segment{ + Op: ot.SegmentOpQuadTo, + Args: [3]SegmentPoint{firstOffCurve, firstOnCurve}, + }) + case firstOffCurveValid && lastOffCurveValid: + out = append(out, Segment{ + Op: ot.SegmentOpQuadTo, + Args: [3]SegmentPoint{ + lastOffCurve, + midPoint(lastOffCurve, firstOffCurve), + }, + }, + Segment{ + Op: ot.SegmentOpQuadTo, + Args: [3]SegmentPoint{firstOffCurve, firstOnCurve}, + }, + ) + } + + firstOnCurveValid = false + firstOffCurveValid = false + lastOffCurveValid = false + } + } + + return out +} + +type errGlyphOutOfRange int + +func (e errGlyphOutOfRange) Error() string { + return fmt.Sprintf("out of range glyph %d", e) +} + +// apply variation when needed +func (f *Face) glyphDataFromGlyf(glyph gID) (GlyphOutline, error) { + if int(glyph) >= len(f.glyf) { + return GlyphOutline{}, errGlyphOutOfRange(glyph) + } + var points []contourPoint + f.getPointsForGlyph(glyph, 0, &points) + segments := buildSegments(points[:len(points)-phantomCount]) + return GlyphOutline{Segments: segments}, nil +} + +var ( + errNoCFFTable error = errors.New("no CFF table") + errNoCFF2Table error = errors.New("no CFF2 table") +) + +func (f *Font) glyphDataFromCFF1(glyph gID) (GlyphOutline, error) { + if f.cff == nil { + return GlyphOutline{}, errNoCFFTable + } + segments, _, err := f.cff.LoadGlyph(glyph) + if err != nil { + return GlyphOutline{}, err + } + return GlyphOutline{Segments: segments}, nil +} + +func (f *Face) glyphDataFromCFF2(glyph gID) (GlyphOutline, error) { + if f.cff2 == nil { + return GlyphOutline{}, errNoCFF2Table + } + segments, _, err := f.cff2.LoadGlyph(glyph, f.coords) + if err != nil { + return GlyphOutline{}, err + } + return GlyphOutline{Segments: segments}, nil +} + +// BitmapSizes returns the size of bitmap glyphs present in the font. +func (font *Font) BitmapSizes() []BitmapSize { + upem := font.head.UnitsPerEm + + avgWidth := font.os2.xAvgCharWidth + + // handle invalid head/os2 tables + if upem == 0 || font.os2.version == 0xFFFF { + avgWidth = 1 + upem = 1 + } + + // adapted from freetype tt_face_load_sbit + if font.bitmap != nil { + return font.bitmap.availableSizes(avgWidth, upem) + } + + if hori := font.hhea; hori != nil { + return font.sbix.availableSizes(hori, avgWidth, upem) + } + + return nil +} diff --git a/vendor/github.com/go-text/typesetting/font/svg.go b/vendor/github.com/go-text/typesetting/font/svg.go new file mode 100644 index 0000000..7b8d5d6 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/svg.go @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package font + +import ( + "fmt" + + "github.com/go-text/typesetting/font/opentype/tables" +) + +type svg []svgDocument + +func newSvg(table tables.SVG) (svg, error) { + rawData := table.SVGDocumentList.SVGRawData + out := make(svg, len(table.SVGDocumentList.DocumentRecords)) + for i, rec := range table.SVGDocumentList.DocumentRecords { + start, end := rec.SvgDocOffset, rec.SvgDocOffset+tables.Offset32(rec.SvgDocLength) + if len(rawData) < int(end) { + return nil, fmt.Errorf("invalid svg table (EOF: expected %d, got %d)", end, len(rawData)) + } + out[i] = svgDocument{ + first: rec.StartGlyphID, + last: rec.EndGlyphID, + svg: rawData[start:end], + } + } + return out, nil +} + +type svgDocument struct { + // svg document + // each glyph description must be written + // in an element with id=glyphXXX + svg []byte + first gID // The first glyph ID in the range described by this index entry. + last gID // The last glyph ID in the range described by this index entry. Must be >= startGlyphID. +} + +// rawGlyphData returns the SVG document for [gid], or false. +func (s svg) rawGlyphData(gid gID) ([]byte, bool) { + // binary search + for i, j := 0, len(s); i < j; { + h := i + (j-i)/2 + entry := s[h] + if gid < entry.first { + j = h + } else if entry.last < gid { + i = h + 1 + } else { + return entry.svg, true + } + } + return nil, false +} diff --git a/vendor/github.com/go-text/typesetting/font/variations.go b/vendor/github.com/go-text/typesetting/font/variations.go new file mode 100644 index 0000000..8775582 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/font/variations.go @@ -0,0 +1,618 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package font + +import ( + "encoding/binary" + "errors" + "fmt" + "math" + + "github.com/go-text/typesetting/font/opentype/tables" +) + +// axis records +type fvar []tables.VariationAxisRecord + +func newFvar(table tables.Fvar) fvar { return table.FvarRecords.Axis } + +type mvar struct { + store tables.ItemVarStore + values []tables.VarValueRecord +} + +func newMvar(mv tables.MVAR, axisCount int) (mvar, error) { + if got := mv.ItemVariationStore.AxisCount(); got != axisCount { + return mvar{}, fmt.Errorf("mvar: invalid number of axis (%d != %d)", got, axisCount) + } + return mvar{mv.ItemVariationStore, mv.ValueRecords}, nil +} + +// return 0 if `tag` is not found +func (mv mvar) getVar(tag Tag, coords []VarCoord) float32 { + // binary search + for i, j := 0, len(mv.values); i < j; { + h := i + (j-i)/2 + entry := mv.values[h] + if tag < entry.ValueTag { + j = h + } else if entry.ValueTag < tag { + i = h + 1 + } else { + return mv.store.GetDelta(entry.Index, coords) + } + } + return 0 +} + +// ---------------------------------- gvar ---------------------------------- + +type gvar struct { + sharedTuples [][]VarCoord // with size tupleCount x axisCount + variations [][]tupleVariation // with length glyphCount + sharedTupleActiveIdx []int // with length tupleCount +} + +func newGvar(table tables.Gvar, glyf tables.Glyf) (gvar, error) { + if len(table.GlyphVariationDatas) != len(glyf) { + return gvar{}, fmt.Errorf("invalid 'gvar' table: mismatch in glyphs count") + } + + out := gvar{ + sharedTuples: make([][]VarCoord, len(table.SharedTuples.SharedTuples)), + variations: make([][]tupleVariation, len(table.GlyphVariationDatas)), + sharedTupleActiveIdx: make([]int, len(table.SharedTuples.SharedTuples)), + } + for i, ts := range table.SharedTuples.SharedTuples { + out.sharedTuples[i] = ts.Values + } + for i, vs := range table.GlyphVariationDatas { + tvs := make([]tupleVariation, len(vs.TupleVariationHeaders)) + for j, header := range vs.TupleVariationHeaders { + tvs[j].TupleVariationHeader = header + } + + pointsNumberCountAll := pointNumbersCount(glyf[i]) + phantomCount + err := parseGlyphVariationSerializedData(vs.SerializedData, + vs.HasSharedPointNumbers(), pointsNumberCountAll, false, tvs) + if err != nil { + return out, err + } + out.variations[i] = tvs + } + + // For shared tuples that only have one axis active, share the index of + // that axis as a cache. This will speed up caclulateScalar() a lot + // for fonts with lots of axes and many "monovar" tuples. + for i, tuple := range out.sharedTuples { + idx := -1 + for j, peak := range tuple { + if peak != 0 { + if idx != -1 { // two peaks or more, do not cache + idx = -1 + break + } + idx = j + } + } + out.sharedTupleActiveIdx[i] = idx + } + + return out, nil +} + +type tupleVariation struct { + tables.TupleVariationHeader + + pointNumbers []uint16 // nil means allPointsNumbers + // length 2*len(pointNumbers) for gvar table or 2*allPointsNumbers if zero + deltas []int16 +} + +// sharedTuples has length tupleCount x axisCount +// sharedTupleActiveIdx has length tupleCount +func (t tupleVariation) calculateScalar(coords []VarCoord, sharedTuples [][]VarCoord, sharedTupleActiveIdx []int) float32 { + startIdx, endIdx := 0, len(coords) + peakTuple := t.PeakTuple.Values + if peakTuple == nil { // no peak specified -> use shared tuple + index := t.Index() + if int(index) >= len(sharedTuples) { // should not happend + return 0. + } + peakTuple = sharedTuples[index] + + // use the cache to restrict the range + if v := sharedTupleActiveIdx[index]; v != -1 { + startIdx = v + endIdx = startIdx + 1 + } + } + + startTuple, endTuple := t.IntermediateTuples[0].Values, t.IntermediateTuples[1].Values + hasIntermediate := startTuple != nil + + var scalar float32 = 1. + for i := startIdx; i < endIdx; i++ { + v, peak := coords[i], peakTuple[i] + if peak == 0 || v == peak { + continue + } + + if hasIntermediate { + start := startTuple[i] + end := endTuple[i] + if start > peak || peak > end || (start < 0 && end > 0 && peak != 0) { + continue + } + if v < start || v > end { + return 0. + } + if v < peak { + if peak != start { + scalar *= float32(v-start) / float32(peak-start) + } + } else { + if peak != end { + scalar *= float32(end-v) / float32(end-peak) + } + } + } else if v == 0 || v < minC(0, peak) || v > maxC(0, peak) { + return 0. + } else { + scalar *= float32(v) / float32(peak) + } + } + return scalar +} + +// complete `out`, which contains the parsed tuple headers. +// pointNumbersCountAll is used when the tuple variation data provides deltas for all glyph points +func parseGlyphVariationSerializedData(data []byte, hasSharedPoints bool, pointNumbersCountAll int, isCvar bool, out []tupleVariation) error { + var ( + sharedPointNumbers []uint16 + err error + ) + if hasSharedPoints { + sharedPointNumbers, data, err = parsePointNumbers(data) + if err != nil { + return err + } + } + + for i, h := range out { + // adjust for the next iteration + if len(data) < int(h.VariationDataSize) { + return errors.New("invalid glyph variation serialized data (EOF)") + } + nextData := data[h.VariationDataSize:] + + // default to shared points + privatePointNumbers := sharedPointNumbers + if h.HasPrivatePointNumbers() { + privatePointNumbers, data, err = parsePointNumbers(data) + if err != nil { + return err + } + } + // the number of point is precised or defaut to all the points + pointCount := pointNumbersCountAll + if privatePointNumbers != nil { + pointCount = len(privatePointNumbers) + } + + out[i].pointNumbers = privatePointNumbers + + if !isCvar { + pointCount *= 2 // for X and Y + } + + out[i].deltas, err = unpackDeltas(data, pointCount) + if err != nil { + return err + } + + data = nextData + } + return nil +} + +// the returned slice is nil if all glyph points are used +func parsePointNumbers(data []byte) ([]uint16, []byte, error) { + count, data, err := getPackedPointCount(data) + if err != nil { + return nil, nil, err + } + if count == 0 { + return nil, data, nil + } + + var lastPoint uint16 + points := make([]uint16, 0, count) // max value of count is 32767 + for len(points) < int(count) { // loop through the runs + if len(data) == 0 { + return nil, nil, errors.New("invalid glyph variation points numbers (EOF)") + } + control := data[0] + is16bit := control&0x80 != 0 + runLength := int(control&0x7F + 1) + if is16bit { + pts, err := tables.ParseUint16s(data[1:], runLength) + if err != nil { + return nil, nil, fmt.Errorf("invalid glyph variation points numbers: %s", err) + } + for _, pt := range pts { + actualValue := pt + lastPoint + points = append(points, actualValue) + lastPoint = actualValue + } + data = data[1+2*runLength:] + } else { + if len(data) < 1+runLength { + return nil, nil, errors.New("invalid glyph variation points numbers (EOF)") + } + for _, b := range data[1 : 1+runLength] { + actualValue := uint16(b) + lastPoint + points = append(points, actualValue) + lastPoint = actualValue + } + data = data[1+runLength:] + } + } + + return points, data, nil +} + +// return the remaining data and special case of 00 +func getPackedPointCount(data []byte) (uint16, []byte, error) { + const highOrderBit byte = 1 << 7 + if len(data) < 1 { + return 0, nil, errors.New("invalid glyph variation points numbers (EOF)") + } + if data[0] == 0 { + return 0, data[1:], nil + } else if data[0]&highOrderBit == 0 { + count := uint16(data[0]) + return count, data[1:], nil + } else { + if len(data) < 2 { + return 0, nil, errors.New("invalid glyph variation points numbers (EOF)") + } + count := uint16(data[0]&^highOrderBit)<<8 | uint16(data[1]) + return count, data[2:], nil + } +} + +func unpackDeltas(data []byte, pointNumbersCount int) ([]int16, error) { + const ( + deltasAreZero = 0x80 + deltasAreWords = 0x40 + deltaRunCountMask = 0x3F + ) + out := make([]int16, pointNumbersCount) + nbRead := 0 // number of point read : out[:nbRead] is valid + // The data is read until the expected logic count of deltas is obtained. + for nbRead < pointNumbersCount { + if len(data) == 0 { + return nil, errors.New("invalid packed deltas (EOF)") + } + control := data[0] + count := control&deltaRunCountMask + 1 + if isZero := control&deltasAreZero != 0; isZero { + // no additional value to read, just fill with zeros + nbRead += int(count) + data = data[1:] + } else { + // we want to fill out[nbRead:nbRead+count-1], that is we must have + // nbRead+count-1 < pointNumbersCount, ie + // nbRead+count <= pointNumbersCount + if got := nbRead + int(count); got > pointNumbersCount { + return nil, fmt.Errorf("invalid packed deltas (expected %d point numbers, got %d)", pointNumbersCount, got) + } + isInt16 := control&deltasAreWords != 0 + if isInt16 { + if len(data) < 1+2*int(count) { + return nil, errors.New("invalid packed deltas (EOF)") + } + for i := byte(0); i < count; i++ { // count < 64 -> no overflow + out[nbRead] = int16(binary.BigEndian.Uint16(data[1+2*i:])) + nbRead++ + } + data = data[1+2*count:] + } else { + if len(data) < 1+int(count) { + return nil, errors.New("invalid packed deltas (EOF)") + } + for i := byte(0); i < count; i++ { // count < 64 -> no overflow + out[nbRead] = int16(int8(data[1+i])) + nbRead++ + } + data = data[1+count:] + } + } + } + return out, nil +} + +// update `points` in place +func (gvar gvar) applyDeltasToPoints(glyph gID, coords []VarCoord, points []contourPoint) { + // adapted from harfbuzz/src/hb-ot-var-gvar-table.hh + + if int(glyph) >= len(gvar.variations) { // should not happend + return + } + + // save original points for inferred delta calculation + origPoints := append([]contourPoint(nil), points...) + // flag is used to indicate referenced point + deltas := make([]contourPoint, len(points)) + + var endPoints []int // index into points + for i, p := range points { + if p.isEndPoint { + endPoints = append(endPoints, i) + } + } + + varData := gvar.variations[glyph] + for _, tuple := range varData { + scalar := tuple.calculateScalar(coords, gvar.sharedTuples, gvar.sharedTupleActiveIdx) + if scalar == 0 { + continue + } + L := len(tuple.deltas) + applyToAll := tuple.pointNumbers == nil + xDeltas, yDeltas := tuple.deltas[:L/2], tuple.deltas[L/2:] + + // reset the current deltas + for i := range deltas { + deltas[i] = contourPoint{} + } + + for i := range xDeltas { + ptIndex := uint16(i) + if !applyToAll { + ptIndex = tuple.pointNumbers[i] + } + deltas[ptIndex].isExplicit = true + deltas[ptIndex].X += float32(xDeltas[i]) * scalar + deltas[ptIndex].Y += float32(yDeltas[i]) * scalar + } + + /* infer deltas for unreferenced points */ + startPoint := 0 + for _, endPoint := range endPoints { + // check the number of unreferenced points in a contour. + // If no unref points or no ref points, nothing to do. + unrefCount := 0 + for _, p := range deltas[startPoint : endPoint+1] { + if !p.isExplicit { + unrefCount++ + } + } + j := startPoint + if unrefCount == 0 || unrefCount > endPoint-startPoint { + goto noMoreGaps + } + + for { + /* Locate the next gap of unreferenced points between two referenced points prev and next. + * Note that a gap may wrap around at left (startPoint) and/or at right (endPoint). + */ + var prev, next, i int + for { + i = j + j = nextIndex(i, startPoint, endPoint) + if deltas[i].isExplicit && !deltas[j].isExplicit { + break + } + } + prev, j = i, i + for { + i = j + j = nextIndex(i, startPoint, endPoint) + if !deltas[i].isExplicit && deltas[j].isExplicit { + break + } + } + next = j + /* Infer deltas for all unref points in the gap between prev and next */ + i = prev + for { + i = nextIndex(i, startPoint, endPoint) + if i == next { + break + } + deltas[i].X = inferDelta(origPoints[i].X, origPoints[prev].X, origPoints[next].X, deltas[prev].X, deltas[next].X) + deltas[i].Y = inferDelta(origPoints[i].Y, origPoints[prev].Y, origPoints[next].Y, deltas[prev].Y, deltas[next].Y) + unrefCount-- + if unrefCount == 0 { + goto noMoreGaps + } + } + } + noMoreGaps: + startPoint = endPoint + 1 + } + + // apply specified / inferred deltas to points + for i, d := range deltas { + points[i].translate(d.X, d.Y) + } + } +} + +func nextIndex(i, start, end int) int { + if i >= end { + return start + } + return i + 1 +} + +func inferDelta(targetVal, prevVal, nextVal, prevDelta, nextDelta float32) float32 { + if prevVal == nextVal { + if prevDelta == nextDelta { + return prevDelta + } + return 0 + } else if targetVal <= minF(prevVal, nextVal) { + if prevVal < nextVal { + return prevDelta + } + return nextDelta + } else if targetVal >= maxF(prevVal, nextVal) { + if prevVal > nextVal { + return prevDelta + } + return nextDelta + } + + // linear interpolation + r := (targetVal - prevVal) / (nextVal - prevVal) + return prevDelta + r*(nextDelta-prevDelta) +} + +// ------------------------------ hvar/vvar ------------------------------ + +func getAdvanceDeltaUnscaled(t *tables.HVAR, glyph tables.GlyphID, coords []VarCoord) float32 { + index := t.AdvanceWidthMapping.Index(glyph) + return t.ItemVariationStore.GetDelta(index, coords) +} + +func getLsbDeltaUnscaled(t *tables.HVAR, glyph tables.GlyphID, coords []VarCoord) float32 { + if t.LsbMapping == nil { + return 0 + } + index := t.LsbMapping.Index(glyph) + return t.ItemVariationStore.GetDelta(index, coords) +} + +func sanitizeGDEF(table tables.GDEF, axisCount int) error { + // check axis count + if got := table.ItemVarStore.AxisCount(); got != -1 && got != axisCount { + return fmt.Errorf("GDEF: invalid number of axis (%d != %d)", axisCount, got) + } + + // check LigCarets length + if table.LigCaretList.Coverage != nil { + expected := table.LigCaretList.Coverage.Len() + got := len(table.LigCaretList.LigGlyphs) + if expected != got { + return fmt.Errorf("GDEF: invalid number of lig gyphs (%d != %d)", expected, got) + } + } + return nil +} + +// ------------------------------------- external API ------------------------------------- + +// Variation defines a value for a wanted variation axis. +type Variation struct { + Tag Tag // Variation-axis identifier tag + Value float32 // In design units +} + +// SetVariations applies a list of font-variation settings to a font, +// defaulting to the values given in the `fvar` table. +// Note that passing an empty slice will instead remove the coordinates. +func (face *Face) SetVariations(variations []Variation) { + if len(variations) == 0 { + face.SetCoords(nil) + return + } + + fv := face.Font.fvar + if len(fv) == 0 { // the font is not variable... + face.SetCoords(nil) + return + } + + designCoords := fv.getDesignCoordsDefault(variations) + + face.SetCoords(face.NormalizeVariations(designCoords)) +} + +// getDesignCoordsDefault returns the design coordinates corresponding to the given pairs of axis/value. +// The default value of the axis is used when not specified in the variations. +func (fv fvar) getDesignCoordsDefault(variations []Variation) []float32 { + designCoords := make([]float32, len(fv)) + // start with default values + for i, axis := range fv { + designCoords[i] = axis.Default + } + + fv.getDesignCoords(variations, designCoords) + + return designCoords +} + +// getDesignCoords updates the design coordinates, with the given pairs of axis/value. +// It will panic if `designCoords` has not the length expected by the table, that is the number of axis. +func (fv fvar) getDesignCoords(variations []Variation, designCoords []float32) { + for _, variation := range variations { + // allow for multiple axis with the same tag + for index, axis := range fv { + if axis.Tag == variation.Tag { + designCoords[index] = variation.Value + } + } + } +} + +// normalize based on the [min,def,max] values for the axis to be [-1,0,1]. +func (fv fvar) normalizeCoordinates(coords []float32) []VarCoord { + normalized := make([]VarCoord, len(coords)) + for i, a := range fv { + coord := coords[i] + + // out of range: clamping + if coord > a.Maximum { + coord = a.Maximum + } else if coord < a.Minimum { + coord = a.Minimum + } + + if coord < a.Default { + coord = -(coord - a.Default) / (a.Minimum - a.Default) + } else if coord > a.Default { + coord = (coord - a.Default) / (a.Maximum - a.Default) + } else { + coord = 0 + } + + normalized[i] = VarCoord(math.Round(float64(coord * 16384))) // 1 << 14 + } + return normalized +} + +// NormalizeVariations normalize the given design-space coordinates. The minimum and maximum +// values for the axis are mapped to the interval [-1,1], with the default +// axis value mapped to 0. +// +// Any additional scaling defined in the face's `avar` table is also +// applied, as described at https://docs.microsoft.com/en-us/typography/opentype/spec/avar. +// +// This method panics if `coords` has not the correct length, that is the number of axis inf 'fvar'. +func (f *Font) NormalizeVariations(coords []float32) []VarCoord { + // ported from freetype2 + + // Axis normalization is a two-stage process. First we normalize + // based on the [min,def,max] values for the axis to be [-1,0,1]. + // Then, if there's an `avar' table, we renormalize this range. + normalized := f.fvar.normalizeCoordinates(coords) + + // now applying 'avar' + for i, av := range f.avar.AxisSegmentMaps { + l := av.AxisValueMaps + for j := 1; j < len(l); j++ { + previous, pair := l[j-1], l[j] + if normalized[i] < pair.FromCoordinate { + + normalized[i] = previous.ToCoordinate + VarCoord(math.Round(float64(normalized[i]-previous.FromCoordinate)* + float64(pair.ToCoordinate-previous.ToCoordinate)/float64(pair.FromCoordinate-previous.FromCoordinate))) + break + } + } + } + + return normalized +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/LICENSE b/vendor/github.com/go-text/typesetting/harfbuzz/LICENSE new file mode 100644 index 0000000..bd0162c --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/LICENSE @@ -0,0 +1,34 @@ +MIT License + +Copyright (c) 2021 B. KUGLER +Copyright © 2010,2011,2012,2013,2014,2015,2016,2017,2018,2019,2020 Google, Inc. +Copyright © 2018,2019,2020 Ebrahim Byagowi +Copyright © 2019,2020 Facebook, Inc. +Copyright © 2012 Mozilla Foundation +Copyright © 2011 Codethink Limited +Copyright © 2008,2010 Nokia Corporation and/or its subsidiary(-ies) +Copyright © 2009 Keith Stribley +Copyright © 2009 Martin Hosken and SIL International +Copyright © 2007 Chris Wilson +Copyright © 2006 Behdad Esfahbod +Copyright © 2005 David Turner +Copyright © 2004,2007,2008,2009,2010 Red Hat, Inc. +Copyright © 1998-2004 David Turner and Werner Lemberg + +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. \ No newline at end of file diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/buffer.go b/vendor/github.com/go-text/typesetting/harfbuzz/buffer.go new file mode 100644 index 0000000..568cfa7 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/buffer.go @@ -0,0 +1,902 @@ +package harfbuzz + +import ( + "github.com/go-text/typesetting/font/opentype/tables" + "github.com/go-text/typesetting/language" +) + +/* ported from harfbuzz/src/hb-buffer.hh and hb-buffer.h + * Copyright © 1998-2004 David Turner and Werner Lemberg + * Copyright © 2004,2007,2009,2010 Red Hat, Inc. + * Copyright © 2011,2012 Google, Inc. + * Red Hat Author(s): Owen Taylor, Behdad Esfahbod + * Google Author(s): Behdad Esfahbod */ + +const ( + // The following are used internally; not derived from GDEF. + substituted tables.GlyphProps = 1 << (iota + 4) + ligated + multiplied + + preserve = substituted | ligated | multiplied +) + +type bufferScratchFlags uint32 + +const ( + bsfHasNonASCII bufferScratchFlags = 1 << iota + bsfHasDefaultIgnorables + bsfHasSpaceFallback + bsfHasGPOSAttachment + // bsfHasUnsafeToBreak + bsfHasCGJ + bsfHasGlyphFlags + bsfHasBrokenSyllable + + bsfDefault bufferScratchFlags = 0x00000000 + + // reserved for shapers' internal use. + bsfShaper0 bufferScratchFlags = 0x01000000 + bsfShaper1 bufferScratchFlags = 0x02000000 + bsfShaper2 bufferScratchFlags = 0x04000000 + bsfShaper3 bufferScratchFlags = 0x08000000 +) + +// maximum length of additional context added outside +// input text +const contextLength = 5 + +const ( + maxOpsDefault = 0x1FFFFFFF + maxLenDefault = 0x3FFFFFFF +) + +// Buffer is the main structure holding the input text segment and its properties before shaping, +// and output glyphs and their information after shaping. +type Buffer struct { + // Info is used as internal storage during the shaping, + // and also exposes the result: the glyph to display + // and its original Cluster value. + Info []GlyphInfo + + // Pos gives the position of the glyphs resulting from the shapping + // It has the same length has `Info`. + Pos []GlyphPosition + + // Text before / after the main buffer contents, ordered outward ! + // Index 0 is for "pre-Context", 1 for "post-Context". + context [2][]rune + + // temporary storage, usully used the following way: + // - truncate the slice + // - walk through Info and append glyphs to outInfo + // - swap back Into and outInfo with 'swapBuffers' + outInfo []GlyphInfo + + // Props is required to correctly interpret the input runes. + Props SegmentProperties + // Glyph that replaces invisible characters in + // the shaping result. If set to zero (default), the glyph for the + // U+0020 SPACE character is used. Otherwise, this value is used + // verbatim. + Invisible GID + + // Glyph that replaces characters not found in the font during shaping. + // The not-found glyph defaults to zero, sometimes knows as the + // ".notdef" glyph. + NotFound GID + + // Information about how the text in the buffer should be treated. + Flags ShappingOptions + // Precise the cluster handling behavior. + ClusterLevel ClusterLevel + + // some pathological cases can be constructed + // (for example with GSUB tables), where the size of the buffer + // grows out of bounds + // these bounds avoid such cases, which should never happen with + // decent font files + maxOps int // maximum operations allowed + maxLen int // maximum length allowed + + serial uint + idx int // Cursor into `info` and `pos` arrays + scratchFlags bufferScratchFlags // Have space-fallback, etc. + + haveOutput bool + + planCache map[Face][]*shapePlan +} + +// NewBuffer allocate a storage with default options. +// It should then be populated with `AddRunes` and shapped with `Shape`. +func NewBuffer() *Buffer { + return &Buffer{ + ClusterLevel: MonotoneGraphemes, + maxOps: maxOpsDefault, + planCache: map[Face][]*shapePlan{}, + } +} + +// AddRune appends a character with the Unicode value of `codepoint` to `b`, and +// gives it the initial cluster value of `cluster`. Clusters can be any thing +// the client wants, they are usually used to refer to the index of the +// character in the input text stream and are output in the +// `GlyphInfo.Cluster` field. +// This also clears the posterior context (see `AddRunes`). +func (b *Buffer) AddRune(codepoint rune, cluster int) { + b.append(codepoint, cluster) + b.clearContext(1) +} + +func (b *Buffer) append(codepoint rune, cluster int) { + b.Info = append(b.Info, GlyphInfo{codepoint: codepoint, Cluster: cluster}) + b.Pos = append(b.Pos, GlyphPosition{}) +} + +// AddRunes appends characters from `text` array to `b`. `itemOffset` is the +// position of the first character from `text` that will be appended, and +// `itemLength` is the number of character to add (-1 means the end of the slice). +// When shaping part of a larger text (e.g. a run of text from a paragraph), +// instead of passing just the substring +// corresponding to the run, it is preferable to pass the whole +// paragraph and specify the run start and length as `itemOffset` and +// `itemLength`, respectively, to give HarfBuzz the full context to be able, +// for example, to do cross-run Arabic shaping or properly handle combining +// marks at start of run. +// The cluster value attributed to each rune is the index in the `text` slice. +func (b *Buffer) AddRunes(text []rune, itemOffset, itemLength int) { + /* If buffer is empty and pre-context provided, install it. + * This check is written this way, to make sure people can + * provide pre-context in one add_utf() call, then provide + * text in a follow-up call. See: + * + * https://bugzilla.mozilla.org/show_bug.cgi?id=801410#c13 */ + if len(b.Info) == 0 && itemOffset > 0 { + // add pre-context + b.clearContext(0) + for prev := itemOffset - 1; prev >= 0 && len(b.context[0]) < contextLength; prev-- { + b.context[0] = append(b.context[0], text[prev]) + } + } + + if itemLength < 0 { + itemLength = len(text) - itemOffset + } + + for i, u := range text[itemOffset : itemOffset+itemLength] { + b.append(u, itemOffset+i) + } + + // add post-context + s := itemOffset + itemLength + contextLength + if s > len(text) { + s = len(text) + } + b.context[1] = text[itemOffset+itemLength : s] +} + +// GuessSegmentProperties fills unset buffer segment properties based on buffer Unicode +// contents and can be used when no other information is available. +// +// If buffer `Props.Script` is zero, it +// will be set to the Unicode script of the first character in +// the buffer that has a script other than Common, +// Inherited, and Unknown. +// +// Next, if buffer `Props.Direction` is zero, +// it will be set to the natural horizontal direction of the +// buffer script, defaulting to `LeftToRight`. +// +// Finally, if buffer Props.Language is empty, +// it will be set to the process's default language. +func (b *Buffer) GuessSegmentProperties() { + /* If script is not set, guess from buffer contents */ + if b.Props.Script == 0 { + for _, info := range b.Info { + script := language.LookupScript(info.codepoint) + if script != language.Common && script != language.Inherited && script != language.Unknown { + b.Props.Script = script + break + } + } + } + + /* If direction is unset, guess from script */ + if b.Props.Direction == 0 { + b.Props.Direction = getHorizontalDirection(b.Props.Script) + if b.Props.Direction == 0 { + b.Props.Direction = LeftToRight + } + } + + /* If language is not set, use default language from locale */ + if b.Props.Language == "" { + b.Props.Language = language.DefaultLanguage() + } +} + +// Clear resets `b` to its initial empty state (including user settings). +// This method should be used to reuse the allocated memory. +func (b *Buffer) Clear() { + b.ClusterLevel = 0 + b.Flags = 0 + b.Invisible = 0 + b.NotFound = 0 + + b.Props = SegmentProperties{} + b.scratchFlags = 0 + + b.haveOutput = false + + b.idx = 0 + b.Info = b.Info[:0] + b.outInfo = b.outInfo[:0] + b.Pos = b.Pos[:0] + b.clearContext(0) + b.clearContext(1) + + b.serial = 0 +} + +// cur returns the glyph at the cursor, optionaly shifted by `i`. +// Its simply a syntactic sugar for `&b.Info[b.idx+i] ` +func (b *Buffer) cur(i int) *GlyphInfo { return &b.Info[b.idx+i] } + +// cur returns the position at the cursor, optionaly shifted by `i`. +// Its simply a syntactic sugar for `&b.Pos[b.idx+i] +func (b *Buffer) curPos(i int) *GlyphPosition { return &b.Pos[b.idx+i] } + +// returns the last glyph of `outInfo` +func (b *Buffer) prev() *GlyphInfo { + return &b.outInfo[len(b.outInfo)-1] +} + +func (b *Buffer) digest() (d setDigest) { + for _, glyph := range b.Info { + d.add(gID(glyph.Glyph)) + } + return d +} + +// func (b Buffer) has_separate_output() bool { return info != b.outInfo } + +func (b *Buffer) backtrackLen() int { + if b.haveOutput { + return len(b.outInfo) + } + return b.idx +} + +func (b *Buffer) lookaheadLen() int { return len(b.Info) - b.idx } + +// func (b *Buffer) nextSerial() uint { +// out := b.serial +// b.serial++ +// return out +// } + +// Copies glyph at `idx` to `outInfo` before replacing its codepoint by `u` +// Advances `idx` +func (b *Buffer) replaceGlyph(u rune) { + b.replaceGlyphs(1, []rune{u}, nil) +} + +// Copies glyph at `idx` to `outInfo` before replacing its codepoint by `u` +// Advances `idx` +func (b *Buffer) replaceGlyphIndex(g GID) { + b.outInfo = append(b.outInfo, b.Info[b.idx]) + b.outInfo[len(b.outInfo)-1].Glyph = g + b.idx++ +} + +// Merges clusters in [idx:idx+numIn], then duplicate `Info[idx]` len(codepoints) times to `outInfo`. +// Advances `idx` by `numIn`. Assume that idx + numIn <= len(Info) +// Also replaces their codepoint by `codepoints` and their glyph by `glyphs` if non nil +func (b *Buffer) replaceGlyphs(numIn int, codepoints []rune, glyphs []GID) { + b.mergeClusters(b.idx, b.idx+numIn) + + var origInfo *GlyphInfo + if b.idx < len(b.Info) { + origInfo = b.cur(0) + } else { + origInfo = b.prev() + } + replaceCodepoints := codepoints != nil + replaceGlyphs := glyphs != nil + L := len(b.outInfo) + + Lplus := max(len(codepoints), len(glyphs)) + b.outInfo = append(b.outInfo, make([]GlyphInfo, Lplus)...) + for i := 0; i < Lplus; i++ { + b.outInfo[L+i] = *origInfo + if replaceCodepoints { + b.outInfo[L+i].codepoint = codepoints[i] + } + if replaceGlyphs { + b.outInfo[L+i].Glyph = glyphs[i] + } + } + + b.idx += numIn +} + +// makes a copy of the glyph at idx to output and replace in output `codepoint` +// by `r`. Does NOT adavance `idx` +func (b *Buffer) outputRune(r rune) { + b.replaceGlyphs(0, []rune{r}, nil) +} + +// same as outputRune +func (b *Buffer) outputGlyphIndex(g GID) { + b.replaceGlyphs(0, nil, []GID{g}) +} + +// Copies glyph at idx to output but doesn't advance idx +func (b *Buffer) copyGlyph() { + b.outInfo = append(b.outInfo, b.Info[b.idx]) +} + +// Copies glyph at `idx` to `outInfo` and advance `idx`. +// If there's no output, just advance `idx`. +func (b *Buffer) nextGlyph() { + if b.haveOutput { + b.outInfo = append(b.outInfo, b.Info[b.idx]) + } + + b.idx++ +} + +// Copies `n` glyphs from `idx` to `outInfo` and advances `idx`. +// If there's no output, just advance idx. +func (b *Buffer) nextGlyphs(n int) { + if b.haveOutput { + b.outInfo = append(b.outInfo, b.Info[b.idx:b.idx+n]...) + } + b.idx += n +} + +// skipGlyph advances idx without copying to output +func (b *Buffer) skipGlyph() { b.idx++ } + +func (b *Buffer) resetMasks(mask GlyphMask) { + for j := range b.Info { + b.Info[j].Mask = mask + } +} + +// Adds glyph flags in mask to infos with clusters between start and end. +// The start index will be from out-buffer if [fromOutBuffer] is true. +// If [interior] is true, then the cluster having the minimum value is skipped. +func (b *Buffer) setGlyphFlags(mask GlyphMask, start, end int, interior, fromOutBuffer bool) { + end = min(end, len(b.Info)) + + if interior && !fromOutBuffer && end-start < 2 { + return + } + + b.scratchFlags |= bsfHasGlyphFlags + + info := b.Info + if !fromOutBuffer || !b.haveOutput { + if !interior { + for i := start; i < end; i++ { + info[i].Mask |= mask + } + } else { + cluster := b.findMinCluster(info, start, end, maxInt) + b.infosSetGlyphFlags(info, start, end, cluster, mask) + } + } else { + // assert (start <= out_len); + // assert (idx <= end); + outInfo := b.outInfo + if !interior { + for i := start; i < len(outInfo); i++ { + outInfo[i].Mask |= mask + } + for i := b.idx; i < end; i++ { + info[i].Mask |= mask + } + } else { + cluster := b.findMinCluster(info, b.idx, end, maxInt) + cluster = b.findMinCluster(outInfo, start, len(outInfo), cluster) + + b.infosSetGlyphFlags(outInfo, start, len(outInfo), cluster, mask) + b.infosSetGlyphFlags(info, b.idx, end, cluster, mask) + } + } +} + +func (b *Buffer) setMasks(value, mask GlyphMask, clusterStart, clusterEnd int) { + notMask := ^mask + value &= mask + + if mask == 0 { + return + } + + for i, info := range b.Info { + if clusterStart <= info.Cluster && info.Cluster < clusterEnd { + b.Info[i].Mask = (info.Mask & notMask) | value + } + } +} + +func (b *Buffer) mergeClusters(start, end int) { + if end-start < 2 { + return + } + + if b.ClusterLevel == Characters { + b.unsafeToBreak(start, end) + return + } + + cluster := b.Info[start].Cluster + + for i := start + 1; i < end; i++ { + cluster = min(cluster, b.Info[i].Cluster) + } + + // Extend end + if cluster != b.Info[end-1].Cluster { + for end < len(b.Info) && b.Info[end-1].Cluster == b.Info[end].Cluster { + end++ + } + } + + // Extend start + if cluster != b.Info[start].Cluster { + for b.idx < start && b.Info[start-1].Cluster == b.Info[start].Cluster { + start-- + } + } + + // If we hit the start of buffer, continue in out-buffer. + if b.idx == start && b.Info[start].Cluster != cluster { + startC := b.Info[start].Cluster + for i := len(b.outInfo); i != 0 && b.outInfo[i-1].Cluster == startC; i-- { + b.outInfo[i-1].setCluster(cluster, 0) + } + } + + for i := start; i < end; i++ { + b.Info[i].setCluster(cluster, 0) + } +} + +// merge clusters for deleting current glyph, and skip it. +func (b *Buffer) deleteGlyph() { + // The logic here is duplicated in hb_ot_hide_default_ignorables(). + + cluster := b.Info[b.idx].Cluster + if L := len(b.outInfo); b.idx+1 < len(b.Info) && cluster == b.Info[b.idx+1].Cluster || + L != 0 && cluster == b.outInfo[L-1].Cluster { + /* Cluster survives; do nothing. */ + goto done + } + + if L := len(b.outInfo); L != 0 { + /* Merge cluster backward. */ + if cluster < b.outInfo[L-1].Cluster { + mask := b.Info[b.idx].Mask + oldCluster := b.outInfo[L-1].Cluster + for i := L; i != 0 && b.outInfo[i-1].Cluster == oldCluster; i-- { + b.outInfo[i-1].setCluster(cluster, mask) + } + } + goto done + } + + if b.idx+1 < len(b.Info) { + /* Merge cluster forward. */ + b.mergeClusters(b.idx, b.idx+2) + goto done + } + +done: + b.skipGlyph() +} + +func (b *Buffer) deleteGlyphsInplace(filter func(*GlyphInfo) bool) { + // Merge clusters and delete filtered glyphs. + // NOTE! We can't use out-buffer as we have positioning data. + var ( + j int + info = b.Info + pos = b.Pos + ) + for i := range info { + if filter(&info[i]) { + /* Merge clusters. + * Same logic as buffer.deleteGlyph(), but for in-place removal. */ + + cluster := info[i].Cluster + if i+1 < len(b.Info) && cluster == info[i+1].Cluster { + // Cluster survives; do nothing. + continue + } + + if j != 0 { + // Merge cluster backward. + if cluster < info[j-1].Cluster { + mask := info[i].Mask + oldCluster := info[j-1].Cluster + for k := j; k != 0 && info[k-1].Cluster == oldCluster; k-- { + info[k-1].setCluster(cluster, mask) + } + } + continue + } + + if i+1 < len(b.Info) { + // Merge cluster forward. + b.mergeClusters(i, i+2) + } + + continue + } + + if j != i { + info[j] = info[i] + pos[j] = pos[i] + } + j++ + } + b.Info = b.Info[:j] + b.Pos = b.Pos[:j] +} + +// unsafeToBreak adds the flag `GlyphFlagUnsafeToBreak` +// when needed, between `start` and `end`. +func (b *Buffer) unsafeToBreak(start, end int) { + b.setGlyphFlags(GlyphUnsafeToBreak|GlyphUnsafeToConcat, start, end, true, false) +} + +func (b *Buffer) safeToInsertTatweel(start, end int) { + if (b.Flags & ProduceSafeToInsertTatweel) == 0 { + b.unsafeToBreak(start, end) + return + } + b.setGlyphFlags(GlyphSafeToInsertTatweel, start, end, true, false) +} + +// start = 0, end = maxInt +func (b *Buffer) unsafeToConcat(start, end int) { + if (b.Flags & ProduceUnsafeToConcat) == 0 { + return + } + b.setGlyphFlags(GlyphUnsafeToConcat, start, end, true, false) +} + +func (b *Buffer) unsafeToBreakFromOutbuffer(start, end int) { + b.setGlyphFlags(GlyphUnsafeToBreak|GlyphUnsafeToConcat, start, end, true, true) +} + +func (b *Buffer) unsafeToConcatFromOutbuffer(start, end int) { + if (b.Flags & ProduceUnsafeToConcat) == 0 { + return + } + b.setGlyphFlags(GlyphUnsafeToConcat, start, end, false, true) +} + +// return the smallest cluster between `cluster` and infos[start:end] +func (b *Buffer) findMinCluster(infos []GlyphInfo, start, end, cluster int) int { + if start == end { + return cluster + } + if b.ClusterLevel == Characters { + for i := start; i < end; i++ { + cluster = min(cluster, infos[i].Cluster) + } + return cluster + } + return min(cluster, min(infos[start].Cluster, infos[end-1].Cluster)) +} + +func (b *Buffer) infosSetGlyphFlags(infos []GlyphInfo, start, end, cluster int, mask GlyphMask) { + if start == end { + return + } + + clusterFirst := infos[start].Cluster + clusterLast := infos[end-1].Cluster + + if b.ClusterLevel == Characters || (cluster != clusterFirst && cluster != clusterLast) { + for i := start; i < end; i++ { + if cluster != infos[i].Cluster { + b.scratchFlags |= bsfHasGlyphFlags + infos[i].Mask |= mask + } + } + return + } + + /* Monotone clusters */ + + if cluster == clusterFirst { + for i := end; start < i && infos[i-1].Cluster != clusterFirst; i-- { + b.scratchFlags |= bsfHasGlyphFlags + infos[i-1].Mask |= mask + } + } else /* cluster == clusterLast */ { + for i := start; i < end && infos[i].Cluster != clusterLast; i++ { + b.scratchFlags |= bsfHasGlyphFlags + infos[i].Mask |= mask + } + } +} + +// reset `b.outInfo`, and adjust `pos` to have +// same length as `Info` (without zeroing its values) +func (b *Buffer) clearPositions() { + b.haveOutput = false + // b.have_positions = true + + b.outInfo = b.outInfo[:0] + + L := len(b.Info) + if cap(b.Pos) >= L { + b.Pos = b.Pos[:L] + } else { + b.Pos = make([]GlyphPosition, L) + } +} + +// truncate `outInfo` and set `haveOutput` +func (b *Buffer) removeOutput(setOutput bool) { + b.haveOutput = setOutput + // b.have_positions = false + + b.outInfo = b.outInfo[:0] +} + +// truncate `outInfo` and set `haveOutput` to true +func (b *Buffer) clearOutput() { + b.removeOutput(true) + b.idx = 0 +} + +func (b *Buffer) clearContext(side uint) { b.context[side] = b.context[side][:0] } + +// reverses the subslice [start:end] of the buffer contents +func (b *Buffer) reverseRange(start, end int) { + if end-start < 2 { + return + } + info := b.Info[start:end] + pos := b.Pos[start:end] + L := len(info) + _ = pos[L-1] // BCE + for i := L/2 - 1; i >= 0; i-- { + opp := L - 1 - i + info[i], info[opp] = info[opp], info[i] + pos[i], pos[opp] = pos[opp], pos[i] // same length + } +} + +// Reverse reverses buffer contents, that is the `Info` and `Pos` slices. +func (b *Buffer) Reverse() { b.reverseRange(0, len(b.Info)) } + +func (b *Buffer) reverseClusters() { + b.reverseGroups(func(gi1, gi2 *GlyphInfo) bool { + return gi1.Cluster == gi2.Cluster + }, false) +} + +// mergeClusters = false +func (b *Buffer) reverseGroups(groupFunc func(*GlyphInfo, *GlyphInfo) bool, mergeClusters bool) { + if len(b.Info) == 0 { + return + } + + count := len(b.Info) + start := 0 + var i int + for i = 1; i < count; i++ { + if !groupFunc(&b.Info[i-1], &b.Info[i]) { + if mergeClusters { + b.mergeClusters(start, i) + } + b.reverseRange(start, i) + start = i + } + } + + if mergeClusters { + b.mergeClusters(start, i) + } + b.reverseRange(start, i) + + b.Reverse() +} + +// swap back the temporary outInfo buffer to `Info` +// and resets the cursor `idx`. +// Assume that haveOutput is true, and toogle it. +func (b *Buffer) swapBuffers() { + b.nextGlyphs(len(b.Info) - b.idx) + b.haveOutput = false + b.Info, b.outInfo = b.outInfo, b.Info + b.idx = 0 +} + +// returns an unique id +func (b *Buffer) allocateLigID() uint8 { + ligID := uint8(b.serial & 0x07) + b.serial++ + if ligID == 0 { // in case of overflow + ligID = b.allocateLigID() + } + return ligID +} + +func (b *Buffer) shiftForward(count int) { + // assert (have_output); + L := len(b.Info) + b.Info = append(b.Info, make([]GlyphInfo, count)...) + copy(b.Info[b.idx+count:], b.Info[b.idx:L]) + b.idx += count +} + +func (b *Buffer) moveTo(i int) { + if !b.haveOutput { + // assert(i <= len) + b.idx = i + return + } + + // assert(i <= out_len+(len-idx)) + outL := len(b.outInfo) + if outL < i { + count := i - outL + b.outInfo = append(b.outInfo, b.Info[b.idx:count+b.idx]...) + b.idx += count + } else if outL > i { + /* Tricky part: rewinding... */ + count := outL - i + + if b.idx < count { + b.shiftForward(count - b.idx) + } + + // assert(idx >= count) + + b.idx -= count + copy(b.Info[b.idx:], b.outInfo[outL-count:outL]) + b.outInfo = b.outInfo[:outL-count] + } +} + +// iterator over the grapheme of a buffer +type graphemesIterator struct { + buffer *Buffer + start int +} + +// at the end of the buffer, start >= len(info) +func (g *graphemesIterator) next() (start, end int) { + info := g.buffer.Info + count := len(info) + start = g.start + if start >= count { + return + } + for end = g.start + 1; end < count && info[end].isContinuation(); end++ { + } + g.start = end + return start, end +} + +func (b *Buffer) graphemesIterator() (*graphemesIterator, int) { + return &graphemesIterator{buffer: b}, len(b.Info) +} + +// iterator over clusters of a buffer with the loop +// for start, end := iter.Next(); start < count; start, end = iter.Next() {} +type clusterIterator struct { + buffer *Buffer + start int +} + +// returns the next cluster delimited by [start, end[ +func (c *clusterIterator) next() (start, end int) { + info := c.buffer.Info + count := len(info) + start = c.start + if start >= count { + return + } + cluster := info[start].Cluster + for end = start + 1; end < count && cluster == info[end].Cluster; end++ { + } + c.start = end + + return start, end +} + +func (b *Buffer) clusterIterator() (*clusterIterator, int) { + return &clusterIterator{buffer: b}, len(b.Info) +} + +// iterator over syllables of a buffer +type syllableIterator struct { + buffer *Buffer + start int +} + +func (c *syllableIterator) next() (start, end int) { + info := c.buffer.Info + count := len(c.buffer.Info) + start = c.start + if start >= count { + return + } + syllable := info[start].syllable + for end = start + 1; end < count && syllable == info[end].syllable; end++ { + } + c.start = end + return start, end +} + +func (b *Buffer) syllableIterator() (*syllableIterator, int) { + return &syllableIterator{buffer: b}, len(b.Info) +} + +// only modifies Info, thus assume Pos is not used yet +func (b *Buffer) sort(start, end int, compar func(a, b *GlyphInfo) int) { + for i := start + 1; i < end; i++ { + j := i + for j > start && compar(&b.Info[j-1], &b.Info[i]) > 0 { + j-- + } + if i == j { + continue + } + // move item i to occupy place for item j, shift what's in between. + b.mergeClusters(j, i+1) + + t := b.Info[i] + copy(b.Info[j+1:], b.Info[j:i]) + b.Info[j] = t + } +} + +func (b *Buffer) mergeOutClusters(start, end int) { + if b.ClusterLevel == Characters { + return + } + + if end-start < 2 { + return + } + + cluster := b.outInfo[start].Cluster + + for i := start + 1; i < end; i++ { + cluster = min(cluster, b.outInfo[i].Cluster) + } + + /* Extend start */ + for start != 0 && b.outInfo[start-1].Cluster == b.outInfo[start].Cluster { + start-- + } + + /* Extend end */ + for end < len(b.outInfo) && b.outInfo[end-1].Cluster == b.outInfo[end].Cluster { + end++ + } + + /* If we hit the end of out-buffer, continue in buffer. */ + if end == len(b.outInfo) { + endC := b.outInfo[end-1].Cluster + for i := b.idx; i < len(b.Info) && b.Info[i].Cluster == endC; i++ { + b.Info[i].setCluster(cluster, 0) + } + } + + for i := start; i < end; i++ { + b.outInfo[i].setCluster(cluster, 0) + } +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/fonts.go b/vendor/github.com/go-text/typesetting/harfbuzz/fonts.go new file mode 100644 index 0000000..fc9d532 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/fonts.go @@ -0,0 +1,387 @@ +package harfbuzz + +import ( + "github.com/go-text/typesetting/font" + "github.com/go-text/typesetting/font/opentype/tables" +) + +// ported from src/hb-font.hh, src/hb-font.cc Copyright © 2009 Red Hat, Inc., 2012 Google, Inc. Behdad Esfahbod + +type Face = *font.Face + +// Font is used internally as a wrapper around the provided Face. +// +// Font are constructed with `NewFont` and adjusted by accessing the fields +// Ptem, XScale, YScale. +// +// Fonts private fields only depend on the provided [*font.Font], so a Font object is suitable for caching. +type Font struct { + face Face + + gsubAccels, gposAccels []otLayoutLookupAccelerator // accelators for lookup + faceUpem int32 // cached value of Face.Upem() + + // Point size of the font. Set to zero to unset. + // This is used in AAT layout, when applying 'trak' table. + Ptem float32 + + // Horizontal and vertical scale of the font. + // + // The font scale is a number related to, but not the same as, + // font size. Typically the client establishes a scale factor + // to be used between the two. For example, 64, or 256, which + // would be the fractional-precision part of the font scale. + // This is necessary because [Position] values are integer + // types and you need to leave room for fractional values + // in there. + // + // For example, to set the font size to 20, with 64 + // levels of fractional precision you would use a scale of + // 20 * 64. + // + // In the example above, even what font size 20 means is up to + // you. It might be 20 pixels, or 20 points, or 20 millimeters. + // HarfBuzz does not care about that. You can set the point + // size of the font using [Ptem], and the pixel + // size using [Face.Ppem] + // + // The choice of scale is yours but needs to be consistent between + // what you set here, and what you expect out of [Position] + // as well has draw / paint API output values. + // + // Fonts default to a scale equal to the UPEM value of their face. + // A font with this setting is sometimes called an "unscaled" font. + // + // The resulting positions are computed with: fontUnit * Scale / faceUpem, + // where faceUpem is given by the face. + // + // Given a device resolution (in dpi) and a point size, the scale to + // get result in pixels is given by : pointSize * dpi / 72 + XScale, YScale int32 +} + +// NewFont constructs a new font object from the specified face. +// +// The scale is set to the face Upem, meaning that by default +// the output results will be expressed in font units. +// +// The `face` object should not be modified after this call. +func NewFont(face Face) *Font { + var font Font + + font.face = face + font.faceUpem = Position(font.face.Upem()) + font.XScale = font.faceUpem + font.YScale = font.faceUpem + + // accelerators + font.gsubAccels = make([]otLayoutLookupAccelerator, len(face.GSUB.Lookups)) + for i, l := range face.GSUB.Lookups { + font.gsubAccels[i].init(lookupGSUB(l)) + } + font.gposAccels = make([]otLayoutLookupAccelerator, len(face.GPOS.Lookups)) + for i, l := range face.GPOS.Lookups { + font.gposAccels[i].init(lookupGPOS(l)) + } + + return &font +} + +// SetVarCoordsDesign applies a list of variation coordinates, in design-space units, +// to the font. +func (f *Font) SetVarCoordsDesign(coords []float32) { + f.face.SetCoords(f.face.NormalizeVariations(coords)) +} + +// Face returns the underlying face. +// Note that field is readonly, since some caching may happen +// in the `NewFont` constructor. +func (f *Font) Face() Face { return f.face } + +func (f *Font) nominalGlyph(r rune, notFound GID) (GID, bool) { + g, ok := f.face.NominalGlyph(r) + if !ok { + g = notFound + } + return g, ok +} + +// ---- Convert from font-space to user-space ---- + +func (f *Font) emScaleX(v int16) Position { return Position(v) * f.XScale / f.faceUpem } +func (f *Font) emScaleY(v int16) Position { return Position(v) * f.YScale / f.faceUpem } +func (f *Font) emScalefX(v float32) Position { return emScalef(v, f.XScale, f.faceUpem) } +func (f *Font) emScalefY(v float32) Position { return emScalef(v, f.YScale, f.faceUpem) } +func (f *Font) emFscaleX(v int16) float32 { return emFscale(v, f.XScale, f.faceUpem) } +func (f *Font) emFscaleY(v int16) float32 { return emFscale(v, f.YScale, f.faceUpem) } + +func emScalef(v float32, scale, faceUpem int32) Position { + return roundf(v * float32(scale) / float32(faceUpem)) +} + +func emFscale(v int16, scale, faceUpem int32) float32 { + return float32(v) * float32(scale) / float32(faceUpem) +} + +// GlyphExtents is the same as fonts.GlyphExtents but with int type +type GlyphExtents struct { + XBearing int32 + YBearing int32 + Width int32 + Height int32 +} + +// GlyphExtents fetches the GlyphExtents data for a glyph ID +// in the specified font, or false if not found +func (f *Font) GlyphExtents(glyph GID) (out GlyphExtents, ok bool) { + ext, ok := f.face.GlyphExtents(glyph) + if !ok { + return out, false + } + out.XBearing = f.emScalefX(ext.XBearing) + out.Width = f.emScalefX(ext.Width) + out.YBearing = f.emScalefY(ext.YBearing) + out.Height = f.emScalefY(ext.Height) + return out, true +} + +// GlyphAdvanceForDirection fetches the advance for a glyph ID from the specified font, +// in a text segment of the specified direction. +// +// Calls the appropriate direction-specific variant (horizontal +// or vertical) depending on the value of `dir`. +func (f *Font) GlyphAdvanceForDirection(glyph GID, dir Direction) (x, y Position) { + if dir.isHorizontal() { + return f.GlyphHAdvance(glyph), 0 + } + return 0, f.getGlyphVAdvance(glyph) +} + +// GlyphHAdvance fetches the advance for a glyph ID in the font, +// for horizontal text segments. +func (f *Font) GlyphHAdvance(glyph GID) Position { + adv := f.face.HorizontalAdvance(glyph) + return f.emScalefX(adv) +} + +// Fetches the advance for a glyph ID in the font, +// for vertical text segments. +func (f *Font) getGlyphVAdvance(glyph GID) Position { + if f.face.HasVerticalMetrics() { + adv := f.face.VerticalAdvance(glyph) + return f.emScalefY(adv) + } else { + fontExtents := f.fontHExtentsWithFallback() + advance := Position(-(fontExtents.Ascender - fontExtents.Descender)) + return advance + } +} + +// Subtracts the origin coordinates from an (X,Y) point coordinate, +// in the specified glyph ID in the specified font. +// +// Calls the appropriate direction-specific variant (horizontal +// or vertical) depending on the value of @direction. +func (f *Font) subtractGlyphOriginForDirection(glyph GID, direction Direction, + x, y Position, +) (Position, Position) { + originX, originY := f.getGlyphOriginForDirection(glyph, direction) + + return x - originX, y - originY +} + +// Fetches the (X,Y) coordinates of the origin for a glyph in +// the specified font. +// +// Calls the appropriate direction-specific variant (horizontal +// or vertical) depending on the value of @direction. +func (f *Font) getGlyphOriginForDirection(glyph GID, direction Direction) (x, y Position) { + if direction.isHorizontal() { + return f.getGlyphHOriginWithFallback(glyph) + } + return f.getGlyphVOriginWithFallback(glyph) +} + +func (f *Font) getGlyphHOriginWithFallback(glyph GID) (Position, Position) { + x, y, ok := f.face.GlyphHOrigin(glyph) + if !ok { + x, y, ok = f.face.GlyphVOrigin(glyph) + if ok { + x, y := f.emScalefX(float32(x)), f.emScalefY(float32(y)) + dx, dy := f.guessVOriginMinusHOrigin(glyph) + return x - dx, y - dy + } + } + return f.emScalefX(float32(x)), f.emScalefY(float32(y)) +} + +func (f *Font) getGlyphVOriginWithFallback(glyph GID) (Position, Position) { + x, y, ok := f.face.GlyphVOrigin(glyph) + if !ok { + x, y, ok = f.face.GlyphHOrigin(glyph) + if ok { + x, y := f.emScalefX(float32(x)), f.emScalefY(float32(y)) + dx, dy := f.guessVOriginMinusHOrigin(glyph) + return x + dx, y + dy + } + } + return f.emScalefX(float32(x)), f.emScalefY(float32(y)) +} + +func (f *Font) guessVOriginMinusHOrigin(glyph GID) (x, y Position) { + x = f.GlyphHAdvance(glyph) / 2 + y = f.getHExtendsAscender() + return x, y +} + +func (f *Font) getHExtendsAscender() Position { + extents, ok := f.face.FontHExtents() + if !ok { + return f.YScale * 4 / 5 + } + return f.emScalefY(extents.Ascender) +} + +func (f *Font) hasGlyph(ch rune) bool { + _, ok := f.face.NominalGlyph(ch) + return ok +} + +func (f *Font) subtractGlyphHOrigin(glyph GID, x, y Position) (Position, Position) { + originX, originY := f.getGlyphHOriginWithFallback(glyph) + return x - originX, y - originY +} + +func (f *Font) subtractGlyphVOrigin(glyph GID, x, y Position) (Position, Position) { + originX, originY := f.getGlyphVOriginWithFallback(glyph) + return x - originX, y - originY +} + +func (f *Font) addGlyphHOrigin(glyph GID, x, y Position) (Position, Position) { + originX, originY := f.getGlyphHOriginWithFallback(glyph) + return x + originX, y + originY +} + +func (f *Font) getGlyphContourPointForOrigin(glyph GID, pointIndex uint16, direction Direction) (x, y Position, ok bool) { + x, y, ok = f.face.GetGlyphContourPoint(glyph, pointIndex) + if ok { + x, y = f.subtractGlyphOriginForDirection(glyph, direction, x, y) + } + + return x, y, ok +} + +func (f *Font) fontHExtentsWithFallback() font.FontExtents { + extents, ok := f.face.FontHExtents() + extents.Ascender = float32(f.emScalefY(extents.Ascender)) + extents.Descender = float32(f.emScalefY(extents.Descender)) + extents.LineGap = float32(f.emScalefY(extents.LineGap)) + if !ok { + extents.Ascender = float32(f.YScale) * 0.8 + extents.Descender = extents.Ascender - float32(f.YScale) + extents.LineGap = 0 + } + return extents +} + +// ExtentsForDirection fetches the extents for a font in a text segment of the +// specified direction, applying the scaling. +// +// Calls the appropriate direction-specific variant (horizontal +// or vertical) depending on the value of `direction`. +func (f *Font) ExtentsForDirection(direction Direction) font.FontExtents { + var ( + extents font.FontExtents + ok bool + ) + if direction.isHorizontal() { + return f.fontHExtentsWithFallback() + } else { + extents, ok = f.face.FontVExtents() + extents.Ascender = float32(f.emScalefX(extents.Ascender)) + extents.Descender = float32(f.emScalefX(extents.Descender)) + extents.LineGap = float32(f.emScalefX(extents.LineGap)) + if !ok { + extents.Ascender = float32(f.XScale) * 0.5 + extents.Descender = extents.Ascender - float32(f.XScale) + extents.LineGap = 0 + } + } + return extents +} + +func (font *Font) varCoords() []tables.Coord { return font.face.Coords() } + +func (font *Font) getXDelta(varStore tables.ItemVarStore, device tables.DeviceTable) Position { + switch device := device.(type) { + case tables.DeviceHinting: + xPpem, _ := font.face.Ppem() + return device.GetDelta(xPpem, font.XScale) + case tables.DeviceVariation: + return font.emScalefX(varStore.GetDelta(tables.VariationStoreIndex(device), font.varCoords())) + default: + return 0 + } +} + +func (font *Font) getYDelta(varStore tables.ItemVarStore, device tables.DeviceTable) Position { + switch device := device.(type) { + case tables.DeviceHinting: + _, yPpem := font.face.Ppem() + return device.GetDelta(yPpem, font.YScale) + case tables.DeviceVariation: + return font.emScalefY(varStore.GetDelta(tables.VariationStoreIndex(device), font.varCoords())) + default: + return 0 + } +} + +// GetOTLigatureCarets fetches a list of the caret positions defined for a ligature glyph in the GDEF +// table of the font (or nil if not found). +func (f *Font) GetOTLigatureCarets(direction Direction, glyph GID) []Position { + varStore := f.face.GDEF.ItemVarStore + + list := f.face.GDEF.LigCaretList + if list.Coverage == nil { + return nil + } + + index, ok := list.Coverage.Index(gID(glyph)) + if !ok { + return nil + } + + glyphCarets := list.LigGlyphs[index].CaretValues + out := make([]Position, len(glyphCarets)) + for i, c := range glyphCarets { + out[i] = f.getCaretValue(c, direction, glyph, varStore) + } + return out +} + +// interpreted the CaretValue according to its format +func (f *Font) getCaretValue(caret tables.CaretValue, direction Direction, glyph GID, varStore tables.ItemVarStore) Position { + switch caret := caret.(type) { + case tables.CaretValue1: + if direction.isHorizontal() { + return f.emScaleX(int16(caret.Coordinate)) + } else { + return f.emScaleY(int16(caret.Coordinate)) + } + case tables.CaretValue2: + x, y, _ := f.getGlyphContourPointForOrigin(glyph, uint16(caret.CaretValuePointIndex), direction) + if direction.isHorizontal() { + return x + } else { + return y + } + case tables.CaretValue3: + if direction.isHorizontal() { + return f.emScaleX(caret.Coordinate) + f.getXDelta(varStore, caret.Device) + } else { + return f.emScaleY(caret.Coordinate) + f.getYDelta(varStore, caret.Device) + } + default: + return 0 + } +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/glyph.go b/vendor/github.com/go-text/typesetting/harfbuzz/glyph.go new file mode 100644 index 0000000..51d57bf --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/glyph.go @@ -0,0 +1,347 @@ +package harfbuzz + +import ( + "fmt" + + "github.com/go-text/typesetting/font/opentype/tables" +) + +// Position stores a position, scaled according to the `Font` +// scale parameters. +type Position = int32 + +// GlyphPosition holds the positions of the +// glyph in both horizontal and vertical directions. +// All positions are relative to the current point. +type GlyphPosition struct { + // How much the line advances after drawing this glyph when setting + // text in horizontal direction. + XAdvance Position + // How much the glyph moves on the X-axis before drawing it, this + // should not affect how much the line advances. + XOffset Position + + // How much the line advances after drawing this glyph when setting + // text in vertical direction. + YAdvance Position + // How much the glyph moves on the Y-axis before drawing it, this + // should not affect how much the line advances. + YOffset Position + + // glyph to which this attaches to, relative to current glyphs; + // negative for going back, positive for forward. + attachChain int16 + attachType uint8 // attachment type, irrelevant if attachChain is 0 +} + +// unicodeProp is a two-byte number. The low byte includes: +// - General_Category: 5 bits +// - A bit each for: +// -> Is it Default_Ignorable(); we have a modified Default_Ignorable(). +// -> Whether it's one of the four Mongolian Free Variation Selectors, +// CGJ, or other characters that are hidden but should not be ignored +// like most other Default_Ignorable()s do during matching. +// -> Whether it's a grapheme continuation. +// +// The high-byte has different meanings, switched by the General_Category: +// - For Mn,Mc,Me: the modified Combining_Class. +// - For Cf: whether it's ZWJ, ZWNJ, or something else. +// - For Ws: index of which space character this is, if space fallback +// is needed, ie. we don't set this by default, only if asked to. +type unicodeProp uint16 + +const ( + upropsMaskIgnorable unicodeProp = 1 << (5 + iota) + upropsMaskHidden // MONGOLIAN FREE VARIATION SELECTOR 1..4, or TAG characters + upropsMaskContinuation + + // if GEN_CAT=FORMAT, top byte masks + upropsMaskCfZwj + upropsMaskCfZwnj + + upropsMaskGenCat unicodeProp = 1<<5 - 1 // 11111 +) + +const isLigBase = 0x10 + +// generalCategory extracts the general category. +func (prop unicodeProp) generalCategory() generalCategory { + return generalCategory(prop & upropsMaskGenCat) +} + +type GlyphMask = uint32 + +const ( + // Indicates that if input text is broken at the beginning of the cluster this glyph is part of, + // then both sides need to be re-shaped, as the result might be different. + // On the flip side, it means that when this flag is not present, + // then it's safe to break the glyph-run at the beginning of this cluster, + // and the two sides represent the exact same result one would get + // if breaking input text at the beginning of this cluster and shaping the two sides + // separately. + // This can be used to optimize paragraph layout, by avoiding re-shaping + // of each line after line-breaking. + GlyphUnsafeToBreak GlyphMask = 1 << iota + + // Indicates that if input text is changed on one side of the beginning of the cluster this glyph + // is part of, then the shaping results for the other side might change. + // Note that the absence of this flag will NOT by itself mean that it IS safe to concat text. + // Only two pieces of text both of which clear of this flag can be concatenated safely. + // This can be used to optimize paragraph layout, by avoiding re-shaping of each line + // after line-breaking, by limiting the reshaping to a small piece around the + // breaking positin only, even if the breaking position carries the + // [GlyphUnsafeToBreak] or when hyphenation or other text transformation + // happens at line-break position, in the following way: + // 1. Iterate back from the line-break position until the first cluster start position that is + // NOT unsafe-to-concat, + // 2. Shape the segment from there till the end of line, + // 3. Check whether the resulting glyph-run also is clear of the unsafe-to-concat at its start-of-text position; + // if it is, just splice it into place and the line is shaped; If not, move on to a position further + // back that is clear of unsafe-to-concat and retry from there, and repeat. + // At the start of next line a similar algorithm can be implemented. That is: + // 1. Iterate forward from the line-break position until the first cluster start position that is NOT unsafe-to-concat, + // 2. Shape the segment from beginning of the line to that position, + // 3. Check whether the resulting glyph-run also is clear of the unsafe-to-concat at its end-of-text position; + // if it is, just splice it into place and the beginning is shaped; If not, move on to a position further forward that is clear + // of unsafe-to-concat and retry up to there, and repeat. + // A slight complication will arise in the implementation of the algorithm above, because while our buffer API has a way to + // return flags for position corresponding to start-of-text, there is currently no position + // corresponding to end-of-text. This limitation can be alleviated by shaping more text than needed + // and looking for unsafe-to-concat flag within text clusters. + // The [GlyphUnsafeToBreak] flag will always imply this flag. + // To use this flag, you must enable the buffer flag [ProduceUnsafeToConcat] during + // shaping, otherwise the buffer flag will not be reliably produced. + GlyphUnsafeToConcat + + // In scripts that use elongation (Arabic, Mongolian, Syriac, etc.), this flag signifies + // that it is safe to insert a U+0640 TATWEEL character before this cluster for elongation. + // This flag does not determine the script-specific elongation places, but only + // when it is safe to do the elongation without interrupting text shaping. + GlyphSafeToInsertTatweel + + // OR of all defined flags + glyphFlagDefined GlyphMask = GlyphUnsafeToBreak | GlyphUnsafeToConcat | GlyphSafeToInsertTatweel +) + +// GlyphInfo holds information about the +// glyphs and their relation to input text. +// They are internally created from user input, +// and the shapping sets the `Glyph` field. +type GlyphInfo struct { + // Cluster is the index of the character in the original text that corresponds + // to this `GlyphInfo`, or whatever the client passes to `Buffer.Add()`. + // More than one glyph can have the same `Cluster` value, + // if they resulted from the same character (e.g. one to many glyph substitution), + // and when more than one character gets merged in the same glyph (e.g. many to one glyph substitution) + // the glyph will have the smallest Cluster value of them. + // By default some characters are merged into the same Cluster + // (e.g. combining marks have the same Cluster as their bases) + // even if they are separate glyphs. + // See Buffer.ClusterLevel for more fine-grained Cluster handling. + Cluster int + + // input value of the shapping + codepoint rune + + // Glyph is the result of the selection of concrete glyph + // after shaping, and refers to the font used. + Glyph GID + + // Mask exposes glyph attributes (see the constants). + // It is also used internally during the shaping. + Mask GlyphMask + + // in C code: var1 + + // GDEF glyph properties + glyphProps uint16 + + // GSUB/GPOS ligature tracking + // When a ligature is formed: + // + // - The ligature glyph and any marks in between all the same newly allocated + // lig_id, + // - The ligature glyph will get lig_num_comps set to the number of components + // - The marks get lig_comp > 0, reflecting which component of the ligature + // they were applied to. + // - This is used in GPOS to attach marks to the right component of a ligature + // in MarkLigPos, + // - Note that when marks are ligated together, much of the above is skipped + // and the current lig_id reused. + // + // When a multiple-substitution is done: + // + // - All resulting glyphs will have lig_id = 0, + // - The resulting glyphs will have lig_comp = 0, 1, 2, ... respectively. + // - This is used in GPOS to attach marks to the first component of a + // multiple substitution in MarkBasePos. + // + // The numbers are also used in GPOS to do mark-to-mark positioning only + // to marks that belong to the same component of the same ligature. + ligProps uint8 + // GSUB/GPOS shaping boundaries + syllable uint8 + + // in C code: var2 + + unicode unicodeProp + + complexCategory, complexAux uint8 // storage interpreted by complex shapers +} + +// String returns a simple description of the glyph of the form Glyph=Cluster(mask) +func (info GlyphInfo) String() string { + return fmt.Sprintf("%d=%d(0x%x)", info.Glyph, info.Cluster, info.Mask&glyphFlagDefined) +} + +func (info *GlyphInfo) setUnicodeProps(buffer *Buffer) { + u := info.codepoint + var flags bufferScratchFlags + info.unicode, flags = computeUnicodeProps(u) + buffer.scratchFlags |= flags +} + +func (info *GlyphInfo) setGeneralCategory(genCat generalCategory) { + /* Clears top-byte. */ + info.unicode = unicodeProp(genCat) | (info.unicode & (0xFF & ^upropsMaskGenCat)) +} + +func (info *GlyphInfo) setCluster(cluster int, mask GlyphMask) { + if info.Cluster != cluster { + info.Mask = (info.Mask & ^glyphFlagDefined) | (mask & glyphFlagDefined) + } + info.Cluster = cluster +} + +func (info *GlyphInfo) setContinuation() { + info.unicode |= upropsMaskContinuation +} + +func (info *GlyphInfo) isContinuation() bool { + return info.unicode&upropsMaskContinuation != 0 +} + +func (info *GlyphInfo) resetContinutation() { info.unicode &= ^upropsMaskContinuation } + +func (info *GlyphInfo) isUnicodeSpace() bool { + return info.unicode.generalCategory() == spaceSeparator +} + +func (info *GlyphInfo) isUnicodeFormat() bool { + return info.unicode.generalCategory() == format +} + +func (info *GlyphInfo) isZwnj() bool { + return info.isUnicodeFormat() && (info.unicode&upropsMaskCfZwnj) != 0 +} + +func (info *GlyphInfo) isZwj() bool { + return info.isUnicodeFormat() && (info.unicode&upropsMaskCfZwj) != 0 +} + +func (info *GlyphInfo) isUnicodeMark() bool { + return (info.unicode & upropsMaskGenCat).generalCategory().isMark() +} + +func (info *GlyphInfo) setUnicodeSpaceFallbackType(s uint8) { + if !info.isUnicodeSpace() { + return + } + info.unicode = unicodeProp(s)<<8 | info.unicode&0xFF +} + +func (info *GlyphInfo) getModifiedCombiningClass() uint8 { + if info.isUnicodeMark() { + return uint8(info.unicode >> 8) + } + return 0 +} + +func (info *GlyphInfo) unhide() { + info.unicode &= ^upropsMaskHidden +} + +func (info *GlyphInfo) setModifiedCombiningClass(modifiedClass uint8) { + if !info.isUnicodeMark() { + return + } + info.unicode = (unicodeProp(modifiedClass) << 8) | (info.unicode & 0xFF) +} + +func (info *GlyphInfo) ligated() bool { + return info.glyphProps&ligated != 0 +} + +func (info *GlyphInfo) getLigID() uint8 { + return info.ligProps >> 5 +} + +func (info *GlyphInfo) ligatedInternal() bool { + return info.ligProps&isLigBase != 0 +} + +func (info *GlyphInfo) getLigComp() uint8 { + if info.ligatedInternal() { + return 0 + } + return info.ligProps & 0x0F +} + +func (info *GlyphInfo) getLigNumComps() uint8 { + if (info.glyphProps&tables.GPLigature) != 0 && info.ligatedInternal() { + return info.ligProps & 0x0F + } + return 1 +} + +func (info *GlyphInfo) setLigPropsForMark(ligID, ligComp uint8) { + info.ligProps = (ligID << 5) | ligComp&0x0F +} + +func (info *GlyphInfo) setLigPropsForLigature(ligID, ligNumComps uint8) { + info.ligProps = (ligID << 5) | isLigBase | ligNumComps&0x0F +} + +func (info *GlyphInfo) isDefaultIgnorable() bool { + return (info.unicode&upropsMaskIgnorable) != 0 && !info.substituted() +} + +func (info *GlyphInfo) isDefaultIgnorableAndNotHidden() bool { + return (info.unicode&(upropsMaskIgnorable|upropsMaskHidden) == upropsMaskIgnorable) && + !info.substituted() +} + +func (info *GlyphInfo) getUnicodeSpaceFallbackType() uint8 { + if info.isUnicodeSpace() { + return uint8(info.unicode >> 8) + } + return notSpace +} + +func (info *GlyphInfo) isMark() bool { + return info.glyphProps&tables.GPMark != 0 +} + +func (info *GlyphInfo) isBaseGlyph() bool { + return info.glyphProps&tables.GPBaseGlyph != 0 +} + +func (info *GlyphInfo) isLigature() bool { + return info.glyphProps&tables.GPLigature != 0 +} + +func (info *GlyphInfo) multiplied() bool { + return info.glyphProps&multiplied != 0 +} + +func (info *GlyphInfo) clearLigatedAndMultiplied() { + info.glyphProps &= ^(ligated | multiplied) +} + +func (info *GlyphInfo) ligatedAndDidntMultiply() bool { + return info.ligated() && !info.multiplied() +} + +func (info *GlyphInfo) substituted() bool { + return info.glyphProps&substituted != 0 +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/harfbuzz.go b/vendor/github.com/go-text/typesetting/harfbuzz/harfbuzz.go new file mode 100644 index 0000000..ee85859 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/harfbuzz.go @@ -0,0 +1,501 @@ +// Package harfbuzz provides advanced text layout for various scripts and languages, +// with font-aware substitutions and positionning. +// +// Given a font and an input specified as runes, the package shapes this input +// and returns a slice of positionned glyphs, identified by their index in the font. +// See `Buffer` and its methods for more details. +// +// This package is a direct port of the C/C++ library. +package harfbuzz + +import ( + "errors" + "fmt" + "math" + "math/bits" + "strconv" + + "github.com/go-text/typesetting/font" + ot "github.com/go-text/typesetting/font/opentype" + "github.com/go-text/typesetting/font/opentype/tables" + "github.com/go-text/typesetting/language" +) + +// based on upstream commit 5d543d64222c6ce45332d0c188790f90691ef112 + +// debugMode is only used in test: if true, it prints detailed information +// about shaping +const debugMode = false + +type ( + GID = ot.GID + gID = tables.GlyphID +) + +// Direction is the text direction. +// The zero value is the initial, unset, invalid direction. +type Direction uint8 + +const ( + LeftToRight Direction = 4 + iota // Text is set horizontally from left to right. + RightToLeft // Text is set horizontally from right to left. + TopToBottom // Text is set vertically from top to bottom. + BottomToTop // Text is set vertically from bottom to top. +) + +// Fetches the `Direction` of a script when it is +// set horizontally. All right-to-left scripts will return +// `RightToLeft`. All left-to-right scripts will return +// `LeftToRight`. Scripts that can be written either +// horizontally or vertically will return `Invalid`. +// Unknown scripts will return `LeftToRight`. +func getHorizontalDirection(script language.Script) Direction { + /* https://docs.google.com/spreadsheets/d/1Y90M0Ie3MUJ6UVCRDOypOtijlMDLNNyyLk36T6iMu0o */ + switch script { + case language.Arabic, language.Hebrew, language.Syriac, language.Thaana, + language.Cypriot, language.Kharoshthi, language.Phoenician, language.Nko, language.Lydian, + language.Avestan, language.Imperial_Aramaic, language.Inscriptional_Pahlavi, language.Inscriptional_Parthian, language.Old_South_Arabian, language.Old_Turkic, + language.Samaritan, language.Mandaic, language.Meroitic_Cursive, language.Meroitic_Hieroglyphs, language.Manichaean, language.Mende_Kikakui, + language.Nabataean, language.Old_North_Arabian, language.Palmyrene, language.Psalter_Pahlavi, language.Hatran, language.Adlam, language.Hanifi_Rohingya, + language.Old_Sogdian, language.Sogdian, language.Elymaic, language.Chorasmian, language.Yezidi: + + return RightToLeft + + /* https://github.com/harfbuzz/harfbuzz/issues/1000 */ + case language.Old_Hungarian, language.Old_Italic, language.Runic, language.Tifinagh: + return 0 + } + + return LeftToRight +} + +// Tests whether a text direction is horizontal. Requires +// that the direction be valid. +func (dir Direction) isHorizontal() bool { return dir & ^Direction(1) == 4 } + +// Tests whether a text direction is vertical. Requires +// that the direction be valid. +func (dir Direction) isVertical() bool { return dir & ^Direction(1) == 6 } + +// Tests whether a text direction moves backward (from right to left, or from +// bottom to top). Requires that the direction be valid. +func (dir Direction) isBackward() bool { return dir & ^Direction(2) == 5 } + +// Tests whether a text direction moves forward (from left to right, or from +// top to bottom). Requires that the direction be valid. +func (dir Direction) isForward() bool { return dir & ^Direction(2) == 4 } + +// Reverses a text direction. Requires that the direction +// is valid. +func (dir Direction) Reverse() Direction { + return dir ^ 1 +} + +// SegmentProperties holds various text properties of a `Buffer`. +type SegmentProperties struct { + // Languages are crucial for selecting which OpenType feature to apply to the + // buffer which can result in applying language-specific behaviour. Languages + // are orthogonal to the scripts, and though they are related, they are + // different concepts and should not be confused with each other. + Language language.Language + + // Script is crucial for choosing the proper shaping behaviour for scripts that + // require it (e.g. Arabic) and the OpenType features defined in the font + // to be applied. + // + // See the package language for predefined values. + Script language.Script + + // Direction is the text flow direction of the buffer. No shaping can happen without + // setting direction, and it controls the visual direction for the + // output glyphs; for RTL direction the glyphs will be reversed. Many layout + // features depend on the proper setting of the direction, for example, + // reversing RTL text before shaping, then shaping with LTR direction is not + // the same as keeping the text in logical order and shaping with RTL + // direction. + Direction Direction +} + +// ShappingOptions controls some fine tunning of the shaping +// (see the constants). +type ShappingOptions uint16 + +const ( + // Flag indicating that special handling of the beginning + // of text paragraph can be applied to this buffer. Should usually + // be set, unless you are passing to the buffer only part + // of the text without the full context. + Bot ShappingOptions = 1 << iota + // Flag indicating that special handling of the end of text + // paragraph can be applied to this buffer, similar to + // `Bot`. + Eot + // Flag indication that character with Default_Ignorable + // Unicode property should use the corresponding glyph + // from the font, instead of hiding them (done by + // replacing them with the space glyph and zeroing the + // advance width.) This flag takes precedence over + // `RemoveDefaultIgnorables`. + PreserveDefaultIgnorables + // Flag indication that character with Default_Ignorable + // Unicode property should be removed from glyph string + // instead of hiding them (done by replacing them with the + // space glyph and zeroing the advance width.) + // `PreserveDefaultIgnorables` takes + // precedence over this flag. + RemoveDefaultIgnorables + // Flag indicating that a dotted circle should + // not be inserted in the rendering of incorrect + // character sequences (such at <0905 093E>). + DoNotinsertDottedCircle + + // Flag indicating that the [GlyphUnsafeToConcat] + // glyph-flag should be produced by the shaper. By default + // it will not be produced since it incurs a cost. + ProduceUnsafeToConcat + + // Flag indicating that the [GlyphSafeToInsertTatweel] + // glyph-flag should be produced by the shaper. By default + // it will not be produced. + ProduceSafeToInsertTatweel +) + +// ClusterLevel allows selecting more fine-grained Cluster handling. +// It defaults to `MonotoneGraphemes`. +type ClusterLevel uint8 + +const ( + // Return cluster values grouped by graphemes into monotone order. + MonotoneGraphemes ClusterLevel = iota + // Return cluster values grouped into monotone order. + MonotoneCharacters + // Don't group cluster values. + Characters +) + +func (cl ClusterLevel) String() string { + switch cl { + case MonotoneCharacters: + return "MonotoneCharacters" + case MonotoneGraphemes: + return "MonotoneGraphemes" + case Characters: + return "Characters" + default: + return fmt.Sprintf("", cl) + } +} + +// Feature holds information about requested +// feature application. The feature will be applied with the given value to all +// glyphs which are in clusters between `start` (inclusive) and `end` (exclusive). +// Setting start to `FeatureGlobalStart` and end to `FeatureGlobalEnd` +// specifies that the feature always applies to the entire buffer. +type Feature struct { + Tag ot.Tag + // Value of the feature: 0 disables the feature, non-zero (usually + // 1) enables the feature. For features implemented as lookup type 3 (like + // 'salt') `Value` is a one-based index into the alternates. + Value uint32 + // The cluster to Start applying this feature setting (inclusive) + Start int + // The cluster to End applying this feature setting (exclusive) + End int +} + +const ( + // Special setting for `Feature.Start` to apply the feature from the start + // of the buffer. + FeatureGlobalStart = 0 + // Special setting for `Feature.End` to apply the feature from to the end + // of the buffer. + FeatureGlobalEnd = maxInt +) + +// ParseVariation parse the string representation of a variation +// of the form tag=value +func ParseVariation(s string) (font.Variation, error) { + pr := parser{data: []byte(s)} + return pr.parseOneVariation() +} + +type parser struct { + data []byte + pos int +} + +func isSpace(c byte) bool { + return c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v' +} + +func (p *parser) skipSpaces() { + for p.pos < len(p.data) && isSpace(p.data[p.pos]) { + p.pos++ + } +} + +// return true if `c` was found +func (p *parser) parseChar(c byte) bool { + p.skipSpaces() + + if p.pos == len(p.data) || p.data[p.pos] != c { + return false + } + p.pos++ + return true +} + +func (p *parser) parseUint32() (uint32, bool) { + start := p.pos + // go to the next space + for p.pos < len(p.data) && isAlnum(p.data[p.pos]) { + p.pos++ + } + out, err := strconv.Atoi(string(p.data[start:p.pos])) + return uint32(out), err == nil +} + +func (p *parser) parseBool() (uint32, bool) { + p.skipSpaces() + + startPos := p.pos + for p.pos < len(p.data) && isAlpha(p.data[p.pos]) { + p.pos++ + } + data := string(p.data[startPos:p.pos]) + + /* CSS allows on/off as aliases 1/0. */ + if data == "on" { + return 1, true + } else if data == "off" { + return 0, true + } else { + return 0, false + } +} + +func (p *parser) parseTag() (ot.Tag, error) { + p.skipSpaces() + + var quote byte + + if p.pos < len(p.data) && (p.data[p.pos] == '\'' || p.data[p.pos] == '"') { + quote = p.data[p.pos] + p.pos++ + } + + start := p.pos + for p.pos < len(p.data) && (isAlnum(p.data[p.pos]) || p.data[p.pos] == '_') { + p.pos++ + } + + if p.pos == start || p.pos > start+4 { + return 0, errors.New("invalid tag length") + } + + // padd with space if necessary, since MustNewTag requires 4 bytes + tagBytes := [4]byte{' ', ' ', ' ', ' '} + copy(tagBytes[:], p.data[start:p.pos]) + tag := ot.MustNewTag(string(tagBytes[:])) + + if quote != 0 { + /* CSS expects exactly four bytes. And we only allow quotations for + * CSS compatibility. So, enforce the length. */ + if p.pos != start+4 { + return 0, errors.New("tag must have 4 bytes") + } + if p.pos == len(p.data) || p.data[p.pos] != quote { + return 0, errors.New("tag is missing end quote") + } + p.pos++ + } + + return tag, nil +} + +func (p *parser) parseVariationValue() (float32, error) { + p.parseChar('=') // Optional. + start := p.pos + // go to the next space + for p.pos < len(p.data) && !isSpace(p.data[p.pos]) { + p.pos++ + } + v, err := strconv.ParseFloat(string(p.data[start:p.pos]), 32) + return float32(v), err +} + +func (p *parser) parseOneVariation() (vari font.Variation, err error) { + vari.Tag, err = p.parseTag() + if err != nil { + return + } + vari.Value, err = p.parseVariationValue() + if err != nil { + return + } + p.skipSpaces() + return +} + +func (p *parser) parseFeatureIndices() (start, end int, err error) { + p.skipSpaces() + + start, end = FeatureGlobalStart, FeatureGlobalEnd + + if !p.parseChar('[') { + return start, end, nil + } + + startU, hasStart := p.parseUint32() + start = int(startU) + + if p.parseChar(':') || p.parseChar(';') { + if endU, ok := p.parseUint32(); ok { + end = int(endU) + } + } else { + if hasStart { + end = start + 1 + } + } + + if !p.parseChar(']') { + return 0, 0, errors.New("expecting closing bracked after feature indices") + } + + return start, end, nil +} + +// return true if a value was specified +func (p *parser) parseFeatureValuePostfix() (uint32, bool) { + /* CSS doesn't use equal-sign between tag and value. + * If there was an equal-sign, then there *must* be a value. + * A value without an equal-sign is ok, but not required. */ + p.parseChar('=') + + val, hadValue := p.parseUint32() + if !hadValue { + val, hadValue = p.parseBool() + } + return val, hadValue +} + +func (p *parser) parseFeatureValuePrefix() uint32 { + if p.parseChar('-') { + return 0 + } else { + _ = p.parseChar('+') + return 1 + } +} + +func (p *parser) parseOneFeature() (feature Feature, err error) { + feature.Value = p.parseFeatureValuePrefix() + feature.Tag, err = p.parseTag() + if err != nil { + return feature, err + } + feature.Start, feature.End, err = p.parseFeatureIndices() + if err != nil { + return feature, err + } + if val, ok := p.parseFeatureValuePostfix(); ok { + feature.Value = val + } + p.skipSpaces() + return feature, nil +} + +// ParseFeature parses one feature string (usually coming from a comma-separated list of font features). +// +// Features can be enabled or disabled, either globally or limited to +// specific character ranges. The format for specifying feature settings +// follows. All valid CSS font-feature-settings values other than 'normal' +// and the global values are also accepted, though not documented below. +// CSS string escapes are not supported. +// +// The range indices refer to the positions between Unicode characters, +// unless the --utf8-clusters is provided, in which case range indices +// refer to UTF-8 byte indices. The position before the first character +// is always 0. +// +// The format is Python-esque. Here is how it all works: +// +// Syntax: Value: Start: End: +// +// Setting value: +// "kern" 1 0 ∞ // Turn feature on +// "+kern" 1 0 ∞ // Turn feature on +// "-kern" 0 0 ∞ // Turn feature off +// "kern=0" 0 0 ∞ // Turn feature off +// "kern=1" 1 0 ∞ // Turn feature on +// "aalt=2" 2 0 ∞ // Choose 2nd alternate +// +// Setting index: +// "kern[]" 1 0 ∞ // Turn feature on +// "kern[:]" 1 0 ∞ // Turn feature on +// "kern[5:]" 1 5 ∞ // Turn feature on, partial +// "kern[:5]" 1 0 5 // Turn feature on, partial +// "kern[3:5]" 1 3 5 // Turn feature on, range +// "kern[3]" 1 3 3+1 // Turn feature on, single char +// +// Mixing it all: +// +// "aalt[3:5]=2" 2 3 5 // Turn 2nd alternate on for range +func ParseFeature(feature string) (Feature, error) { + pr := parser{data: []byte(feature)} + return pr.parseOneFeature() +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} + +func min8(a, b uint8) uint8 { + if a < b { + return a + } + return b +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func max32(a, b uint32) uint32 { + if a > b { + return a + } + return b +} + +func isAlpha(c byte) bool { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') } +func isAlnum(c byte) bool { return isAlpha(c) || (c >= '0' && c <= '9') } +func toUpper(c byte) byte { + if c >= 'a' && c <= 'z' { + return c - 'a' + 'A' + } + return c +} + +func toLower(c byte) byte { + if c >= 'A' && c <= 'Z' { + return c - 'A' + 'a' + } + return c +} + +const maxInt = int(^uint(0) >> 1) + +// bitStorage returns the number of bits needed to store the number. +func bitStorage(v uint32) int { return 32 - bits.LeadingZeros32(v) } + +func roundf(f float32) Position { + return Position(math.Round(float64(f))) +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_aat_layout.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_aat_layout.go new file mode 100644 index 0000000..1623d43 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_aat_layout.go @@ -0,0 +1,1696 @@ +package harfbuzz + +import ( + "fmt" + + "github.com/go-text/typesetting/font" + ot "github.com/go-text/typesetting/font/opentype" + "github.com/go-text/typesetting/font/opentype/tables" +) + +// ported from harfbuzz/src/hb-aat-layout.h Copyright © 2018 Ebrahim Byagowi, Behdad Esfahbod + +// The possible feature types defined for AAT shaping, +// from https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html +type aatLayoutFeatureType = uint16 + +const ( + // Initial, unset feature type + // aatLayoutFeatureTypeInvalid = 0xFFFF + // [All Typographic Features](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type0) + // aatLayoutFeatureTypeAllTypographic = 0 + // [Ligatures](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type1) + aatLayoutFeatureTypeLigatures = 1 + // [Cursive Connection](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type2) + // aatLayoutFeatureTypeCurisveConnection = 2 + // [Letter Case](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type3) + aatLayoutFeatureTypeLetterCase = 3 + // [Vertical Substitution](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type4) + aatLayoutFeatureTypeVerticalSubstitution = 4 + // [Linguistic Rearrangement](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type5) + // aatLayoutFeatureTypeLinguisticRearrangement = 5 + // [Number Spacing](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type6) + aatLayoutFeatureTypeNumberSpacing = 6 + // [Smart Swash](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type8) + // aatLayoutFeatureTypeSmartSwashType = 8 + // [Diacritics](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type9) + // aatLayoutFeatureTypeDiacriticsType = 9 + // [Vertical Position](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type10) + aatLayoutFeatureTypeVerticalPosition = 10 + // [Fractions](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type11) + aatLayoutFeatureTypeFractions = 11 + // [Overlapping Characters](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type13) + // aatLayoutFeatureTypeOverlappingCharactersType = 13 + // [Typographic Extras](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type14) + aatLayoutFeatureTypeTypographicExtras = 14 + // [Mathematical Extras](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type15) + aatLayoutFeatureTypeMathematicalExtras = 15 + // [Ornament Sets](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type16) + // aatLayoutFeatureTypeOrnamentSetsType = 16 + // [Character Alternatives](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type17) + aatLayoutFeatureTypeCharacterAlternatives = 17 + // [Style Options](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type19) + aatLayoutFeatureTypeStyleOptions = 19 + // [Character Shape](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type20) + aatLayoutFeatureTypeCharacterShape = 20 + // [Number Case](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type21) + aatLayoutFeatureTypeNumberCase = 21 + // [Text Spacing](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type22) + aatLayoutFeatureTypeTextSpacing = 22 + // [Transliteration](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type23) + aatLayoutFeatureTypeTransliteration = 23 + + // [Ruby Kana](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type28) + aatLayoutFeatureTypeRubyKana = 28 + + // [Italic CJK Roman](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type32) + aatLayoutFeatureTypeItalicCjkRoman = 32 + // [Case Sensitive Layout](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type33) + aatLayoutFeatureTypeCaseSensitiveLayout = 33 + // [Alternate Kana](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type34) + aatLayoutFeatureTypeAlternateKana = 34 + // [Stylistic Alternatives](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type35) + aatLayoutFeatureTypeStylisticAlternatives = 35 + // [Contextual Alternatives](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type36) + aatLayoutFeatureTypeContextualAlternatives = 36 + // [Lower Case](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type37) + aatLayoutFeatureTypeLowerCase = 37 + // [Upper Case](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type38) + aatLayoutFeatureTypeUpperCase = 38 + // [Language Tag](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html#Type39) + aatLayoutFeatureTypeLanguageTagType = 39 +) + +// The selectors defined for specifying AAT feature settings. +type aatLayoutFeatureSelector = uint16 + +const ( + /* Selectors for #aatLayoutFeatureTypeLigatures */ + // for #aatLayoutFeatureTypeLigatures + aatLayoutFeatureSelectorRequiredLigaturesOn = 0 + // for #aatLayoutFeatureTypeLigatures + aatLayoutFeatureSelectorRequiredLigaturesOff = 1 + // for #aatLayoutFeatureTypeLigatures + aatLayoutFeatureSelectorCommonLigaturesOn = 2 + // for #aatLayoutFeatureTypeLigatures + aatLayoutFeatureSelectorCommonLigaturesOff = 3 + // for #aatLayoutFeatureTypeLigatures + aatLayoutFeatureSelectorRareLigaturesOn = 4 + // for #aatLayoutFeatureTypeLigatures + aatLayoutFeatureSelectorRareLigaturesOff = 5 + + // for #aatLayoutFeatureTypeLigatures + aatLayoutFeatureSelectorContextualLigaturesOn = 18 + // for #aatLayoutFeatureTypeLigatures + aatLayoutFeatureSelectorContextualLigaturesOff = 19 + // for #aatLayoutFeatureTypeLigatures + aatLayoutFeatureSelectorHistoricalLigaturesOn = 20 + // for #aatLayoutFeatureTypeLigatures + aatLayoutFeatureSelectorHistoricalLigaturesOff = 21 + + /* Selectors for #aatLayoutFeatureTypeLetterCase */ + + // Deprecated + aatLayoutFeatureSelectorSmallCaps = 3 /* deprecated */ + + /* Selectors for #aatLayoutFeatureTypeVerticalSubstitution */ + // for #aatLayoutFeatureTypeVerticalSubstitution + aatLayoutFeatureSelectorSubstituteVerticalFormsOn = 0 + // for #aatLayoutFeatureTypeVerticalSubstitution + aatLayoutFeatureSelectorSubstituteVerticalFormsOff = 1 + + /* Selectors for #aatLayoutFeatureTypeNumberSpacing */ + // for #aatLayoutFeatureTypeNumberSpacing + aatLayoutFeatureSelectorMonospacedNumbers = 0 + // for #aatLayoutFeatureTypeNumberSpacing + aatLayoutFeatureSelectorProportionalNumbers = 1 + + /* Selectors for #aatLayoutFeatureTypeVerticalPosition */ + // for #aatLayoutFeatureTypeVerticalPosition + aatLayoutFeatureSelectorNormalPosition = 0 + // for #aatLayoutFeatureTypeVerticalPosition + aatLayoutFeatureSelectorSuperiors = 1 + // for #aatLayoutFeatureTypeVerticalPosition + aatLayoutFeatureSelectorInferiors = 2 + // for #aatLayoutFeatureTypeVerticalPosition + aatLayoutFeatureSelectorOrdinals = 3 + // for #aatLayoutFeatureTypeVerticalPosition + aatLayoutFeatureSelectorScientificInferiors = 4 + + /* Selectors for #aatLayoutFeatureTypeFractions */ + // for #aatLayoutFeatureTypeFractions + aatLayoutFeatureSelectorNoFractions = 0 + // for #aatLayoutFeatureTypeFractions + aatLayoutFeatureSelectorVerticalFractions = 1 + // for #aatLayoutFeatureTypeFractions + aatLayoutFeatureSelectorDiagonalFractions = 2 + + // for #aatLayoutFeatureTypeTypographicExtras + aatLayoutFeatureSelectorSlashedZeroOn = 4 + // for #aatLayoutFeatureTypeTypographicExtras + aatLayoutFeatureSelectorSlashedZeroOff = 5 + + /* Selectors for #aatLayoutFeatureTypeMathematicalExtras */ + // for #aatLayoutFeatureTypeMathematicalExtras + aatLayoutFeatureSelectorMathematicalGreekOn = 10 + // for #aatLayoutFeatureTypeMathematicalExtras + aatLayoutFeatureSelectorMathematicalGreekOff = 11 + + /* Selectors for #aatLayoutFeatureTypeStyleOptions */ + // for #aatLayoutFeatureTypeStyleOptions + aatLayoutFeatureSelectorNoStyleOptions = 0 + + // for #aatLayoutFeatureTypeStyleOptions + aatLayoutFeatureSelectorTitlingCaps = 4 + + /* Selectors for #aatLayoutFeatureTypeCharacterShape */ + // for #aatLayoutFeatureTypeCharacterShape + aatLayoutFeatureSelectorTraditionalCharacters = 0 + // for #aatLayoutFeatureTypeCharacterShape + aatLayoutFeatureSelectorSimplifiedCharacters = 1 + // for #aatLayoutFeatureTypeCharacterShape + aatLayoutFeatureSelectorJis1978Characters = 2 + // for #aatLayoutFeatureTypeCharacterShape + aatLayoutFeatureSelectorJis1983Characters = 3 + // for #aatLayoutFeatureTypeCharacterShape + aatLayoutFeatureSelectorJis1990Characters = 4 + + // for #aatLayoutFeatureTypeCharacterShape + aatLayoutFeatureSelectorExpertCharacters = 10 + // for #aatLayoutFeatureTypeCharacterShape + aatLayoutFeatureSelectorJis2004Characters = 11 + // for #aatLayoutFeatureTypeCharacterShape + aatLayoutFeatureSelectorHojoCharacters = 12 + // for #aatLayoutFeatureTypeCharacterShape + aatLayoutFeatureSelectorNlccharacters = 13 + // for #aatLayoutFeatureTypeCharacterShape + aatLayoutFeatureSelectorTraditionalNamesCharacters = 14 + + /* Selectors for #aatLayoutFeatureTypeNumberCase */ + // for #aatLayoutFeatureTypeNumberCase + aatLayoutFeatureSelectorLowerCaseNumbers = 0 + // for #aatLayoutFeatureTypeNumberCase + aatLayoutFeatureSelectorUpperCaseNumbers = 1 + + /* Selectors for #aatLayoutFeatureTypeTextSpacing */ + // for #aatLayoutFeatureTypeTextSpacing + aatLayoutFeatureSelectorProportionalText = 0 + // for #aatLayoutFeatureTypeTextSpacing + aatLayoutFeatureSelectorMonospacedText = 1 + // for #aatLayoutFeatureTypeTextSpacing + aatLayoutFeatureSelectorHalfWidthText = 2 + // for #aatLayoutFeatureTypeTextSpacing + aatLayoutFeatureSelectorThirdWidthText = 3 + // for #aatLayoutFeatureTypeTextSpacing + aatLayoutFeatureSelectorQuarterWidthText = 4 + // for #aatLayoutFeatureTypeTextSpacing + aatLayoutFeatureSelectorAltProportionalText = 5 + // for #aatLayoutFeatureTypeTextSpacing + aatLayoutFeatureSelectorAltHalfWidthText = 6 + + /* Selectors for #aatLayoutFeatureTypeTransliteration */ + // for #aatLayoutFeatureTypeTransliteration + aatLayoutFeatureSelectorNoTransliteration = 0 + // for #aatLayoutFeatureTypeTransliteration + aatLayoutFeatureSelectorHanjaToHangul = 1 + + /* Selectors for #aatLayoutFeatureTypeRubyKana */ + // for #aatLayoutFeatureTypeRubyKana + aatLayoutFeatureSelectorRubyKanaOn = 2 + // for #aatLayoutFeatureTypeRubyKana + aatLayoutFeatureSelectorRubyKanaOff = 3 + + /* Selectors for #aatLayoutFeatureTypeItalicCjkRoman */ + // for #aatLayoutFeatureTypeItalicCjkRoman + aatLayoutFeatureSelectorCjkItalicRomanOn = 2 + // for #aatLayoutFeatureTypeItalicCjkRoman + aatLayoutFeatureSelectorCjkItalicRomanOff = 3 + + /* Selectors for #aatLayoutFeatureTypeCaseSensitiveLayout */ + // for #aatLayoutFeatureTypeCaseSensitiveLayout + aatLayoutFeatureSelectorCaseSensitiveLayoutOn = 0 + // for #aatLayoutFeatureTypeCaseSensitiveLayout + aatLayoutFeatureSelectorCaseSensitiveLayoutOff = 1 + // for #aatLayoutFeatureTypeCaseSensitiveLayout + aatLayoutFeatureSelectorCaseSensitiveSpacingOn = 2 + // for #aatLayoutFeatureTypeCaseSensitiveLayout + aatLayoutFeatureSelectorCaseSensitiveSpacingOff = 3 + + /* Selectors for #aatLayoutFeatureTypeAlternateKana */ + // for #aatLayoutFeatureTypeAlternateKana + aatLayoutFeatureSelectorAlternateHorizKanaOn = 0 + // for #aatLayoutFeatureTypeAlternateKana + aatLayoutFeatureSelectorAlternateHorizKanaOff = 1 + // for #aatLayoutFeatureTypeAlternateKana + aatLayoutFeatureSelectorAlternateVertKanaOn = 2 + // for #aatLayoutFeatureTypeAlternateKana + aatLayoutFeatureSelectorAlternateVertKanaOff = 3 + + /* Selectors for #aatLayoutFeatureTypeStylisticAlternatives */ + + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltOneOn = 2 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltOneOff = 3 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltTwoOn = 4 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltTwoOff = 5 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltThreeOn = 6 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltThreeOff = 7 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltFourOn = 8 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltFourOff = 9 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltFiveOn = 10 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltFiveOff = 11 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltSixOn = 12 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltSixOff = 13 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltSevenOn = 14 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltSevenOff = 15 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltEightOn = 16 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltEightOff = 17 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltNineOn = 18 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltNineOff = 19 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltTenOn = 20 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltTenOff = 21 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltElevenOn = 22 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltElevenOff = 23 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltTwelveOn = 24 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltTwelveOff = 25 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltThirteenOn = 26 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltThirteenOff = 27 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltFourteenOn = 28 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltFourteenOff = 29 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltFifteenOn = 30 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltFifteenOff = 31 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltSixteenOn = 32 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltSixteenOff = 33 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltSeventeenOn = 34 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltSeventeenOff = 35 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltEighteenOn = 36 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltEighteenOff = 37 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltNineteenOn = 38 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltNineteenOff = 39 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltTwentyOn = 40 + // for #aatLayoutFeatureTypeStylisticAlternatives + aatLayoutFeatureSelectorStylisticAltTwentyOff = 41 + + /* Selectors for #aatLayoutFeatureTypeContextualAlternatives */ + // for #aatLayoutFeatureTypeContextualAlternatives + aatLayoutFeatureSelectorContextualAlternatesOn = 0 + // for #aatLayoutFeatureTypeContextualAlternatives + aatLayoutFeatureSelectorContextualAlternatesOff = 1 + // for #aatLayoutFeatureTypeContextualAlternatives + aatLayoutFeatureSelectorSwashAlternatesOn = 2 + // for #aatLayoutFeatureTypeContextualAlternatives + aatLayoutFeatureSelectorSwashAlternatesOff = 3 + // for #aatLayoutFeatureTypeContextualAlternatives + aatLayoutFeatureSelectorContextualSwashAlternatesOn = 4 + // for #aatLayoutFeatureTypeContextualAlternatives + aatLayoutFeatureSelectorContextualSwashAlternatesOff = 5 + + /* Selectors for #aatLayoutFeatureTypeLowerCase */ + // for #aatLayoutFeatureTypeLowerCase + aatLayoutFeatureSelectorDefaultLowerCase = 0 + // for #aatLayoutFeatureTypeLowerCase + aatLayoutFeatureSelectorLowerCaseSmallCaps = 1 + // for #aatLayoutFeatureTypeLowerCase + aatLayoutFeatureSelectorLowerCasePetiteCaps = 2 + + /* Selectors for #aatLayoutFeatureTypeUpperCase */ + // for #aatLayoutFeatureTypeUpperCase + aatLayoutFeatureSelectorDefaultUpperCase = 0 + // for #aatLayoutFeatureTypeUpperCase + aatLayoutFeatureSelectorUpperCaseSmallCaps = 1 + // for #aatLayoutFeatureTypeUpperCase + aatLayoutFeatureSelectorUpperCasePetiteCaps = 2 +) + +// Mapping from OpenType feature tags to AAT feature names and selectors. +// +// Table data courtesy of Apple. Converted from mnemonics to integers +// when moving to this file. +var featureMappings = [...]aatFeatureMapping{ + {ot.NewTag('a', 'f', 'r', 'c'), aatLayoutFeatureTypeFractions, aatLayoutFeatureSelectorVerticalFractions, aatLayoutFeatureSelectorNoFractions}, + {ot.NewTag('c', '2', 'p', 'c'), aatLayoutFeatureTypeUpperCase, aatLayoutFeatureSelectorUpperCasePetiteCaps, aatLayoutFeatureSelectorDefaultUpperCase}, + {ot.NewTag('c', '2', 's', 'c'), aatLayoutFeatureTypeUpperCase, aatLayoutFeatureSelectorUpperCaseSmallCaps, aatLayoutFeatureSelectorDefaultUpperCase}, + {ot.NewTag('c', 'a', 'l', 't'), aatLayoutFeatureTypeContextualAlternatives, aatLayoutFeatureSelectorContextualAlternatesOn, aatLayoutFeatureSelectorContextualAlternatesOff}, + {ot.NewTag('c', 'a', 's', 'e'), aatLayoutFeatureTypeCaseSensitiveLayout, aatLayoutFeatureSelectorCaseSensitiveLayoutOn, aatLayoutFeatureSelectorCaseSensitiveLayoutOff}, + {ot.NewTag('c', 'l', 'i', 'g'), aatLayoutFeatureTypeLigatures, aatLayoutFeatureSelectorContextualLigaturesOn, aatLayoutFeatureSelectorContextualLigaturesOff}, + {ot.NewTag('c', 'p', 's', 'p'), aatLayoutFeatureTypeCaseSensitiveLayout, aatLayoutFeatureSelectorCaseSensitiveSpacingOn, aatLayoutFeatureSelectorCaseSensitiveSpacingOff}, + {ot.NewTag('c', 's', 'w', 'h'), aatLayoutFeatureTypeContextualAlternatives, aatLayoutFeatureSelectorContextualSwashAlternatesOn, aatLayoutFeatureSelectorContextualSwashAlternatesOff}, + {ot.NewTag('d', 'l', 'i', 'g'), aatLayoutFeatureTypeLigatures, aatLayoutFeatureSelectorRareLigaturesOn, aatLayoutFeatureSelectorRareLigaturesOff}, + {ot.NewTag('e', 'x', 'p', 't'), aatLayoutFeatureTypeCharacterShape, aatLayoutFeatureSelectorExpertCharacters, 16}, + {ot.NewTag('f', 'r', 'a', 'c'), aatLayoutFeatureTypeFractions, aatLayoutFeatureSelectorDiagonalFractions, aatLayoutFeatureSelectorNoFractions}, + {ot.NewTag('f', 'w', 'i', 'd'), aatLayoutFeatureTypeTextSpacing, aatLayoutFeatureSelectorMonospacedText, 7}, + {ot.NewTag('h', 'a', 'l', 't'), aatLayoutFeatureTypeTextSpacing, aatLayoutFeatureSelectorAltHalfWidthText, 7}, + {ot.NewTag('h', 'i', 's', 't'), 40, 0, 1}, + {ot.NewTag('h', 'k', 'n', 'a'), aatLayoutFeatureTypeAlternateKana, aatLayoutFeatureSelectorAlternateHorizKanaOn, aatLayoutFeatureSelectorAlternateHorizKanaOff}, + {ot.NewTag('h', 'l', 'i', 'g'), aatLayoutFeatureTypeLigatures, aatLayoutFeatureSelectorHistoricalLigaturesOn, aatLayoutFeatureSelectorHistoricalLigaturesOff}, + {ot.NewTag('h', 'n', 'g', 'l'), aatLayoutFeatureTypeTransliteration, aatLayoutFeatureSelectorHanjaToHangul, aatLayoutFeatureSelectorNoTransliteration}, + {ot.NewTag('h', 'o', 'j', 'o'), aatLayoutFeatureTypeCharacterShape, aatLayoutFeatureSelectorHojoCharacters, 16}, + {ot.NewTag('h', 'w', 'i', 'd'), aatLayoutFeatureTypeTextSpacing, aatLayoutFeatureSelectorHalfWidthText, 7}, + {ot.NewTag('i', 't', 'a', 'l'), aatLayoutFeatureTypeItalicCjkRoman, aatLayoutFeatureSelectorCjkItalicRomanOn, aatLayoutFeatureSelectorCjkItalicRomanOff}, + {ot.NewTag('j', 'p', '0', '4'), aatLayoutFeatureTypeCharacterShape, aatLayoutFeatureSelectorJis2004Characters, 16}, + {ot.NewTag('j', 'p', '7', '8'), aatLayoutFeatureTypeCharacterShape, aatLayoutFeatureSelectorJis1978Characters, 16}, + {ot.NewTag('j', 'p', '8', '3'), aatLayoutFeatureTypeCharacterShape, aatLayoutFeatureSelectorJis1983Characters, 16}, + {ot.NewTag('j', 'p', '9', '0'), aatLayoutFeatureTypeCharacterShape, aatLayoutFeatureSelectorJis1990Characters, 16}, + {ot.NewTag('l', 'i', 'g', 'a'), aatLayoutFeatureTypeLigatures, aatLayoutFeatureSelectorCommonLigaturesOn, aatLayoutFeatureSelectorCommonLigaturesOff}, + {ot.NewTag('l', 'n', 'u', 'm'), aatLayoutFeatureTypeNumberCase, aatLayoutFeatureSelectorUpperCaseNumbers, 2}, + {ot.NewTag('m', 'g', 'r', 'k'), aatLayoutFeatureTypeMathematicalExtras, aatLayoutFeatureSelectorMathematicalGreekOn, aatLayoutFeatureSelectorMathematicalGreekOff}, + {ot.NewTag('n', 'l', 'c', 'k'), aatLayoutFeatureTypeCharacterShape, aatLayoutFeatureSelectorNlccharacters, 16}, + {ot.NewTag('o', 'n', 'u', 'm'), aatLayoutFeatureTypeNumberCase, aatLayoutFeatureSelectorLowerCaseNumbers, 2}, + {ot.NewTag('o', 'r', 'd', 'n'), aatLayoutFeatureTypeVerticalPosition, aatLayoutFeatureSelectorOrdinals, aatLayoutFeatureSelectorNormalPosition}, + {ot.NewTag('p', 'a', 'l', 't'), aatLayoutFeatureTypeTextSpacing, aatLayoutFeatureSelectorAltProportionalText, 7}, + {ot.NewTag('p', 'c', 'a', 'p'), aatLayoutFeatureTypeLowerCase, aatLayoutFeatureSelectorLowerCasePetiteCaps, aatLayoutFeatureSelectorDefaultLowerCase}, + {ot.NewTag('p', 'k', 'n', 'a'), aatLayoutFeatureTypeTextSpacing, aatLayoutFeatureSelectorProportionalText, 7}, + {ot.NewTag('p', 'n', 'u', 'm'), aatLayoutFeatureTypeNumberSpacing, aatLayoutFeatureSelectorProportionalNumbers, 4}, + {ot.NewTag('p', 'w', 'i', 'd'), aatLayoutFeatureTypeTextSpacing, aatLayoutFeatureSelectorProportionalText, 7}, + {ot.NewTag('q', 'w', 'i', 'd'), aatLayoutFeatureTypeTextSpacing, aatLayoutFeatureSelectorQuarterWidthText, 7}, + {ot.NewTag('r', 'l', 'i', 'g'), aatLayoutFeatureTypeLigatures, aatLayoutFeatureSelectorRequiredLigaturesOn, aatLayoutFeatureSelectorRequiredLigaturesOff}, + {ot.NewTag('r', 'u', 'b', 'y'), aatLayoutFeatureTypeRubyKana, aatLayoutFeatureSelectorRubyKanaOn, aatLayoutFeatureSelectorRubyKanaOff}, + {ot.NewTag('s', 'i', 'n', 'f'), aatLayoutFeatureTypeVerticalPosition, aatLayoutFeatureSelectorScientificInferiors, aatLayoutFeatureSelectorNormalPosition}, + {ot.NewTag('s', 'm', 'c', 'p'), aatLayoutFeatureTypeLowerCase, aatLayoutFeatureSelectorLowerCaseSmallCaps, aatLayoutFeatureSelectorDefaultLowerCase}, + {ot.NewTag('s', 'm', 'p', 'l'), aatLayoutFeatureTypeCharacterShape, aatLayoutFeatureSelectorSimplifiedCharacters, 16}, + {ot.NewTag('s', 's', '0', '1'), aatLayoutFeatureTypeStylisticAlternatives, aatLayoutFeatureSelectorStylisticAltOneOn, aatLayoutFeatureSelectorStylisticAltOneOff}, + {ot.NewTag('s', 's', '0', '2'), aatLayoutFeatureTypeStylisticAlternatives, aatLayoutFeatureSelectorStylisticAltTwoOn, aatLayoutFeatureSelectorStylisticAltTwoOff}, + {ot.NewTag('s', 's', '0', '3'), aatLayoutFeatureTypeStylisticAlternatives, aatLayoutFeatureSelectorStylisticAltThreeOn, aatLayoutFeatureSelectorStylisticAltThreeOff}, + {ot.NewTag('s', 's', '0', '4'), aatLayoutFeatureTypeStylisticAlternatives, aatLayoutFeatureSelectorStylisticAltFourOn, aatLayoutFeatureSelectorStylisticAltFourOff}, + {ot.NewTag('s', 's', '0', '5'), aatLayoutFeatureTypeStylisticAlternatives, aatLayoutFeatureSelectorStylisticAltFiveOn, aatLayoutFeatureSelectorStylisticAltFiveOff}, + {ot.NewTag('s', 's', '0', '6'), aatLayoutFeatureTypeStylisticAlternatives, aatLayoutFeatureSelectorStylisticAltSixOn, aatLayoutFeatureSelectorStylisticAltSixOff}, + {ot.NewTag('s', 's', '0', '7'), aatLayoutFeatureTypeStylisticAlternatives, aatLayoutFeatureSelectorStylisticAltSevenOn, aatLayoutFeatureSelectorStylisticAltSevenOff}, + {ot.NewTag('s', 's', '0', '8'), aatLayoutFeatureTypeStylisticAlternatives, aatLayoutFeatureSelectorStylisticAltEightOn, aatLayoutFeatureSelectorStylisticAltEightOff}, + {ot.NewTag('s', 's', '0', '9'), aatLayoutFeatureTypeStylisticAlternatives, aatLayoutFeatureSelectorStylisticAltNineOn, aatLayoutFeatureSelectorStylisticAltNineOff}, + {ot.NewTag('s', 's', '1', '0'), aatLayoutFeatureTypeStylisticAlternatives, aatLayoutFeatureSelectorStylisticAltTenOn, aatLayoutFeatureSelectorStylisticAltTenOff}, + {ot.NewTag('s', 's', '1', '1'), aatLayoutFeatureTypeStylisticAlternatives, aatLayoutFeatureSelectorStylisticAltElevenOn, aatLayoutFeatureSelectorStylisticAltElevenOff}, + {ot.NewTag('s', 's', '1', '2'), aatLayoutFeatureTypeStylisticAlternatives, aatLayoutFeatureSelectorStylisticAltTwelveOn, aatLayoutFeatureSelectorStylisticAltTwelveOff}, + {ot.NewTag('s', 's', '1', '3'), aatLayoutFeatureTypeStylisticAlternatives, aatLayoutFeatureSelectorStylisticAltThirteenOn, aatLayoutFeatureSelectorStylisticAltThirteenOff}, + {ot.NewTag('s', 's', '1', '4'), aatLayoutFeatureTypeStylisticAlternatives, aatLayoutFeatureSelectorStylisticAltFourteenOn, aatLayoutFeatureSelectorStylisticAltFourteenOff}, + {ot.NewTag('s', 's', '1', '5'), aatLayoutFeatureTypeStylisticAlternatives, aatLayoutFeatureSelectorStylisticAltFifteenOn, aatLayoutFeatureSelectorStylisticAltFifteenOff}, + {ot.NewTag('s', 's', '1', '6'), aatLayoutFeatureTypeStylisticAlternatives, aatLayoutFeatureSelectorStylisticAltSixteenOn, aatLayoutFeatureSelectorStylisticAltSixteenOff}, + {ot.NewTag('s', 's', '1', '7'), aatLayoutFeatureTypeStylisticAlternatives, aatLayoutFeatureSelectorStylisticAltSeventeenOn, aatLayoutFeatureSelectorStylisticAltSeventeenOff}, + {ot.NewTag('s', 's', '1', '8'), aatLayoutFeatureTypeStylisticAlternatives, aatLayoutFeatureSelectorStylisticAltEighteenOn, aatLayoutFeatureSelectorStylisticAltEighteenOff}, + {ot.NewTag('s', 's', '1', '9'), aatLayoutFeatureTypeStylisticAlternatives, aatLayoutFeatureSelectorStylisticAltNineteenOn, aatLayoutFeatureSelectorStylisticAltNineteenOff}, + {ot.NewTag('s', 's', '2', '0'), aatLayoutFeatureTypeStylisticAlternatives, aatLayoutFeatureSelectorStylisticAltTwentyOn, aatLayoutFeatureSelectorStylisticAltTwentyOff}, + {ot.NewTag('s', 'u', 'b', 's'), aatLayoutFeatureTypeVerticalPosition, aatLayoutFeatureSelectorInferiors, aatLayoutFeatureSelectorNormalPosition}, + {ot.NewTag('s', 'u', 'p', 's'), aatLayoutFeatureTypeVerticalPosition, aatLayoutFeatureSelectorSuperiors, aatLayoutFeatureSelectorNormalPosition}, + {ot.NewTag('s', 'w', 's', 'h'), aatLayoutFeatureTypeContextualAlternatives, aatLayoutFeatureSelectorSwashAlternatesOn, aatLayoutFeatureSelectorSwashAlternatesOff}, + {ot.NewTag('t', 'i', 't', 'l'), aatLayoutFeatureTypeStyleOptions, aatLayoutFeatureSelectorTitlingCaps, aatLayoutFeatureSelectorNoStyleOptions}, + {ot.NewTag('t', 'n', 'a', 'm'), aatLayoutFeatureTypeCharacterShape, aatLayoutFeatureSelectorTraditionalNamesCharacters, 16}, + {ot.NewTag('t', 'n', 'u', 'm'), aatLayoutFeatureTypeNumberSpacing, aatLayoutFeatureSelectorMonospacedNumbers, 4}, + {ot.NewTag('t', 'r', 'a', 'd'), aatLayoutFeatureTypeCharacterShape, aatLayoutFeatureSelectorTraditionalCharacters, 16}, + {ot.NewTag('t', 'w', 'i', 'd'), aatLayoutFeatureTypeTextSpacing, aatLayoutFeatureSelectorThirdWidthText, 7}, + {ot.NewTag('u', 'n', 'i', 'c'), aatLayoutFeatureTypeLetterCase, 14, 15}, + {ot.NewTag('v', 'a', 'l', 't'), aatLayoutFeatureTypeTextSpacing, aatLayoutFeatureSelectorAltProportionalText, 7}, + {ot.NewTag('v', 'e', 'r', 't'), aatLayoutFeatureTypeVerticalSubstitution, aatLayoutFeatureSelectorSubstituteVerticalFormsOn, aatLayoutFeatureSelectorSubstituteVerticalFormsOff}, + {ot.NewTag('v', 'h', 'a', 'l'), aatLayoutFeatureTypeTextSpacing, aatLayoutFeatureSelectorAltHalfWidthText, 7}, + {ot.NewTag('v', 'k', 'n', 'a'), aatLayoutFeatureTypeAlternateKana, aatLayoutFeatureSelectorAlternateVertKanaOn, aatLayoutFeatureSelectorAlternateVertKanaOff}, + {ot.NewTag('v', 'p', 'a', 'l'), aatLayoutFeatureTypeTextSpacing, aatLayoutFeatureSelectorAltProportionalText, 7}, + {ot.NewTag('v', 'r', 't', '2'), aatLayoutFeatureTypeVerticalSubstitution, aatLayoutFeatureSelectorSubstituteVerticalFormsOn, aatLayoutFeatureSelectorSubstituteVerticalFormsOff}, + {ot.NewTag('v', 'r', 't', 'r'), aatLayoutFeatureTypeVerticalSubstitution, 2, 3}, + {ot.NewTag('z', 'e', 'r', 'o'), aatLayoutFeatureTypeTypographicExtras, aatLayoutFeatureSelectorSlashedZeroOn, aatLayoutFeatureSelectorSlashedZeroOff}, +} + +/* Note: This context is used for kerning, even without AAT, hence the condition. */ + +type aatApplyContext struct { + plan *otShapePlan + font *Font + face Face + buffer *Buffer + gdefTable *tables.GDEF + ankrTable tables.Ankr + + rangeFlags []rangeFlags + subtableFlags GlyphMask +} + +func newAatApplyContext(plan *otShapePlan, font *Font, buffer *Buffer) *aatApplyContext { + var out aatApplyContext + out.plan = plan + out.font = font + out.face = font.face + out.buffer = buffer + out.gdefTable = &font.face.GDEF + return &out +} + +func (c *aatApplyContext) hasAnyFlags(flag GlyphMask) bool { + for _, fl := range c.rangeFlags { + if fl.flags&flag != 0 { + return true + } + } + return false +} + +func (c *aatApplyContext) applyMorx(chain font.MorxChain) { + // Coverage, see https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6morx.html + const ( + Vertical = 0x80 + Backwards = 0x40 + AllDirections = 0x20 + Logical = 0x10 + ) + + for i, subtable := range chain.Subtables { + + if !c.hasAnyFlags(subtable.Flags) { + continue + } + + c.subtableFlags = subtable.Flags + if subtable.Coverage&AllDirections == 0 && c.buffer.Props.Direction.isVertical() != + (subtable.Coverage&Vertical != 0) { + continue + } + + /* Buffer contents is always in logical direction. Determine if + we need to reverse before applying this subtable. We reverse + back after if we did reverse indeed. + + Quoting the spec: + """ + Bits 28 and 30 of the coverage field control the order in which + glyphs are processed when the subtable is run by the layout engine. + Bit 28 is used to indicate if the glyph processing direction is + the same as logical order or layout order. Bit 30 is used to + indicate whether glyphs are processed forwards or backwards within + that order. + + Bit 30 Bit 28 Interpretation for Horizontal Text + 0 0 The subtable is processed in layout order (the same order as the glyphs, which is + always left-to-right). + 1 0 The subtable is processed in reverse layout order (the order opposite that of the glyphs, which is + always right-to-left). + 0 1 The subtable is processed in logical order (the same order as the characters, which may be + left-to-right or right-to-left). + 1 1 The subtable is processed in reverse logical order (the order opposite that of the characters, which + may be right-to-left or left-to-right). + """ + */ + var reverse bool + if subtable.Coverage&Logical != 0 { + reverse = subtable.Coverage&Backwards != 0 + } else { + reverse = subtable.Coverage&Backwards != 0 != c.buffer.Props.Direction.isBackward() + } + + if debugMode { + fmt.Printf("MORX - start chainsubtable %d\n", i) + } + + if reverse { + c.buffer.Reverse() + } + + c.applyMorxSubtable(subtable) + + if reverse { + c.buffer.Reverse() + } + + if debugMode { + fmt.Printf("MORX - end chainsubtable %d\n", i) + fmt.Println(c.buffer.Info) + } + + } +} + +func (c *aatApplyContext) applyMorxSubtable(subtable font.MorxSubtable) bool { + if debugMode { + fmt.Printf("\tMORX subtable %T\n", subtable.Data) + } + switch data := subtable.Data.(type) { + case font.MorxRearrangementSubtable: + var dc driverContextRearrangement + driver := newStateTableDriver(font.AATStateTable(data), c.buffer, c.face) + driver.drive(&dc, c) + case font.MorxContextualSubtable: + dc := driverContextContextual{table: data, gdef: c.gdefTable, hasGlyphClass: c.gdefTable.GlyphClassDef != nil} + driver := newStateTableDriver(data.Machine, c.buffer, c.face) + driver.drive(&dc, c) + return dc.ret + case font.MorxLigatureSubtable: + dc := driverContextLigature{table: data} + driver := newStateTableDriver(data.Machine, c.buffer, c.face) + driver.drive(&dc, c) + case font.MorxInsertionSubtable: + dc := driverContextInsertion{insertionAction: data.Insertions} + driver := newStateTableDriver(data.Machine, c.buffer, c.face) + driver.drive(&dc, c) + case font.MorxNonContextualSubtable: + return c.applyNonContextualSubtable(data) + } + return false +} + +/** + * + * Functions for querying AAT Layout features in the font face. + * + * HarfBuzz supports all of the AAT tables (in their modern version) used to implement shaping. Other + * AAT tables and their associated features are not supported. + **/ + +// execute the state machine in AAT tables +type stateTableDriver struct { + buffer *Buffer + machine font.AATStateTable +} + +func newStateTableDriver(machine font.AATStateTable, buffer *Buffer, _ Face) stateTableDriver { + return stateTableDriver{ + machine: machine, + buffer: buffer, + } +} + +// implemented by the subtables +type driverContext interface { + inPlace() bool + isActionable(s stateTableDriver, entry tables.AATStateEntry) bool + transition(s stateTableDriver, entry tables.AATStateEntry) +} + +func (s stateTableDriver) drive(c driverContext, ac *aatApplyContext) { + const ( + stateStartOfText = uint16(0) + + classEndOfText = uint16(0) + + DontAdvance = 0x4000 + ) + if !c.inPlace() { + s.buffer.clearOutput() + } + + state := stateStartOfText + // If there's only one range, we already checked the flag. + var lastRange int = -1 // index in ac.rangeFlags, or -1 + if len(ac.rangeFlags) > 1 { + lastRange = 0 + } + for s.buffer.idx = 0; ; { + // This block is copied in NoncontextualSubtable::apply. Keep in sync. + if lastRange != -1 { + range_ := lastRange + if s.buffer.idx < len(s.buffer.Info) { + cluster := s.buffer.cur(0).Cluster + for cluster < ac.rangeFlags[range_].clusterFirst { + range_-- + } + for cluster > ac.rangeFlags[range_].clusterLast { + range_++ + } + + lastRange = range_ + } + if !(ac.rangeFlags[range_].flags&ac.subtableFlags != 0) { + if s.buffer.idx == len(s.buffer.Info) { + break + } + + state = stateStartOfText + s.buffer.nextGlyph() + continue + } + } + + class := classEndOfText + if s.buffer.idx < len(s.buffer.Info) { + class = s.machine.GetClass(s.buffer.Info[s.buffer.idx].Glyph) + } + + if debugMode { + fmt.Printf("\t\tState machine - state %d, class %d at index %d\n", state, class, s.buffer.idx) + } + + entry := s.machine.GetEntry(state, class) + nextState := entry.NewState // we only supported extended table + + /* Conditions under which it's guaranteed safe-to-break before current glyph: + * + * 1. There was no action in this transition; and + * + * 2. If we break before current glyph, the results will be the same. That + * is guaranteed if: + * + * 2a. We were already in start-of-text state; or + * + * 2b. We are epsilon-transitioning to start-of-text state; or + * + * 2c. Starting from start-of-text state seeing current glyph: + * + * 2c'. There won't be any actions; and + * + * 2c". We would end up in the same state that we were going to end up + * in now, including whether epsilon-transitioning. + * + * and + * + * 3. If we break before current glyph, there won't be any end-of-text action + * after previous glyph. + * + * This triples the transitions we need to look up, but is worth returning + * granular unsafe-to-break results. See eg.: + * + * https://github.com/harfbuzz/harfbuzz/issues/2860 + */ + + wouldbeEntry := s.machine.GetEntry(stateStartOfText, class) + safeToBreak := /* 1. */ !c.isActionable(s, entry) && + /* 2. */ + ( + /* 2a. */ + state == stateStartOfText || + /* 2b. */ + ((entry.Flags&DontAdvance != 0) && nextState == stateStartOfText) || + /* 2c. */ + ( + /* 2c'. */ + !c.isActionable(s, wouldbeEntry) && + /* 2c". */ + (nextState == wouldbeEntry.NewState) && + (entry.Flags&DontAdvance) == (wouldbeEntry.Flags&DontAdvance))) && + /* 3. */ + !c.isActionable(s, s.machine.GetEntry(state, classEndOfText)) + + if !safeToBreak && s.buffer.backtrackLen() != 0 && s.buffer.idx < len(s.buffer.Info) { + s.buffer.unsafeToBreakFromOutbuffer(s.buffer.backtrackLen()-1, s.buffer.idx+1) + } + + c.transition(s, entry) + + state = nextState + + if debugMode { + fmt.Printf("\t\tState machine - new state %d\n", state) + } + + if s.buffer.idx == len(s.buffer.Info) { + break + } + + if entry.Flags&DontAdvance == 0 { + s.buffer.nextGlyph() + } else { + if s.buffer.maxOps <= 0 { + s.buffer.maxOps-- + s.buffer.nextGlyph() + } + s.buffer.maxOps-- + } + } + + if !c.inPlace() { + s.buffer.swapBuffers() + } +} + +// MorxRearrangemen flags +const ( + /* If set, make the current glyph the first + * glyph to be rearranged. */ + mrMarkFirst = 0x8000 + /* If set, don't advance to the next glyph + * before going to the new state. This means + * that the glyph index doesn't change, even + * if the glyph at that index has changed. */ + _ = 0x4000 + /* If set, make the current glyph the last + * glyph to be rearranged. */ + mrMarkLast = 0x2000 + /* These bits are reserved and should be set to 0. */ + _ = 0x1FF0 + /* The type of rearrangement specified. */ + mrVerb = 0x000F +) + +type driverContextRearrangement struct { + start int + end int +} + +func (driverContextRearrangement) inPlace() bool { return true } + +func (d driverContextRearrangement) isActionable(_ stateTableDriver, entry tables.AATStateEntry) bool { + return (entry.Flags&mrVerb) != 0 && d.start < d.end +} + +/* The following map has two nibbles, for start-side + * and end-side. Values of 0,1,2 mean move that many + * to the other side. Value of 3 means move 2 and + * flip them. */ +var mapRearrangement = [16]int{ + 0x00, /* 0 no change */ + 0x10, /* 1 Ax => xA */ + 0x01, /* 2 xD => Dx */ + 0x11, /* 3 AxD => DxA */ + 0x20, /* 4 ABx => xAB */ + 0x30, /* 5 ABx => xBA */ + 0x02, /* 6 xCD => CDx */ + 0x03, /* 7 xCD => DCx */ + 0x12, /* 8 AxCD => CDxA */ + 0x13, /* 9 AxCD => DCxA */ + 0x21, /* 10 ABxD => DxAB */ + 0x31, /* 11 ABxD => DxBA */ + 0x22, /* 12 ABxCD => CDxAB */ + 0x32, /* 13 ABxCD => CDxBA */ + 0x23, /* 14 ABxCD => DCxAB */ + 0x33, /* 15 ABxCD => DCxBA */ +} + +func (d *driverContextRearrangement) transition(driver stateTableDriver, entry tables.AATStateEntry) { + buffer := driver.buffer + flags := entry.Flags + + if flags&mrMarkFirst != 0 { + d.start = buffer.idx + } + + if flags&mrMarkLast != 0 { + d.end = min(buffer.idx+1, len(buffer.Info)) + } + + if (flags&mrVerb) != 0 && d.start < d.end { + + m := mapRearrangement[flags&mrVerb] + l := min(2, m>>4) + r := min(2, m&0x0F) + reverseL := m>>4 == 3 + reverseR := m&0x0F == 3 + + if d.end-d.start >= l+r && d.end-d.start <= maxContextLength { + buffer.mergeClusters(d.start, min(buffer.idx+1, len(buffer.Info))) + buffer.mergeClusters(d.start, d.end) + + info := buffer.Info + var buf [4]GlyphInfo + + copy(buf[:], info[d.start:d.start+l]) + copy(buf[2:], info[d.end-r:d.end]) + + if l != r { + copy(info[d.start+r:], info[d.start+l:d.end-r]) + } + + copy(info[d.start:d.start+r], buf[2:]) + copy(info[d.end-l:d.end], buf[:]) + if reverseL { + buf[0] = info[d.end-1] + info[d.end-1] = info[d.end-2] + info[d.end-2] = buf[0] + } + if reverseR { + buf[0] = info[d.start] + info[d.start] = info[d.start+1] + info[d.start+1] = buf[0] + } + } + } +} + +// MorxContextualSubtable flags +const ( + mcSetMark = 0x8000 /* If set, make the current glyph the marked glyph. */ + /* If set, don't advance to the next glyph before + * going to the new state. */ + _ = 0x4000 + _ = 0x3FFF /* These bits are reserved and should be set to 0. */ +) + +type driverContextContextual struct { + gdef *tables.GDEF + table font.MorxContextualSubtable + mark int + markSet bool + ret bool + hasGlyphClass bool // cached version from gdef +} + +func (driverContextContextual) inPlace() bool { return true } + +func (dc driverContextContextual) isActionable(driver stateTableDriver, entry tables.AATStateEntry) bool { + buffer := driver.buffer + + if buffer.idx == len(buffer.Info) && !dc.markSet { + return false + } + markIndex, currentIndex := entry.AsMorxContextual() + return markIndex != 0xFFFF || currentIndex != 0xFFFF +} + +func (dc *driverContextContextual) transition(driver stateTableDriver, entry tables.AATStateEntry) { + buffer := driver.buffer + + /* Looks like CoreText applies neither mark nor current substitution for + * end-of-text if mark was not explicitly set. */ + if buffer.idx == len(buffer.Info) && !dc.markSet { + return + } + + var ( + replacement uint16 // intepreted as GlyphIndex + hasRep bool + markIndex, currentIndex = entry.AsMorxContextual() + ) + if markIndex != 0xFFFF { + lookup := dc.table.Substitutions[markIndex] + replacement, hasRep = lookup.Class(gID(buffer.Info[dc.mark].Glyph)) + } + if hasRep { + buffer.unsafeToBreak(dc.mark, min(buffer.idx+1, len(buffer.Info))) + buffer.Info[dc.mark].Glyph = GID(replacement) + if dc.hasGlyphClass { + buffer.Info[dc.mark].glyphProps = dc.gdef.GlyphProps(gID(replacement)) + } + dc.ret = true + } + + hasRep = false + idx := min(buffer.idx, len(buffer.Info)-1) + if currentIndex != 0xFFFF { + lookup := dc.table.Substitutions[currentIndex] + replacement, hasRep = lookup.Class(gID(buffer.Info[idx].Glyph)) + } + + if hasRep { + buffer.Info[idx].Glyph = GID(replacement) + if dc.hasGlyphClass { + buffer.Info[idx].glyphProps = dc.gdef.GlyphProps(gID(replacement)) + } + dc.ret = true + } + + if entry.Flags&mcSetMark != 0 { + dc.markSet = true + dc.mark = buffer.idx + } +} + +type driverContextLigature struct { + table font.MorxLigatureSubtable + matchLength int + matchPositions [maxContextLength]int +} + +func (driverContextLigature) inPlace() bool { return false } + +func (driverContextLigature) isActionable(_ stateTableDriver, entry tables.AATStateEntry) bool { + return entry.Flags&tables.MLOffset != 0 +} + +func (dc *driverContextLigature) transition(driver stateTableDriver, entry tables.AATStateEntry) { + buffer := driver.buffer + + if debugMode { + fmt.Printf("\tLigature - Ligature transition at %d\n", buffer.idx) + } + + if entry.Flags&tables.MLSetComponent != 0 { + /* Never mark same index twice, in case DontAdvance was used... */ + if dc.matchLength != 0 && dc.matchPositions[(dc.matchLength-1)%len(dc.matchPositions)] == len(buffer.outInfo) { + dc.matchLength-- + } + + dc.matchPositions[dc.matchLength%len(dc.matchPositions)] = len(buffer.outInfo) + dc.matchLength++ + + if debugMode { + fmt.Printf("\tLigature - Set component at %d\n", len(buffer.outInfo)) + } + + } + + if dc.isActionable(driver, entry) { + + if debugMode { + fmt.Printf("\tLigature - Perform action with %d\n", dc.matchLength) + } + + end := len(buffer.outInfo) + + if dc.matchLength == 0 { + return + } + + if buffer.idx >= len(buffer.Info) { + return + } + cursor := dc.matchLength + + actionIdx := entry.AsMorxLigature() + actionData := dc.table.LigatureAction[actionIdx:] + + ligatureIdx := 0 + var action uint32 + for do := true; do; do = action&tables.MLActionLast == 0 { + if cursor == 0 { + /* Stack underflow. Clear the stack. */ + if debugMode { + fmt.Println("\tLigature - Stack underflow") + } + dc.matchLength = 0 + break + } + + if debugMode { + fmt.Printf("\tLigature - Moving to stack position %d\n", cursor-1) + } + + cursor-- + buffer.moveTo(dc.matchPositions[cursor%len(dc.matchPositions)]) + + if len(actionData) == 0 { + break + } + action = actionData[0] + + uoffset := action & tables.MLActionOffset + if uoffset&0x20000000 != 0 { + uoffset |= 0xC0000000 /* Sign-extend. */ + } + offset := int32(uoffset) + componentIdx := int32(buffer.cur(0).Glyph) + offset + if int(componentIdx) >= len(dc.table.Components) { + break + } + componentData := dc.table.Components[componentIdx] + ligatureIdx += int(componentData) + + if debugMode { + fmt.Printf("\tLigature - Action store %d last %d\n", action&tables.MLActionStore, action&tables.MLActionLast) + } + + if action&(tables.MLActionStore|tables.MLActionLast) != 0 { + if ligatureIdx >= len(dc.table.Ligatures) { + break + } + lig := dc.table.Ligatures[ligatureIdx] + + if debugMode { + fmt.Printf("\tLigature - Produced ligature %d\n", lig) + } + + buffer.replaceGlyphIndex(lig) + + ligEnd := dc.matchPositions[(dc.matchLength-1)%len(dc.matchPositions)] + 1 + /* Now go and delete all subsequent components. */ + for dc.matchLength-1 > cursor { + + if debugMode { + fmt.Println("\tLigature - Skipping ligature component") + } + + dc.matchLength-- + buffer.moveTo(dc.matchPositions[dc.matchLength%len(dc.matchPositions)]) + buffer.replaceGlyphIndex(0xFFFF) + } + + buffer.moveTo(ligEnd) + buffer.mergeOutClusters(dc.matchPositions[cursor%len(dc.matchPositions)], len(buffer.outInfo)) + } + + actionData = actionData[1:] + } + buffer.moveTo(end) + } +} + +// MorxInsertionSubtable flags +const ( + // If set, mark the current glyph. + miSetMark = 0x8000 + // If set, don't advance to the next glyph before + // going to the new state. This does not mean + // that the glyph pointed to is the same one as + // before. If you've made insertions immediately + // downstream of the current glyph, the next glyph + // processed would in fact be the first one + // inserted. + miDontAdvance = 0x4000 + // If set, and the currentInsertList is nonzero, + // then the specified glyph list will be inserted + // as a kashida-like insertion, either before or + // after the current glyph (depending on the state + // of the currentInsertBefore flag). If clear, and + // the currentInsertList is nonzero, then the + // specified glyph list will be inserted as a + // split-vowel-like insertion, either before or + // after the current glyph (depending on the state + // of the currentInsertBefore flag). + _ = 0x2000 + // If set, and the markedInsertList is nonzero, + // then the specified glyph list will be inserted + // as a kashida-like insertion, either before or + // after the marked glyph (depending on the state + // of the markedInsertBefore flag). If clear, and + // the markedInsertList is nonzero, then the + // specified glyph list will be inserted as a + // split-vowel-like insertion, either before or + // after the marked glyph (depending on the state + // of the markedInsertBefore flag). + _ = 0x1000 + // If set, specifies that insertions are to be made + // to the left of the current glyph. If clear, + // they're made to the right of the current glyph. + miCurrentInsertBefore = 0x0800 + // If set, specifies that insertions are to be + // made to the left of the marked glyph. If clear, + // they're made to the right of the marked glyph. + miMarkedInsertBefore = 0x0400 + // This 5-bit field is treated as a count of the + // number of glyphs to insert at the current + // position. Since zero means no insertions, the + // largest number of insertions at any given + // current location is 31 glyphs. + miCurrentInsertCount = 0x3E0 + // This 5-bit field is treated as a count of the + // number of glyphs to insert at the marked + // position. Since zero means no insertions, the + // largest number of insertions at any given + // marked location is 31 glyphs. + miMarkedInsertCount = 0x001F +) + +type driverContextInsertion struct { + insertionAction []GID + mark int +} + +func (driverContextInsertion) inPlace() bool { return false } + +func (driverContextInsertion) isActionable(_ stateTableDriver, entry tables.AATStateEntry) bool { + current, marked := entry.AsMorxInsertion() + return entry.Flags&(miCurrentInsertCount|miMarkedInsertCount) != 0 && (current != 0xFFFF || marked != 0xFFFF) +} + +func (dc *driverContextInsertion) transition(driver stateTableDriver, entry tables.AATStateEntry) { + buffer := driver.buffer + flags := entry.Flags + + markLoc := len(buffer.outInfo) + currentInsertIndex, markedInsertIndex := entry.AsMorxInsertion() + if markedInsertIndex != 0xFFFF { + count := int(flags & miMarkedInsertCount) + buffer.maxOps -= count + if buffer.maxOps <= 0 { + return + } + start := markedInsertIndex + glyphs := dc.insertionAction[start:] + + before := flags&miMarkedInsertBefore != 0 + + end := len(buffer.outInfo) + buffer.moveTo(dc.mark) + + if buffer.idx < len(buffer.Info) && !before { + buffer.copyGlyph() + } + /* TODO We ignore KashidaLike setting. */ + buffer.replaceGlyphs(0, nil, glyphs[:count]) + + if buffer.idx < len(buffer.Info) && !before { + buffer.skipGlyph() + } + + buffer.moveTo(end + count) + + buffer.unsafeToBreakFromOutbuffer(dc.mark, min(buffer.idx+1, len(buffer.Info))) + } + + if flags&miSetMark != 0 { + dc.mark = markLoc + } + + if currentInsertIndex != 0xFFFF { + count := int(flags&miCurrentInsertCount) >> 5 + if buffer.maxOps <= 0 { + buffer.maxOps -= count + return + } + buffer.maxOps -= count + start := currentInsertIndex + glyphs := dc.insertionAction[start:] + + before := flags&miCurrentInsertBefore != 0 + + end := len(buffer.outInfo) + + if buffer.idx < len(buffer.Info) && !before { + buffer.copyGlyph() + } + + /* TODO We ignore KashidaLike setting. */ + buffer.replaceGlyphs(0, nil, glyphs[:count]) + + if buffer.idx < len(buffer.Info) && !before { + buffer.skipGlyph() + } + + /* Humm. Not sure where to move to. There's this wording under + * DontAdvance flag: + * + * "If set, don't update the glyph index before going to the new state. + * This does not mean that the glyph pointed to is the same one as + * before. If you've made insertions immediately downstream of the + * current glyph, the next glyph processed would in fact be the first + * one inserted." + * + * This suggests that if DontAdvance is NOT set, we should move to + * end+count. If it *was*, then move to end, such that newly inserted + * glyphs are now visible. + * + * https://github.com/harfbuzz/harfbuzz/issues/1224#issuecomment-427691417 + */ + moveTo := end + if flags&miDontAdvance == 0 { + moveTo = end + count + } + buffer.moveTo(moveTo) + } +} + +func (c *aatApplyContext) applyNonContextualSubtable(data font.MorxNonContextualSubtable) bool { + var ret bool + gdef := c.gdefTable + hasGlyphClass := gdef.GlyphClassDef != nil + info := c.buffer.Info + // If there's only one range, we already checked the flag. + var lastRange int = -1 // index in ac.rangeFlags, or -1 + if len(c.rangeFlags) > 1 { + lastRange = 0 + } + for i := range info { + // This block is copied in NoncontextualSubtable::apply. Keep in sync. + if lastRange != -1 { + range_ := lastRange + cluster := info[i].Cluster + for cluster < c.rangeFlags[range_].clusterFirst { + range_-- + } + for cluster > c.rangeFlags[range_].clusterLast { + range_++ + } + + lastRange = range_ + if c.rangeFlags[range_].flags&c.subtableFlags == 0 { + continue + } + } + + replacement, has := data.Class.Class(gID(info[i].Glyph)) + if has { + info[i].Glyph = GID(replacement) + if hasGlyphClass { + info[i].glyphProps = gdef.GlyphProps(gID(replacement)) + } + ret = true + } + } + return ret +} + +/////// + +type aatFeatureMapping struct { + otFeatureTag font.Tag + aatFeatureType aatLayoutFeatureType + selectorToEnable aatLayoutFeatureSelector + selectorToDisable aatLayoutFeatureSelector +} + +// FaatLayoutFindFeatureMapping fetches the AAT feature-and-selector combination that corresponds +// to a given OpenType feature tag, or `nil` if not found. +func aatLayoutFindFeatureMapping(tag font.Tag) *aatFeatureMapping { + low, high := 0, len(featureMappings) + for low < high { + mid := low + (high-low)/2 // avoid overflow when computing mid + p := featureMappings[mid].otFeatureTag + if tag < p { + high = mid + } else if tag > p { + low = mid + 1 + } else { + return &featureMappings[mid] + } + } + return nil +} + +func (sp *otShapePlan) aatLayoutSubstitute(font *Font, buffer *Buffer, features []Feature) { + morx := font.face.Morx + builder := newAatMapBuilder(font.face.Font, sp.props) + for _, feature := range features { + builder.addFeature(feature) + } + var map_ aatMap + builder.compile(&map_) + + c := newAatApplyContext(sp, font, buffer) + c.buffer.unsafeToConcat(0, maxInt) + for i, chain := range morx { + c.rangeFlags = map_.chainFlags[i] + c.applyMorx(chain) + } + // NOTE: we dont support obsolete 'mort' table +} + +func aatLayoutZeroWidthDeletedGlyphs(buffer *Buffer) { + pos := buffer.Pos + for i, inf := range buffer.Info { + if inf.Glyph == 0xFFFF { + pos[i].XAdvance, pos[i].YAdvance, pos[i].XOffset, pos[i].YOffset = 0, 0, 0, 0 + } + } +} + +func aatLayoutRemoveDeletedGlyphs(buffer *Buffer) { + buffer.deleteGlyphsInplace(func(info *GlyphInfo) bool { return info.Glyph == 0xFFFF }) +} + +func (sp *otShapePlan) aatLayoutPosition(font *Font, buffer *Buffer) { + kerx := font.face.Kerx + + c := newAatApplyContext(sp, font, buffer) + c.ankrTable = font.face.Ankr + c.applyKernx(kerx) +} + +func (c *aatApplyContext) applyKernx(kerx font.Kernx) { + var ret, seenCrossStream bool + + c.buffer.unsafeToConcat(0, maxInt) + for i, st := range kerx { + var reverse bool + + if !st.IsExtended && st.IsVariation() { + continue + } + + if c.buffer.Props.Direction.isHorizontal() != st.IsHorizontal() { + continue + } + reverse = st.IsBackwards() != c.buffer.Props.Direction.isBackward() + + if debugMode { + fmt.Printf("AAT kerx : start subtable %d\n", i) + } + + if !seenCrossStream && st.IsCrossStream() { + /* Attach all glyphs into a chain. */ + seenCrossStream = true + pos := c.buffer.Pos + for i := range pos { + pos[i].attachType = attachTypeCursive + if c.buffer.Props.Direction.isForward() { + pos[i].attachChain = -1 + } else { + pos[i].attachChain = +1 + } + /* We intentionally don't set HB_BUFFER_SCRATCH_FLAG_HAS_GPOS_ATTACHMENT, + * since there needs to be a non-zero attachment for post-positioning to + * be needed. */ + } + } + + if reverse { + c.buffer.Reverse() + } + + applied := c.applyKerxSubtable(st) + ret = ret || applied + + if reverse { + c.buffer.Reverse() + } + + if debugMode { + fmt.Printf("AAT kerx : end subtable %d\n", i) + fmt.Println(c.buffer.Pos) + } + + } +} + +func (c *aatApplyContext) applyKerxSubtable(st font.KernSubtable) bool { + if debugMode { + fmt.Printf("\tKERNX table %T\n", st.Data) + } + switch data := st.Data.(type) { + case font.Kern0: + if !c.plan.requestedKerning { + return false + } + if st.IsBackwards() { + return false + } + kern(data, st.IsCrossStream(), c.font, c.buffer, c.plan.kernMask, true) + case font.Kern1: + crossStream := st.IsCrossStream() + if !c.plan.requestedKerning && !crossStream { + return false + } + dc := driverContextKerx1{c: c, table: data, crossStream: crossStream} + driver := newStateTableDriver(data.Machine, c.buffer, c.face) + driver.drive(&dc, c) + case font.Kern2: + if !c.plan.requestedKerning { + return false + } + if st.IsBackwards() { + return false + } + kern(data, st.IsCrossStream(), c.font, c.buffer, c.plan.kernMask, true) + case font.Kern3: + if !c.plan.requestedKerning { + return false + } + if st.IsBackwards() { + return false + } + kern(data, st.IsCrossStream(), c.font, c.buffer, c.plan.kernMask, true) + case font.Kern4: + crossStream := st.IsCrossStream() + if !c.plan.requestedKerning && !crossStream { + return false + } + dc := driverContextKerx4{c: c, table: data, actionType: data.ActionType()} + driver := newStateTableDriver(data.Machine, c.buffer, c.face) + driver.drive(&dc, c) + case font.Kern6: + if !c.plan.requestedKerning { + return false + } + if st.IsBackwards() { + return false + } + kern(data, st.IsCrossStream(), c.font, c.buffer, c.plan.kernMask, true) + } + return true +} + +// Kernx1 state entry flags +const ( + kerx1Push = 0x8000 // If set, push this glyph on the kerning stack. + kerx1DontAdvance = 0x4000 // If set, don't advance to the next glyph before going to the new state. + kerx1Reset = 0x2000 // If set, reset the kerning data (clear the stack) + kern1Offset = 0x3FFF // Byte offset from beginning of subtable to the value table for the glyphs on the kerning stack. +) + +type driverContextKerx1 struct { + c *aatApplyContext + table font.Kern1 + stack [8]int + depth int + crossStream bool +} + +func (driverContextKerx1) inPlace() bool { return true } + +func (dc driverContextKerx1) isActionable(_ stateTableDriver, entry tables.AATStateEntry) bool { + return entry.AsKernxIndex() != 0xFFFF +} + +func (dc *driverContextKerx1) transition(driver stateTableDriver, entry tables.AATStateEntry) { + buffer := driver.buffer + flags := entry.Flags + + if flags&kerx1Reset != 0 { + dc.depth = 0 + } + + if flags&kerx1Push != 0 { + if dc.depth < len(dc.stack) { + dc.stack[dc.depth] = buffer.idx + dc.depth++ + } else { + dc.depth = 0 /* Probably not what CoreText does, but better? */ + } + } + + if dc.isActionable(driver, entry) && dc.depth != 0 { + tupleCount := 1 // we do not support tupleCount > 0 + + kernIdx := entry.AsKernxIndex() + + actions := dc.table.Values[kernIdx:] + if len(actions) < tupleCount*dc.depth { + dc.depth = 0 + return + } + + kernMask := dc.c.plan.kernMask + + /* From Apple 'kern' spec: + * "Each pops one glyph from the kerning stack and applies the kerning value to it. + * The end of the list is marked by an odd value... */ + var last bool + for !last && dc.depth != 0 { + dc.depth-- + idx := dc.stack[dc.depth] + v := actions[0] + actions = actions[tupleCount:] + if idx >= len(buffer.Pos) { + continue + } + + /* "The end of the list is marked by an odd value..." */ + last = v&1 != 0 + v &= ^1 + + o := &buffer.Pos[idx] + if buffer.Props.Direction.isHorizontal() { + if dc.crossStream { + /* The following flag is undocumented in the spec, but described + * in the 'kern' table example. */ + if v == -0x8000 { + o.attachType = attachTypeNone + o.attachChain = 0 + o.YOffset = 0 + } else if o.attachType != 0 { + o.YOffset += dc.c.font.emScaleY(v) + buffer.scratchFlags |= bsfHasGPOSAttachment + } + } else if buffer.Info[idx].Mask&kernMask != 0 { + o.XAdvance += dc.c.font.emScaleX(v) + o.XOffset += dc.c.font.emScaleX(v) + } + } else { + if dc.crossStream { + /* CoreText doesn't do crossStream kerning in vertical. We do. */ + if v == -0x8000 { + o.attachType = attachTypeNone + o.attachChain = 0 + o.XOffset = 0 + } else if o.attachType != 0 { + o.XOffset += dc.c.font.emScaleX(v) + buffer.scratchFlags |= bsfHasGPOSAttachment + } + } else if buffer.Info[idx].Mask&kernMask != 0 { + o.YAdvance += dc.c.font.emScaleY(v) + o.YOffset += dc.c.font.emScaleY(v) + } + } + } + } +} + +type driverContextKerx4 struct { + c *aatApplyContext + table font.Kern4 + mark int + markSet bool + actionType uint8 +} + +func (driverContextKerx4) inPlace() bool { return true } + +func (driverContextKerx4) isActionable(_ stateTableDriver, entry tables.AATStateEntry) bool { + return entry.AsKernxIndex() != 0xFFFF +} + +func (dc *driverContextKerx4) transition(driver stateTableDriver, entry tables.AATStateEntry) { + buffer := driver.buffer + + ankrActionIndex := entry.AsKernxIndex() + if dc.markSet && ankrActionIndex != 0xFFFF && buffer.idx < len(buffer.Pos) { + o := buffer.curPos(0) + switch dc.actionType { + case 0: /* Control Point Actions.*/ + /* Indexed into glyph outline. */ + action := dc.table.Anchors.(tables.KerxAnchorControls).Anchors[ankrActionIndex] + + markX, markY, okMark := dc.c.font.getGlyphContourPointForOrigin(dc.c.buffer.Info[dc.mark].Glyph, + action.Mark, LeftToRight) + currX, currY, okCurr := dc.c.font.getGlyphContourPointForOrigin(dc.c.buffer.cur(0).Glyph, + action.Current, LeftToRight) + if !okMark || !okCurr { + return + } + + o.XOffset = markX - currX + o.YOffset = markY - currY + + case 1: /* Anchor Point Actions. */ + /* Indexed into 'ankr' table. */ + action := dc.table.Anchors.(tables.KerxAnchorAnchors).Anchors[ankrActionIndex] + + markAnchor := dc.c.ankrTable.GetAnchor(gID(dc.c.buffer.Info[dc.mark].Glyph), int(action.Mark)) + currAnchor := dc.c.ankrTable.GetAnchor(gID(dc.c.buffer.cur(0).Glyph), int(action.Current)) + + o.XOffset = dc.c.font.emScaleX(markAnchor.X) - dc.c.font.emScaleX(currAnchor.X) + o.YOffset = dc.c.font.emScaleY(markAnchor.Y) - dc.c.font.emScaleY(currAnchor.Y) + + case 2: /* Control Point Coordinate Actions. */ + action := dc.table.Anchors.(tables.KerxAnchorCoordinates).Anchors[ankrActionIndex] + o.XOffset = dc.c.font.emScaleX(action.MarkX) - dc.c.font.emScaleX(action.CurrentX) + o.YOffset = dc.c.font.emScaleY(action.MarkY) - dc.c.font.emScaleY(action.CurrentY) + } + o.attachType = attachTypeMark + o.attachChain = int16(dc.mark - buffer.idx) + buffer.scratchFlags |= bsfHasGPOSAttachment + } + + const Mark = 0x8000 /* If set, remember this glyph as the marked glyph. */ + if entry.Flags&Mark != 0 { + dc.markSet = true + dc.mark = buffer.idx + } +} + +func (sp *otShapePlan) aatLayoutTrack(font *Font, buffer *Buffer) { + trak := font.face.Trak + + c := newAatApplyContext(sp, font, buffer) + c.applyTrak(trak) +} + +func (c *aatApplyContext) applyTrak(trak tables.Trak) { + trakMask := c.plan.trakMask + + ptem := c.font.Ptem + if ptem <= 0. { + return + } + + buffer := c.buffer + if buffer.Props.Direction.isHorizontal() { + trackData := trak.Horiz + tracking := int(getTracking(trackData, ptem, 0)) + advanceToAdd := c.font.emScalefX(float32(tracking)) + offsetToAdd := c.font.emScalefX(float32(tracking / 2)) + + iter, count := buffer.graphemesIterator() + for start, _ := iter.next(); start < count; start, _ = iter.next() { + if buffer.Info[start].Mask&trakMask == 0 { + continue + } + buffer.Pos[start].XAdvance += advanceToAdd + buffer.Pos[start].XOffset += offsetToAdd + } + + } else { + trackData := trak.Vert + tracking := int(getTracking(trackData, ptem, 0)) + advanceToAdd := c.font.emScalefY(float32(tracking)) + offsetToAdd := c.font.emScalefY(float32(tracking / 2)) + iter, count := buffer.graphemesIterator() + for start, _ := iter.next(); start < count; start, _ = iter.next() { + if buffer.Info[start].Mask&trakMask == 0 { + continue + } + buffer.Pos[start].YAdvance += advanceToAdd + buffer.Pos[start].YOffset += offsetToAdd + } + + } +} + +// idx is assumed to verify idx <= len(Sizes) - 2 +func interpolateAt(td tables.TrackData, idx int, targetSize float32, trackSizes []int16) float32 { + s0 := td.SizeTable[idx] + s1 := td.SizeTable[idx+1] + var t float32 + if s0 != s1 { + t = (targetSize - s0) / (s1 - s0) + } + return t*float32(trackSizes[idx+1]) + (1.-t)*float32(trackSizes[idx]) +} + +// GetTracking select the tracking for the given `trackValue` and apply it +// for `ptem`. It returns 0 if not found. +func getTracking(td tables.TrackData, ptem float32, trackValue float32) float32 { + // Choose track. + + var trackTableEntry *tables.TrackTableEntry + for i := range td.TrackTable { + /* Note: Seems like the track entries are sorted by values. But the + * spec doesn't explicitly say that. It just mentions it in the example. */ + + if td.TrackTable[i].Track == trackValue { + trackTableEntry = &td.TrackTable[i] + break + } + } + if trackTableEntry == nil { + return 0. + } + + // Choose size. + + if len(td.SizeTable) == 0 { + return 0. + } + if len(td.SizeTable) == 1 { + return float32(trackTableEntry.PerSizeTracking[0]) + } + + var sizeIndex int + for sizeIndex = range td.SizeTable { + if td.SizeTable[sizeIndex] >= ptem { + break + } + } + if sizeIndex != 0 { + sizeIndex = sizeIndex - 1 + } + return interpolateAt(td, sizeIndex, ptem, trackTableEntry.PerSizeTracking) +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_aat_map.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_aat_map.go new file mode 100644 index 0000000..a276c89 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_aat_map.go @@ -0,0 +1,300 @@ +package harfbuzz + +import ( + "sort" + + "github.com/go-text/typesetting/font" + ot "github.com/go-text/typesetting/font/opentype" +) + +// ported from harfbuzz/src/hb-aat-map.cc, hb-att-map.hh Copyright © 2018 Google, Inc. Behdad Esfahbod + +type rangeFlags struct { + flags GlyphMask + clusterFirst int + clusterLast int // end - 1 +} + +type aatMap struct { + chainFlags [][]rangeFlags +} + +func (map_ *aatMap) resizeChainFlags(N int) { + if cap(map_.chainFlags) >= N { + map_.chainFlags = map_.chainFlags[0:N] + } else { + map_.chainFlags = make([][]rangeFlags, N) + } +} + +type aatFeatureRange struct { + info aatFeatureInfo + start, end int +} + +type aatFeatureEvent struct { + index int + start bool + feature aatFeatureInfo +} + +func (a aatFeatureEvent) isLess(b aatFeatureEvent) bool { + if a.index < b.index { + return true + } else if a.index > b.index { + return false + } else { + if !a.start && b.start { + return true + } else if a.start && !b.start { + return false + } + return a.feature.isLess(b.feature) + } +} + +type aatFeatureInfo struct { + type_ aatLayoutFeatureType + setting aatLayoutFeatureSelector + isExclusive bool +} + +func (fi aatFeatureInfo) key() uint32 { + return uint32(fi.type_)<<16 | uint32(fi.setting) +} + +const selMask = ^aatLayoutFeatureSelector(1) + +func (a aatFeatureInfo) isLess(b aatFeatureInfo) bool { + if a.type_ != b.type_ { + return a.type_ < b.type_ + } + if !a.isExclusive && (a.setting&selMask) != (b.setting&selMask) { + return a.setting < b.setting + } + return false +} + +type aatMapBuilder struct { + tables *font.Font + props SegmentProperties + + features []aatFeatureRange + currentFeatures []aatFeatureInfo // sorted by (type_, setting) after compilation + rangeFirst int + rangeLast int +} + +func newAatMapBuilder(tables *font.Font, props SegmentProperties) aatMapBuilder { + return aatMapBuilder{ + tables: tables, + props: props, + rangeFirst: FeatureGlobalStart, + rangeLast: FeatureGlobalEnd, + } +} + +// binary search into `currentFeatures`, comparing type_ and setting only +func (mb *aatMapBuilder) hasFeature(info aatFeatureInfo) bool { + key := info.key() + for i, j := 0, len(mb.currentFeatures); i < j; { + h := i + (j-i)/2 + entry := mb.currentFeatures[h].key() + if key < entry { + j = h + } else if entry < key { + i = h + 1 + } else { + return true + } + } + return false +} + +func (mb *aatMapBuilder) compileMap(map_ *aatMap) { + morx := mb.tables.Morx + map_.resizeChainFlags(len(morx)) + for i, chain := range morx { + map_.chainFlags[i] = append(map_.chainFlags[i], rangeFlags{ + flags: mb.compileMorxFlag(chain), + clusterFirst: mb.rangeFirst, + clusterLast: mb.rangeLast, + }) + } + + // TODO: for now we dont support deprecated mort table + // mort := mapper.face.table.mort + // if mort.has_data() { + // mort.compile_flags(mapper, map_) + // return + // } +} + +func (mb *aatMapBuilder) compileMorxFlag(chain font.MorxChain) GlyphMask { + flags := chain.DefaultFlags + + for _, feature := range chain.Features { + type_, setting := feature.FeatureType, feature.FeatureSetting + + retry: + // Check whether this type_/setting pair was requested in the map, and if so, apply its flags. + // (The search here only looks at the type_ and setting fields of feature_info_t.) + info := aatFeatureInfo{type_, setting, false} + if mb.hasFeature(info) { + flags &= feature.DisableFlags + flags |= feature.EnableFlags + } else if type_ == aatLayoutFeatureTypeLetterCase && setting == aatLayoutFeatureSelectorSmallCaps { + /* Deprecated. https://github.com/harfbuzz/harfbuzz/issues/1342 */ + type_ = aatLayoutFeatureTypeLowerCase + setting = aatLayoutFeatureSelectorLowerCaseSmallCaps + goto retry + } else if type_ == aatLayoutFeatureTypeLanguageTagType && setting != 0 && langMatches(string(mb.tables.Ltag.Language(setting-1)), string(mb.props.Language)) { + flags &= feature.DisableFlags + flags |= feature.EnableFlags + } + } + return flags +} + +func (mb *aatMapBuilder) addFeature(feature Feature) { + feat := mb.tables.Feat + if len(feat.Names) == 0 { + return + } + + if feature.Tag == ot.NewTag('a', 'a', 'l', 't') { + if fn := feat.GetFeature(aatLayoutFeatureTypeCharacterAlternatives); fn == nil || len(fn.SettingTable) == 0 { + return + } + range_ := aatFeatureRange{ + info: aatFeatureInfo{ + type_: aatLayoutFeatureTypeCharacterAlternatives, + setting: aatLayoutFeatureSelector(feature.Value), + isExclusive: true, + }, + start: feature.Start, + end: feature.End, + } + mb.features = append(mb.features, range_) + return + } + + mapping := aatLayoutFindFeatureMapping(feature.Tag) + if mapping == nil { + return + } + + featureName := feat.GetFeature(mapping.aatFeatureType) + if featureName == nil || len(featureName.SettingTable) == 0 { + /* Special case: compileMorxFlag() will fall back to the deprecated version of + * small-caps if necessary, so we need to check for that possibility. + * https://github.com/harfbuzz/harfbuzz/issues/2307 */ + if mapping.aatFeatureType == aatLayoutFeatureTypeLowerCase && + mapping.selectorToEnable == aatLayoutFeatureSelectorLowerCaseSmallCaps { + featureName = feat.GetFeature(aatLayoutFeatureTypeLetterCase) + if featureName == nil || len(featureName.SettingTable) == 0 { + return + } + } else { + return + } + } + + var info aatFeatureInfo + info.type_ = mapping.aatFeatureType + if feature.Value != 0 { + info.setting = mapping.selectorToEnable + } else { + info.setting = mapping.selectorToDisable + } + info.isExclusive = featureName.IsExclusive() + mb.features = append(mb.features, aatFeatureRange{ + info: info, + start: feature.Start, + end: feature.End, + }) +} + +func (mb *aatMapBuilder) compile(m *aatMap) { + // Compute active features per range, and compile each. + + // Sort features by start/end events. + var featureEvents []aatFeatureEvent + for _, feature := range mb.features { + if feature.start == feature.end { + continue + } + + featureEvents = append(featureEvents, aatFeatureEvent{ + index: feature.start, + start: true, + feature: feature.info, + }, aatFeatureEvent{ + index: feature.end, + start: false, + feature: feature.info, + }) + } + sort.SliceStable(featureEvents, func(i, j int) bool { return featureEvents[i].isLess(featureEvents[j]) }) + + // Add a strategic final event. + { + featureEvents = append(featureEvents, aatFeatureEvent{ + index: -1, /* This value does magic. */ + start: false, + feature: aatFeatureInfo{}, + }) + } + + // Scan events and save features for each range. + var activeFeatures []aatFeatureInfo + lastIndex := 0 + for _, event := range featureEvents { + if event.index != lastIndex { + // Save a snapshot of active features and the range. + + // sort features and merge duplicates + mb.currentFeatures = activeFeatures + mb.rangeFirst = lastIndex + mb.rangeLast = event.index - 1 + if len(mb.currentFeatures) != 0 { + sort.SliceStable(mb.currentFeatures, func(i, j int) bool { + return mb.currentFeatures[i].isLess(mb.currentFeatures[j]) + }) + j := 0 + for i := 1; i < len(mb.currentFeatures); i++ { + /* Nonexclusive feature selectors come in even/odd pairs to turn a setting on/off + * respectively, so we mask out the low-order bit when checking for "duplicates" + * (selectors referring to the same feature setting) here. */ + if mb.currentFeatures[i].type_ != mb.currentFeatures[j].type_ || + (!mb.currentFeatures[i].isExclusive && ((mb.currentFeatures[i].setting & selMask) != (mb.currentFeatures[j].setting & selMask))) { + j++ + mb.currentFeatures[j] = mb.currentFeatures[i] + } + } + mb.currentFeatures = mb.currentFeatures[:j+1] + } + + mb.compileMap(m) + + lastIndex = event.index + } + + if event.start { + activeFeatures = append(activeFeatures, event.feature) + } else { + for i, f := range activeFeatures { + if f.key() == event.feature.key() { + // remove the item + activeFeatures = append(activeFeatures[:i], activeFeatures[i+1:]...) + break + } + } + } + } + + for _, chainFlags := range m.chainFlags { + // With our above setup this value is one less than desired; adjust it. + chainFlags[len(chainFlags)-1].clusterLast = FeatureGlobalEnd + } +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_arabic.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_arabic.go new file mode 100644 index 0000000..f854ab1 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_arabic.go @@ -0,0 +1,900 @@ +package harfbuzz + +import ( + "fmt" + "sort" + + "github.com/go-text/typesetting/font" + ot "github.com/go-text/typesetting/font/opentype" + "github.com/go-text/typesetting/font/opentype/tables" + "github.com/go-text/typesetting/language" +) + +// ported from harfbuzz/src/hb-ot-shape-complex-arabic.cc, hb-ot-shape-complex-arabic-fallback.hh Copyright © 2010,2012 Google, Inc. Behdad Esfahbod + +var _ otComplexShaper = (*complexShaperArabic)(nil) + +const flagArabicHasStch = bsfShaper0 + +/* See: + * https://github.com/harfbuzz/harfbuzz/commit/6e6f82b6f3dde0fc6c3c7d991d9ec6cfff57823d#commitcomment-14248516 */ +func isWord(genCat generalCategory) bool { + const mask = 1<= joiningTypeR { + buffer.unsafeToConcatFromOutbuffer(0, i+1) + } + } else { + if thisType >= joiningTypeR || + (2 <= state && state <= 5) /* States that have a possible prevAction. */ { + buffer.unsafeToConcat(prev, i+1) + } + } + } + + info[i].complexAux = entry.currAction + + prev = i + state = entry.nextState + } + + for _, u := range buffer.context[1] { + thisType := getJoiningType(u, uni.generalCategory(u)) + + if thisType == joiningTypeT { + continue + } + + entry := &arabicStateTable[state][thisType] + if entry.prevAction != arabNone && prev != -1 { + info[prev].complexAux = entry.prevAction + buffer.safeToInsertTatweel(prev, len(buffer.Info)) + } else if 2 <= state && state <= 5 /* States that have a possible prevAction. */ { + buffer.unsafeToConcat(prev, len(buffer.Info)) + } + break + } +} + +func mongolianVariationSelectors(buffer *Buffer) { + // copy complexAux from base to Mongolian variation selectors. + info := buffer.Info + for i := 1; i < len(info); i++ { + if cp := info[i].codepoint; 0x180B <= cp && cp <= 0x180D || cp == 0x180F { + info[i].complexAux = info[i-1].complexAux + } + } +} + +func (arabicPlan arabicShapePlan) setupMasks(buffer *Buffer, script language.Script) { + applyArabicJoining(buffer) + if script == language.Mongolian { + mongolianVariationSelectors(buffer) + } + + info := buffer.Info + for i := range info { + info[i].Mask |= arabicPlan.maskArray[info[i].complexAux] + } +} + +func (cs *complexShaperArabic) setupMasks(plan *otShapePlan, buffer *Buffer, _ *Font) { + cs.plan.setupMasks(buffer, plan.props.Script) +} + +func arabicFallbackShape(plan *otShapePlan, font *Font, buffer *Buffer) bool { + arabicPlan := plan.shaper.(*complexShaperArabic).plan + + if !arabicPlan.doFallback { + return false + } + + fallbackPlan := arabicPlan.fallbackPlan + if fallbackPlan == nil { + // this sucks. We need a font to build the fallback plan... + fallbackPlan = newArabicFallbackPlan(plan, font) + } + + fallbackPlan.shape(font, buffer) + return true +} + +// +// Stretch feature: "stch". +// See example here: +// https://docs.microsoft.com/en-us/typography/script-development/syriac +// We implement this in a generic way, such that the Arabic subtending +// marks can use it as well. +// + +func recordStch(plan *otShapePlan, _ *Font, buffer *Buffer) bool { + arabicPlan := plan.shaper.(*complexShaperArabic).plan + if !arabicPlan.hasStch { + return false + } + + /* 'stch' feature was just applied. Look for anything that multiplied, + * and record it for stch treatment later. Note that rtlm, frac, etc + * are applied before stch, but we assume that they didn't result in + * anything multiplying into 5 pieces, so it's safe-ish... */ + + info := buffer.Info + for i := range info { + if info[i].multiplied() { + comp := info[i].getLigComp() + if comp%2 != 0 { + info[i].complexAux = arabStchRepeating + } else { + info[i].complexAux = arabStchFixed + } + buffer.scratchFlags |= flagArabicHasStch + } + } + + return false +} + +func inRange(sa uint8) bool { + return arabStchFixed <= sa && sa <= arabStchRepeating +} + +func (cs *complexShaperArabic) postprocessGlyphs(plan *otShapePlan, buffer *Buffer, font *Font) { + if buffer.scratchFlags&flagArabicHasStch == 0 { + return + } + + /* The Arabic shaper currently always processes in RTL mode, so we should + * stretch / position the stretched pieces to the left / preceding glyphs. */ + + /* We do a two pass implementation: + * First pass calculates the exact number of extra glyphs we need, + * We then enlarge buffer to have that much room, + * Second pass applies the stretch, copying things to the end of buffer. */ + + sign := Position(+1) + if font.XScale < 0 { + sign = -1 + } + const ( + MEASURE = iota + CUT + ) + var ( + originCount = len(buffer.Info) // before enlarging + extraGlyphsNeeded = 0 // Set during MEASURE, used during CUT + ) + for step := MEASURE; step <= CUT; step++ { + info := buffer.Info + pos := buffer.Pos + j := len(info) // enlarged after MEASURE + for i := originCount; i != 0; i-- { + if sa := info[i-1].complexAux; !inRange(sa) { + if step == CUT { + j-- + info[j] = info[i-1] + pos[j] = pos[i-1] + } + continue + } + + /* Yay, justification! */ + var ( + wTotal Position // Total to be filled + wFixed Position // Sum of fixed tiles + wRepeating Position // Sum of repeating tiles + nFixed = 0 + nRepeating = 0 + ) + end := i + for i != 0 && inRange(info[i-1].complexAux) { + i-- + width := font.GlyphHAdvance(info[i].Glyph) + if info[i].complexAux == arabStchFixed { + wFixed += width + nFixed++ + } else { + wRepeating += width + nRepeating++ + } + } + start := i + context := i + for context != 0 && !inRange(info[context-1].complexAux) && + ((&info[context-1]).isDefaultIgnorable() || + isWord((&info[context-1]).unicode.generalCategory())) { + context-- + wTotal += pos[context].XAdvance + } + i++ // Don't touch i again. + + if debugMode { + fmt.Printf("ARABIC - step %d: stretch at (%d,%d,%d)\n", step+1, context, start, end) + fmt.Printf("ARABIC - rest of word: count=%d width %d\n", start-context, wTotal) + fmt.Printf("ARABIC - fixed tiles: count=%d width=%d\n", nFixed, wFixed) + fmt.Printf("ARABIC - repeating tiles: count=%d width=%d\n", nRepeating, wRepeating) + } + + // number of additional times to repeat each repeating tile. + var nCopies int + + wRemaining := wTotal - wFixed + if sign*wRemaining > sign*wRepeating && sign*wRepeating > 0 { + nCopies = int((sign*wRemaining)/(sign*wRepeating) - 1) + } + + // see if we can improve the fit by adding an extra repeat and squeezing them together a bit. + var extraRepeatOverlap Position + shortfall := sign*wRemaining - sign*wRepeating*(Position(nCopies)+1) + if shortfall > 0 && nRepeating > 0 { + nCopies++ + excess := (Position(nCopies)+1)*sign*wRepeating - sign*wRemaining + if excess > 0 { + extraRepeatOverlap = excess / Position(nCopies*nRepeating) + } + } + + if step == MEASURE { + extraGlyphsNeeded += nCopies * nRepeating + if debugMode { + fmt.Printf("ARABIC - will add extra %d copies of repeating tiles\n", nCopies) + } + } else { + buffer.unsafeToBreak(context, end) + var xOffset Position + for k := end; k > start; k-- { + width := font.GlyphHAdvance(info[k-1].Glyph) + + repeat := 1 + if info[k-1].complexAux == arabStchRepeating { + repeat += nCopies + } + + if debugMode { + fmt.Printf("ARABIC - appending %d copies of glyph %d; j=%d\n", repeat, info[k-1].codepoint, j) + } + for n := 0; n < repeat; n++ { + xOffset -= width + if n > 0 { + xOffset += extraRepeatOverlap + } + pos[k-1].XOffset = xOffset + // append copy. + j-- + info[j] = info[k-1] + pos[j] = pos[k-1] + } + } + } + } + + if step == MEASURE { // enlarge + buffer.Info = append(buffer.Info, make([]GlyphInfo, extraGlyphsNeeded)...) + buffer.Pos = append(buffer.Pos, make([]GlyphPosition, extraGlyphsNeeded)...) + } + } +} + +// https://www.unicode.org/reports/tr53/ +var modifierCombiningMarks = [...]rune{ + 0x0654, /* ARABIC HAMZA ABOVE */ + 0x0655, /* ARABIC HAMZA BELOW */ + 0x0658, /* ARABIC MARK NOON GHUNNA */ + 0x06DC, /* ARABIC SMALL HIGH SEEN */ + 0x06E3, /* ARABIC SMALL LOW SEEN */ + 0x06E7, /* ARABIC SMALL HIGH YEH */ + 0x06E8, /* ARABIC SMALL HIGH NOON */ + 0x08CA, /* ARABIC SMALL HIGH FARSI YEH */ + 0x08CB, /* ARABIC SMALL HIGH YEH BARREE WITH TWO DOTS BELOW */ + 0x08CD, /* ARABIC SMALL HIGH ZAH */ + 0x08CE, /* ARABIC LARGE ROUND DOT ABOVE */ + 0x08CF, /* ARABIC LARGE ROUND DOT BELOW */ + 0x08D3, /* ARABIC SMALL LOW WAW */ + 0x08F3, /* ARABIC SMALL HIGH WAW */ +} + +func infoIsMcm(info *GlyphInfo) bool { + u := info.codepoint + for i := 0; i < len(modifierCombiningMarks); i++ { + if u == modifierCombiningMarks[i] { + return true + } + } + return false +} + +func (cs *complexShaperArabic) reorderMarks(_ *otShapePlan, buffer *Buffer, start, end int) { + info := buffer.Info + + if debugMode { + fmt.Printf("ARABIC - Reordering marks from %d to %d\n", start, end) + } + + i := start + for cc := uint8(220); cc <= 230; cc += 10 { + if debugMode { + fmt.Printf("ARABIC - Looking for combining class %d's starting at %d\n", cc, i) + } + for i < end && info[i].getModifiedCombiningClass() < cc { + i++ + } + if debugMode { + fmt.Printf("ARABIC - Looking for %d's stopped at %d\n", cc, i) + } + + if i == end { + break + } + + if info[i].getModifiedCombiningClass() > cc { + continue + } + + j := i + for j < end && info[j].getModifiedCombiningClass() == cc && infoIsMcm(&info[j]) { + j++ + } + + if i == j { + continue + } + + if debugMode { + fmt.Printf("ARABIC - Found %d's from %d to %d", cc, i, j) + // shift it! + fmt.Printf("ARABIC - Shifting %d's: %d %d", cc, i, j) + } + + var temp [shapeComplexMaxCombiningMarks]GlyphInfo + // assert (j - i <= len (temp)); + buffer.mergeClusters(start, j) + copy(temp[:j-i], info[i:]) + copy(info[start+j-i:], info[start:i]) + copy(info[start:], temp[:j-i]) + + /* Renumber CC such that the reordered sequence is still sorted. + * 22 and 26 are chosen because they are smaller than all Arabic categories, + * and are folded back to 220/230 respectively during fallback mark positioning. + * + * We do this because the CGJ-handling logic in the normalizer relies on + * mark sequences having an increasing order even after this reordering. + * https://github.com/harfbuzz/harfbuzz/issues/554 + * This, however, does break some obscure sequences, where the normalizer + * might compose a sequence that it should not. For example, in the seequence + * ALEF, HAMZAH, MADDAH, we should NOT try to compose ALEF+MADDAH, but with this + * renumbering, we will. */ + newStart := start + j - i + newCc := mcc26 + if cc == 220 { + newCc = mcc26 + } + for start < newStart { + info[start].setModifiedCombiningClass(newCc) + start++ + } + + i = j + } +} + +// Features ordered the same as the entries in [arabicShaping] rows, +// followed by rlig. Don't change. +// We currently support one subtable per lookup, and one lookup +// per feature. But we allow duplicate features, so we use that! +var arabicFallbackFeatures = [...]ot.Tag{ + ot.NewTag('i', 'n', 'i', 't'), + ot.NewTag('m', 'e', 'd', 'i'), + ot.NewTag('f', 'i', 'n', 'a'), + ot.NewTag('i', 's', 'o', 'l'), + ot.NewTag('r', 'l', 'i', 'g'), + ot.NewTag('r', 'l', 'i', 'g'), + ot.NewTag('r', 'l', 'i', 'g'), +} + +// used to sort both array at the same time +type jointGlyphs struct { + glyphs, substitutes []gID +} + +func (a jointGlyphs) Len() int { return len(a.glyphs) } +func (a jointGlyphs) Swap(i, j int) { + a.glyphs[i], a.glyphs[j] = a.glyphs[j], a.glyphs[i] + a.substitutes[i], a.substitutes[j] = a.substitutes[j], a.substitutes[i] +} +func (a jointGlyphs) Less(i, j int) bool { return a.glyphs[i] < a.glyphs[j] } + +func arabicFallbackSynthesizeLookupSingle(ft *Font, featureIndex int) *lookupGSUB { + var glyphs, substitutes []gID + + // populate arrays + for u := rune(firstArabicShape); u <= lastArabicShape; u++ { + s := rune(arabicShaping[u-firstArabicShape][featureIndex]) + uGlyph, hasU := ft.face.NominalGlyph(u) + sGlyph, hasS := ft.face.NominalGlyph(s) + + if s == 0 || !hasU || !hasS || uGlyph == sGlyph || uGlyph > 0xFFFF || sGlyph > 0xFFFF { + continue + } + + glyphs = append(glyphs, gID(uGlyph)) + substitutes = append(substitutes, gID(sGlyph)) + } + + if len(glyphs) == 0 { + return nil + } + + sort.Stable(jointGlyphs{glyphs: glyphs, substitutes: substitutes}) + + return &lookupGSUB{ + LookupOptions: font.LookupOptions{Flag: otIgnoreMarks}, + Subtables: []tables.GSUBLookup{ + tables.SingleSubs{Data: tables.SingleSubstData2{ + Coverage: tables.Coverage1{Glyphs: glyphs}, + SubstituteGlyphIDs: substitutes, + }}, + }, + } +} + +// used to sort both array at the same time +type glyphsIndirections struct { + glyphs []gID + indirections []int +} + +func (a glyphsIndirections) Len() int { return len(a.glyphs) } +func (a glyphsIndirections) Swap(i, j int) { + a.glyphs[i], a.glyphs[j] = a.glyphs[j], a.glyphs[i] + a.indirections[i], a.indirections[j] = a.indirections[j], a.indirections[i] +} +func (a glyphsIndirections) Less(i, j int) bool { return a.glyphs[i] < a.glyphs[j] } + +func arabicFallbackSynthesizeLookupLigature(ft *Font, ligatureTable []arabicTableEntry, lookupFlags uint16) *lookupGSUB { + var ( + firstGlyphs []gID + firstGlyphsIndirection []int // original index into ArabicLigatures + ) + + // Populate arrays + + // sort out the first-glyphs + for firstGlyphIdx, lig := range ligatureTable { + firstGlyph, ok := ft.face.NominalGlyph(lig.First) + if !ok { + continue + } + firstGlyphs = append(firstGlyphs, gID(firstGlyph)) + firstGlyphsIndirection = append(firstGlyphsIndirection, firstGlyphIdx) + } + + if len(firstGlyphs) == 0 { + return nil + } + + sort.Stable(glyphsIndirections{glyphs: firstGlyphs, indirections: firstGlyphsIndirection}) + + var out tables.LigatureSubs + out.Coverage = tables.Coverage1{Glyphs: firstGlyphs} + + // now that the first-glyphs are sorted, walk again, populate ligatures. + for _, firstGlyphIdx := range firstGlyphsIndirection { + ligs := ligatureTable[firstGlyphIdx].Ligatures + var ligatureSet tables.LigatureSet + for _, v := range ligs { + ligatureU := v.ligature + ligatureGlyph, hasLigature := ft.face.NominalGlyph(ligatureU) + if !hasLigature { + continue + } + + components := v.components + var componentGIDs []gID + for _, componentU := range components { + componentGlyph, hasComponent := ft.face.NominalGlyph(componentU) + if !hasComponent { + break + } + componentGIDs = append(componentGIDs, gID(componentGlyph)) + } + + if len(components) != len(componentGIDs) { + continue + } + + ligatureSet.Ligatures = append(ligatureSet.Ligatures, tables.Ligature{ + LigatureGlyph: gID(ligatureGlyph), + ComponentGlyphIDs: componentGIDs, // ligatures are 2-component + }) + } + out.LigatureSets = append(out.LigatureSets, ligatureSet) + } + + return &lookupGSUB{ + LookupOptions: font.LookupOptions{Flag: lookupFlags}, + Subtables: []tables.GSUBLookup{ + out, + }, + } +} + +func arabicFallbackSynthesizeLookup(font *Font, featureIndex int) *lookupGSUB { + switch featureIndex { + case 0, 1, 2, 3: + return arabicFallbackSynthesizeLookupSingle(font, featureIndex) + case 4: + return arabicFallbackSynthesizeLookupLigature(font, arabicLigature3Table[:], otIgnoreMarks) + case 5: + return arabicFallbackSynthesizeLookupLigature(font, arabicLigatureTable[:], otIgnoreMarks) + case 6: + return arabicFallbackSynthesizeLookupLigature(font, arabicLigatureMarkTable[:], 0) + default: + panic("unexpected arabic fallback feature index") + } +} + +const arabicFallbackMaxLookups = len(arabicFallbackFeatures) + +type arabicFallbackPlan struct { + accelArray [arabicFallbackMaxLookups]otLayoutLookupAccelerator + numLookups int + maskArray [arabicFallbackMaxLookups]GlyphMask +} + +func (fbPlan *arabicFallbackPlan) initWin1256(plan *otShapePlan, font *Font) bool { + // does this font look like it's Windows-1256-encoded? + g1, _ := font.face.NominalGlyph(0x0627) /* ALEF */ + g2, _ := font.face.NominalGlyph(0x0644) /* LAM */ + g3, _ := font.face.NominalGlyph(0x0649) /* ALEF MAKSURA */ + g4, _ := font.face.NominalGlyph(0x064A) /* YEH */ + g5, _ := font.face.NominalGlyph(0x0652) /* SUKUN */ + if !(g1 == 199 && g2 == 225 && g3 == 236 && g4 == 237 && g5 == 250) { + return false + } + + var j int + for _, man := range arabicWin1256GsubLookups { + fbPlan.maskArray[j] = plan.map_.getMask1(man.tag) + if fbPlan.maskArray[j] != 0 { + if man.lookup != nil { + fbPlan.accelArray[j].init(*man.lookup) + j++ + } + } + } + + fbPlan.numLookups = j + + return j > 0 +} + +func (fbPlan *arabicFallbackPlan) initUnicode(plan *otShapePlan, font *Font) bool { + var j int + for i, feat := range arabicFallbackFeatures { + fbPlan.maskArray[j] = plan.map_.getMask1(feat) + if fbPlan.maskArray[j] != 0 { + lk := arabicFallbackSynthesizeLookup(font, i) + if lk != nil { + fbPlan.accelArray[j].init(*lk) + j++ + } + } + } + + fbPlan.numLookups = j + + return j > 0 +} + +func newArabicFallbackPlan(plan *otShapePlan, font *Font) *arabicFallbackPlan { + var fbPlan arabicFallbackPlan + + /* Try synthesizing GSUB table using Unicode Arabic Presentation Forms, + * in case the font has cmap entries for the presentation-forms characters. */ + if fbPlan.initUnicode(plan, font) { + return &fbPlan + } + + /* See if this looks like a Windows-1256-encoded font. If it does, use a + * hand-coded GSUB table. */ + if fbPlan.initWin1256(plan, font) { + return &fbPlan + } + + return &arabicFallbackPlan{} +} + +func (fbPlan *arabicFallbackPlan) shape(font *Font, buffer *Buffer) { + var c otApplyContext + c.reset(0, font, buffer) + for i := 0; i < fbPlan.numLookups; i++ { + if fbPlan.accelArray[i].lookup != nil { + c.setLookupMask(fbPlan.maskArray[i]) + c.substituteLookup(&fbPlan.accelArray[i]) + } + } +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_arabic_pua_table.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_arabic_pua_table.go new file mode 100644 index 0000000..0cd764e --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_arabic_pua_table.go @@ -0,0 +1,161 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package harfbuzz + +// Code generated by typesettings-utils/generators/unicodedata/cmd/main.go DO NOT EDIT. + +// Legacy Simplified Arabic encoding. Returns 0 if not found. +func arabicPUASimpMap(r rune) rune { + switch { + case 0x20 <= r && r <= 0x22: + return [...]rune{0xf120, 0xf121, 0xf122}[r-0x20] + case 0x25 == r: + return 0xf125 + case 0x28 <= r && r <= 0x3b: + return [...]rune{0xf128, 0xf129, 0xf12a, 0xf12b, 0xf15e, 0xf12d, 0xf12e, 0xf12f, 0xf1b0, 0xf1b1, 0xf1b2, 0xf1b3, 0xf1b4, 0xf1b5, 0xf1b6, 0xf1b7, 0xf1b8, 0xf1b9, 0xf13a, 0xf13b}[r-0x28] + case 0x3d == r: + return 0xf13d + case 0x3f == r: + return 0xf13f + case 0x5b <= r && r <= 0x5d: + return [...]rune{0xf15b, 0xf15c, 0xf15d}[r-0x5b] + case 0xab == r: + return 0xf123 + case 0xbb == r: + return 0xf124 + case 0xd7 == r: + return 0xf126 + case 0xf7 == r: + return 0xf127 + case 0x60c == r: + return 0xf12c + case 0x61b == r: + return 0xf13b + case 0x61f == r: + return 0xf13f + case 0x621 <= r && r <= 0x65e: + return [...]rune{0xf1ad, 0xf145, 0xf143, 0xf1bb, 0xf147, 0xf1ba, 0xf141, 0xf14a, 0xf1a9, 0xf14c, 0xf14e, 0xf151, 0xf154, 0xf157, 0xf158, 0xf159, 0xf15a, 0xf160, 0xf162, 0xf164, 0xf166, 0xf168, 0xf169, 0xf16a, 0xf16e, 0xf172, 0xf100, 0xf100, 0xf100, 0xf100, 0xf100, 0xf15f, 0xf175, 0xf178, 0xf17a, 0xf17c, 0xf17e, 0xf1e1, 0xf1a4, 0xf1a5, 0xf1ac, 0xf1a8, 0xf1c7, 0xf1c8, 0xf1cb, 0xf1c4, 0xf1c5, 0xf1ca, 0xf1c9, 0xf1c6, 0xf100, 0xf100, 0xf100, 0xf100, 0xf100, 0xf100, 0xf100, 0xf100, 0xf100, 0xf100, 0xf100, 0xf100}[r-0x621] + case 0x660 <= r && r <= 0x669: + return [...]rune{0xf130, 0xf131, 0xf132, 0xf133, 0xf134, 0xf135, 0xf136, 0xf137, 0xf138, 0xf139}[r-0x660] + case 0x66b <= r && r <= 0x66c: + return [...]rune{0xf15e, 0xf15e}[r-0x66b] + case 0x200c <= r && r <= 0x200f: + return [...]rune{0xf10c, 0xf10d, 0xf10e, 0xf10f}[r-0x200c] + case 0x2018 <= r && r <= 0x2019: + return [...]rune{0xf13c, 0xf13e}[r-0x2018] + case 0xfe81 <= r && r <= 0xfefc: + return [...]rune{0xf145, 0xf146, 0xf143, 0xf144, 0xf1bb, 0xf1bb, 0xf147, 0xf148, 0xf1ba, 0xf1af, 0xf1ae, 0xf1ae, 0xf141, 0xf142, 0xf14a, 0xf14a, 0xf149, 0xf149, 0xf1a9, 0xf1aa, 0xf14c, 0xf14c, 0xf14b, 0xf14b, 0xf14e, 0xf14e, 0xf14d, 0xf14d, 0xf151, 0xf150, 0xf14f, 0xf14f, 0xf154, 0xf153, 0xf152, 0xf152, 0xf157, 0xf156, 0xf155, 0xf155, 0xf158, 0xf158, 0xf159, 0xf159, 0xf15a, 0xf15a, 0xf160, 0xf160, 0xf162, 0xf162, 0xf161, 0xf161, 0xf164, 0xf164, 0xf163, 0xf163, 0xf166, 0xf166, 0xf165, 0xf165, 0xf168, 0xf168, 0xf167, 0xf167, 0xf169, 0xf169, 0xf169, 0xf169, 0xf16a, 0xf16a, 0xf16a, 0xf16a, 0xf16e, 0xf16d, 0xf16b, 0xf16c, 0xf172, 0xf171, 0xf16f, 0xf170, 0xf175, 0xf175, 0xf173, 0xf174, 0xf178, 0xf178, 0xf176, 0xf177, 0xf17a, 0xf17a, 0xf179, 0xf179, 0xf17c, 0xf17c, 0xf17b, 0xf17b, 0xf17e, 0xf17e, 0xf17d, 0xf17d, 0xf1e1, 0xf1e1, 0xf17f, 0xf17f, 0xf1a4, 0xf1a3, 0xf1a1, 0xf1a2, 0xf1a5, 0xf1a5, 0xf1ac, 0xf1ab, 0xf1a8, 0xf1a7, 0xf1a6, 0xf1a6, 0xf1c0, 0xf1c1, 0xf1be, 0xf1bf, 0xf1c2, 0xf1c3, 0xf1bd, 0xf1bc}[r-0xfe81] + } + return 0 +} + +// Legacy Traditional Arabic encoding. Returns 0 if not found. +func arabicPUATradMap(r rune) rune { + switch { + case 0x20 <= r && r <= 0x22: + return [...]rune{0xf220, 0xf221, 0xf222}[r-0x20] + case 0x25 == r: + return 0xf225 + case 0x28 <= r && r <= 0x2f: + return [...]rune{0xf228, 0xf229, 0xf22a, 0xf22b, 0xf25e, 0xf22d, 0xf22e, 0xf22f}[r-0x28] + case 0x3a <= r && r <= 0x3b: + return [...]rune{0xf23a, 0xf23b}[r-0x3a] + case 0x3d == r: + return 0xf23d + case 0x3f == r: + return 0xf23f + case 0x5b == r: + return 0xf25b + case 0x5d == r: + return 0xf25d + case 0xab == r: + return 0xf223 + case 0xbb == r: + return 0xf224 + case 0xd7 == r: + return 0xf226 + case 0xf7 == r: + return 0xf227 + case 0x60c == r: + return 0xf22c + case 0x61b == r: + return 0xf23b + case 0x61f == r: + return 0xf23f + case 0x621 <= r && r <= 0x65e: + return [...]rune{0xf2d5, 0xf245, 0xf243, 0xf2da, 0xf247, 0xf2d9, 0xf241, 0xf24c, 0xf2d1, 0xf250, 0xf254, 0xf258, 0xf260, 0xf264, 0xf265, 0xf267, 0xf269, 0xf26b, 0xf270, 0xf274, 0xf278, 0xf27e, 0xf2a2, 0xf2a3, 0xf2aa, 0xf2ae, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf25f, 0xf2b2, 0xf2b6, 0xf2ba, 0xf2be, 0xf2c2, 0xf2c6, 0xf2ca, 0xf2cb, 0xf2d4, 0xf2d0, 0xf2e7, 0xf2e8, 0xf2eb, 0xf2e4, 0xf2e5, 0xf2ea, 0xf2e9, 0xf2e6, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200}[r-0x621] + case 0x660 <= r && r <= 0x669: + return [...]rune{0xf230, 0xf231, 0xf232, 0xf233, 0xf234, 0xf235, 0xf236, 0xf237, 0xf238, 0xf239}[r-0x660] + case 0x66b <= r && r <= 0x66c: + return [...]rune{0xf25e, 0xf25e}[r-0x66b] + case 0x200c <= r && r <= 0x200f: + return [...]rune{0xf20c, 0xf20d, 0xf20e, 0xf20f}[r-0x200c] + case 0x201c <= r && r <= 0x201d: + return [...]rune{0xf23c, 0xf23e}[r-0x201c] + case 0xfc08 == r: + return 0xf202 + case 0xfc0a == r: + return 0xf21d + case 0xfc0e == r: + return 0xf203 + case 0xfc10 == r: + return 0xf21e + case 0xfc12 == r: + return 0xf204 + case 0xfc32 == r: + return 0xf29f + case 0xfc3f <= r && r <= 0xfc42: + return [...]rune{0xf212, 0xf213, 0xf214, 0xf205}[r-0xfc3f] + case 0xfc44 == r: + return 0xf21c + case 0xfc4e == r: + return 0xf206 + case 0xfc50 == r: + return 0xf21f + case 0xfc5e == r: + return 0xf2ef + case 0xfc60 <= r && r <= 0xfc62: + return [...]rune{0xf2ec, 0xf2ed, 0xf2f0}[r-0xfc60] + case 0xfc6a == r: + return 0xf215 + case 0xfc6d == r: + return 0xf292 + case 0xfc70 == r: + return 0xf216 + case 0xfc73 == r: + return 0xf293 + case 0xfc86 == r: + return 0xf295 + case 0xfc91 == r: + return 0xf217 + case 0xfc94 == r: + return 0xf294 + case 0xfc9c <= r && r <= 0xfc9f: + return [...]rune{0xf280, 0xf281, 0xf282, 0xf296}[r-0xfc9c] + case 0xfca1 <= r && r <= 0xfca4: + return [...]rune{0xf283, 0xf284, 0xf285, 0xf297}[r-0xfca1] + case 0xfca8 == r: + return 0xf29a + case 0xfcaa == r: + return 0xf29b + case 0xfcac == r: + return 0xf29c + case 0xfcb0 == r: + return 0xf218 + case 0xfcc9 <= r && r <= 0xfcd3: + return [...]rune{0xf286, 0xf287, 0xf288, 0xf29d, 0xf21a, 0xf289, 0xf28a, 0xf28b, 0xf29e, 0xf28d, 0xf28e}[r-0xfcc9] + case 0xfcd5 == r: + return 0xf298 + case 0xfcda <= r && r <= 0xfcdd: + return [...]rune{0xf28f, 0xf290, 0xf291, 0xf299}[r-0xfcda] + case 0xfd30 == r: + return 0xf219 + case 0xfd3e <= r && r <= 0xfd3f: + return [...]rune{0xf27b, 0xf27d}[r-0xfd3e] + case 0xfd88 == r: + return 0xf210 + case 0xfe81 <= r && r <= 0xfefc: + return [...]rune{0xf245, 0xf246, 0xf243, 0xf244, 0xf2da, 0xf2db, 0xf247, 0xf248, 0xf2d9, 0xf2d8, 0xf2d6, 0xf2d7, 0xf241, 0xf242, 0xf24c, 0xf24b, 0xf249, 0xf24a, 0xf2d1, 0xf2d2, 0xf250, 0xf24f, 0xf24d, 0xf24e, 0xf254, 0xf253, 0xf251, 0xf252, 0xf258, 0xf257, 0xf255, 0xf256, 0xf260, 0xf25c, 0xf259, 0xf25a, 0xf264, 0xf263, 0xf261, 0xf262, 0xf265, 0xf266, 0xf267, 0xf268, 0xf269, 0xf26a, 0xf26b, 0xf26c, 0xf270, 0xf26f, 0xf26d, 0xf26e, 0xf274, 0xf273, 0xf271, 0xf272, 0xf278, 0xf277, 0xf275, 0xf276, 0xf27e, 0xf27c, 0xf279, 0xf27a, 0xf2a2, 0xf2a1, 0xf27f, 0xf2f1, 0xf2a6, 0xf2a5, 0xf2a3, 0xf2a4, 0xf2aa, 0xf2a9, 0xf2a7, 0xf2a8, 0xf2ae, 0xf2ad, 0xf2ab, 0xf2ac, 0xf2b2, 0xf2b1, 0xf2af, 0xf2b0, 0xf2b6, 0xf2b5, 0xf2b3, 0xf2b4, 0xf2ba, 0xf2b9, 0xf2b7, 0xf2b8, 0xf2be, 0xf2bd, 0xf2bb, 0xf2bc, 0xf2c2, 0xf2c1, 0xf2bf, 0xf2c0, 0xf2c6, 0xf2c5, 0xf2c3, 0xf2c4, 0xf2ca, 0xf2c9, 0xf2c7, 0xf2c8, 0xf2cb, 0xf2cc, 0xf2d4, 0xf2d3, 0xf2d0, 0xf2cf, 0xf2cd, 0xf2ce, 0xf2e0, 0xf2e1, 0xf2de, 0xf2df, 0xf2e2, 0xf2e3, 0xf2dc, 0xf2dd}[r-0xfe81] + } + return 0 +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_arabic_table.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_arabic_table.go new file mode 100644 index 0000000..07bd61d --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_arabic_table.go @@ -0,0 +1,1165 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package harfbuzz + +// Code generated by typesettings-utils/generators/unicodedata/cmd/main.go DO NOT EDIT. + +import "github.com/go-text/typesetting/language" + +var arabicJoinings = map[rune]arabicJoining{ // 828 entries + 0x0600: 'U', + 0x0601: 'U', + 0x0602: 'U', + 0x0603: 'U', + 0x0604: 'U', + 0x0605: 'U', + 0x0608: 'U', + 0x060b: 'U', + 0x0620: 'D', + 0x0621: 'U', + 0x0622: 'R', + 0x0623: 'R', + 0x0624: 'R', + 0x0625: 'R', + 0x0626: 'D', + 0x0627: 'R', + 0x0628: 'D', + 0x0629: 'R', + 0x062a: 'D', + 0x062b: 'D', + 0x062c: 'D', + 0x062d: 'D', + 0x062e: 'D', + 0x062f: 'R', + 0x0630: 'R', + 0x0631: 'R', + 0x0632: 'R', + 0x0633: 'D', + 0x0634: 'D', + 0x0635: 'D', + 0x0636: 'D', + 0x0637: 'D', + 0x0638: 'D', + 0x0639: 'D', + 0x063a: 'D', + 0x063b: 'D', + 0x063c: 'D', + 0x063d: 'D', + 0x063e: 'D', + 0x063f: 'D', + 0x0640: 'C', + 0x0641: 'D', + 0x0642: 'D', + 0x0643: 'D', + 0x0644: 'D', + 0x0645: 'D', + 0x0646: 'D', + 0x0647: 'D', + 0x0648: 'R', + 0x0649: 'D', + 0x064a: 'D', + 0x066e: 'D', + 0x066f: 'D', + 0x0671: 'R', + 0x0672: 'R', + 0x0673: 'R', + 0x0674: 'U', + 0x0675: 'R', + 0x0676: 'R', + 0x0677: 'R', + 0x0678: 'D', + 0x0679: 'D', + 0x067a: 'D', + 0x067b: 'D', + 0x067c: 'D', + 0x067d: 'D', + 0x067e: 'D', + 0x067f: 'D', + 0x0680: 'D', + 0x0681: 'D', + 0x0682: 'D', + 0x0683: 'D', + 0x0684: 'D', + 0x0685: 'D', + 0x0686: 'D', + 0x0687: 'D', + 0x0688: 'R', + 0x0689: 'R', + 0x068a: 'R', + 0x068b: 'R', + 0x068c: 'R', + 0x068d: 'R', + 0x068e: 'R', + 0x068f: 'R', + 0x0690: 'R', + 0x0691: 'R', + 0x0692: 'R', + 0x0693: 'R', + 0x0694: 'R', + 0x0695: 'R', + 0x0696: 'R', + 0x0697: 'R', + 0x0698: 'R', + 0x0699: 'R', + 0x069a: 'D', + 0x069b: 'D', + 0x069c: 'D', + 0x069d: 'D', + 0x069e: 'D', + 0x069f: 'D', + 0x06a0: 'D', + 0x06a1: 'D', + 0x06a2: 'D', + 0x06a3: 'D', + 0x06a4: 'D', + 0x06a5: 'D', + 0x06a6: 'D', + 0x06a7: 'D', + 0x06a8: 'D', + 0x06a9: 'D', + 0x06aa: 'D', + 0x06ab: 'D', + 0x06ac: 'D', + 0x06ad: 'D', + 0x06ae: 'D', + 0x06af: 'D', + 0x06b0: 'D', + 0x06b1: 'D', + 0x06b2: 'D', + 0x06b3: 'D', + 0x06b4: 'D', + 0x06b5: 'D', + 0x06b6: 'D', + 0x06b7: 'D', + 0x06b8: 'D', + 0x06b9: 'D', + 0x06ba: 'D', + 0x06bb: 'D', + 0x06bc: 'D', + 0x06bd: 'D', + 0x06be: 'D', + 0x06bf: 'D', + 0x06c0: 'R', + 0x06c1: 'D', + 0x06c2: 'D', + 0x06c3: 'R', + 0x06c4: 'R', + 0x06c5: 'R', + 0x06c6: 'R', + 0x06c7: 'R', + 0x06c8: 'R', + 0x06c9: 'R', + 0x06ca: 'R', + 0x06cb: 'R', + 0x06cc: 'D', + 0x06cd: 'R', + 0x06ce: 'D', + 0x06cf: 'R', + 0x06d0: 'D', + 0x06d1: 'D', + 0x06d2: 'R', + 0x06d3: 'R', + 0x06d5: 'R', + 0x06dd: 'U', + 0x06ee: 'R', + 0x06ef: 'R', + 0x06fa: 'D', + 0x06fb: 'D', + 0x06fc: 'D', + 0x06ff: 'D', + 0x070f: 'T', + 0x0710: 'a', + 0x0712: 'D', + 0x0713: 'D', + 0x0714: 'D', + 0x0715: 'd', + 0x0716: 'd', + 0x0717: 'R', + 0x0718: 'R', + 0x0719: 'R', + 0x071a: 'D', + 0x071b: 'D', + 0x071c: 'D', + 0x071d: 'D', + 0x071e: 'R', + 0x071f: 'D', + 0x0720: 'D', + 0x0721: 'D', + 0x0722: 'D', + 0x0723: 'D', + 0x0724: 'D', + 0x0725: 'D', + 0x0726: 'D', + 0x0727: 'D', + 0x0728: 'R', + 0x0729: 'D', + 0x072a: 'd', + 0x072b: 'D', + 0x072c: 'R', + 0x072d: 'D', + 0x072e: 'D', + 0x072f: 'd', + 0x074d: 'R', + 0x074e: 'D', + 0x074f: 'D', + 0x0750: 'D', + 0x0751: 'D', + 0x0752: 'D', + 0x0753: 'D', + 0x0754: 'D', + 0x0755: 'D', + 0x0756: 'D', + 0x0757: 'D', + 0x0758: 'D', + 0x0759: 'R', + 0x075a: 'R', + 0x075b: 'R', + 0x075c: 'D', + 0x075d: 'D', + 0x075e: 'D', + 0x075f: 'D', + 0x0760: 'D', + 0x0761: 'D', + 0x0762: 'D', + 0x0763: 'D', + 0x0764: 'D', + 0x0765: 'D', + 0x0766: 'D', + 0x0767: 'D', + 0x0768: 'D', + 0x0769: 'D', + 0x076a: 'D', + 0x076b: 'R', + 0x076c: 'R', + 0x076d: 'D', + 0x076e: 'D', + 0x076f: 'D', + 0x0770: 'D', + 0x0771: 'R', + 0x0772: 'D', + 0x0773: 'R', + 0x0774: 'R', + 0x0775: 'D', + 0x0776: 'D', + 0x0777: 'D', + 0x0778: 'R', + 0x0779: 'R', + 0x077a: 'D', + 0x077b: 'D', + 0x077c: 'D', + 0x077d: 'D', + 0x077e: 'D', + 0x077f: 'D', + 0x07ca: 'D', + 0x07cb: 'D', + 0x07cc: 'D', + 0x07cd: 'D', + 0x07ce: 'D', + 0x07cf: 'D', + 0x07d0: 'D', + 0x07d1: 'D', + 0x07d2: 'D', + 0x07d3: 'D', + 0x07d4: 'D', + 0x07d5: 'D', + 0x07d6: 'D', + 0x07d7: 'D', + 0x07d8: 'D', + 0x07d9: 'D', + 0x07da: 'D', + 0x07db: 'D', + 0x07dc: 'D', + 0x07dd: 'D', + 0x07de: 'D', + 0x07df: 'D', + 0x07e0: 'D', + 0x07e1: 'D', + 0x07e2: 'D', + 0x07e3: 'D', + 0x07e4: 'D', + 0x07e5: 'D', + 0x07e6: 'D', + 0x07e7: 'D', + 0x07e8: 'D', + 0x07e9: 'D', + 0x07ea: 'D', + 0x07fa: 'C', + 0x0840: 'R', + 0x0841: 'D', + 0x0842: 'D', + 0x0843: 'D', + 0x0844: 'D', + 0x0845: 'D', + 0x0846: 'R', + 0x0847: 'R', + 0x0848: 'D', + 0x0849: 'R', + 0x084a: 'D', + 0x084b: 'D', + 0x084c: 'D', + 0x084d: 'D', + 0x084e: 'D', + 0x084f: 'D', + 0x0850: 'D', + 0x0851: 'D', + 0x0852: 'D', + 0x0853: 'D', + 0x0854: 'R', + 0x0855: 'D', + 0x0856: 'R', + 0x0857: 'R', + 0x0858: 'R', + 0x0860: 'D', + 0x0861: 'U', + 0x0862: 'D', + 0x0863: 'D', + 0x0864: 'D', + 0x0865: 'D', + 0x0866: 'U', + 0x0867: 'R', + 0x0868: 'D', + 0x0869: 'R', + 0x086a: 'R', + 0x0870: 'R', + 0x0871: 'R', + 0x0872: 'R', + 0x0873: 'R', + 0x0874: 'R', + 0x0875: 'R', + 0x0876: 'R', + 0x0877: 'R', + 0x0878: 'R', + 0x0879: 'R', + 0x087a: 'R', + 0x087b: 'R', + 0x087c: 'R', + 0x087d: 'R', + 0x087e: 'R', + 0x087f: 'R', + 0x0880: 'R', + 0x0881: 'R', + 0x0882: 'R', + 0x0883: 'C', + 0x0884: 'C', + 0x0885: 'C', + 0x0886: 'D', + 0x0887: 'U', + 0x0888: 'U', + 0x0889: 'D', + 0x088a: 'D', + 0x088b: 'D', + 0x088c: 'D', + 0x088d: 'D', + 0x088e: 'R', + 0x0890: 'U', + 0x0891: 'U', + 0x08a0: 'D', + 0x08a1: 'D', + 0x08a2: 'D', + 0x08a3: 'D', + 0x08a4: 'D', + 0x08a5: 'D', + 0x08a6: 'D', + 0x08a7: 'D', + 0x08a8: 'D', + 0x08a9: 'D', + 0x08aa: 'R', + 0x08ab: 'R', + 0x08ac: 'R', + 0x08ad: 'U', + 0x08ae: 'R', + 0x08af: 'D', + 0x08b0: 'D', + 0x08b1: 'R', + 0x08b2: 'R', + 0x08b3: 'D', + 0x08b4: 'D', + 0x08b5: 'D', + 0x08b6: 'D', + 0x08b7: 'D', + 0x08b8: 'D', + 0x08b9: 'R', + 0x08ba: 'D', + 0x08bb: 'D', + 0x08bc: 'D', + 0x08bd: 'D', + 0x08be: 'D', + 0x08bf: 'D', + 0x08c0: 'D', + 0x08c1: 'D', + 0x08c2: 'D', + 0x08c3: 'D', + 0x08c4: 'D', + 0x08c5: 'D', + 0x08c6: 'D', + 0x08c7: 'D', + 0x08c8: 'D', + 0x08e2: 'U', + 0x1806: 'U', + 0x1807: 'D', + 0x180a: 'C', + 0x180e: 'U', + 0x1820: 'D', + 0x1821: 'D', + 0x1822: 'D', + 0x1823: 'D', + 0x1824: 'D', + 0x1825: 'D', + 0x1826: 'D', + 0x1827: 'D', + 0x1828: 'D', + 0x1829: 'D', + 0x182a: 'D', + 0x182b: 'D', + 0x182c: 'D', + 0x182d: 'D', + 0x182e: 'D', + 0x182f: 'D', + 0x1830: 'D', + 0x1831: 'D', + 0x1832: 'D', + 0x1833: 'D', + 0x1834: 'D', + 0x1835: 'D', + 0x1836: 'D', + 0x1837: 'D', + 0x1838: 'D', + 0x1839: 'D', + 0x183a: 'D', + 0x183b: 'D', + 0x183c: 'D', + 0x183d: 'D', + 0x183e: 'D', + 0x183f: 'D', + 0x1840: 'D', + 0x1841: 'D', + 0x1842: 'D', + 0x1843: 'D', + 0x1844: 'D', + 0x1845: 'D', + 0x1846: 'D', + 0x1847: 'D', + 0x1848: 'D', + 0x1849: 'D', + 0x184a: 'D', + 0x184b: 'D', + 0x184c: 'D', + 0x184d: 'D', + 0x184e: 'D', + 0x184f: 'D', + 0x1850: 'D', + 0x1851: 'D', + 0x1852: 'D', + 0x1853: 'D', + 0x1854: 'D', + 0x1855: 'D', + 0x1856: 'D', + 0x1857: 'D', + 0x1858: 'D', + 0x1859: 'D', + 0x185a: 'D', + 0x185b: 'D', + 0x185c: 'D', + 0x185d: 'D', + 0x185e: 'D', + 0x185f: 'D', + 0x1860: 'D', + 0x1861: 'D', + 0x1862: 'D', + 0x1863: 'D', + 0x1864: 'D', + 0x1865: 'D', + 0x1866: 'D', + 0x1867: 'D', + 0x1868: 'D', + 0x1869: 'D', + 0x186a: 'D', + 0x186b: 'D', + 0x186c: 'D', + 0x186d: 'D', + 0x186e: 'D', + 0x186f: 'D', + 0x1870: 'D', + 0x1871: 'D', + 0x1872: 'D', + 0x1873: 'D', + 0x1874: 'D', + 0x1875: 'D', + 0x1876: 'D', + 0x1877: 'D', + 0x1878: 'D', + 0x1880: 'U', + 0x1881: 'U', + 0x1882: 'U', + 0x1883: 'U', + 0x1884: 'U', + 0x1885: 'T', + 0x1886: 'T', + 0x1887: 'D', + 0x1888: 'D', + 0x1889: 'D', + 0x188a: 'D', + 0x188b: 'D', + 0x188c: 'D', + 0x188d: 'D', + 0x188e: 'D', + 0x188f: 'D', + 0x1890: 'D', + 0x1891: 'D', + 0x1892: 'D', + 0x1893: 'D', + 0x1894: 'D', + 0x1895: 'D', + 0x1896: 'D', + 0x1897: 'D', + 0x1898: 'D', + 0x1899: 'D', + 0x189a: 'D', + 0x189b: 'D', + 0x189c: 'D', + 0x189d: 'D', + 0x189e: 'D', + 0x189f: 'D', + 0x18a0: 'D', + 0x18a1: 'D', + 0x18a2: 'D', + 0x18a3: 'D', + 0x18a4: 'D', + 0x18a5: 'D', + 0x18a6: 'D', + 0x18a7: 'D', + 0x18a8: 'D', + 0x18aa: 'D', + 0x200c: 'U', + 0x200d: 'C', + 0x202f: 'U', + 0x2066: 'U', + 0x2067: 'U', + 0x2068: 'U', + 0x2069: 'U', + 0xa840: 'D', + 0xa841: 'D', + 0xa842: 'D', + 0xa843: 'D', + 0xa844: 'D', + 0xa845: 'D', + 0xa846: 'D', + 0xa847: 'D', + 0xa848: 'D', + 0xa849: 'D', + 0xa84a: 'D', + 0xa84b: 'D', + 0xa84c: 'D', + 0xa84d: 'D', + 0xa84e: 'D', + 0xa84f: 'D', + 0xa850: 'D', + 0xa851: 'D', + 0xa852: 'D', + 0xa853: 'D', + 0xa854: 'D', + 0xa855: 'D', + 0xa856: 'D', + 0xa857: 'D', + 0xa858: 'D', + 0xa859: 'D', + 0xa85a: 'D', + 0xa85b: 'D', + 0xa85c: 'D', + 0xa85d: 'D', + 0xa85e: 'D', + 0xa85f: 'D', + 0xa860: 'D', + 0xa861: 'D', + 0xa862: 'D', + 0xa863: 'D', + 0xa864: 'D', + 0xa865: 'D', + 0xa866: 'D', + 0xa867: 'D', + 0xa868: 'D', + 0xa869: 'D', + 0xa86a: 'D', + 0xa86b: 'D', + 0xa86c: 'D', + 0xa86d: 'D', + 0xa86e: 'D', + 0xa86f: 'D', + 0xa870: 'D', + 0xa871: 'D', + 0xa872: 'L', + 0xa873: 'U', + 0x10ac0: 'D', + 0x10ac1: 'D', + 0x10ac2: 'D', + 0x10ac3: 'D', + 0x10ac4: 'D', + 0x10ac5: 'R', + 0x10ac6: 'U', + 0x10ac7: 'R', + 0x10ac8: 'U', + 0x10ac9: 'R', + 0x10aca: 'R', + 0x10acb: 'U', + 0x10acc: 'U', + 0x10acd: 'L', + 0x10ace: 'R', + 0x10acf: 'R', + 0x10ad0: 'R', + 0x10ad1: 'R', + 0x10ad2: 'R', + 0x10ad3: 'D', + 0x10ad4: 'D', + 0x10ad5: 'D', + 0x10ad6: 'D', + 0x10ad7: 'L', + 0x10ad8: 'D', + 0x10ad9: 'D', + 0x10ada: 'D', + 0x10adb: 'D', + 0x10adc: 'D', + 0x10add: 'R', + 0x10ade: 'D', + 0x10adf: 'D', + 0x10ae0: 'D', + 0x10ae1: 'R', + 0x10ae2: 'U', + 0x10ae3: 'U', + 0x10ae4: 'R', + 0x10aeb: 'D', + 0x10aec: 'D', + 0x10aed: 'D', + 0x10aee: 'D', + 0x10aef: 'R', + 0x10b80: 'D', + 0x10b81: 'R', + 0x10b82: 'D', + 0x10b83: 'R', + 0x10b84: 'R', + 0x10b85: 'R', + 0x10b86: 'D', + 0x10b87: 'D', + 0x10b88: 'D', + 0x10b89: 'R', + 0x10b8a: 'D', + 0x10b8b: 'D', + 0x10b8c: 'R', + 0x10b8d: 'D', + 0x10b8e: 'R', + 0x10b8f: 'R', + 0x10b90: 'D', + 0x10b91: 'R', + 0x10ba9: 'R', + 0x10baa: 'R', + 0x10bab: 'R', + 0x10bac: 'R', + 0x10bad: 'D', + 0x10bae: 'D', + 0x10baf: 'U', + 0x10d00: 'L', + 0x10d01: 'D', + 0x10d02: 'D', + 0x10d03: 'D', + 0x10d04: 'D', + 0x10d05: 'D', + 0x10d06: 'D', + 0x10d07: 'D', + 0x10d08: 'D', + 0x10d09: 'D', + 0x10d0a: 'D', + 0x10d0b: 'D', + 0x10d0c: 'D', + 0x10d0d: 'D', + 0x10d0e: 'D', + 0x10d0f: 'D', + 0x10d10: 'D', + 0x10d11: 'D', + 0x10d12: 'D', + 0x10d13: 'D', + 0x10d14: 'D', + 0x10d15: 'D', + 0x10d16: 'D', + 0x10d17: 'D', + 0x10d18: 'D', + 0x10d19: 'D', + 0x10d1a: 'D', + 0x10d1b: 'D', + 0x10d1c: 'D', + 0x10d1d: 'D', + 0x10d1e: 'D', + 0x10d1f: 'D', + 0x10d20: 'D', + 0x10d21: 'D', + 0x10d22: 'R', + 0x10d23: 'D', + 0x10f30: 'D', + 0x10f31: 'D', + 0x10f32: 'D', + 0x10f33: 'R', + 0x10f34: 'D', + 0x10f35: 'D', + 0x10f36: 'D', + 0x10f37: 'D', + 0x10f38: 'D', + 0x10f39: 'D', + 0x10f3a: 'D', + 0x10f3b: 'D', + 0x10f3c: 'D', + 0x10f3d: 'D', + 0x10f3e: 'D', + 0x10f3f: 'D', + 0x10f40: 'D', + 0x10f41: 'D', + 0x10f42: 'D', + 0x10f43: 'D', + 0x10f44: 'D', + 0x10f45: 'U', + 0x10f51: 'D', + 0x10f52: 'D', + 0x10f53: 'D', + 0x10f54: 'R', + 0x10f70: 'D', + 0x10f71: 'D', + 0x10f72: 'D', + 0x10f73: 'D', + 0x10f74: 'R', + 0x10f75: 'R', + 0x10f76: 'D', + 0x10f77: 'D', + 0x10f78: 'D', + 0x10f79: 'D', + 0x10f7a: 'D', + 0x10f7b: 'D', + 0x10f7c: 'D', + 0x10f7d: 'D', + 0x10f7e: 'D', + 0x10f7f: 'D', + 0x10f80: 'D', + 0x10f81: 'D', + 0x10fb0: 'D', + 0x10fb1: 'U', + 0x10fb2: 'D', + 0x10fb3: 'D', + 0x10fb4: 'R', + 0x10fb5: 'R', + 0x10fb6: 'R', + 0x10fb7: 'U', + 0x10fb8: 'D', + 0x10fb9: 'R', + 0x10fba: 'R', + 0x10fbb: 'D', + 0x10fbc: 'D', + 0x10fbd: 'R', + 0x10fbe: 'D', + 0x10fbf: 'D', + 0x10fc0: 'U', + 0x10fc1: 'D', + 0x10fc2: 'R', + 0x10fc3: 'R', + 0x10fc4: 'D', + 0x10fc5: 'U', + 0x10fc6: 'U', + 0x10fc7: 'U', + 0x10fc8: 'U', + 0x10fc9: 'R', + 0x10fca: 'D', + 0x10fcb: 'L', + 0x110bd: 'U', + 0x110cd: 'U', + 0x1e900: 'D', + 0x1e901: 'D', + 0x1e902: 'D', + 0x1e903: 'D', + 0x1e904: 'D', + 0x1e905: 'D', + 0x1e906: 'D', + 0x1e907: 'D', + 0x1e908: 'D', + 0x1e909: 'D', + 0x1e90a: 'D', + 0x1e90b: 'D', + 0x1e90c: 'D', + 0x1e90d: 'D', + 0x1e90e: 'D', + 0x1e90f: 'D', + 0x1e910: 'D', + 0x1e911: 'D', + 0x1e912: 'D', + 0x1e913: 'D', + 0x1e914: 'D', + 0x1e915: 'D', + 0x1e916: 'D', + 0x1e917: 'D', + 0x1e918: 'D', + 0x1e919: 'D', + 0x1e91a: 'D', + 0x1e91b: 'D', + 0x1e91c: 'D', + 0x1e91d: 'D', + 0x1e91e: 'D', + 0x1e91f: 'D', + 0x1e920: 'D', + 0x1e921: 'D', + 0x1e922: 'D', + 0x1e923: 'D', + 0x1e924: 'D', + 0x1e925: 'D', + 0x1e926: 'D', + 0x1e927: 'D', + 0x1e928: 'D', + 0x1e929: 'D', + 0x1e92a: 'D', + 0x1e92b: 'D', + 0x1e92c: 'D', + 0x1e92d: 'D', + 0x1e92e: 'D', + 0x1e92f: 'D', + 0x1e930: 'D', + 0x1e931: 'D', + 0x1e932: 'D', + 0x1e933: 'D', + 0x1e934: 'D', + 0x1e935: 'D', + 0x1e936: 'D', + 0x1e937: 'D', + 0x1e938: 'D', + 0x1e939: 'D', + 0x1e93a: 'D', + 0x1e93b: 'D', + 0x1e93c: 'D', + 0x1e93d: 'D', + 0x1e93e: 'D', + 0x1e93f: 'D', + 0x1e940: 'D', + 0x1e941: 'D', + 0x1e942: 'D', + 0x1e943: 'D', + 0x1e94b: 'T', +} + +const firstArabicShape = 0x0621 +const lastArabicShape = 0x06d3 + +// arabicShaping defines the shaping for arabic runes. Each entry is indexed by +// the shape, between 0 and 3: +// - 0: initial +// - 1: medial +// - 2: final +// - 3: isolated +// See also the bounds given by [firstArabicShape] and [lastArabicShape]. +var arabicShaping = [...][4]uint16{ // required memory: 2 KB + {0x0000, 0x0000, 0x0000, 0xfe80}, + {0x0000, 0x0000, 0xfe82, 0xfe81}, + {0x0000, 0x0000, 0xfe84, 0xfe83}, + {0x0000, 0x0000, 0xfe86, 0xfe85}, + {0x0000, 0x0000, 0xfe88, 0xfe87}, + {0xfe8b, 0xfe8c, 0xfe8a, 0xfe89}, + {0x0000, 0x0000, 0xfe8e, 0xfe8d}, + {0xfe91, 0xfe92, 0xfe90, 0xfe8f}, + {0x0000, 0x0000, 0xfe94, 0xfe93}, + {0xfe97, 0xfe98, 0xfe96, 0xfe95}, + {0xfe9b, 0xfe9c, 0xfe9a, 0xfe99}, + {0xfe9f, 0xfea0, 0xfe9e, 0xfe9d}, + {0xfea3, 0xfea4, 0xfea2, 0xfea1}, + {0xfea7, 0xfea8, 0xfea6, 0xfea5}, + {0x0000, 0x0000, 0xfeaa, 0xfea9}, + {0x0000, 0x0000, 0xfeac, 0xfeab}, + {0x0000, 0x0000, 0xfeae, 0xfead}, + {0x0000, 0x0000, 0xfeb0, 0xfeaf}, + {0xfeb3, 0xfeb4, 0xfeb2, 0xfeb1}, + {0xfeb7, 0xfeb8, 0xfeb6, 0xfeb5}, + {0xfebb, 0xfebc, 0xfeba, 0xfeb9}, + {0xfebf, 0xfec0, 0xfebe, 0xfebd}, + {0xfec3, 0xfec4, 0xfec2, 0xfec1}, + {0xfec7, 0xfec8, 0xfec6, 0xfec5}, + {0xfecb, 0xfecc, 0xfeca, 0xfec9}, + {0xfecf, 0xfed0, 0xfece, 0xfecd}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0xfed3, 0xfed4, 0xfed2, 0xfed1}, + {0xfed7, 0xfed8, 0xfed6, 0xfed5}, + {0xfedb, 0xfedc, 0xfeda, 0xfed9}, + {0xfedf, 0xfee0, 0xfede, 0xfedd}, + {0xfee3, 0xfee4, 0xfee2, 0xfee1}, + {0xfee7, 0xfee8, 0xfee6, 0xfee5}, + {0xfeeb, 0xfeec, 0xfeea, 0xfee9}, + {0x0000, 0x0000, 0xfeee, 0xfeed}, + {0xfbe8, 0xfbe9, 0xfef0, 0xfeef}, + {0xfef3, 0xfef4, 0xfef2, 0xfef1}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0xfb51, 0xfb50}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0xfbdd}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0xfb68, 0xfb69, 0xfb67, 0xfb66}, + {0xfb60, 0xfb61, 0xfb5f, 0xfb5e}, + {0xfb54, 0xfb55, 0xfb53, 0xfb52}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0xfb58, 0xfb59, 0xfb57, 0xfb56}, + {0xfb64, 0xfb65, 0xfb63, 0xfb62}, + {0xfb5c, 0xfb5d, 0xfb5b, 0xfb5a}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0xfb78, 0xfb79, 0xfb77, 0xfb76}, + {0xfb74, 0xfb75, 0xfb73, 0xfb72}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0xfb7c, 0xfb7d, 0xfb7b, 0xfb7a}, + {0xfb80, 0xfb81, 0xfb7f, 0xfb7e}, + {0x0000, 0x0000, 0xfb89, 0xfb88}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0xfb85, 0xfb84}, + {0x0000, 0x0000, 0xfb83, 0xfb82}, + {0x0000, 0x0000, 0xfb87, 0xfb86}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0xfb8d, 0xfb8c}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0xfb8b, 0xfb8a}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0xfb6c, 0xfb6d, 0xfb6b, 0xfb6a}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0xfb70, 0xfb71, 0xfb6f, 0xfb6e}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0xfb90, 0xfb91, 0xfb8f, 0xfb8e}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0xfbd5, 0xfbd6, 0xfbd4, 0xfbd3}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0xfb94, 0xfb95, 0xfb93, 0xfb92}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0xfb9c, 0xfb9d, 0xfb9b, 0xfb9a}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0xfb98, 0xfb99, 0xfb97, 0xfb96}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0xfb9f, 0xfb9e}, + {0xfba2, 0xfba3, 0xfba1, 0xfba0}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0xfbac, 0xfbad, 0xfbab, 0xfbaa}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0xfba5, 0xfba4}, + {0xfba8, 0xfba9, 0xfba7, 0xfba6}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0xfbe1, 0xfbe0}, + {0x0000, 0x0000, 0xfbda, 0xfbd9}, + {0x0000, 0x0000, 0xfbd8, 0xfbd7}, + {0x0000, 0x0000, 0xfbdc, 0xfbdb}, + {0x0000, 0x0000, 0xfbe3, 0xfbe2}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0xfbdf, 0xfbde}, + {0xfbfe, 0xfbff, 0xfbfd, 0xfbfc}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0xfbe6, 0xfbe7, 0xfbe5, 0xfbe4}, + {0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0xfbaf, 0xfbae}, + {0x0000, 0x0000, 0xfbb1, 0xfbb0}, +} + +type arabicLig struct { + components []rune // currently with length 1 or 2 + ligature rune +} + +type arabicTableEntry struct { + First rune + Ligatures []arabicLig +} + +// arabicLigatureTable exposes lam-alef ligatures +var arabicLigatureTable = [...]arabicTableEntry{ + {0xfe91, []arabicLig{ + {[]rune{0xfea0}, 0xfc9c}, + {[]rune{0xfea4}, 0xfc9d}, + {[]rune{0xfea8}, 0xfc9e}, + {[]rune{0xfee2}, 0xfc08}, + {[]rune{0xfee4}, 0xfc9f}, + }}, + {0xfe92, []arabicLig{ + {[]rune{0xfeae}, 0xfc6a}, + {[]rune{0xfee6}, 0xfc6d}, + {[]rune{0xfef2}, 0xfc6f}, + }}, + {0xfe97, []arabicLig{ + {[]rune{0xfea0}, 0xfca1}, + {[]rune{0xfea4}, 0xfca2}, + {[]rune{0xfea8}, 0xfca3}, + {[]rune{0xfee2}, 0xfc0e}, + {[]rune{0xfee4}, 0xfca4}, + }}, + {0xfe98, []arabicLig{ + {[]rune{0xfeae}, 0xfc70}, + {[]rune{0xfee6}, 0xfc73}, + {[]rune{0xfef2}, 0xfc75}, + }}, + {0xfe9b, []arabicLig{ + {[]rune{0xfee2}, 0xfc12}, + }}, + {0xfe9f, []arabicLig{ + {[]rune{0xfee4}, 0xfca8}, + }}, + {0xfea3, []arabicLig{ + {[]rune{0xfee4}, 0xfcaa}, + }}, + {0xfea7, []arabicLig{ + {[]rune{0xfee4}, 0xfcac}, + }}, + {0xfeb3, []arabicLig{ + {[]rune{0xfee4}, 0xfcb0}, + }}, + {0xfeb7, []arabicLig{ + {[]rune{0xfee4}, 0xfd30}, + }}, + {0xfed3, []arabicLig{ + {[]rune{0xfef2}, 0xfc32}, + }}, + {0xfedf, []arabicLig{ + {[]rune{0xfe82}, 0xfef5}, + {[]rune{0xfe84}, 0xfef7}, + {[]rune{0xfe88}, 0xfef9}, + {[]rune{0xfe8e}, 0xfefb}, + {[]rune{0xfe9e}, 0xfc3f}, + {[]rune{0xfea0}, 0xfcc9}, + {[]rune{0xfea2}, 0xfc40}, + {[]rune{0xfea4}, 0xfcca}, + {[]rune{0xfea6}, 0xfc41}, + {[]rune{0xfea8}, 0xfccb}, + {[]rune{0xfee2}, 0xfc42}, + {[]rune{0xfee4}, 0xfccc}, + {[]rune{0xfeec}, 0xfccd}, + {[]rune{0xfef2}, 0xfc44}, + }}, + {0xfee0, []arabicLig{ + {[]rune{0xfe82}, 0xfef6}, + {[]rune{0xfe84}, 0xfef8}, + {[]rune{0xfe88}, 0xfefa}, + {[]rune{0xfe8e}, 0xfefc}, + {[]rune{0xfef0}, 0xfc86}, + }}, + {0xfee3, []arabicLig{ + {[]rune{0xfea0}, 0xfcce}, + {[]rune{0xfea4}, 0xfccf}, + {[]rune{0xfea8}, 0xfcd0}, + {[]rune{0xfee4}, 0xfcd1}, + }}, + {0xfee7, []arabicLig{ + {[]rune{0xfea0}, 0xfcd2}, + {[]rune{0xfea4}, 0xfcd3}, + {[]rune{0xfee2}, 0xfc4e}, + {[]rune{0xfee4}, 0xfcd5}, + }}, + {0xfee8, []arabicLig{ + {[]rune{0xfef2}, 0xfc8f}, + }}, + {0xfef3, []arabicLig{ + {[]rune{0xfea0}, 0xfcda}, + {[]rune{0xfea4}, 0xfcdb}, + {[]rune{0xfea8}, 0xfcdc}, + {[]rune{0xfee4}, 0xfcdd}, + }}, + {0xfef4, []arabicLig{ + {[]rune{0xfeae}, 0xfc91}, + {[]rune{0xfee6}, 0xfc94}, + }}, +} + +var arabicLigatureMarkTable = [...]arabicTableEntry{ + {0x0651, []arabicLig{ + {[]rune{0x064b}, 0xf2ee}, + {[]rune{0x064c}, 0xfc5e}, + {[]rune{0x064e}, 0xfc60}, + {[]rune{0x064f}, 0xfc61}, + {[]rune{0x0650}, 0xfc62}, + }}, +} + +var arabicLigature3Table = [...]arabicTableEntry{ + {0xfedf, []arabicLig{ + {[]rune{0xfee0, 0xfeea}, 0xf201}, + {[]rune{0xfee4, 0xfea0}, 0xf211}, + {[]rune{0xfee4, 0xfea4}, 0xfd88}, + }}, +} + +// hasArabicJoining return 'true' if the given script has arabic joining. +func hasArabicJoining(script language.Script) bool { + switch script { + case language.Adlam, language.Arabic, language.Chorasmian, language.Hanifi_Rohingya, language.Mandaic, language.Manichaean, language.Mongolian, language.Nko, language.Old_Uyghur, language.Phags_Pa, language.Psalter_Pahlavi, language.Sogdian, language.Syriac: + return true + default: + return false + } +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_arabic_win1256.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_arabic_win1256.go new file mode 100644 index 0000000..5be6e48 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_arabic_win1256.go @@ -0,0 +1,130 @@ +package harfbuzz + +import ( + "github.com/go-text/typesetting/font" + ot "github.com/go-text/typesetting/font/opentype" + "github.com/go-text/typesetting/font/opentype/tables" +) + +// ported from harfbuzz/src/hb-ot-shape-complex-arabic-win1256.hh Copyright © 2014 Google, Inc. Behdad Esfahbod + +type manifest struct { + lookup *lookupGSUB + tag tables.Tag +} + +var arabicWin1256GsubLookups = [...]manifest{ + {&rligLookup, ot.NewTag('r', 'l', 'i', 'g')}, + {&initLookup, ot.NewTag('i', 'n', 'i', 't')}, + {&mediLookup, ot.NewTag('m', 'e', 'd', 'i')}, + {&finaLookup, ot.NewTag('f', 'i', 'n', 'a')}, + {&rligMarksLookup, ot.NewTag('r', 'l', 'i', 'g')}, +} + +// Lookups +var ( + initLookup = lookupGSUB{ + LookupOptions: font.LookupOptions{Flag: otIgnoreMarks}, + Subtables: []tables.GSUBLookup{ + initmediSubLookup, + initSubLookup, + }, + } + mediLookup = lookupGSUB{ + LookupOptions: font.LookupOptions{Flag: otIgnoreMarks}, + Subtables: []tables.GSUBLookup{ + initmediSubLookup, + mediSubLookup, + medifinaLamAlefSubLookup, + }, + } + finaLookup = lookupGSUB{ + LookupOptions: font.LookupOptions{Flag: otIgnoreMarks}, + Subtables: []tables.GSUBLookup{ + finaSubLookup, + /* We don't need this one currently as the sequence inherits masks + * from the first item. Just in case we change that in the future + * to be smart about Arabic masks when ligating... */ + medifinaLamAlefSubLookup, + }, + } + rligLookup = lookupGSUB{ + LookupOptions: font.LookupOptions{Flag: otIgnoreMarks}, + Subtables: []tables.GSUBLookup{lamAlefLigaturesSubLookup}, + } + rligMarksLookup = lookupGSUB{ + Subtables: []tables.GSUBLookup{shaddaLigaturesSubLookup}, + } +) + +// init/medi/fina forms +var ( + initmediSubLookup = tables.SingleSubs{Data: tables.SingleSubstData2{ + Coverage: tables.Coverage1{Glyphs: []gID{198, 200, 201, 202, 203, 204, 205, 206, 211, 212, 213, 214, 223, 225, 227, 228, 236, 237}}, + SubstituteGlyphIDs: []gID{162, 4, 5, 5, 6, 7, 9, 11, 13, 14, 15, 26, 140, 141, 142, 143, 154, 154}, + }} + initSubLookup = tables.SingleSubs{Data: tables.SingleSubstData2{ + Coverage: tables.Coverage1{Glyphs: []gID{218, 219, 221, 222, 229}}, + SubstituteGlyphIDs: []gID{27, 30, 128, 131, 144}, + }} + mediSubLookup = tables.SingleSubs{Data: tables.SingleSubstData2{ + Coverage: tables.Coverage1{Glyphs: []gID{218, 219, 221, 222, 229}}, + SubstituteGlyphIDs: []gID{28, 31, 129, 138, 149}, + }} + finaSubLookup = tables.SingleSubs{Data: tables.SingleSubstData2{ + Coverage: tables.Coverage1{Glyphs: []gID{194, 195, 197, 198, 199, 201, 204, 205, 206, 218, 219, 229, 236, 237}}, + SubstituteGlyphIDs: []gID{2, 1, 3, 181, 0, 159, 8, 10, 12, 29, 127, 152, 160, 156}, + }} + medifinaLamAlefSubLookup = tables.SingleSubs{Data: tables.SingleSubstData2{ + Coverage: tables.Coverage1{Glyphs: []gID{165, 178, 180, 252}}, + SubstituteGlyphIDs: []gID{170, 179, 185, 255}, + }} +) + +type ligs = []tables.Ligature + +var ( + // Lam+Alef ligatures + lamAlefLigaturesSubLookup = tables.LigatureSubs{ + Coverage: tables.Coverage1{Glyphs: []gID{225}}, + LigatureSets: []tables.LigatureSet{{Ligatures: lamLigatureSet}}, + } + lamLigatureSet = ligs{ + { + LigatureGlyph: 199, + ComponentGlyphIDs: []uint16{165}, + }, + { + LigatureGlyph: 195, + ComponentGlyphIDs: []uint16{178}, + }, + { + LigatureGlyph: 194, + ComponentGlyphIDs: []uint16{180}, + }, + { + LigatureGlyph: 197, + ComponentGlyphIDs: []uint16{252}, + }, + } + + // Shadda ligatures + shaddaLigaturesSubLookup = tables.LigatureSubs{ + Coverage: tables.Coverage1{Glyphs: []gID{248}}, + LigatureSets: []tables.LigatureSet{{Ligatures: shaddaLigatureSet}}, + } + shaddaLigatureSet = ligs{ + { + LigatureGlyph: 243, + ComponentGlyphIDs: []uint16{172}, + }, + { + LigatureGlyph: 245, + ComponentGlyphIDs: []uint16{173}, + }, + { + LigatureGlyph: 246, + ComponentGlyphIDs: []uint16{175}, + }, + } +) diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_hangul.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_hangul.go new file mode 100644 index 0000000..c83f172 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_hangul.go @@ -0,0 +1,346 @@ +package harfbuzz + +import ( + ot "github.com/go-text/typesetting/font/opentype" + "github.com/go-text/typesetting/font/opentype/tables" + ucd "github.com/go-text/typesetting/unicodedata" +) + +// ported from harfbuzz/src/hb-ot-shape-complex-hangul.cc Copyright © 2013 Google, Inc. Behdad Esfahbod + +var _ otComplexShaper = (*complexShaperHangul)(nil) + +// Hangul shaper +type complexShaperHangul struct { + complexShaperNil + + plan hangulShapePlan +} + +/* Same order as the feature array below */ +const ( + _ = iota // jmo + + ljmo + vjmo + tjmo + + firstHangulFeature = ljmo + hangulFeatureCount = tjmo + 1 +) + +var hangulFeatures = [hangulFeatureCount]tables.Tag{ + 0, + ot.NewTag('l', 'j', 'm', 'o'), + ot.NewTag('v', 'j', 'm', 'o'), + ot.NewTag('t', 'j', 'm', 'o'), +} + +func (complexShaperHangul) collectFeatures(plan *otShapePlanner) { + map_ := &plan.map_ + + for i := firstHangulFeature; i < hangulFeatureCount; i++ { + map_.addFeature(hangulFeatures[i]) + } +} + +func (complexShaperHangul) overrideFeatures(plan *otShapePlanner) { + /* Uniscribe does not apply 'calt' for Hangul, and certain fonts + * (Noto Sans CJK, Source Sans Han, etc) apply all of jamo lookups + * in calt, which is not desirable. */ + plan.map_.disableFeature(ot.NewTag('c', 'a', 'l', 't')) +} + +type hangulShapePlan struct { + maskArray [hangulFeatureCount]GlyphMask +} + +func (cs *complexShaperHangul) dataCreate(plan *otShapePlan) { + var hangulPlan hangulShapePlan + + for i := range hangulPlan.maskArray { + hangulPlan.maskArray[i] = plan.map_.getMask1(hangulFeatures[i]) + } + + cs.plan = hangulPlan +} + +func isCombiningT(u rune) bool { + return ucd.HangulTBase+1 <= u && u <= ucd.HangulTBase+ucd.HangulTCount-1 +} + +func isL(u rune) bool { + return 0x1100 <= u && u <= 0x115F || 0xA960 <= u && u <= 0xA97C +} + +func isV(u rune) bool { + return 0x1160 <= u && u <= 0x11A7 || 0xD7B0 <= u && u <= 0xD7C6 +} + +func isT(u rune) bool { + return 0x11A8 <= u && u <= 0x11FF || 0xD7CB <= u && u <= 0xD7FB +} + +func isZeroWidthChar(font *Font, unicode rune) bool { + glyph, ok := font.face.NominalGlyph(unicode) + return ok && font.GlyphHAdvance(glyph) == 0 +} + +func (cs *complexShaperHangul) preprocessText(_ *otShapePlan, buffer *Buffer, font *Font) { + /* Hangul syllables come in two shapes: LV, and LVT. Of those: + * + * - LV can be precomposed, or decomposed. Lets call those + * and , + * - LVT can be fully precomposed, partially precomposed, or + * fully decomposed. Ie. , , or . + * + * The composition / decomposition is mechanical. However, not + * all sequences compose, and not all sequences + * compose. + * + * Here are the specifics: + * + * - : U+1100..115F, U+A960..A97F + * - : U+1160..11A7, U+D7B0..D7C7 + * - : U+11A8..11FF, U+D7CB..D7FB + * + * - Only the sequences for some of the U+11xx ranges combine. + * - Only sequences for some of the Ts in U+11xx range combine. + * + * Here is what we want to accomplish in this shaper: + * + * - If the whole syllable can be precomposed, do that, + * - Otherwise, fully decompose and apply ljmo/vjmo/tjmo features. + * - If a valid syllable is followed by a Hangul tone mark, reorder the tone + * mark to precede the whole syllable - unless it is a zero-width glyph, in + * which case we leave it untouched, assuming it's designed to overstrike. + * + * That is, of the different possible syllables: + * + * + * + * + * + * + * + * + * - needs no work. + * + * - and can stay the way they are if the font supports them, otherwise we + * should fully decompose them if font supports. + * + * - and we should compose if the whole thing can be composed. + * + * - we should compose if the whole thing can be composed, otherwise we should + * decompose. + */ + + buffer.clearOutput() + // Extent of most recently seen syllable; valid only if start < end + var start, end int + count := len(buffer.Info) + + for buffer.idx = 0; buffer.idx < count; { + u := buffer.cur(0).codepoint + + if 0x302E <= u && u <= 0x302F { // isHangulTone + /* + * We could cache the width of the tone marks and the existence of dotted-circle, + * but the use of the Hangul tone mark characters seems to be rare enough that + * I didn't bother for now. + */ + if start < end && end == len(buffer.outInfo) { + /* Tone mark follows a valid syllable; move it in front, unless it's zero width. */ + buffer.unsafeToBreakFromOutbuffer(start, buffer.idx) + buffer.nextGlyph() + if !isZeroWidthChar(font, u) { + buffer.mergeOutClusters(start, end+1) + info := buffer.outInfo + tone := info[end] + copy(info[start+1:], info[start:end]) + info[start] = tone + } + } else { + /* No valid syllable as base for tone mark; try to insert dotted circle. */ + if buffer.Flags&DoNotinsertDottedCircle == 0 && font.hasGlyph(0x25CC) { + var chars [2]rune + if !isZeroWidthChar(font, u) { + chars[0] = u + chars[1] = 0x25CC + } else { + chars[0] = 0x25CC + chars[1] = u + } + buffer.replaceGlyphs(1, chars[:], nil) + } else { + /* No dotted circle available in the font; just leave tone mark untouched. */ + buffer.nextGlyph() + } + } + start = len(buffer.outInfo) + end = len(buffer.outInfo) + continue + } + + start = len(buffer.outInfo) /* Remember current position as a potential syllable start; + * will only be used if we set end to a later position. + */ + + if isL(u) && buffer.idx+1 < count { + l := u + v := buffer.cur(+1).codepoint + if isV(v) { + /* Have or . */ + var t, tindex rune + if buffer.idx+2 < count { + t = buffer.cur(+2).codepoint + if isT(t) { + tindex = t - ucd.HangulTBase /* Only used if isCombiningT (t); otherwise invalid. */ + } else { + t = 0 /* The next character was not a trailing jamo. */ + } + } + offset := 2 + if t != 0 { + offset = 3 + } + buffer.unsafeToBreak(buffer.idx, buffer.idx+offset) + + /* We've got a syllable ; see if it can potentially be composed. */ + if (ucd.HangulLBase <= l && l <= ucd.HangulLBase+ucd.HangulLCount-1) && (ucd.HangulVBase <= v && v <= ucd.HangulVBase+ucd.HangulVCount-1) && (t == 0 || isCombiningT(t)) { + /* Try to compose; if this succeeds, end is set to start+1. */ + s := ucd.HangulSBase + (l-ucd.HangulLBase)*ucd.HangulNCount + (v-ucd.HangulVBase)*ucd.HangulTCount + tindex + if font.hasGlyph(s) { + buffer.replaceGlyphs(offset, []rune{s}, nil) + end = start + 1 + continue + } + } + + /* We didn't compose, either because it's an Old Hangul syllable without a + * precomposed character in Unicode, or because the font didn't support the + * necessary precomposed glyph. + * Set jamo features on the individual glyphs, and advance past them. + */ + buffer.cur(0).complexAux = ljmo + buffer.nextGlyph() + buffer.cur(0).complexAux = vjmo + buffer.nextGlyph() + if t != 0 { + buffer.cur(0).complexAux = tjmo + buffer.nextGlyph() + end = start + 3 + } else { + end = start + 2 + } + if buffer.ClusterLevel == MonotoneGraphemes { + buffer.mergeOutClusters(start, end) + } + continue + } + } else if ucd.HangulSBase <= u && u <= ucd.HangulSBase+ucd.HangulSCount-1 { // is combined S + /* Have , , or */ + s := u + HasGlyph := font.hasGlyph(s) + lindex := (s - ucd.HangulSBase) / ucd.HangulNCount + nindex := (s - ucd.HangulSBase) % ucd.HangulNCount + vindex := nindex / ucd.HangulTCount + tindex := nindex % ucd.HangulTCount + + if tindex == 0 && buffer.idx+1 < count && isCombiningT(buffer.cur(+1).codepoint) { + /* , try to combine. */ + newTindex := buffer.cur(+1).codepoint - ucd.HangulTBase + newS := s + newTindex + if font.hasGlyph(newS) { + buffer.replaceGlyphs(2, []rune{newS}, nil) + end = start + 1 + continue + } else { + buffer.unsafeToBreak(buffer.idx, buffer.idx+2) /* Mark unsafe between LV and T. */ + } + } + + /* Otherwise, decompose if font doesn't support or , + * or if having non-combining . Note that we already handled + * combining above. */ + if !HasGlyph || (tindex == 0 && buffer.idx+1 < count && isT(buffer.cur(+1).codepoint)) { + decomposed := [3]rune{ + ucd.HangulLBase + lindex, + ucd.HangulVBase + vindex, + ucd.HangulTBase + tindex, + } + if font.hasGlyph(decomposed[0]) && font.hasGlyph(decomposed[1]) && + (tindex == 0 || font.hasGlyph(decomposed[2])) { + sLen := 2 + if tindex != 0 { + sLen = 3 + } + buffer.replaceGlyphs(1, decomposed[:sLen], nil) + + /* If we decomposed an LV because of a non-combining T following, + * we want to include this T in the syllable. + */ + if HasGlyph && tindex == 0 { + buffer.nextGlyph() + sLen++ + } + + /* We decomposed S: apply jamo features to the individual glyphs + * that are now in buffer.OutInfo. + */ + info := buffer.outInfo + end = start + sLen + + i := start + info[i].complexAux = ljmo + i++ + info[i].complexAux = vjmo + i++ + if i < end { + info[i].complexAux = tjmo + i++ + } + + if buffer.ClusterLevel == MonotoneGraphemes { + buffer.mergeOutClusters(start, end) + } + continue + } else if tindex == 0 && buffer.idx+1 < count && isT(buffer.cur(+1).codepoint) { + buffer.unsafeToBreak(buffer.idx, buffer.idx+2) /* Mark unsafe between LV and T. */ + } + } + + if HasGlyph { + /* We didn't decompose the S, so just advance past it. */ + end = start + 1 + buffer.nextGlyph() + continue + } + } + + /* Didn't find a recognizable syllable, so we leave end <= start; + * this will prevent tone-mark reordering happening. + */ + buffer.nextGlyph() + } + buffer.swapBuffers() +} + +func (cs *complexShaperHangul) setupMasks(_ *otShapePlan, buffer *Buffer, _ *Font) { + hangulPlan := cs.plan + + info := buffer.Info + for i := range info { + info[i].Mask |= hangulPlan.maskArray[info[i].complexAux] + } +} + +func (complexShaperHangul) marksBehavior() (zeroWidthMarks, bool) { + return zeroWidthMarksNone, false +} + +func (complexShaperHangul) normalizationPreference() normalizationMode { + return nmNone +} + +func (complexShaperHangul) gposTag() tables.Tag { return 0 } diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_hebrew.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_hebrew.go new file mode 100644 index 0000000..5aa0da3 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_hebrew.go @@ -0,0 +1,140 @@ +package harfbuzz + +import ( + ot "github.com/go-text/typesetting/font/opentype" + "github.com/go-text/typesetting/font/opentype/tables" +) + +// ported from harfbuzz/src/hb-ot-shape-complex-hebrew.cc Copyright © 2010,2012 Google, Inc. Behdad Esfahbod + +var _ otComplexShaper = complexShaperHebrew{} + +type complexShaperHebrew struct { + complexShaperNil +} + +/* Hebrew presentation-form shaping. +* https://bugzilla.mozilla.org/show_bug.cgi?id=728866 +* Hebrew presentation forms with dagesh, for characters U+05D0..05EA; +* Note that some letters do not have a dagesh presForm encoded. */ +var sDageshForms = [0x05EA - 0x05D0 + 1]rune{ + 0xFB30, /* ALEF */ + 0xFB31, /* BET */ + 0xFB32, /* GIMEL */ + 0xFB33, /* DALET */ + 0xFB34, /* HE */ + 0xFB35, /* VAV */ + 0xFB36, /* ZAYIN */ + 0x0000, /* HET */ + 0xFB38, /* TET */ + 0xFB39, /* YOD */ + 0xFB3A, /* FINAL KAF */ + 0xFB3B, /* KAF */ + 0xFB3C, /* LAMED */ + 0x0000, /* FINAL MEM */ + 0xFB3E, /* MEM */ + 0x0000, /* FINAL NUN */ + 0xFB40, /* NUN */ + 0xFB41, /* SAMEKH */ + 0x0000, /* AYIN */ + 0xFB43, /* FINAL PE */ + 0xFB44, /* PE */ + 0x0000, /* FINAL TSADI */ + 0xFB46, /* TSADI */ + 0xFB47, /* QOF */ + 0xFB48, /* RESH */ + 0xFB49, /* SHIN */ + 0xFB4A, /* TAV */ +} + +func (complexShaperHebrew) compose(c *otNormalizeContext, a, b rune) (rune, bool) { + ab, found := uni.compose(a, b) + + if !found && !c.plan.hasGposMark { + /* Special-case Hebrew presentation forms that are excluded from + * standard normalization, but wanted for old fonts. */ + switch b { + case 0x05B4: /* HIRIQ */ + if a == 0x05D9 { /* YOD */ + return 0xFB1D, true + } + case 0x05B7: /* PATAH */ + if a == 0x05F2 { /* YIDDISH YOD YOD */ + return 0xFB1F, true + } else if a == 0x05D0 { /* ALEF */ + return 0xFB2E, true + } + case 0x05B8: /* QAMATS */ + if a == 0x05D0 { /* ALEF */ + return 0xFB2F, true + } + case 0x05B9: /* HOLAM */ + if a == 0x05D5 { /* VAV */ + return 0xFB4B, true + } + case 0x05BC: /* DAGESH */ + if a >= 0x05D0 && a <= 0x05EA { + ab = sDageshForms[a-0x05D0] + return ab, ab != 0 + } else if a == 0xFB2A { /* SHIN WITH SHIN DOT */ + return 0xFB2C, true + } else if a == 0xFB2B { /* SHIN WITH SIN DOT */ + return 0xFB2D, true + } + case 0x05BF: /* RAFE */ + switch a { + case 0x05D1: /* BET */ + return 0xFB4C, true + case 0x05DB: /* KAF */ + return 0xFB4D, true + case 0x05E4: /* PE */ + return 0xFB4E, true + } + case 0x05C1: /* SHIN DOT */ + if a == 0x05E9 { /* SHIN */ + return 0xFB2A, true + } else if a == 0xFB49 { /* SHIN WITH DAGESH */ + return 0xFB2C, true + } + case 0x05C2: /* SIN DOT */ + if a == 0x05E9 { /* SHIN */ + return 0xFB2B, true + } else if a == 0xFB49 { /* SHIN WITH DAGESH */ + return 0xFB2D, true + } + } + } + + return ab, found +} + +func (complexShaperHebrew) marksBehavior() (zeroWidthMarks, bool) { + return zeroWidthMarksByGdefLate, true +} + +func (complexShaperHebrew) normalizationPreference() normalizationMode { + return nmDefault +} + +func (complexShaperHebrew) gposTag() tables.Tag { + // https://github.com/harfbuzz/harfbuzz/issues/347#issuecomment-267838368 + return ot.NewTag('h', 'e', 'b', 'r') +} + +func (complexShaperHebrew) reorderMarks(_ *otShapePlan, buffer *Buffer, start, end int) { + info := buffer.Info + + for i := start + 2; i < end; i++ { + c0 := info[i-2].getModifiedCombiningClass() + c1 := info[i-1].getModifiedCombiningClass() + c2 := info[i-0].getModifiedCombiningClass() + + if (c0 == mcc17 || c0 == mcc18) /* patach or qamats */ && + (c1 == mcc10 || c1 == mcc14) /* sheva or hiriq */ && + (c2 == mcc22 || c2 == combiningClassBelow) /* meteg or below */ { + buffer.mergeClusters(i-1, i+1) + info[i-1], info[i] = info[i], info[i-1] // swap + break + } + } +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_indic.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_indic.go new file mode 100644 index 0000000..4616170 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_indic.go @@ -0,0 +1,1439 @@ +package harfbuzz + +import ( + "fmt" + "sort" + + ot "github.com/go-text/typesetting/font/opentype" + "github.com/go-text/typesetting/font/opentype/tables" + "github.com/go-text/typesetting/language" +) + +// ported from harfbuzz/src/hb-ot-shape-complex-indic.cc, .hh Copyright © 2011,2012 Google, Inc. Behdad Esfahbod + +// UniscribeBugCompatible alters shaping of indic and khmer scripts: +// - when `false`, it applies the recommended shaping choices +// - when `true`, Uniscribe behavior is reproduced +var UniscribeBugCompatible = false + +// Keep in sync with the code generator. +const ( + posStart = iota + + posRaToBecomeReph + posPreM + posPreC + + posBaseC + posAfterMain + + posAboveC + + posBeforeSub + posBelowC + posAfterSub + + posBeforePost + posPostC + posAfterPost + + posSmvd + + posEnd +) + +var _ otComplexShaper = (*complexShaperIndic)(nil) + +// Indic shaper. +type complexShaperIndic struct { + complexShaperNil + + plan indicShapePlan +} + +/* Note: + * + * We treat Vowels and placeholders as if they were consonants. This is safe because Vowels + * cannot happen in a consonant syllable. The plus side however is, we can call the + * consonant syllable logic from the vowel syllable function and get it all right! */ +const ( + consonantFlags = 1<>8) +} + +type indicWouldSubstituteFeature struct { + lookups []lookupMap + // count int + zeroContext bool +} + +func newIndicWouldSubstituteFeature(map_ *otMap, featureTag tables.Tag, zeroContext bool) indicWouldSubstituteFeature { + var out indicWouldSubstituteFeature + out.zeroContext = zeroContext + out.lookups = map_.getStageLookups(0 /*GSUB*/, map_.getFeatureStage(0 /*GSUB*/, featureTag)) + return out +} + +func (ws indicWouldSubstituteFeature) wouldSubstitute(glyphs []GID, font *Font) bool { + for _, lk := range ws.lookups { + if otLayoutLookupWouldSubstitute(font, lk.index, glyphs, ws.zeroContext) { + return true + } + } + return false +} + +/* + * Indic configurations. Note that we do not want to keep every single script-specific + * behavior in these tables necessarily. This should mainly be used for per-script + * properties that are cheaper keeping here, than in the code. Ie. if, say, one and + * only one script has an exception, that one script can be if'ed directly in the code, + * instead of adding a new flag in these structs. + */ + +// reph_position_t +const ( + rephPosAfterMain = posAfterMain + rephPosBeforeSub = posBeforeSub + rephPosAfterSub = posAfterSub + rephPosBeforePost = posBeforePost + rephPosAfterPost = posAfterPost +) + +// reph_mode_t +const ( + rephModeImplicit = iota /* Reph formed out of initial Ra,H sequence. */ + rephModeExplicit /* Reph formed out of initial Ra,H,ZWJ sequence. */ + rephModeLogRepha /* Encoded Repha character, needs reordering. */ +) + +// blwf_mode_t +const ( + blwfModePreAndPost = iota /* Below-forms feature applied to pre-base and post-base. */ + blwfModePostOnly /* Below-forms feature applied to post-base only. */ +) + +type indicConfig struct { + script language.Script + hasOldSpec bool + virama rune + rephPos uint8 + rephMode uint8 + blwfMode uint8 +} + +var indicConfigs = [...]indicConfig{ + /* Default. Should be first. */ + {0, false, 0, rephPosBeforePost, rephModeImplicit, blwfModePreAndPost}, + {language.Devanagari, true, 0x094D, rephPosBeforePost, rephModeImplicit, blwfModePreAndPost}, + {language.Bengali, true, 0x09CD, rephPosAfterSub, rephModeImplicit, blwfModePreAndPost}, + {language.Gurmukhi, true, 0x0A4D, rephPosBeforeSub, rephModeImplicit, blwfModePreAndPost}, + {language.Gujarati, true, 0x0ACD, rephPosBeforePost, rephModeImplicit, blwfModePreAndPost}, + {language.Oriya, true, 0x0B4D, rephPosAfterMain, rephModeImplicit, blwfModePreAndPost}, + {language.Tamil, true, 0x0BCD, rephPosAfterPost, rephModeImplicit, blwfModePreAndPost}, + {language.Telugu, true, 0x0C4D, rephPosAfterPost, rephModeExplicit, blwfModePostOnly}, + {language.Kannada, true, 0x0CCD, rephPosAfterPost, rephModeImplicit, blwfModePostOnly}, + {language.Malayalam, true, 0x0D4D, rephPosAfterMain, rephModeLogRepha, blwfModePreAndPost}, +} + +var indicFeatures = [...]otMapFeature{ + /* + * Basic features. + * These features are applied in order, one at a time, after initial_reordering. + */ + {ot.NewTag('n', 'u', 'k', 't'), ffGlobalManualJoiners | ffPerSyllable}, + {ot.NewTag('a', 'k', 'h', 'n'), ffGlobalManualJoiners | ffPerSyllable}, + {ot.NewTag('r', 'p', 'h', 'f'), ffManualJoiners | ffPerSyllable}, + {ot.NewTag('r', 'k', 'r', 'f'), ffGlobalManualJoiners | ffPerSyllable}, + {ot.NewTag('p', 'r', 'e', 'f'), ffManualJoiners | ffPerSyllable}, + {ot.NewTag('b', 'l', 'w', 'f'), ffManualJoiners | ffPerSyllable}, + {ot.NewTag('a', 'b', 'v', 'f'), ffManualJoiners | ffPerSyllable}, + {ot.NewTag('h', 'a', 'l', 'f'), ffManualJoiners | ffPerSyllable}, + {ot.NewTag('p', 's', 't', 'f'), ffManualJoiners | ffPerSyllable}, + {ot.NewTag('v', 'a', 't', 'u'), ffGlobalManualJoiners | ffPerSyllable}, + {ot.NewTag('c', 'j', 'c', 't'), ffGlobalManualJoiners | ffPerSyllable}, + /* + * Other features. + * These features are applied all at once, after final_reordering + * but before clearing syllables. + * Default Bengali font in Windows for example has intermixed + * lookups for init,pres,abvs,blws features. + */ + {ot.NewTag('i', 'n', 'i', 't'), ffManualJoiners | ffPerSyllable}, + {ot.NewTag('p', 'r', 'e', 's'), ffGlobalManualJoiners | ffPerSyllable}, + {ot.NewTag('a', 'b', 'v', 's'), ffGlobalManualJoiners | ffPerSyllable}, + {ot.NewTag('b', 'l', 'w', 's'), ffGlobalManualJoiners | ffPerSyllable}, + {ot.NewTag('p', 's', 't', 's'), ffGlobalManualJoiners | ffPerSyllable}, + {ot.NewTag('h', 'a', 'l', 'n'), ffGlobalManualJoiners | ffPerSyllable}, +} + +// in the same order as the indicFeatures array +const ( + indicNukt = iota + indicAkhn + indicRphf + indicRkrf + indicPref + indicBlwf + indicAbvf + indicHalf + indicPstf + indicVatu + indicCjct + + indicInit + indicPres + indicAbvs + indicBlws + indicPsts + indicHaln + + indicNumFeatures + indicBasicFeatures = indicInit /* Don't forget to update this! */ +) + +func (cs *complexShaperIndic) collectFeatures(plan *otShapePlanner) { + map_ := &plan.map_ + + /* Do this before any lookups have been applied. */ + map_.addGSUBPause(setupSyllablesIndic) + + map_.enableFeatureExt(ot.NewTag('l', 'o', 'c', 'l'), ffPerSyllable, 1) + /* The Indic specs do not require ccmp, but we apply it here since if + * there is a use of it, it's typically at the beginning. */ + map_.enableFeatureExt(ot.NewTag('c', 'c', 'm', 'p'), ffPerSyllable, 1) + + i := 0 + map_.addGSUBPause(cs.initialReorderingIndic) + + for ; i < indicBasicFeatures; i++ { + map_.addFeatureExt(indicFeatures[i].tag, indicFeatures[i].flags, 1) + map_.addGSUBPause(nil) + } + + map_.addGSUBPause(cs.plan.finalReorderingIndic) + + for ; i < indicNumFeatures; i++ { + map_.addFeatureExt(indicFeatures[i].tag, indicFeatures[i].flags, 1) + } +} + +func (complexShaperIndic) overrideFeatures(plan *otShapePlanner) { + plan.map_.disableFeature(ot.NewTag('l', 'i', 'g', 'a')) + plan.map_.addGSUBPause(nil) +} + +type indicShapePlan struct { + blwf indicWouldSubstituteFeature + pstf indicWouldSubstituteFeature + vatu indicWouldSubstituteFeature + rphf indicWouldSubstituteFeature + pref indicWouldSubstituteFeature + + maskArray [indicNumFeatures]GlyphMask + config indicConfig + viramaGlyph GID // cached value + + isOldSpec bool + uniscribeBugCompatible bool +} + +func (indicPlan *indicShapePlan) loadViramaGlyph(font *Font) GID { + if indicPlan.viramaGlyph == ^GID(0) { + glyph, ok := font.face.NominalGlyph(indicPlan.config.virama) + if indicPlan.config.virama == 0 || !ok { + glyph = 0 + } + /* Technically speaking, the spec says we should apply 'locl' to virama too. + * Maybe one day... */ + + /* Our get_nominal_glyph() function needs a font, so we can't get the virama glyph + * during shape planning... Instead, overwrite it here. */ + indicPlan.viramaGlyph = glyph + } + + return indicPlan.viramaGlyph +} + +func (cs *complexShaperIndic) dataCreate(plan *otShapePlan) { + var indicPlan indicShapePlan + + indicPlan.config = indicConfigs[0] + for i := 1; i < len(indicConfigs); i++ { + if plan.props.Script == indicConfigs[i].script { + indicPlan.config = indicConfigs[i] + break + } + } + + indicPlan.isOldSpec = indicPlan.config.hasOldSpec && ((plan.map_.chosenScript[0] & 0x000000FF) != '2') + indicPlan.uniscribeBugCompatible = UniscribeBugCompatible + indicPlan.viramaGlyph = ^GID(0) + + /* Use zero-context wouldSubstitute() matching for new-spec of the main + * Indic scripts, and scripts with one spec only, but not for old-specs. + * The new-spec for all dual-spec scripts says zero-context matching happens. + * + * However, testing with Malayalam shows that old and new spec both allow + * context. Testing with Bengali new-spec however shows that it doesn't. + * So, the heuristic here is the way it is. It should *only* be changed, + * as we discover more cases of what Windows does. DON'T TOUCH OTHERWISE. */ + zeroContext := !indicPlan.isOldSpec && plan.props.Script != language.Malayalam + indicPlan.rphf = newIndicWouldSubstituteFeature(&plan.map_, ot.NewTag('r', 'p', 'h', 'f'), zeroContext) + indicPlan.pref = newIndicWouldSubstituteFeature(&plan.map_, ot.NewTag('p', 'r', 'e', 'f'), zeroContext) + indicPlan.blwf = newIndicWouldSubstituteFeature(&plan.map_, ot.NewTag('b', 'l', 'w', 'f'), zeroContext) + indicPlan.pstf = newIndicWouldSubstituteFeature(&plan.map_, ot.NewTag('p', 's', 't', 'f'), zeroContext) + indicPlan.vatu = newIndicWouldSubstituteFeature(&plan.map_, ot.NewTag('v', 'a', 't', 'u'), zeroContext) + + for i := range indicPlan.maskArray { + if indicFeatures[i].flags&ffGLOBAL != 0 { + indicPlan.maskArray[i] = 0 + } else { + indicPlan.maskArray[i] = plan.map_.getMask1(indicFeatures[i].tag) + } + } + + cs.plan = indicPlan +} + +func (indicPlan *indicShapePlan) consonantPositionFromFace(consonant, virama GID, font *Font) uint8 { + /* For old-spec, the order of glyphs is Consonant,Virama, + * whereas for new-spec, it's Virama,Consonant. However, + * some broken fonts (like Free Sans) simply copied lookups + * from old-spec to new-spec without modification. + * And oddly enough, Uniscribe seems to respect those lookups. + * Eg. in the sequence U+0924,U+094D,U+0930, Uniscribe finds + * base at 0. The font however, only has lookups matching + * 930,94D in 'blwf', not the expected 94D,930 (with new-spec + * table). As such, we simply match both sequences. Seems + * to work. + * + * Vatu is done as well, for: + * https://github.com/harfbuzz/harfbuzz/issues/1587 + */ + glyphs := [3]GID{virama, consonant, virama} + if indicPlan.blwf.wouldSubstitute(glyphs[0:2], font) || + indicPlan.blwf.wouldSubstitute(glyphs[1:3], font) || + indicPlan.vatu.wouldSubstitute(glyphs[0:2], font) || + indicPlan.vatu.wouldSubstitute(glyphs[1:3], font) { + return posBelowC + } + if indicPlan.pstf.wouldSubstitute(glyphs[0:2], font) || + indicPlan.pstf.wouldSubstitute(glyphs[1:3], font) { + return posPostC + } + if indicPlan.pref.wouldSubstitute(glyphs[0:2], font) || + indicPlan.pref.wouldSubstitute(glyphs[1:3], font) { + return posPostC + } + return posBaseC +} + +func (cs *complexShaperIndic) setupMasks(plan *otShapePlan, buffer *Buffer, _ *Font) { + /* We cannot setup masks here. We save information about characters + * and setup masks later on in a pause-callback. */ + + info := buffer.Info + for i := range info { + info[i].setIndicProperties() + } +} + +func setupSyllablesIndic(_ *otShapePlan, _ *Font, buffer *Buffer) bool { + findSyllablesIndic(buffer) + iter, count := buffer.syllableIterator() + for start, end := iter.next(); start < count; start, end = iter.next() { + buffer.unsafeToBreak(start, end) + } + return false +} + +func foundSyllableIndic(syllableType uint8, ts, te int, info []GlyphInfo, syllableSerial *uint8) { + for i := ts; i < te; i++ { + info[i].syllable = (*syllableSerial << 4) | syllableType + } + *syllableSerial++ + if *syllableSerial == 16 { + *syllableSerial = 1 + } +} + +func (indicPlan *indicShapePlan) updateConsonantPositionsIndic(font *Font, buffer *Buffer) { + virama := indicPlan.loadViramaGlyph(font) + if virama != 0 { + info := buffer.Info + for i := range info { + if info[i].complexAux == posBaseC { + consonant := info[i].Glyph + info[i].complexAux = indicPlan.consonantPositionFromFace(consonant, virama, font) + } + } + } +} + +/* Rules from: + * https://docs.microsqoft.com/en-us/typography/script-development/devanagari */ +func (indicPlan *indicShapePlan) initialReorderingConsonantSyllable(font *Font, buffer *Buffer, start, end int) { + info := buffer.Info + + /* https://github.com/harfbuzz/harfbuzz/issues/435#issuecomment-335560167 + * For compatibility with legacy usage in Kannada, + * Ra+h+ZWJ must behave like Ra+ZWJ+h... */ + if buffer.Props.Script == language.Kannada && + start+3 <= end && + isOneOf(&info[start], 1< limit { + i-- + /* . until a consonant is found */ + if isConsonant(&info[i]) { + /* . that does not have a below-base or post-base form + * (post-base forms have to follow below-base forms), */ + if info[i].complexAux != posBelowC && + (info[i].complexAux != posPostC || seenBelow) { + base = i + break + } + if info[i].complexAux == posBelowC { + seenBelow = true + } + + /* . or that is not a pre-base-reordering Ra, + * + * IMPLEMENTATION NOTES: + * + * Our pre-base-reordering Ra's are marked posPostC, so will be skipped + * by the logic above already. + */ + + /* . or arrive at the first consonant. The consonant stopped at will + * be the base. */ + base = i + } else { + /* A ZWJ after a Halant stops the base search, and requests an explicit + * half form. + * A ZWJ before a Halant, requests a subjoined form instead, and hence + * search continues. This is particularly important for Bengali + * sequence Ra,H,Ya that should form Ya-Phalaa by subjoining Ya. */ + if start < i && + info[i].complexCategory == indSM_ex_ZWJ && + info[i-1].complexCategory == indSM_ex_H { + break + } + } + } + } + + /* . If the syllable starts with Ra + Halant (in a script that has Reph) + * and has more than one consonant, Ra is excluded from candidates for + * base consonants. + * + * Only do this for unforced Reph. (ie. not for Ra,H,ZWJ. */ + if hasReph && base == start && limit-base <= 2 { + /* Have no other consonant, so Reph is not formed and Ra becomes base. */ + hasReph = false + } + } + + /* 2. Decompose and reorder Matras: + * + * Each matra and any syllable modifier sign in the syllable are moved to the + * appropriate position relative to the consonant(s) in the syllable. The + * shaping engine decomposes two- or three-part matras into their constituent + * parts before any repositioning. Matra characters are classified by which + * consonant in a conjunct they have affinity for and are reordered to the + * following positions: + * + * o Before first half form in the syllable + * o After subjoined consonants + * o After post-form consonant + * o After main consonant (for above marks) + * + * IMPLEMENTATION NOTES: + * + * The normalize() routine has already decomposed matras for us, so we don't + * need to worry about that. + */ + + /* 3. Reorder marks to canonical order: + * + * Adjacent nukta and halant or nukta and vedic sign are always repositioned + * if necessary, so that the nukta is first. + * + * IMPLEMENTATION NOTES: + * + * We don't need to do this: the normalize() routine already did this for us. + */ + + /* Reorder characters */ + + for i := start; i < base; i++ { + info[i].complexAux = min8(posPreC, info[i].complexAux) + } + + if base < end { + info[base].complexAux = posBaseC + } + + /* Handle beginning Ra */ + if hasReph { + info[start].complexAux = posRaToBecomeReph + } + + /* For old-style Indic script tags, move the first post-base Halant after + * last consonant. + * + * Reports suggest that in some scripts Uniscribe does this only if there + * is *not* a Halant after last consonant already. We know that is the + * case for Kannada, while it reorders unconditionally in other scripts, + * eg. Malayalam, Bengali, and Devanagari. We don't currently know about + * other scripts, so we block Kannada. + * + * Kannada test case: + * U+0C9A,U+0CCD,U+0C9A,U+0CCD + * With some versions of Lohit Kannada. + * https://bugs.freedesktop.org/show_bug.cgi?id=59118 + * + * Malayalam test case: + * U+0D38,U+0D4D,U+0D31,U+0D4D,U+0D31,U+0D4D + * With lohit-ttf-20121122/Lohit-Malayalam.ttf + * + * Bengali test case: + * U+0998,U+09CD,U+09AF,U+09CD + * With Windows XP vrinda.ttf + * https://github.com/harfbuzz/harfbuzz/issues/1073 + * + * Devanagari test case: + * U+091F,U+094D,U+0930,U+094D + * With chandas.ttf + * https://github.com/harfbuzz/harfbuzz/issues/1071 + */ + if indicPlan.isOldSpec { + disallowDoubleHalants := buffer.Props.Script == language.Kannada + for i := base + 1; i < end; i++ { + if info[i].complexCategory == indSM_ex_H { + var j int + for j = end - 1; j > i; j-- { + if isConsonant(&info[j]) || + (disallowDoubleHalants && info[j].complexCategory == indSM_ex_H) { + break + } + } + if info[j].complexCategory != indSM_ex_H && j > i { + /* Move Halant to after last consonant. */ + if debugMode { + fmt.Printf("INDIC - halant: switching glyph %d to %d (and shifting between)", i, j) + } + t := info[i] + copy(info[i:j], info[i+1:]) + info[j] = t + } + break + } + } + } + + /* Attach misc marks to previous char to move with them. */ + { + var lastPos uint8 = posStart + for i := start; i < end; i++ { + if 1< start; j-- { + if info[j-1].complexAux != posPreM { + info[i].complexAux = info[j-1].complexAux + break + } + } + } + } else if info[i].complexAux != posSmvd { + if info[i].complexCategory == indSM_ex_MPst && + i > start && info[i-1].complexCategory == indSM_ex_SM { + info[i-1].complexAux = info[i].complexAux + } + + lastPos = info[i].complexAux + } + } + } + + /* For post-base consonants let them own anything before them + * since the last consonant or matra. */ + { + last := base + for i := base + 1; i < end; i++ { + if isConsonant(&info[i]) { + for j := last + 1; j < i; j++ { + if info[j].complexAux < posSmvd { + info[j].complexAux = info[i].complexAux + } + } + last = i + } else if ic := info[i].complexCategory; ic == indSM_ex_M || ic == indSM_ex_MPst { + last = i + } + } + } + + { + /* Use Syllable for sort accounting temporarily. */ + syllable := info[start].syllable + for i := start; i < end; i++ { + info[i].syllable = uint8(i - start) + } + + /* Sit tight, rock 'n roll! */ + + if debugMode { + fmt.Printf("INDIC - post-base: sorting between glyph %d and %d\n", start, end) + } + + subSlice := info[start:end] + sort.SliceStable(subSlice, func(i, j int) bool { return subSlice[i].complexAux < subSlice[j].complexAux }) + + // Find base again; also flip left-matra sequence. + firstLeftMatra := end + lastLeftMatra := end + base = end + for i := start; i < end; i++ { + if info[i].complexAux == posBaseC { + base = i + break + } else if info[i].complexAux == posPreM { + if firstLeftMatra == end { + firstLeftMatra = i + } + lastLeftMatra = i + } + } + + /* https://github.com/harfbuzz/harfbuzz/issues/3863 */ + if firstLeftMatra < lastLeftMatra { + /* No need to merge clusters, handled later. */ + buffer.reverseRange(firstLeftMatra, lastLeftMatra+1) + /* Reverse back nuktas, etc. */ + i := firstLeftMatra + for j := i; j <= lastLeftMatra; j++ { + if ic := info[j].complexCategory; ic == indSM_ex_M || ic == indSM_ex_MPst { + buffer.reverseRange(i, j+1) + i = j + 1 + } + } + } + + // Things are out-of-control for post base positions, they may shuffle + // around like crazy. In old-spec mode, we move halants around, so in + // that case merge all clusters after base. Otherwise, check the sort + // order and merge as needed. + // For pre-base stuff, we handle cluster issues in final reordering. + // + // We could use buffer.sort() for this, if there was no special + // reordering of pre-base stuff happening later... + // We don't want to mergeClusters all of that, which buffer.sort() + // would. Here's a concrete example: + // + // Assume there's a pre-base consonant and explicit Halant before base, + // followed by a prebase-reordering (left) Matra: + // + // C,H,ZWNJ,B,M + // + // At this point in reordering we would have: + // + // M,C,H,ZWNJ,B + // + // whereas in final reordering we will bring the Matra closer to Base: + // + // C,H,ZWNJ,M,B + // + // That's why we don't want to merge-clusters anything before the Base + // at this point. But if something moved from after Base to before it, + // we should merge clusters from base to them. In final-reordering, we + // only move things around before base, and merge-clusters up to base. + // These two merge-clusters from the two sides of base will interlock + // to merge things correctly. See: + // https://github.com/harfbuzz/harfbuzz/issues/2272 + if indicPlan.isOldSpec || end-start > 127 { + buffer.mergeClusters(base, end) + } else { + /* Note! Syllable is a one-byte field. */ + for i := base; i < end; i++ { + if info[i].syllable != 255 { + ma, mi := i, i + j := start + int(info[i].syllable) + for j != i { + mi = min(mi, j) + ma = max(ma, j) + next := start + int(info[j].syllable) + info[j].syllable = 255 /* So we don't process j later again. */ + j = next + } + buffer.mergeClusters(max(base, mi), ma+1) + } + } + } + + /* Put syllable back in. */ + for i := start; i < end; i++ { + info[i].syllable = syllable + } + } + + /* Setup masks now */ + + { + var mask GlyphMask + + /* Reph */ + for i := start; i < end && info[i].complexAux == posRaToBecomeReph; i++ { + info[i].Mask |= indicPlan.maskArray[indicRphf] + } + + /* Pre-base */ + mask = indicPlan.maskArray[indicHalf] + if !indicPlan.isOldSpec && + indicPlan.config.blwfMode == blwfModePreAndPost { + mask |= indicPlan.maskArray[indicBlwf] + } + for i := start; i < base; i++ { + info[i].Mask |= mask + } + /* Base */ + mask = 0 + if base < end { + info[base].Mask |= mask + } + /* Post-base */ + mask = indicPlan.maskArray[indicBlwf] | + indicPlan.maskArray[indicAbvf] | + indicPlan.maskArray[indicPstf] + for i := base + 1; i < end; i++ { + info[i].Mask |= mask + } + } + + if indicPlan.isOldSpec && + buffer.Props.Script == language.Devanagari { + /* Old-spec eye-lash Ra needs special handling. From the + * spec: + * + * "The feature 'below-base form' is applied to consonants + * having below-base forms and following the base consonant. + * The exception is vattu, which may appear below half forms + * as well as below the base glyph. The feature 'below-base + * form' will be applied to all such occurrences of Ra as well." + * + * Test case: U+0924,U+094D,U+0930,U+094d,U+0915 + * with Sanskrit 2003 font. + * + * However, note that Ra,Halant,ZWJ is the correct way to + * request eyelash form of Ra, so we wouldbn't inhibit it + * in that sequence. + * + * Test case: U+0924,U+094D,U+0930,U+094d,U+200D,U+0915 + */ + for i := start; i+1 < base; i++ { + if info[i].complexCategory == indSM_ex_Ra && + info[i+1].complexCategory == indSM_ex_H && + (i+2 == base || + info[i+2].complexCategory != indSM_ex_ZWJ) { + info[i].Mask |= indicPlan.maskArray[indicBlwf] + info[i+1].Mask |= indicPlan.maskArray[indicBlwf] + } + } + } + + prefLen := 2 + if indicPlan.maskArray[indicPref] != 0 && base+prefLen < end { + /* Find a Halant,Ra sequence and mark it for pre-base-reordering processing. */ + for i := base + 1; i+prefLen-1 < end; i++ { + var glyphs [2]GID + for j := 0; j < prefLen; j++ { + glyphs[j] = info[i+j].Glyph + } + if indicPlan.pref.wouldSubstitute(glyphs[:prefLen], font) { + for j := 0; j < prefLen; j++ { + info[i].Mask |= indicPlan.maskArray[indicPref] + i++ + } + break + } + } + } + + /* Apply ZWJ/ZWNJ effects */ + for i := start + 1; i < end; i++ { + if isJoiner(&info[i]) { + nonJoiner := info[i].complexCategory == indSM_ex_ZWNJ + j := i + + for do := true; do; do = (j > start && !isConsonant(&info[j])) { + j-- + + /* ZWJ/ZWNJ should disable CJCT. They do that by simply + * being there, since we don't skip them for the CJCT + * feature (ie. F_MANUAL_ZWJ) */ + + /* A ZWNJ disables HALF. */ + if nonJoiner { + info[j].Mask &= ^indicPlan.maskArray[indicHalf] + } + + } + } + } +} + +func (indicPlan *indicShapePlan) initialReorderingStandaloneCluster(font *Font, buffer *Buffer, start, end int) { + /* We treat placeholder/dotted-circle as if they are consonants, so we + * should just chain. Only if not in compatibility mode that is... */ + + if indicPlan.uniscribeBugCompatible { + /* For dotted-circle, this is what Uniscribe does: + * If dotted-circle is the last glyph, it just does nothing. + * Ie. It doesn't form Reph. */ + if buffer.Info[end-1].complexCategory == indSM_ex_DOTTEDCIRCLE { + return + } + } + + indicPlan.initialReorderingConsonantSyllable(font, buffer, start, end) +} + +func (indicPlan *indicShapePlan) initialReorderingSyllableIndic(font *Font, buffer *Buffer, start, end int) { + syllableType := (buffer.Info[start].syllable & 0x0F) + switch syllableType { + case indicVowelSyllable, indicConsonantSyllable: /* We made the vowels look like consonants. So let's call the consonant logic! */ + indicPlan.initialReorderingConsonantSyllable(font, buffer, start, end) + case indicBrokenCluster, indicStandaloneCluster: /* We already inserted dotted-circles, so just call the standalone_cluster. */ + indicPlan.initialReorderingStandaloneCluster(font, buffer, start, end) + } +} + +func (cs *complexShaperIndic) initialReorderingIndic(_ *otShapePlan, font *Font, buffer *Buffer) bool { + if debugMode { + fmt.Println("INDIC - start reordering indic initial") + } + + cs.plan.updateConsonantPositionsIndic(font, buffer) + ret := syllabicInsertDottedCircles(font, buffer, indicBrokenCluster, + indSM_ex_DOTTEDCIRCLE, indSM_ex_Repha, posEnd) + + iter, count := buffer.syllableIterator() + for start, end := iter.next(); start < count; start, end = iter.next() { + cs.plan.initialReorderingSyllableIndic(font, buffer, start, end) + } + + if debugMode { + fmt.Println("INDIC - end reordering indic initial") + } + + return ret +} + +func (indicPlan *indicShapePlan) finalReorderingSyllableIndic(plan *otShapePlan, buffer *Buffer, start, end int) { + info := buffer.Info + + /* This function relies heavily on halant glyphs. Lots of ligation + * and possibly multiple substitutions happened prior to this + * phase, and that might have messed up our properties. Recover + * from a particular case of that where we're fairly sure that a + * class of otH is desired but has been lost. */ + /* We don't call loadViramaGlyph(), since we know it's already + * loaded. */ + viramaGlyph := indicPlan.viramaGlyph + if viramaGlyph != 0 { + for i := start; i < end; i++ { + if info[i].Glyph == viramaGlyph && + info[i].ligated() && info[i].multiplied() { + /* This will make sure that this glyph passes isHalant() test. */ + info[i].complexCategory = indSM_ex_H + info[i].clearLigatedAndMultiplied() + } + } + } + + /* 4. Final reordering: + * + * After the localized forms and basic shaping forms GSUB features have been + * applied (see below), the shaping engine performs some final glyph + * reordering before applying all the remaining font features to the entire + * syllable. + */ + + tryPref := indicPlan.maskArray[indicPref] != 0 + + /* Find base again */ + var base int + for base = start; base < end; base++ { + if info[base].complexAux >= posBaseC { + if tryPref && base+1 < end { + for i := base + 1; i < end; i++ { + if (info[i].Mask & indicPlan.maskArray[indicPref]) != 0 { + if !(info[i].substituted() && info[i].ligatedAndDidntMultiply()) { + /* Ok, this was a 'pref' candidate but didn't form any. + * Base is around here... */ + base = i + for base < end && isHalant(&info[base]) { + base++ + } + if base < end { + info[base].complexAux = posBaseC + } + + tryPref = false + } + break + } + if base == end { + break + } + } + } + /* For Malayalam, skip over unformed below- (but NOT post-) forms. */ + if buffer.Props.Script == language.Malayalam { + for i := base + 1; i < end; i++ { + for i < end && isJoiner(&info[i]) { + i++ + } + if i == end || !isHalant(&info[i]) { + break + } + i++ /* Skip halant. */ + for i < end && isJoiner(&info[i]) { + i++ + } + if i < end && isConsonant(&info[i]) && info[i].complexAux == posBelowC { + base = i + info[base].complexAux = posBaseC + } + } + } + + if start < base && info[base].complexAux > posBaseC { + base-- + } + break + } + } + if base == end && start < base && isOneOf(&info[base-1], 1< start && !isOneOf(&info[newPos], 1< start { + newPos-- + goto search + } + } + /* . If ZWNJ follows this halant, position is moved after it. + * + * IMPLEMENTATION NOTES: + * + * This is taken care of by the state-machine. A Halant,ZWNJ is a terminating + * sequence for a consonant syllable; any pre-base matras occurring after it + * will belong to the subsequent syllable. + */ + } + } else { + newPos = start /* No move. */ + } + } + + if start < newPos && info[newPos].complexAux != posPreM { + /* Now go see if there's actually any matras... */ + for i := newPos; i > start; i-- { + if info[i-1].complexAux == posPreM { + oldPos := i - 1 + if oldPos < base && base <= newPos { /* Shouldn't actually happen. */ + base-- + } + + if debugMode { + fmt.Printf("INDIC - matras: switching glyph %d to %d (and shifting between)", oldPos, newPos) + } + + tmp := info[oldPos] + copy(info[oldPos:newPos], info[oldPos+1:]) + info[newPos] = tmp + + /* Note: this mergeClusters() is intentionally *after* the reordering. + * Indic matra reordering is special and tricky... */ + buffer.mergeClusters(newPos, min(end, base+1)) + + newPos-- + } + } + } else { + for i := start; i < base; i++ { + if info[i].complexAux == posPreM { + buffer.mergeClusters(i, min(end, base+1)) + break + } + } + } + } + + /* o Reorder reph: + * + * Reph’s original position is always at the beginning of the syllable, + * (i.e. it is not reordered at the character reordering stage). However, + * it will be reordered according to the basic-forms shaping results. + * Possible positions for reph, depending on the script, are; after main, + * before post-base consonant forms, and after post-base consonant forms. + */ + + /* Two cases: + * + * - If repha is encoded as a sequence of characters (Ra,H or Ra,H,ZWJ), then + * we should only move it if the sequence ligated to the repha form. + * + * - If repha is encoded separately and in the logical position, we should only + * move it if it did NOT ligate. If it ligated, it's probably the font trying + * to make it work without the reordering. + */ + if start+1 < end && info[start].complexAux == posRaToBecomeReph && + (info[start].complexCategory == indSM_ex_Repha) != info[start].ligatedAndDidntMultiply() { + var newRephPos int + rephPos := indicPlan.config.rephPos + + /* 1. If reph should be positioned after post-base consonant forms, + * proceed to step 5. + */ + if rephPos == rephPosAfterPost { + goto reph_step_5 + } + + /* 2. If the reph repositioning class is not after post-base: target + * position is after the first explicit halant glyph between the + * first post-reph consonant and last main consonant. If ZWJ or ZWNJ + * are following this halant, position is moved after it. If such + * position is found, this is the target position. Otherwise, + * proceed to the next step. + * + * Note: in old-implementation fonts, where classifications were + * fixed in shaping engine, there was no case where reph position + * will be found on this step. + */ + { + newRephPos = start + 1 + for newRephPos < base && !isHalant(&info[newRephPos]) { + newRephPos++ + } + + if newRephPos < base && isHalant(&info[newRephPos]) { + /* .If ZWJ or ZWNJ are following this halant, position is moved after it. */ + if newRephPos+1 < base && isJoiner(&info[newRephPos+1]) { + newRephPos++ + } + goto reph_move + } + } + + /* 3. If reph should be repositioned after the main consonant: find the + * first consonant not ligated with main, or find the first + * consonant that is not a potential pre-base-reordering Ra. + */ + if rephPos == rephPosAfterMain { + newRephPos = base + for newRephPos+1 < end && info[newRephPos+1].complexAux <= posAfterMain { + newRephPos++ + } + if newRephPos < end { + goto reph_move + } + } + + /* 4. If reph should be positioned before post-base consonant, find + * first post-base classified consonant not ligated with main. If no + * consonant is found, the target position should be before the + * first matra, syllable modifier sign or vedic sign. + */ + /* This is our take on what step 4 is trying to say (and failing, BADLY). */ + if rephPos == rephPosAfterSub { + newRephPos = base + for newRephPos+1 < end && + (1< start && info[newRephPos].complexAux == posSmvd { + newRephPos-- + } + + /* + * If the Reph is to be ending up after a Matra,Halant sequence, + * position it before that Halant so it can interact with the Matra. + * However, if it's a plain Consonant,Halant we shouldn't do that. + * Uniscribe doesn't do this. + * TEST: U+0930,U+094D,U+0915,U+094B,U+094D + */ + if !indicPlan.uniscribeBugCompatible && isHalant(&info[newRephPos]) { + for i := base + 1; i < newRephPos; i++ { + if ic := info[i].complexCategory; ic == indSM_ex_M || ic == indSM_ex_MPst { + /* Ok, got it. */ + newRephPos-- + } + } + } + + goto reph_move + } + + reph_move: + { + + if debugMode { + fmt.Printf("INDIC - reph: switching glyph %d to %d (and shifting between)", start, newRephPos) + } + + /* Move */ + buffer.mergeClusters(start, newRephPos+1) + reph := info[start] + copy(info[start:newRephPos], info[start+1:]) + info[newRephPos] = reph + + if start < base && base <= newRephPos { + base-- + } + } + } + + /* o Reorder pre-base-reordering consonants: + * + * If a pre-base-reordering consonant is found, reorder it according to + * the following rules: + */ + + if tryPref && base+1 < end /* Otherwise there can't be any pre-base-reordering Ra. */ { + for i := base + 1; i < end; i++ { + if (info[i].Mask & indicPlan.maskArray[indicPref]) != 0 { + /* 1. Only reorder a glyph produced by substitution during application + * of the feature. (Note that a font may shape a Ra consonant with + * the feature generally but block it in certain contexts.) + */ + /* Note: We just check that something got substituted. We don't check that + * the feature actually did it... + * + * Reorder pref only if it ligated. */ + if info[i].ligatedAndDidntMultiply() { + /* + * 2. Try to find a target position the same way as for pre-base matra. + * If it is found, reorder pre-base consonant glyph. + * + * 3. If position is not found, reorder immediately before main + * consonant. + */ + + newPos := base + /* Malayalam / Tamil do not have "half" forms or explicit virama forms. + * The glyphs formed by 'half' are Chillus or ligated explicit viramas. + * We want to position matra after them. + */ + if buffer.Props.Script != language.Malayalam && buffer.Props.Script != language.Tamil { + for newPos > start && !isOneOf(&info[newPos-1], 1< start && isHalant(&info[newPos-1]) { + /* . If ZWJ or ZWNJ follow this halant, position is moved after it. */ + if newPos < end && isJoiner(&info[newPos]) { + newPos++ + } + } + + { + + oldPos := i + buffer.mergeClusters(newPos, oldPos+1) + + if debugMode { + fmt.Printf("INDIC - pre-base: switching glyph %d to %d (and shifting between)", oldPos, newPos) + } + + tmp := info[oldPos] + copy(info[newPos+1:], info[newPos:oldPos]) + info[newPos] = tmp + + if newPos <= base && base < oldPos { + base++ + } + } + } + + break + } + } + } + + /* Apply 'init' to the Left Matra if it's a word start. */ + if info[start].complexAux == posPreM { + const flagRange = 1<<(nonSpacingMark+1) - 1< 0; _nacts-- { + _acts++ + switch _indSM_actions[_acts-1] { + case 1: + ts = p + + } + } + + _keys = int(_indSM_key_offsets[cs]) + _trans = int(_indSM_index_offsets[cs]) + + _klen = int(_indSM_single_lengths[cs]) + if _klen > 0 { + _lower := int(_keys) + var _mid int + _upper := int(_keys + _klen - 1) + for { + if _upper < _lower { + break + } + + _mid = _lower + ((_upper - _lower) >> 1) + switch { + case (info[p].complexCategory) < _indSM_trans_keys[_mid]: + _upper = _mid - 1 + case (info[p].complexCategory) > _indSM_trans_keys[_mid]: + _lower = _mid + 1 + default: + _trans += int(_mid - int(_keys)) + goto _match + } + } + _keys += _klen + _trans += _klen + } + + _klen = int(_indSM_range_lengths[cs]) + if _klen > 0 { + _lower := int(_keys) + var _mid int + _upper := int(_keys + (_klen << 1) - 2) + for { + if _upper < _lower { + break + } + + _mid = _lower + (((_upper - _lower) >> 1) & ^1) + switch { + case (info[p].complexCategory) < _indSM_trans_keys[_mid]: + _upper = _mid - 2 + case (info[p].complexCategory) > _indSM_trans_keys[_mid+1]: + _lower = _mid + 2 + default: + _trans += int((_mid - int(_keys)) >> 1) + goto _match + } + } + _trans += _klen + } + + _match: + _trans = int(_indSM_indicies[_trans]) + _eof_trans: + cs = int(_indSM_trans_targs[_trans]) + + if _indSM_trans_actions[_trans] == 0 { + goto _again + } + + _acts = int(_indSM_trans_actions[_trans]) + _nacts = uint(_indSM_actions[_acts]) + _acts++ + for ; _nacts > 0; _nacts-- { + _acts++ + switch _indSM_actions[_acts-1] { + case 2: + te = p + 1 + + case 3: + act = 1 + case 4: + act = 5 + case 5: + act = 6 + case 6: + te = p + 1 + { + foundSyllableIndic(indicNonIndicCluster, ts, te, info, &syllableSerial) + } + case 7: + te = p + p-- + { + foundSyllableIndic(indicConsonantSyllable, ts, te, info, &syllableSerial) + } + case 8: + te = p + p-- + { + foundSyllableIndic(indicVowelSyllable, ts, te, info, &syllableSerial) + } + case 9: + te = p + p-- + { + foundSyllableIndic(indicStandaloneCluster, ts, te, info, &syllableSerial) + } + case 10: + te = p + p-- + { + foundSyllableIndic(indicSymbolCluster, ts, te, info, &syllableSerial) + } + case 11: + te = p + p-- + { + foundSyllableIndic(indicBrokenCluster, ts, te, info, &syllableSerial) + buffer.scratchFlags |= bsfHasBrokenSyllable + } + case 12: + te = p + p-- + { + foundSyllableIndic(indicNonIndicCluster, ts, te, info, &syllableSerial) + } + case 13: + p = (te) - 1 + { + foundSyllableIndic(indicConsonantSyllable, ts, te, info, &syllableSerial) + } + case 14: + p = (te) - 1 + { + foundSyllableIndic(indicVowelSyllable, ts, te, info, &syllableSerial) + } + case 15: + p = (te) - 1 + { + foundSyllableIndic(indicStandaloneCluster, ts, te, info, &syllableSerial) + } + case 16: + p = (te) - 1 + { + foundSyllableIndic(indicSymbolCluster, ts, te, info, &syllableSerial) + } + case 17: + p = (te) - 1 + { + foundSyllableIndic(indicBrokenCluster, ts, te, info, &syllableSerial) + buffer.scratchFlags |= bsfHasBrokenSyllable + } + case 18: + switch act { + case 1: + { + p = (te) - 1 + foundSyllableIndic(indicConsonantSyllable, ts, te, info, &syllableSerial) + } + case 5: + { + p = (te) - 1 + foundSyllableIndic(indicBrokenCluster, ts, te, info, &syllableSerial) + buffer.scratchFlags |= bsfHasBrokenSyllable + } + case 6: + { + p = (te) - 1 + foundSyllableIndic(indicNonIndicCluster, ts, te, info, &syllableSerial) + } + } + + } + } + + _again: + _acts = int(_indSM_to_state_actions[cs]) + _nacts = uint(_indSM_actions[_acts]) + _acts++ + for ; _nacts > 0; _nacts-- { + _acts++ + switch _indSM_actions[_acts-1] { + case 0: + ts = 0 + + } + } + + p++ + if p != pe { + goto _resume + } + _test_eof: + { + } + if p == eof { + if _indSM_eof_trans[cs] > 0 { + _trans = int(_indSM_eof_trans[cs] - 1) + goto _eof_trans + } + } + + } + + _ = act // needed by Ragel, but unused +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_indic_machine.rl b/vendor/github.com/go-text/typesetting/harfbuzz/ot_indic_machine.rl new file mode 100644 index 0000000..83bb9e3 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_indic_machine.rl @@ -0,0 +1,99 @@ +package harfbuzz + +// Code generated with ragel -Z -o ot_indic_machine.go ot_indic_machine.rl ; sed -i '/^\/\/line/ d' ot_indic_machine.go ; goimports -w ot_indic_machine.go DO NOT EDIT. + +// ported from harfbuzz/src/hb-ot-shape-complex-indic-machine.rl Copyright © 2015 Google, Inc. Behdad Esfahbod + +// indic_syllable_type_t +const ( + indicConsonantSyllable = iota + indicVowelSyllable + indicStandaloneCluster + indicSymbolCluster + indicBrokenCluster + indicNonIndicCluster +) + +%%{ + machine indSM; + alphtype byte; + write exports; + write data; +}%% + +%%{ + + +export X = 0; +export C = 1; +export V = 2; +export N = 3; +export H = 4; +export ZWNJ = 5; +export ZWJ = 6; +export M = 7; +export SM = 8; +export A = 9; +export VD = 9; +export PLACEHOLDER = 10; +export DOTTEDCIRCLE = 11; +export RS = 12; +export MPst = 13; +export Repha = 14; +export Ra = 15; +export CM = 16; +export Symbol= 17; +export CS = 18; + +c = (C | Ra); # is_consonant +n = ((ZWNJ?.RS)? (N.N?)?); # is_consonant_modifier +z = ZWJ|ZWNJ; # is_joiner +reph = (Ra H | Repha); # possible reph + +cn = c.ZWJ?.n?; +symbol = Symbol.N?; +matra_group = z*.(M | SM? MPst).N?.H?; +syllable_tail = (z?.SM.SM?.ZWNJ?)? (A | VD)*; +halant_group = (z?.H.(ZWJ.N?)?); +final_halant_group = halant_group | H.ZWNJ; +medial_group = CM?; +halant_or_matra_group = (final_halant_group | matra_group*); + +complex_syllable_tail = (halant_group.cn)* medial_group halant_or_matra_group syllable_tail; + +consonant_syllable = (Repha|CS)? cn complex_syllable_tail; +vowel_syllable = reph? V.n? (ZWJ | complex_syllable_tail); +standalone_cluster = ((Repha|CS)? PLACEHOLDER | reph? DOTTEDCIRCLE).n? complex_syllable_tail; +symbol_cluster = symbol syllable_tail; +broken_cluster = reph? n? complex_syllable_tail; +other = any; + +main := |* + consonant_syllable => { foundSyllableIndic (indicConsonantSyllable,ts, te, info, &syllableSerial); }; + vowel_syllable => { foundSyllableIndic (indicVowelSyllable,ts, te, info, &syllableSerial); }; + standalone_cluster => { foundSyllableIndic (indicStandaloneCluster,ts, te, info, &syllableSerial); }; + symbol_cluster => { foundSyllableIndic (indicSymbolCluster,ts, te, info, &syllableSerial); }; + broken_cluster => { foundSyllableIndic (indicBrokenCluster,ts, te, info, &syllableSerial); buffer.scratchFlags |= bsfHasBrokenSyllable; }; + other => { foundSyllableIndic (indicNonIndicCluster,ts, te, info, &syllableSerial); }; +*|; + +}%% + +func findSyllablesIndic (buffer * Buffer) { + var p, ts, te, act, cs int + info := buffer.Info; + %%{ + write init; + getkey info[p].complexCategory; + }%% + + pe := len(info) + eof := pe + + var syllableSerial uint8 = 1; + %%{ + write exec; + }%% + _ = act // needed by Ragel, but unused +} + diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_indic_table.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_indic_table.go new file mode 100644 index 0000000..9969999 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_indic_table.go @@ -0,0 +1,270 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package harfbuzz + +// Code generated by typesettings-utils/generators/unicodedata/cmd/main.go DO NOT EDIT. +var indicTable = [...]uint16{ + + /* Basic Latin */ + 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0x40a, 0xe00, 0xe00, + /* 0030 */ 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, + + /* Latin-1 Supplement */ + + /* 00B0 */ 0xe00, 0xe00, 0xd08, 0xd08, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, + /* 00C0 */ 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, + /* 00D0 */ 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0x40a, + + /* Devanagari */ + + /* 0900 */ 0xd08, 0xd08, 0xd08, 0xd08, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, + /* 0910 */ 0x402, 0x402, 0x402, 0x402, 0x402, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* 0920 */ 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* 0930 */ 0x40f, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x907, 0x907, 0xe03, 0xd11, 0x907, 0x207, + /* 0940 */ 0x907, 0x907, 0x907, 0x907, 0x907, 0x907, 0x907, 0x907, 0x907, 0x907, 0x907, 0x907, 0x907, 0x804, 0x207, 0x907, + /* 0950 */ 0xe00, 0xd09, 0xd09, 0xd08, 0xd08, 0x907, 0x907, 0x907, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* 0960 */ 0x402, 0x402, 0x907, 0x907, 0xe00, 0xe00, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, + /* 0970 */ 0xe00, 0xe00, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + + /* Bengali */ + + /* 0980 */ 0x40a, 0xd08, 0xd08, 0xd08, 0xe00, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0xe00, 0xe00, 0x402, + /* 0990 */ 0x402, 0xe00, 0xe00, 0x402, 0x402, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* 09A0 */ 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0xe00, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* 09B0 */ 0x40f, 0xe00, 0x401, 0xe00, 0xe00, 0xe00, 0x401, 0x401, 0x401, 0x401, 0xe00, 0xe00, 0xe03, 0xd11, 0xc07, 0x207, + /* 09C0 */ 0xc07, 0x907, 0x907, 0x907, 0x907, 0xe00, 0xe00, 0x207, 0x207, 0xe00, 0xe00, 0xc07, 0xc07, 0x804, 0x401, 0xe00, + /* 09D0 */ 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xc07, 0xe00, 0xe00, 0xe00, 0xe00, 0x401, 0x401, 0xe00, 0x401, + /* 09E0 */ 0x402, 0x402, 0x907, 0x907, 0xe00, 0xe00, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, + /* 09F0 */ 0x40f, 0x401, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0x40a, 0xe00, 0xd08, 0xe00, + + /* Gurmukhi */ + + /* 0A00 */ 0xe00, 0xd08, 0xd08, 0xd08, 0xe00, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0xe00, 0xe00, 0xe00, 0xe00, 0x402, + /* 0A10 */ 0x402, 0xe00, 0xe00, 0x402, 0x402, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* 0A20 */ 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0xe00, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* 0A30 */ 0x40f, 0xe00, 0x401, 0x401, 0xe00, 0x401, 0x401, 0xe00, 0x401, 0x401, 0xe00, 0xe00, 0xe03, 0xe00, 0xc07, 0x207, + /* 0A40 */ 0xc0d, 0xc07, 0xc07, 0xe00, 0xe00, 0xe00, 0xe00, 0xc07, 0xc07, 0xe00, 0xe00, 0xc07, 0xc07, 0x804, 0xe00, 0xe00, + /* 0A50 */ 0xe00, 0x807, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0x401, 0x401, 0x401, 0x401, 0xe00, 0x401, 0xe00, + /* 0A60 */ 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, + /* 0A70 */ 0xd08, 0xd08, 0x401, 0x401, 0xe00, 0x410, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, + + /* Gujarati */ + + /* 0A80 */ 0xe00, 0xd08, 0xd08, 0xd08, 0xe00, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0xe00, 0x402, + /* 0A90 */ 0x402, 0x402, 0xe00, 0x402, 0x402, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* 0AA0 */ 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0xe00, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* 0AB0 */ 0x40f, 0xe00, 0x401, 0x401, 0xe00, 0x401, 0x401, 0x401, 0x401, 0x401, 0xe00, 0xe00, 0xe03, 0xd11, 0xc07, 0x207, + /* 0AC0 */ 0xc07, 0xc07, 0xc07, 0xc07, 0xc07, 0x907, 0xe00, 0x907, 0x907, 0xc07, 0xe00, 0xc07, 0xc07, 0x804, 0xe00, 0xe00, + /* 0AD0 */ 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, + /* 0AE0 */ 0x402, 0x402, 0xc07, 0xc07, 0xe00, 0xe00, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, + /* 0AF0 */ 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0x401, 0xd09, 0xe03, 0xd09, 0xe03, 0xe03, 0xe03, + + /* Oriya */ + + /* 0B00 */ 0xe00, 0x708, 0xd08, 0xd08, 0xe00, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0xe00, 0xe00, 0x402, + /* 0B10 */ 0x402, 0xe00, 0xe00, 0x402, 0x402, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* 0B20 */ 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0xe00, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* 0B30 */ 0x40f, 0xe00, 0x401, 0x401, 0xe00, 0x401, 0x401, 0x401, 0x401, 0x401, 0xe00, 0xe00, 0xe03, 0xd11, 0xc07, 0x507, + /* 0B40 */ 0xc07, 0x907, 0x907, 0x907, 0x907, 0xe00, 0xe00, 0x207, 0x507, 0xe00, 0xe00, 0xc07, 0xc07, 0x804, 0xe00, 0xe00, + /* 0B50 */ 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe03, 0x507, 0xc07, 0xe00, 0xe00, 0xe00, 0xe00, 0x401, 0x401, 0xe00, 0x401, + /* 0B60 */ 0x402, 0x402, 0x907, 0x907, 0xe00, 0xe00, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, + /* 0B70 */ 0xe00, 0x401, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, + + /* Tamil */ + + /* 0B80 */ 0xe00, 0xe00, 0xd08, 0xe00, 0xe00, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0xe00, 0xe00, 0xe00, 0x402, 0x402, + /* 0B90 */ 0x402, 0xe00, 0x402, 0x402, 0x402, 0x401, 0xe00, 0xe00, 0xe00, 0x401, 0x401, 0xe00, 0x401, 0xe00, 0x401, 0x401, + /* 0BA0 */ 0xe00, 0xe00, 0xe00, 0x401, 0x401, 0xe00, 0xe00, 0xe00, 0x401, 0x401, 0x401, 0xe00, 0xe00, 0xe00, 0x401, 0x401, + /* 0BB0 */ 0x40f, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0xe00, 0xe00, 0xe00, 0xe00, 0xc07, 0xc07, + /* 0BC0 */ 0x907, 0xc07, 0xc07, 0xe00, 0xe00, 0xe00, 0x207, 0x207, 0x207, 0xe00, 0xc07, 0xc07, 0xc07, 0x604, 0xe00, 0xe00, + /* 0BD0 */ 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xc07, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, + /* 0BE0 */ 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, + /* 0BF0 */ 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, + + /* Telugu */ + + /* 0C00 */ 0xd08, 0xd08, 0xd08, 0xd08, 0xd08, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0xe00, 0x402, 0x402, + /* 0C10 */ 0x402, 0xe00, 0x402, 0x402, 0x402, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* 0C20 */ 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0xe00, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* 0C30 */ 0x40f, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0xe00, 0xe00, 0xe03, 0xd11, 0x707, 0x707, + /* 0C40 */ 0x707, 0x707, 0x707, 0x907, 0x907, 0xe00, 0x707, 0x707, 0x707, 0xe00, 0x707, 0x707, 0x707, 0x604, 0xe00, 0xe00, + /* 0C50 */ 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0x707, 0x707, 0xe00, 0x401, 0x401, 0x401, 0xe00, 0xe00, 0x401, 0xe00, 0xe00, + /* 0C60 */ 0x402, 0x402, 0x707, 0x707, 0xe00, 0xe00, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, + /* 0C70 */ 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, + + /* Kannada */ + + /* 0C80 */ 0x40a, 0xd08, 0xd08, 0xd08, 0xe00, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0xe00, 0x402, 0x402, + /* 0C90 */ 0x402, 0xe00, 0x402, 0x402, 0x402, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* 0CA0 */ 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0xe00, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* 0CB0 */ 0x40f, 0x401, 0x401, 0x401, 0xe00, 0x401, 0x401, 0x401, 0x401, 0x401, 0xe00, 0xe00, 0xe03, 0xd11, 0x707, 0x707, + /* 0CC0 */ 0x707, 0x707, 0x707, 0x907, 0x907, 0xe00, 0x707, 0x907, 0x907, 0xe00, 0x907, 0x907, 0x707, 0x604, 0xe00, 0xe00, + /* 0CD0 */ 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0x907, 0x907, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0x401, 0x401, 0xe00, + /* 0CE0 */ 0x402, 0x402, 0x707, 0x707, 0xe00, 0xe00, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, + /* 0CF0 */ 0xe00, 0x412, 0x412, 0xd08, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, + + /* Malayalam */ + + /* 0D00 */ 0xd08, 0xd08, 0xd08, 0xd08, 0x40a, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0xe00, 0x402, 0x402, + /* 0D10 */ 0x402, 0xe00, 0x402, 0x402, 0x402, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* 0D20 */ 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* 0D30 */ 0x40f, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x907, 0x907, 0xd11, 0xc07, 0xc07, + /* 0D40 */ 0xc07, 0xc07, 0xc07, 0xc07, 0xc07, 0xe00, 0x207, 0x207, 0x207, 0xe00, 0xc07, 0xc07, 0xc07, 0x604, 0xe0e, 0xe00, + /* 0D50 */ 0xe00, 0xe00, 0xe00, 0xe00, 0x401, 0x401, 0x401, 0xc07, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0x402, + /* 0D60 */ 0x402, 0x402, 0xc07, 0xc07, 0xe00, 0xe00, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, + /* 0D70 */ 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + + /* Myanmar */ + + /* 1000 */ 0x401, 0x401, 0x401, 0x401, 0x40f, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* 1010 */ 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x40f, 0x401, 0x401, 0x401, 0x401, + /* 1020 */ 0x401, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0xb17, 0xb17, 0x614, 0x614, 0x815, + /* 1030 */ 0x815, 0x316, 0xd09, 0x614, 0x614, 0x614, 0xd09, 0xe03, 0xd08, 0xe04, 0xe20, 0xe26, 0xe24, 0xe25, 0xe23, 0x401, + /* 1040 */ 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0xe00, 0xe00, 0x401, 0xe00, + /* 1050 */ 0x401, 0x401, 0x402, 0x402, 0x402, 0x402, 0xb17, 0xb17, 0x815, 0x815, 0x40f, 0x401, 0x401, 0x401, 0xe26, 0xe26, + /* 1060 */ 0xe29, 0x401, 0xb17, 0xe27, 0xe27, 0x401, 0x401, 0xb17, 0xb17, 0xe27, 0xe27, 0xe27, 0xe27, 0xe27, 0x401, 0x401, + /* 1070 */ 0x401, 0x614, 0x614, 0x614, 0x614, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* 1080 */ 0x401, 0x401, 0xe25, 0xb17, 0x316, 0x614, 0x614, 0xd08, 0xd08, 0xd08, 0xd08, 0xd08, 0xd08, 0xd08, 0x401, 0xd08, + /* 1090 */ 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0xd08, 0xd08, 0xd08, 0x614, 0xe00, 0xe00, + + /* Khmer */ + + /* 1780 */ 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* 1790 */ 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x40f, 0x401, 0x401, 0x401, 0x401, 0x401, + /* 17A0 */ 0x401, 0x401, 0x401, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, 0x402, + /* 17B0 */ 0x402, 0x402, 0x402, 0x402, 0xe00, 0xe00, 0xb17, 0x614, 0x614, 0x614, 0x614, 0x815, 0x815, 0x815, 0x614, 0xb17, + /* 17C0 */ 0xb17, 0x316, 0x316, 0x316, 0xb17, 0xb17, 0xe1a, 0xe1b, 0xe1b, 0xe19, 0xe19, 0xe1a, 0xe19, 0xe1a, 0xe1a, 0xe1a, + /* 17D0 */ 0xe1a, 0xe1a, 0xe04, 0xe1b, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0x40a, 0xe00, 0xe00, 0xd11, 0xe1b, 0xe00, 0xe00, + /* 17E0 */ 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, + + /* Vedic Extensions */ + + /* 1CD0 */ 0xd09, 0xd09, 0xd09, 0xe00, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, + /* 1CE0 */ 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd11, 0xd11, 0xd11, 0xd11, 0xd09, 0xd11, 0xd11, + /* 1CF0 */ 0xd11, 0xd11, 0x401, 0x401, 0xd09, 0x401, 0x401, 0xd09, 0xd09, 0xd09, 0x40a, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, + + /* General Punctuation */ + 0xe00, 0xe00, 0xe00, 0xe00, 0xe05, 0xe06, 0xe00, 0xe00, + /* 2010 */ 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, + /* 2020 */ 0xe00, 0xe00, 0x40a, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, + + /* Superscripts and Subscripts */ + + /* 2070 */ 0xe00, 0xe00, 0xe00, 0xe00, 0xd08, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, + /* 2080 */ 0xe00, 0xe00, 0xd08, 0xd08, 0xd08, 0xe00, 0xe00, 0xe00, + + /* Geometric Shapes */ + 0xe00, 0xe00, 0xe00, 0x40a, 0x40a, 0x40a, 0x40a, 0xe00, + + /* Devanagari Extended */ + + /* A8E0 */ 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, 0xd09, + /* A8F0 */ 0xd09, 0xd09, 0xd11, 0xd11, 0xd11, 0xd11, 0xd11, 0xd11, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0x402, 0x907, + + /* Myanmar Extended-B */ + + /* A9E0 */ 0x401, 0x401, 0x401, 0x401, 0x401, 0x614, 0xe00, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* A9F0 */ 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x40a, 0x401, 0x401, 0x401, 0x401, 0x401, 0xe00, + + /* Myanmar Extended-A */ + + /* AA60 */ 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, 0x401, + /* AA70 */ 0xe00, 0x401, 0x401, 0x401, 0x40a, 0x40a, 0x40a, 0xe00, 0xe00, 0xe00, 0x401, 0xe27, 0xe03, 0xe03, 0x401, 0x401, + + /* Variation Selectors */ + + /* FE00 */ 0xe28, 0xe28, 0xe28, 0xe28, 0xe28, 0xe28, 0xe28, 0xe28, 0xe28, 0xe28, 0xe28, 0xe28, 0xe28, 0xe28, 0xe28, 0xe28, + + /* Grantha */ + + /* 11300 */ 0xe00, 0xd08, 0xd08, 0xd08, 0xe00, 0xe00, 0xe00, 0xe00, + + 0xe00, 0xe00, 0xe00, 0xe03, 0xe03, 0xe00, 0xe00, 0xe00, +} /* Table items: 1728; occupancy: 71% */ + +const ( + offsetIndic0x0028u = 0 + offsetIndic0x00b0u = 24 + offsetIndic0x0900u = 64 + offsetIndic0x1000u = 1216 + offsetIndic0x1780u = 1376 + offsetIndic0x1cd0u = 1488 + offsetIndic0x2008u = 1536 + offsetIndic0x2070u = 1568 + offsetIndic0x25f8u = 1592 + offsetIndic0xa8e0u = 1600 + offsetIndic0xa9e0u = 1632 + offsetIndic0xaa60u = 1664 + offsetIndic0xfe00u = 1696 + offsetIndic0x11300u = 1712 + offsetIndic0x11338u = 1720 +) + +func indicGetCategories(u rune) uint16 { + switch u >> 12 { + case 0x0: + if u == 0x00A0 { + return 0x40a + } + if 0x0028 <= u && u <= 0x003F { + return indicTable[u-0x0028+offsetIndic0x0028u] + } + if 0x00B0 <= u && u <= 0x00D7 { + return indicTable[u-0x00B0+offsetIndic0x00b0u] + } + if 0x0900 <= u && u <= 0x0D7F { + return indicTable[u-0x0900+offsetIndic0x0900u] + } + + case 0x1: + if 0x1000 <= u && u <= 0x109F { + return indicTable[u-0x1000+offsetIndic0x1000u] + } + if 0x1780 <= u && u <= 0x17EF { + return indicTable[u-0x1780+offsetIndic0x1780u] + } + if 0x1CD0 <= u && u <= 0x1CFF { + return indicTable[u-0x1CD0+offsetIndic0x1cd0u] + } + + case 0x2: + if u == 0x25CC { + return 0x40b + } + if 0x2008 <= u && u <= 0x2027 { + return indicTable[u-0x2008+offsetIndic0x2008u] + } + if 0x2070 <= u && u <= 0x2087 { + return indicTable[u-0x2070+offsetIndic0x2070u] + } + if 0x25F8 <= u && u <= 0x25FF { + return indicTable[u-0x25F8+offsetIndic0x25f8u] + } + + case 0xA: + if 0xA8E0 <= u && u <= 0xA8FF { + return indicTable[u-0xA8E0+offsetIndic0xa8e0u] + } + if 0xA9E0 <= u && u <= 0xA9FF { + return indicTable[u-0xA9E0+offsetIndic0xa9e0u] + } + if 0xAA60 <= u && u <= 0xAA7F { + return indicTable[u-0xAA60+offsetIndic0xaa60u] + } + + case 0xF: + if 0xFE00 <= u && u <= 0xFE0F { + return indicTable[u-0xFE00+offsetIndic0xfe00u] + } + + case 0x11: + if 0x11300 <= u && u <= 0x11307 { + return indicTable[u-0x11300+offsetIndic0x11300u] + } + if 0x11338 <= u && u <= 0x1133F { + return indicTable[u-0x11338+offsetIndic0x11338u] + } + + } + return 0xe00 +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_kern.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_kern.go new file mode 100644 index 0000000..ac04b57 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_kern.go @@ -0,0 +1,99 @@ +package harfbuzz + +import fontP "github.com/go-text/typesetting/font" + +func simpleKern(kernTable fontP.Kernx) fontP.SimpleKerns { + for _, subtable := range kernTable { + if simple, ok := subtable.Data.(fontP.SimpleKerns); ok { + return simple + } + } + return nil +} + +func kern(driver fontP.SimpleKerns, crossStream bool, font *Font, buffer *Buffer, kernMask GlyphMask, scale bool) { + buffer.unsafeToConcat(0, maxInt) + + var c otApplyContext + + c.reset(1, font, buffer) + c.setLookupMask(kernMask) + c.setLookupProps(uint32(otIgnoreMarks)) + skippyIter := &c.iterInput + horizontal := buffer.Props.Direction.isHorizontal() + info := buffer.Info + pos := buffer.Pos + for idx := 0; idx < len(pos); { + if info[idx].Mask&kernMask == 0 { + idx++ + continue + } + + skippyIter.reset(idx, 1) + if ok, _ := skippyIter.next(); !ok { + idx++ + continue + } + + i := idx + j := skippyIter.idx + + rawKern := driver.KernPair(info[i].Glyph, info[j].Glyph) + kern := Position(rawKern) + + if rawKern == 0 { + goto skip + } + + if horizontal { + if scale { + kern = font.emScaleX(rawKern) + } + if crossStream { + pos[j].YOffset = kern + buffer.scratchFlags |= bsfHasGPOSAttachment + } else { + kern1 := kern >> 1 + kern2 := kern - kern1 + pos[i].XAdvance += kern1 + pos[j].XAdvance += kern2 + pos[j].XOffset += kern2 + } + } else { + if scale { + kern = font.emScaleY(rawKern) + } + if crossStream { + pos[j].XOffset = kern + buffer.scratchFlags |= bsfHasGPOSAttachment + } else { + kern1 := kern >> 1 + kern2 := kern - kern1 + pos[i].YAdvance += kern1 + pos[j].YAdvance += kern2 + pos[j].YOffset += kern2 + } + } + + buffer.unsafeToBreak(i, j+1) + + skip: + idx = skippyIter.idx + } +} + +func (sp *otShapePlan) otApplyFallbackKern(font *Font, buffer *Buffer) { + reverse := buffer.Props.Direction.isBackward() + + if reverse { + buffer.Reverse() + } + + if driver := simpleKern(font.face.Kern); driver != nil { + kern(driver, false, font, buffer, sp.kernMask, false) + } + + if reverse { + buffer.Reverse() + } +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_khmer.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_khmer.go new file mode 100644 index 0000000..3d9519b --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_khmer.go @@ -0,0 +1,299 @@ +package harfbuzz + +import ( + "fmt" + + ot "github.com/go-text/typesetting/font/opentype" + "github.com/go-text/typesetting/font/opentype/tables" +) + +// ported from harfbuzz/src/hb-ot-shape-complex-khmer.cc Copyright © 2011,2012 Google, Inc. Behdad Esfahbod + +var _ otComplexShaper = (*complexShaperKhmer)(nil) + +// Khmer shaper +type complexShaperKhmer struct { + plan khmerShapePlan +} + +var khmerFeatures = [...]otMapFeature{ + /* + * Basic features. + * These features are applied in order, one at a time, after reordering. + */ + {ot.NewTag('p', 'r', 'e', 'f'), ffManualJoiners | ffPerSyllable}, + {ot.NewTag('b', 'l', 'w', 'f'), ffManualJoiners | ffPerSyllable}, + {ot.NewTag('a', 'b', 'v', 'f'), ffManualJoiners | ffPerSyllable}, + {ot.NewTag('p', 's', 't', 'f'), ffManualJoiners | ffPerSyllable}, + {ot.NewTag('c', 'f', 'a', 'r'), ffManualJoiners | ffPerSyllable}, + /* + * Other features. + * These features are applied all at once after clearing syllables. + */ + {ot.NewTag('p', 'r', 'e', 's'), ffGlobalManualJoiners}, + {ot.NewTag('a', 'b', 'v', 's'), ffGlobalManualJoiners}, + {ot.NewTag('b', 'l', 'w', 's'), ffGlobalManualJoiners}, + {ot.NewTag('p', 's', 't', 's'), ffGlobalManualJoiners}, +} + +// Must be in the same order as the khmerFeatures array. +const ( + khmerPref = iota + khmerBlwf + khmerAbvf + khmerPstf + khmerCfar + + khmerPres + khmerAbvs + khmerBlws + khmerPsts + + khmerNumFeatures + khmerBasicFeatures = khmerPres /* Don't forget to update this! */ +) + +func (cs *complexShaperKhmer) collectFeatures(plan *otShapePlanner) { + map_ := &plan.map_ + + /* Do this before any lookups have been applied. */ + map_.addGSUBPause(setupSyllablesKhmer) + map_.addGSUBPause(cs.reorderKhmer) + + /* Testing suggests that Uniscribe does NOT pause between basic + * features. Test with KhmerUI.ttf and the following three + * sequences: + * + * U+1789,U+17BC + * U+1789,U+17D2,U+1789 + * U+1789,U+17D2,U+1789,U+17BC + * + * https://github.com/harfbuzz/harfbuzz/issues/974 + */ + map_.enableFeatureExt(ot.NewTag('l', 'o', 'c', 'l'), ffPerSyllable, 1) + map_.enableFeatureExt(ot.NewTag('c', 'c', 'm', 'p'), ffPerSyllable, 1) + + i := 0 + for ; i < khmerBasicFeatures; i++ { + map_.addFeatureExt(khmerFeatures[i].tag, khmerFeatures[i].flags, 1) + } + + // https://github.com/harfbuzz/harfbuzz/issues/3531 + map_.addGSUBPause(nil) + + for ; i < khmerNumFeatures; i++ { + map_.addFeatureExt(khmerFeatures[i].tag, khmerFeatures[i].flags, 1) + } +} + +func (complexShaperKhmer) overrideFeatures(plan *otShapePlanner) { + map_ := &plan.map_ + + /* Khmer spec has 'clig' as part of required shaping features: + * "Apply feature 'clig' to form ligatures that are desired for + * typographical correctness.", hence in overrides... */ + map_.enableFeature(ot.NewTag('c', 'l', 'i', 'g')) + + /* Uniscribe does not apply 'kern' in Khmer. */ + if UniscribeBugCompatible { + map_.disableFeature(ot.NewTag('k', 'e', 'r', 'n')) + } + + map_.disableFeature(ot.NewTag('l', 'i', 'g', 'a')) +} + +type khmerShapePlan struct { + viramaGlyph GID + maskArray [khmerNumFeatures]GlyphMask +} + +func (cs *complexShaperKhmer) dataCreate(plan *otShapePlan) { + var khmerPlan khmerShapePlan + + khmerPlan.viramaGlyph = ^GID(0) + + for i := range khmerPlan.maskArray { + if khmerFeatures[i].flags&ffGLOBAL == 0 { + khmerPlan.maskArray[i] = plan.map_.getMask1(khmerFeatures[i].tag) + } + } + + cs.plan = khmerPlan +} + +func (cs *complexShaperKhmer) setupMasks(_ *otShapePlan, buffer *Buffer, _ *Font) { + /* We cannot setup masks here. We save information about characters + * and setup masks later on in a pause-callback. */ + + info := buffer.Info + for i := range info { + setKhmerProperties(&info[i]) + } +} + +func setKhmerProperties(info *GlyphInfo) { + u := info.codepoint + type_ := indicGetCategories(u) + info.complexCategory = uint8(type_ & 0xFF) +} + +func setupSyllablesKhmer(_ *otShapePlan, _ *Font, buffer *Buffer) bool { + findSyllablesKhmer(buffer) + iter, count := buffer.syllableIterator() + for start, end := iter.next(); start < count; start, end = iter.next() { + buffer.unsafeToBreak(start, end) + } + return false +} + +func foundSyllableKhmer(syllableType uint8, ts, te int, info []GlyphInfo, syllableSerial *uint8) { + for i := ts; i < te; i++ { + info[i].syllable = (*syllableSerial << 4) | syllableType + } + *syllableSerial++ + if *syllableSerial == 16 { + *syllableSerial = 1 + } +} + +/* Rules from: + * https://docs.microsoft.com/en-us/typography/script-development/devanagari */ +func (khmerPlan *khmerShapePlan) reorderConsonantSyllable(buffer *Buffer, start, end int) { + info := buffer.Info + + /* Setup masks. */ + { + /* Post-base */ + mask := khmerPlan.maskArray[khmerBlwf] | + khmerPlan.maskArray[khmerAbvf] | + khmerPlan.maskArray[khmerPstf] + for i := start + 1; i < end; i++ { + info[i].Mask |= mask + } + } + + numCoengs := 0 + for i := start + 1; i < end; i++ { + /* """ + * When a COENG + (Cons | IndV) combination are found (and subscript count + * is less than two) the character combination is handled according to the + * subscript type of the character following the COENG. + * + * ... + * + * Subscript Type 2 - The COENG + RO characters are reordered to immediately + * before the base glyph. Then the COENG + RO characters are assigned to have + * the 'pref' OpenType feature applied to them. + * """ + */ + if info[i].complexCategory == khmSM_ex_H && numCoengs <= 2 && i+1 < end { + numCoengs++ + + if info[i+1].complexCategory == khmSM_ex_Ra { + for j := 0; j < 2; j++ { + info[i+j].Mask |= khmerPlan.maskArray[khmerPref] + } + + /* Move the Coeng,Ro sequence to the start. */ + buffer.mergeClusters(start, i+2) + t0 := info[i] + t1 := info[i+1] + copy(info[start+2:], info[start:i]) + info[start] = t0 + info[start+1] = t1 + + /* Mark the subsequent stuff with 'cfar'. Used in Khmer. + * Read the feature spec. + * This allows distinguishing the following cases with MS Khmer fonts: + * U+1784,U+17D2,U+179A,U+17D2,U+1782 + * U+1784,U+17D2,U+1782,U+17D2,U+179A + */ + if khmerPlan.maskArray[khmerCfar] != 0 { + for j := i + 2; j < end; j++ { + info[j].Mask |= khmerPlan.maskArray[khmerCfar] + } + } + + numCoengs = 2 /* Done. */ + } + } else if info[i].complexCategory == khmSM_ex_VPre { /* Reorder left matra piece. */ + /* Move to the start. */ + buffer.mergeClusters(start, i+1) + t := info[i] + copy(info[start+1:], info[start:i]) + info[start] = t + } + } +} + +func (cs *complexShaperKhmer) reorderSyllableKhmer(buffer *Buffer, start, end int) { + syllableType := buffer.Info[start].syllable & 0x0F + switch syllableType { + case khmerBrokenCluster, /* We already inserted dotted-circles, so just call the consonant_syllable. */ + khmerConsonantSyllable: + cs.plan.reorderConsonantSyllable(buffer, start, end) + } +} + +func (cs *complexShaperKhmer) reorderKhmer(_ *otShapePlan, font *Font, buffer *Buffer) bool { + if debugMode { + fmt.Println("KHMER - start reordering khmer") + } + + ret := syllabicInsertDottedCircles(font, buffer, khmerBrokenCluster, khmSM_ex_DOTTEDCIRCLE, -1, -1) + iter, count := buffer.syllableIterator() + for start, end := iter.next(); start < count; start, end = iter.next() { + cs.reorderSyllableKhmer(buffer, start, end) + } + + if debugMode { + fmt.Println("KHMER - end reordering khmer") + } + + return ret +} + +func (complexShaperKhmer) decompose(c *otNormalizeContext, ab rune) (rune, rune, bool) { + switch ab { + /* + * Decompose split matras that don't have Unicode decompositions. + */ + + /* Khmer */ + case 0x17BE: + return 0x17C1, 0x17BE, true + case 0x17BF: + return 0x17C1, 0x17BF, true + case 0x17C0: + return 0x17C1, 0x17C0, true + case 0x17C4: + return 0x17C1, 0x17C4, true + case 0x17C5: + return 0x17C1, 0x17C5, true + } + + return uni.decompose(ab) +} + +func (complexShaperKhmer) compose(_ *otNormalizeContext, a, b rune) (rune, bool) { + /* Avoid recomposing split matras. */ + if uni.generalCategory(a).isMark() { + return 0, false + } + + return uni.compose(a, b) +} + +func (complexShaperKhmer) marksBehavior() (zeroWidthMarks, bool) { + return zeroWidthMarksNone, false +} + +func (complexShaperKhmer) normalizationPreference() normalizationMode { + return nmComposedDiacriticsNoShortCircuit +} + +func (complexShaperKhmer) gposTag() tables.Tag { return 0 } +func (complexShaperKhmer) preprocessText(*otShapePlan, *Buffer, *Font) {} +func (complexShaperKhmer) postprocessGlyphs(*otShapePlan, *Buffer, *Font) { +} +func (complexShaperKhmer) reorderMarks(*otShapePlan, *Buffer, int, int) {} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_khmer_machine.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_khmer_machine.go new file mode 100644 index 0000000..acf8566 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_khmer_machine.go @@ -0,0 +1,384 @@ +package harfbuzz + +// Code generated with ragel -Z -o ot_khmer_machine.go ot_khmer_machine.rl ; sed -i '/^\/\/line/ d' ot_khmer_machine.go ; goimports -w ot_khmer_machine.go DO NOT EDIT. + +// ported from harfbuzz/src/hb-ot-shape-complex-khmer-machine.rl Copyright © 2015 Google, Inc. Behdad Esfahbod + +const ( + khmerConsonantSyllable = iota + khmerBrokenCluster + khmerNonKhmerCluster +) + +const khmSM_ex_C = 1 +const khmSM_ex_DOTTEDCIRCLE = 11 +const khmSM_ex_H = 4 +const khmSM_ex_PLACEHOLDER = 10 +const khmSM_ex_Ra = 15 +const khmSM_ex_Robatic = 25 +const khmSM_ex_V = 2 +const khmSM_ex_VAbv = 20 +const khmSM_ex_VBlw = 21 +const khmSM_ex_VPre = 22 +const khmSM_ex_VPst = 23 +const khmSM_ex_Xgroup = 26 +const khmSM_ex_Ygroup = 27 +const khmSM_ex_ZWJ = 6 +const khmSM_ex_ZWNJ = 5 + +var _khmSM_actions []byte = []byte{ + 0, 1, 0, 1, 1, 1, 2, 1, 5, + 1, 6, 1, 7, 1, 8, 1, 9, + 1, 10, 1, 11, 2, 2, 3, 2, + 2, 4, +} + +var _khmSM_key_offsets []byte = []byte{ + 0, 5, 8, 11, 15, 18, 21, 25, + 28, 32, 35, 40, 45, 48, 51, 55, + 58, 61, 65, 68, 72, 75, 90, 100, + 103, 113, 122, 123, 129, 134, 141, 149, + 158, 168, 171, 181, 190, 191, 197, 202, + 209, 217, 226, +} + +var _khmSM_trans_keys []byte = []byte{ + 20, 25, 26, 5, 6, 26, 5, 6, + 15, 1, 2, 20, 26, 5, 6, 26, + 5, 6, 26, 5, 6, 20, 26, 5, + 6, 26, 5, 6, 20, 26, 5, 6, + 26, 5, 6, 20, 25, 26, 5, 6, + 20, 25, 26, 5, 6, 26, 5, 6, + 15, 1, 2, 20, 26, 5, 6, 26, + 5, 6, 26, 5, 6, 20, 26, 5, + 6, 26, 5, 6, 20, 26, 5, 6, + 26, 5, 6, 4, 15, 20, 21, 22, + 23, 25, 26, 27, 1, 2, 5, 6, + 10, 11, 4, 20, 21, 22, 23, 25, + 26, 27, 5, 6, 15, 1, 2, 4, + 20, 21, 22, 23, 25, 26, 27, 5, + 6, 4, 20, 21, 22, 23, 26, 27, + 5, 6, 27, 4, 23, 26, 27, 5, + 6, 4, 26, 27, 5, 6, 4, 20, + 23, 26, 27, 5, 6, 4, 20, 21, + 23, 26, 27, 5, 6, 4, 20, 21, + 22, 23, 26, 27, 5, 6, 4, 20, + 21, 22, 23, 25, 26, 27, 5, 6, + 15, 1, 2, 4, 20, 21, 22, 23, + 25, 26, 27, 5, 6, 4, 20, 21, + 22, 23, 26, 27, 5, 6, 27, 4, + 23, 26, 27, 5, 6, 4, 26, 27, + 5, 6, 4, 20, 23, 26, 27, 5, + 6, 4, 20, 21, 23, 26, 27, 5, + 6, 4, 20, 21, 22, 23, 26, 27, + 5, 6, 20, 26, 5, 6, +} + +var _khmSM_single_lengths []byte = []byte{ + 3, 1, 1, 2, 1, 1, 2, 1, + 2, 1, 3, 3, 1, 1, 2, 1, + 1, 2, 1, 2, 1, 9, 8, 1, + 8, 7, 1, 4, 3, 5, 6, 7, + 8, 1, 8, 7, 1, 4, 3, 5, + 6, 7, 2, +} + +var _khmSM_range_lengths []byte = []byte{ + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 3, 1, 1, + 1, 1, 0, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 0, 1, 1, 1, + 1, 1, 1, +} + +var _khmSM_index_offsets []int16 = []int16{ + 0, 5, 8, 11, 15, 18, 21, 25, + 28, 32, 35, 40, 45, 48, 51, 55, + 58, 61, 65, 68, 72, 75, 88, 98, + 101, 111, 120, 122, 128, 133, 140, 148, + 157, 167, 170, 180, 189, 191, 197, 202, + 209, 217, 226, +} + +var _khmSM_indicies []byte = []byte{ + 2, 3, 4, 1, 0, 4, 1, 0, + 5, 5, 0, 2, 4, 1, 0, 2, + 6, 0, 8, 7, 0, 2, 10, 9, + 0, 10, 9, 0, 2, 12, 11, 0, + 12, 11, 0, 2, 13, 4, 1, 0, + 16, 17, 18, 15, 14, 18, 15, 19, + 20, 20, 14, 16, 18, 15, 14, 16, + 21, 14, 23, 22, 14, 16, 25, 24, + 14, 25, 24, 14, 16, 27, 26, 14, + 27, 26, 14, 30, 29, 16, 25, 27, + 23, 17, 18, 20, 29, 31, 13, 28, + 33, 2, 10, 12, 8, 13, 4, 5, + 34, 32, 35, 35, 32, 33, 2, 10, + 12, 8, 3, 4, 5, 36, 32, 37, + 2, 10, 12, 8, 4, 5, 38, 32, + 5, 32, 37, 8, 2, 5, 6, 32, + 37, 8, 5, 7, 32, 37, 2, 8, + 10, 5, 39, 32, 37, 2, 10, 8, + 12, 5, 40, 32, 33, 2, 10, 12, + 8, 4, 5, 38, 32, 33, 2, 10, + 12, 8, 3, 4, 5, 38, 32, 42, + 42, 41, 30, 16, 25, 27, 23, 17, + 18, 20, 43, 41, 44, 16, 25, 27, + 23, 18, 20, 45, 41, 20, 41, 44, + 23, 16, 20, 21, 41, 44, 23, 20, + 22, 41, 44, 16, 23, 25, 20, 46, + 41, 44, 16, 25, 23, 27, 20, 47, + 41, 30, 16, 25, 27, 23, 18, 20, + 45, 41, 16, 18, 15, 48, +} + +var _khmSM_trans_targs []byte = []byte{ + 21, 1, 27, 31, 25, 26, 4, 5, + 28, 7, 29, 9, 30, 32, 21, 12, + 37, 41, 35, 21, 36, 15, 16, 38, + 18, 39, 20, 40, 21, 22, 33, 42, + 21, 23, 10, 24, 0, 2, 3, 6, + 8, 21, 34, 11, 13, 14, 17, 19, + 21, +} + +var _khmSM_trans_actions []byte = []byte{ + 15, 0, 5, 5, 5, 0, 0, 0, + 5, 0, 5, 0, 5, 5, 17, 0, + 5, 21, 21, 19, 0, 0, 0, 5, + 0, 5, 0, 5, 7, 5, 0, 24, + 9, 0, 0, 5, 0, 0, 0, 0, + 0, 11, 21, 0, 0, 0, 0, 0, + 13, +} + +var _khmSM_to_state_actions []byte = []byte{ + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, +} + +var _khmSM_from_state_actions []byte = []byte{ + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 3, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, +} + +var _khmSM_eof_trans []int16 = []int16{ + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 15, 20, 15, 15, 15, + 15, 15, 15, 15, 15, 0, 33, 33, + 33, 33, 33, 33, 33, 33, 33, 33, + 33, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 49, +} + +const khmSM_start int = 21 +const khmSM_first_final int = 21 +const khmSM_error int = -1 + +const khmSM_en_main int = 21 + +func findSyllablesKhmer(buffer *Buffer) { + var p, ts, te, act, cs int + info := buffer.Info + + { + cs = khmSM_start + ts = 0 + te = 0 + act = 0 + } + + pe := len(info) + eof := pe + + var syllableSerial uint8 = 1 + + { + var _klen int + var _trans int + var _acts int + var _nacts uint + var _keys int + if p == pe { + goto _test_eof + } + _resume: + _acts = int(_khmSM_from_state_actions[cs]) + _nacts = uint(_khmSM_actions[_acts]) + _acts++ + for ; _nacts > 0; _nacts-- { + _acts++ + switch _khmSM_actions[_acts-1] { + case 1: + ts = p + + } + } + + _keys = int(_khmSM_key_offsets[cs]) + _trans = int(_khmSM_index_offsets[cs]) + + _klen = int(_khmSM_single_lengths[cs]) + if _klen > 0 { + _lower := int(_keys) + var _mid int + _upper := int(_keys + _klen - 1) + for { + if _upper < _lower { + break + } + + _mid = _lower + ((_upper - _lower) >> 1) + switch { + case (info[p].complexCategory) < _khmSM_trans_keys[_mid]: + _upper = _mid - 1 + case (info[p].complexCategory) > _khmSM_trans_keys[_mid]: + _lower = _mid + 1 + default: + _trans += int(_mid - int(_keys)) + goto _match + } + } + _keys += _klen + _trans += _klen + } + + _klen = int(_khmSM_range_lengths[cs]) + if _klen > 0 { + _lower := int(_keys) + var _mid int + _upper := int(_keys + (_klen << 1) - 2) + for { + if _upper < _lower { + break + } + + _mid = _lower + (((_upper - _lower) >> 1) & ^1) + switch { + case (info[p].complexCategory) < _khmSM_trans_keys[_mid]: + _upper = _mid - 2 + case (info[p].complexCategory) > _khmSM_trans_keys[_mid+1]: + _lower = _mid + 2 + default: + _trans += int((_mid - int(_keys)) >> 1) + goto _match + } + } + _trans += _klen + } + + _match: + _trans = int(_khmSM_indicies[_trans]) + _eof_trans: + cs = int(_khmSM_trans_targs[_trans]) + + if _khmSM_trans_actions[_trans] == 0 { + goto _again + } + + _acts = int(_khmSM_trans_actions[_trans]) + _nacts = uint(_khmSM_actions[_acts]) + _acts++ + for ; _nacts > 0; _nacts-- { + _acts++ + switch _khmSM_actions[_acts-1] { + case 2: + te = p + 1 + + case 3: + act = 2 + case 4: + act = 3 + case 5: + te = p + 1 + { + foundSyllableKhmer(khmerNonKhmerCluster, ts, te, info, &syllableSerial) + } + case 6: + te = p + p-- + { + foundSyllableKhmer(khmerConsonantSyllable, ts, te, info, &syllableSerial) + } + case 7: + te = p + p-- + { + foundSyllableKhmer(khmerBrokenCluster, ts, te, info, &syllableSerial) + buffer.scratchFlags |= bsfHasBrokenSyllable + } + case 8: + te = p + p-- + { + foundSyllableKhmer(khmerNonKhmerCluster, ts, te, info, &syllableSerial) + } + case 9: + p = (te) - 1 + { + foundSyllableKhmer(khmerConsonantSyllable, ts, te, info, &syllableSerial) + } + case 10: + p = (te) - 1 + { + foundSyllableKhmer(khmerBrokenCluster, ts, te, info, &syllableSerial) + buffer.scratchFlags |= bsfHasBrokenSyllable + } + case 11: + switch act { + case 2: + { + p = (te) - 1 + foundSyllableKhmer(khmerBrokenCluster, ts, te, info, &syllableSerial) + buffer.scratchFlags |= bsfHasBrokenSyllable + } + case 3: + { + p = (te) - 1 + foundSyllableKhmer(khmerNonKhmerCluster, ts, te, info, &syllableSerial) + } + } + + } + } + + _again: + _acts = int(_khmSM_to_state_actions[cs]) + _nacts = uint(_khmSM_actions[_acts]) + _acts++ + for ; _nacts > 0; _nacts-- { + _acts++ + switch _khmSM_actions[_acts-1] { + case 0: + ts = 0 + + } + } + + p++ + if p != pe { + goto _resume + } + _test_eof: + { + } + if p == eof { + if _khmSM_eof_trans[cs] > 0 { + _trans = int(_khmSM_eof_trans[cs] - 1) + goto _eof_trans + } + } + + } + + _ = act // needed by Ragel, but unused +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_khmer_machine.rl b/vendor/github.com/go-text/typesetting/harfbuzz/ot_khmer_machine.rl new file mode 100644 index 0000000..ac74ff6 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_khmer_machine.rl @@ -0,0 +1,88 @@ +package harfbuzz + +// Code generated with ragel -Z -o ot_khmer_machine.go ot_khmer_machine.rl ; sed -i '/^\/\/line/ d' ot_khmer_machine.go ; goimports -w ot_khmer_machine.go DO NOT EDIT. + +// ported from harfbuzz/src/hb-ot-shape-complex-khmer-machine.rl Copyright © 2015 Google, Inc. Behdad Esfahbod + + +const ( + khmerConsonantSyllable = iota + khmerBrokenCluster + khmerNonKhmerCluster +) + +%%{ + machine khmSM; + alphtype byte; + write exports; + write data; +}%% + +%%{ + +# We use category H for spec category Coeng + +export C = 1; +export V = 2; +export H = 4; +export ZWNJ = 5; +export ZWJ = 6; +export PLACEHOLDER = 10; +export DOTTEDCIRCLE = 11; +export Ra = 15; + +export VAbv = 20; +export VBlw = 21; +export VPre = 22; +export VPst = 23; + +export Robatic = 25; +export Xgroup = 26; +export Ygroup = 27; + +c = (C | Ra | V); +cn = c.((ZWJ|ZWNJ)?.Robatic)?; +joiner = (ZWJ | ZWNJ); +xgroup = (joiner*.Xgroup)*; +ygroup = Ygroup*; + +# This grammar was experimentally extracted from what Uniscribe allows. + +matra_group = VPre? xgroup VBlw? xgroup (joiner?.VAbv)? xgroup VPst?; +syllable_tail = xgroup matra_group xgroup (H.c)? ygroup; + + +broken_cluster = Robatic? (H.cn)* (H | syllable_tail); +consonant_syllable = (cn|PLACEHOLDER|DOTTEDCIRCLE) broken_cluster; +other = any; + +main := |* + consonant_syllable => { foundSyllableKhmer (khmerConsonantSyllable, ts, te, info, &syllableSerial); }; + broken_cluster => { foundSyllableKhmer (khmerBrokenCluster, ts, te, info, &syllableSerial); buffer.scratchFlags |= bsfHasBrokenSyllable; }; + other => { foundSyllableKhmer (khmerNonKhmerCluster, ts, te, info, &syllableSerial); }; +*|; + + +}%% + + +func findSyllablesKhmer (buffer * Buffer) { + var p, ts, te, act, cs int + info := buffer.Info; + %%{ + write init; + getkey info[p].complexCategory; + }%% + + pe := len(info) + eof := pe + + var syllableSerial uint8 = 1; + %%{ + write exec; + }%% + _ = act // needed by Ragel, but unused +} + + + diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_language.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_language.go new file mode 100644 index 0000000..d3d9bcd --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_language.go @@ -0,0 +1,73 @@ +package harfbuzz + +import ( + "strings" + + "github.com/go-text/typesetting/font/opentype/tables" +) + +type langTag struct { + language string + tag tables.Tag +} + +// return -1 if `a` < `l` +func (l *langTag) compare(a string) int { + b := l.language + + p := strings.IndexByte(a, '-') + // da := len(a) + if p != -1 { + // da = p + a = a[:p] + } + + p = strings.IndexByte(b, '-') + // db := len(b) + if p != -1 { + // db = p + b = b[:p] + } + // L := min(min(len(a), len(b)), max(da, db)) + return strings.Compare(a, b) +} + +func bfindLanguage(lang string) int { + low, high := 0, len(otLanguages) + for low <= high { + mid := (low + high) / 2 + p := &otLanguages[mid] + cmp := p.compare(lang) + if cmp < 0 { + high = mid - 1 + } else if cmp > 0 { + low = mid + 1 + } else { + return mid + } + } + return -1 +} + +func subtagMatches(langStr string, subtag string) bool { + LS := len(subtag) + if len(langStr) < LS { + return false + } + + for { + s := strings.Index(langStr, subtag) + if s == -1 { + return false + } + if s+LS >= len(langStr) || !isAlnum(langStr[s+LS]) { + return true + } + langStr = langStr[s+LS:] + } +} + +func langMatches(langStr, spec string) bool { + l := len(spec) + return strings.HasPrefix(langStr, spec) && (len(langStr) == l || langStr[l] == '-') +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_language_table.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_language_table.go new file mode 100644 index 0000000..a9366fb --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_language_table.go @@ -0,0 +1,2482 @@ +package harfbuzz + +import ( + "strings" + + "github.com/go-text/typesetting/language" + ot "github.com/go-text/typesetting/font/opentype" + +) + +// Code generated by typesetting-utils/generators/langs/gen.go. DO NOT EDIT. + +var otLanguages = [...]langTag{ + {"aa", 0x41465220}, /* Afar */ + {"aae", 0x53514920}, /* Arbëreshë Albanian -> Albanian */ + {"aao", 0x41524120}, /* Algerian Saharan Arabic -> Arabic */ + {"aat", 0x53514920}, /* Arvanitika Albanian -> Albanian */ + {"ab", 0x41424b20}, /* Abkhazian */ + {"aba", 0}, /* Abé != Abaza */ + {"abh", 0x41524120}, /* Tajiki Arabic -> Arabic */ + {"abq", 0x41424120}, /* Abaza */ + {"abs", 0x43505020}, /* Ambonese Malay -> Creoles */ + {"abv", 0x41524120}, /* Baharna Arabic -> Arabic */ + {"acf", 0x46414e20}, /* Saint Lucian Creole French -> French Antillean */ + {"acf", 0x43505020}, /* Saint Lucian Creole French -> Creoles */ + /*{"ach", 0x41434820},*/ /* Acoli -> Acholi */ + {"acm", 0x41524120}, /* Mesopotamian Arabic -> Arabic */ + {"acq", 0x41524120}, /* Ta'izzi-Adeni Arabic -> Arabic */ + {"acr", 0x41435220}, /* Achi */ + {"acr", 0x4d594e20}, /* Achi -> Mayan */ + {"acw", 0x41524120}, /* Hijazi Arabic -> Arabic */ + {"acx", 0x41524120}, /* Omani Arabic -> Arabic */ + {"acy", 0x41524120}, /* Cypriot Arabic -> Arabic */ + {"ada", 0x444e4720}, /* Adangme -> Dangme */ + {"adf", 0x41524120}, /* Dhofari Arabic -> Arabic */ + {"adp", 0x445a4e20}, /* Adap (retired code) (retired code) -> Dzongkha */ + /*{"ady", 0x41445920},*/ /* Adyghe */ + {"aeb", 0x41524120}, /* Tunisian Arabic -> Arabic */ + {"aec", 0x41524120}, /* Saidi Arabic -> Arabic */ + {"af", 0x41464b20}, /* Afrikaans */ + {"afb", 0x41524120}, /* Gulf Arabic -> Arabic */ + {"afk", 0}, /* Nanubae != Afrikaans */ + {"afs", 0x43505020}, /* Afro-Seminole Creole -> Creoles */ + {"agu", 0x4d594e20}, /* Aguacateco -> Mayan */ + {"agw", 0}, /* Kahua != Agaw */ + {"ahg", 0x41475720}, /* Qimant -> Agaw */ + {"aht", 0x41544820}, /* Ahtena -> Athapaskan */ + {"aig", 0x43505020}, /* Antigua and Barbuda Creole English -> Creoles */ + {"aii", 0x53574120}, /* Assyrian Neo-Aramaic -> Swadaya Aramaic */ + {"aii", 0x53595220}, /* Assyrian Neo-Aramaic -> Syriac */ + /*{"aio", 0x41494f20},*/ /* Aiton */ + {"aiw", 0x41524920}, /* Aari */ + {"ajp", 0x41524120}, /* South Levantine Arabic (retired code) (retired code) -> Arabic */ + {"ajt", 0x41524120}, /* Judeo-Tunisian Arabic (retired code) (retired code) -> Arabic */ + {"ak", 0x414b4120}, /* Akan [macrolanguage] */ + {"akb", 0x414b4220}, /* Batak Angkola */ + {"akb", 0x42544b20}, /* Batak Angkola -> Batak */ + {"aln", 0x53514920}, /* Gheg Albanian -> Albanian */ + {"als", 0x53514920}, /* Tosk Albanian -> Albanian */ + /*{"alt", 0x414c5420},*/ /* Southern Altai -> Altai */ + {"am", 0x414d4820}, /* Amharic */ + {"amf", 0x48424e20}, /* Hamer-Banna -> Hammer-Banna */ + {"amw", 0x53595220}, /* Western Neo-Aramaic -> Syriac */ + {"an", 0x41524720}, /* Aragonese */ + /*{"ang", 0x414e4720},*/ /* Old English (ca. 450-1100) -> Anglo-Saxon */ + {"aoa", 0x43505020}, /* Angolar -> Creoles */ + {"apa", 0x41544820}, /* Apache [collection] -> Athapaskan */ + {"apc", 0x41524120}, /* Levantine Arabic -> Arabic */ + {"apd", 0x41524120}, /* Sudanese Arabic -> Arabic */ + {"apj", 0x41544820}, /* Jicarilla Apache -> Athapaskan */ + {"apk", 0x41544820}, /* Kiowa Apache -> Athapaskan */ + {"apl", 0x41544820}, /* Lipan Apache -> Athapaskan */ + {"apm", 0x41544820}, /* Mescalero-Chiricahua Apache -> Athapaskan */ + {"apw", 0x41544820}, /* Western Apache -> Athapaskan */ + {"ar", 0x41524120}, /* Arabic [macrolanguage] */ + {"arb", 0x41524120}, /* Standard Arabic -> Arabic */ + {"ari", 0}, /* Arikara != Aari */ + {"ark", 0}, /* Arikapú != Rakhine */ + {"arn", 0x4d415020}, /* Mapudungun */ + {"arq", 0x41524120}, /* Algerian Arabic -> Arabic */ + {"ars", 0x41524120}, /* Najdi Arabic -> Arabic */ + {"ary", 0x4d4f5220}, /* Moroccan Arabic -> */ + {"ary", 0x41524120}, /* Moroccan Arabic -> Arabic */ + {"arz", 0x41524120}, /* Egyptian Arabic -> Arabic */ + {"as", 0x41534d20}, /* Assamese */ + /*{"ast", 0x41535420},*/ /* Asturian */ + /*{"ath", 0x41544820},*/ /* Athapascan [collection] -> Athapaskan */ + {"atj", 0x52435220}, /* Atikamekw -> R-Cree */ + {"atv", 0x414c5420}, /* Northern Altai -> Altai */ + {"auj", 0x42425220}, /* Awjilah -> Berber */ + {"auz", 0x41524120}, /* Uzbeki Arabic -> Arabic */ + {"av", 0x41565220}, /* Avaric -> Avar */ + {"avl", 0x41524120}, /* Eastern Egyptian Bedawi Arabic -> Arabic */ + /*{"avn", 0x41564e20},*/ /* Avatime */ + /*{"awa", 0x41574120},*/ /* Awadhi */ + {"ay", 0x41594d20}, /* Aymara [macrolanguage] */ + {"ayc", 0x41594d20}, /* Southern Aymara -> Aymara */ + {"ayh", 0x41524120}, /* Hadrami Arabic -> Arabic */ + {"ayl", 0x41524120}, /* Libyan Arabic -> Arabic */ + {"ayn", 0x41524120}, /* Sanaani Arabic -> Arabic */ + {"ayp", 0x41524120}, /* North Mesopotamian Arabic -> Arabic */ + {"ayr", 0x41594d20}, /* Central Aymara -> Aymara */ + {"az", 0x415a4520}, /* Azerbaijani [macrolanguage] */ + {"azb", 0x415a4220}, /* South Azerbaijani -> Torki */ + {"azb", 0x415a4520}, /* South Azerbaijani -> Azerbaijani */ + {"azd", 0x4e414820}, /* Eastern Durango Nahuatl -> Nahuatl */ + {"azj", 0x415a4520}, /* North Azerbaijani -> Azerbaijani */ + {"azn", 0x4e414820}, /* Western Durango Nahuatl -> Nahuatl */ + {"azz", 0x4e414820}, /* Highland Puebla Nahuatl -> Nahuatl */ + {"ba", 0x42534820}, /* Bashkir */ + {"bad", 0x42414430}, /* Banda [collection] */ + {"bag", 0}, /* Tuki != Baghelkhandi */ + {"bah", 0x43505020}, /* Bahamas Creole English -> Creoles */ + {"bai", 0x424d4c20}, /* Bamileke [collection] */ + {"bal", 0x424c4920}, /* Baluchi [macrolanguage] */ + /*{"ban", 0x42414e20},*/ /* Balinese */ + /*{"bar", 0x42415220},*/ /* Bavarian */ + {"bau", 0}, /* Bada (Nigeria) != Baulé */ + {"bbc", 0x42424320}, /* Batak Toba */ + {"bbc", 0x42544b20}, /* Batak Toba -> Batak */ + {"bbj", 0x424d4c20}, /* Ghomálá' -> Bamileke */ + {"bbp", 0x42414430}, /* West Central Banda -> Banda */ + {"bbr", 0}, /* Girawa != Berber */ + {"bbz", 0x41524120}, /* Babalia Creole Arabic (retired code) (retired code) -> Arabic */ + {"bcc", 0x424c4920}, /* Southern Balochi -> Baluchi */ + {"bch", 0}, /* Bariai != Bench */ + {"bci", 0x42415520}, /* Baoulé -> Baulé */ + {"bcl", 0x42494b20}, /* Central Bikol -> Bikol */ + {"bcq", 0x42434820}, /* Bench */ + {"bcr", 0x41544820}, /* Babine -> Athapaskan */ + /*{"bdy", 0x42445920},*/ /* Bandjalang */ + {"be", 0x42454c20}, /* Belarusian -> Belarussian */ + {"bea", 0x41544820}, /* Beaver -> Athapaskan */ + {"beb", 0x42544920}, /* Bebele -> Beti */ + /*{"bem", 0x42454d20},*/ /* Bemba (Zambia) */ + {"ber", 0x42425220}, /* Berber [collection] */ + {"bew", 0x43505020}, /* Betawi -> Creoles */ + {"bfl", 0x42414430}, /* Banda-Ndélé -> Banda */ + {"bfq", 0x42414420}, /* Badaga */ + {"bft", 0x424c5420}, /* Balti */ + {"bfu", 0x4c414820}, /* Gahri -> Lahuli */ + {"bfy", 0x42414720}, /* Bagheli -> Baghelkhandi */ + {"bg", 0x42475220}, /* Bulgarian */ + /*{"bgc", 0x42474320},*/ /* Haryanvi */ + {"bgn", 0x424c4920}, /* Western Balochi -> Baluchi */ + {"bgp", 0x424c4920}, /* Eastern Balochi -> Baluchi */ + {"bgq", 0x42475120}, /* Bagri */ + {"bgq", 0x52414a20}, /* Bagri -> Rajasthani */ + {"bgr", 0x51494e20}, /* Bawm Chin -> Chin */ + {"bhb", 0x42484920}, /* Bhili */ + /*{"bhi", 0x42484920},*/ /* Bhilali -> Bhili */ + {"bhk", 0x42494b20}, /* Albay Bicolano (retired code) (retired code) -> Bikol */ + /*{"bho", 0x42484f20},*/ /* Bhojpuri */ + {"bhr", 0x4d4c4720}, /* Bara Malagasy -> Malagasy */ + {"bi", 0x42495320}, /* Bislama */ + {"bi", 0x43505020}, /* Bislama -> Creoles */ + /*{"bik", 0x42494b20},*/ /* Bikol [macrolanguage] */ + {"bil", 0}, /* Bile != Bilen */ + {"bin", 0x45444f20}, /* Edo */ + {"biu", 0x51494e20}, /* Biete -> Chin */ + /*{"bjj", 0x424a4a20},*/ /* Kanauji */ + {"bjn", 0x4d4c5920}, /* Banjar -> Malay */ + {"bjo", 0x42414430}, /* Mid-Southern Banda -> Banda */ + {"bjq", 0x4d4c4720}, /* Southern Betsimisaraka Malagasy (retired code) (retired code) -> Malagasy */ + {"bjs", 0x43505020}, /* Bajan -> Creoles */ + {"bjt", 0x424c4e20}, /* Balanta-Ganja -> Balante */ + {"bkf", 0}, /* Beeke != Blackfoot */ + {"bko", 0x424d4c20}, /* Kwa' -> Bamileke */ + {"bla", 0x424b4620}, /* Siksika -> Blackfoot */ + {"ble", 0x424c4e20}, /* Balanta-Kentohe -> Balante */ + {"blg", 0x49424120}, /* Balau (retired code) (retired code) -> Iban */ + {"bli", 0}, /* Bolia != Baluchi */ + {"blk", 0x424c4b20}, /* Pa’o Karen */ + {"blk", 0x4b524e20}, /* Pa'o Karen -> Karen */ + {"bln", 0x42494b20}, /* Southern Catanduanes Bikol -> Bikol */ + {"blt", 0}, /* Tai Dam != Balti */ + {"bm", 0x424d4220}, /* Bambara (Bamanankan) */ + {"bmb", 0}, /* Bembe != Bambara (Bamanankan) */ + {"bml", 0}, /* Bomboli != Bamileke */ + {"bmm", 0x4d4c4720}, /* Northern Betsimisaraka Malagasy -> Malagasy */ + {"bn", 0x42454e20}, /* Bengali */ + {"bo", 0x54494220}, /* Tibetan */ + {"bpd", 0x42414430}, /* Banda-Banda -> Banda */ + {"bpl", 0x43505020}, /* Broome Pearling Lugger Pidgin -> Creoles */ + {"bpq", 0x43505020}, /* Banda Malay -> Creoles */ + /*{"bpy", 0x42505920},*/ /* Bishnupriya -> Bishnupriya Manipuri */ + {"bqi", 0x4c524320}, /* Bakhtiari -> Luri */ + {"bqk", 0x42414430}, /* Banda-Mbrès -> Banda */ + {"br", 0x42524520}, /* Breton */ + {"bra", 0x42524920}, /* Braj -> Braj Bhasha */ + {"brc", 0x43505020}, /* Berbice Creole Dutch -> Creoles */ + /*{"brh", 0x42524820},*/ /* Brahui */ + {"bri", 0}, /* Mokpwe != Braj Bhasha */ + {"brm", 0}, /* Barambu != Burmese */ + /*{"brx", 0x42525820},*/ /* Bodo (India) */ + {"bs", 0x424f5320}, /* Bosnian */ + {"bsh", 0}, /* Kati != Bashkir */ + /*{"bsk", 0x42534b20},*/ /* Burushaski */ + {"btb", 0x42544920}, /* Beti (Cameroon) (retired code) (retired code) */ + {"btd", 0x42544420}, /* Batak Dairi (Pakpak) */ + {"btd", 0x42544b20}, /* Batak Dairi -> Batak */ + {"bti", 0}, /* Burate != Beti */ + {"btj", 0x4d4c5920}, /* Bacanese Malay -> Malay */ + /*{"btk", 0x42544b20},*/ /* Batak [collection] */ + {"btm", 0x42544d20}, /* Batak Mandailing */ + {"btm", 0x42544b20}, /* Batak Mandailing -> Batak */ + {"bto", 0x42494b20}, /* Rinconada Bikol -> Bikol */ + {"bts", 0x42545320}, /* Batak Simalungun */ + {"bts", 0x42544b20}, /* Batak Simalungun -> Batak */ + {"btx", 0x42545820}, /* Batak Karo */ + {"btx", 0x42544b20}, /* Batak Karo -> Batak */ + {"btz", 0x42545a20}, /* Batak Alas-Kluet */ + {"btz", 0x42544b20}, /* Batak Alas-Kluet -> Batak */ + /*{"bug", 0x42554720},*/ /* Buginese -> Bugis */ + {"bum", 0x42544920}, /* Bulu (Cameroon) -> Beti */ + {"bve", 0x4d4c5920}, /* Berau Malay -> Malay */ + {"bvu", 0x4d4c5920}, /* Bukit Malay -> Malay */ + {"bwe", 0x4b524e20}, /* Bwe Karen -> Karen */ + {"bxk", 0x4c554820}, /* Bukusu -> Luyia */ + {"bxo", 0x43505020}, /* Barikanchi -> Creoles */ + {"bxp", 0x42544920}, /* Bebil -> Beti */ + {"bxr", 0x52425520}, /* Russia Buriat -> Russian Buriat */ + {"byn", 0x42494c20}, /* Bilin -> Bilen */ + {"byv", 0x42595620}, /* Medumba */ + {"byv", 0x424d4c20}, /* Medumba -> Bamileke */ + {"bzc", 0x4d4c4720}, /* Southern Betsimisaraka Malagasy -> Malagasy */ + {"bzj", 0x43505020}, /* Belize Kriol English -> Creoles */ + {"bzk", 0x43505020}, /* Nicaragua Creole English -> Creoles */ + {"ca", 0x43415420}, /* Catalan */ + {"caa", 0x4d594e20}, /* Chortí -> Mayan */ + {"cac", 0x4d594e20}, /* Chuj -> Mayan */ + {"caf", 0x43525220}, /* Southern Carrier -> Carrier */ + {"caf", 0x41544820}, /* Southern Carrier -> Athapaskan */ + {"cak", 0x43414b20}, /* Kaqchikel */ + {"cak", 0x4d594e20}, /* Kaqchikel -> Mayan */ + {"cbk", 0x43424b20}, /* Chavacano -> Zamboanga Chavacano */ + {"cbk", 0x43505020}, /* Chavacano -> Creoles */ + {"cbl", 0x51494e20}, /* Bualkhaw Chin -> Chin */ + {"ccl", 0x43505020}, /* Cutchi-Swahili -> Creoles */ + {"ccm", 0x43505020}, /* Malaccan Creole Malay -> Creoles */ + {"cco", 0x4343484e}, /* Comaltepec Chinantec -> Chinantec */ + {"ccq", 0x41524b20}, /* Chaungtha (retired code) (retired code) -> Rakhine */ + {"cdo", 0x5a485320}, /* Min Dong Chinese -> Chinese, Simplified */ + {"ce", 0x43484520}, /* Chechen */ + /*{"ceb", 0x43454220},*/ /* Cebuano */ + {"cek", 0x51494e20}, /* Eastern Khumi Chin -> Chin */ + {"cey", 0x51494e20}, /* Ekai Chin -> Chin */ + {"cfm", 0x48414c20}, /* Halam (Falam Chin) */ + {"cfm", 0x51494e20}, /* Falam Chin -> Chin */ + /*{"cgg", 0x43474720},*/ /* Chiga */ + {"ch", 0x43484120}, /* Chamorro */ + {"chf", 0x4d594e20}, /* Tabasco Chontal -> Mayan */ + {"chg", 0}, /* Chagatai != Chaha Gurage */ + {"chh", 0}, /* Chinook != Chattisgarhi */ + {"chj", 0x4343484e}, /* Ojitlán Chinantec -> Chinantec */ + {"chk", 0x43484b30}, /* Chuukese */ + {"chm", 0x484d4120}, /* Mari (Russia) [macrolanguage] -> High Mari */ + {"chm", 0x4c4d4120}, /* Mari (Russia) [macrolanguage] -> Low Mari */ + {"chn", 0x43505020}, /* Chinook jargon -> Creoles */ + /*{"cho", 0x43484f20},*/ /* Choctaw */ + {"chp", 0x43485020}, /* Chipewyan */ + {"chp", 0x53415920}, /* Chipewyan -> Sayisi */ + {"chp", 0x41544820}, /* Chipewyan -> Athapaskan */ + {"chq", 0x4343484e}, /* Quiotepec Chinantec -> Chinantec */ + /*{"chr", 0x43485220},*/ /* Cherokee */ + /*{"chy", 0x43485920},*/ /* Cheyenne */ + {"chz", 0x4343484e}, /* Ozumacín Chinantec -> Chinantec */ + {"ciw", 0x4f4a4220}, /* Chippewa -> Ojibway */ + /*{"cja", 0x434a4120},*/ /* Western Cham */ + /*{"cjm", 0x434a4d20},*/ /* Eastern Cham */ + {"cjy", 0x5a485320}, /* Jinyu Chinese -> Chinese, Simplified */ + {"cka", 0x51494e20}, /* Khumi Awa Chin (retired code) (retired code) -> Chin */ + {"ckb", 0x4b555220}, /* Central Kurdish -> Kurdish */ + {"ckn", 0x51494e20}, /* Kaang Chin -> Chin */ + {"cks", 0x43505020}, /* Tayo -> Creoles */ + {"ckt", 0x43484b20}, /* Chukot -> Chukchi */ + {"ckz", 0x4d594e20}, /* Cakchiquel-Quiché Mixed Language -> Mayan */ + {"clc", 0x41544820}, /* Chilcotin -> Athapaskan */ + {"cld", 0x53595220}, /* Chaldean Neo-Aramaic -> Syriac */ + {"cle", 0x4343484e}, /* Lealao Chinantec -> Chinantec */ + {"clj", 0x51494e20}, /* Laitu Chin -> Chin */ + {"clt", 0x51494e20}, /* Lautu Chin -> Chin */ + {"cmn", 0x5a485320}, /* Mandarin Chinese -> Chinese, Simplified */ + {"cmr", 0x51494e20}, /* Mro-Khimi Chin -> Chin */ + {"cnb", 0x51494e20}, /* Chinbon Chin -> Chin */ + {"cnh", 0x51494e20}, /* Hakha Chin -> Chin */ + {"cnk", 0x51494e20}, /* Khumi Chin -> Chin */ + {"cnl", 0x4343484e}, /* Lalana Chinantec -> Chinantec */ + {"cnp", 0x5a485320}, /* Northern Ping Chinese -> Chinese, Simplified */ + {"cnr", 0x53524220}, /* Montenegrin -> Serbian */ + {"cnt", 0x4343484e}, /* Tepetotutla Chinantec -> Chinantec */ + {"cnu", 0x42425220}, /* Chenoua -> Berber */ + {"cnw", 0x51494e20}, /* Ngawn Chin -> Chin */ + {"co", 0x434f5320}, /* Corsican */ + {"coa", 0x4d4c5920}, /* Cocos Islands Malay -> Malay */ + {"cob", 0x4d594e20}, /* Chicomuceltec -> Mayan */ + /*{"cop", 0x434f5020},*/ /* Coptic */ + {"coq", 0x41544820}, /* Coquille -> Athapaskan */ + {"cpa", 0x4343484e}, /* Palantla Chinantec -> Chinantec */ + {"cpe", 0x43505020}, /* English-based creoles and pidgins [collection] -> Creoles */ + {"cpf", 0x43505020}, /* French-based creoles and pidgins [collection] -> Creoles */ + {"cpi", 0x43505020}, /* Chinese Pidgin English -> Creoles */ + /*{"cpp", 0x43505020},*/ /* Portuguese-based creoles and pidgins [collection] -> Creoles */ + {"cpx", 0x5a485320}, /* Pu-Xian Chinese -> Chinese, Simplified */ + {"cqd", 0x484d4e20}, /* Chuanqiandian Cluster Miao -> Hmong */ + {"cqu", 0x51554820}, /* Chilean Quechua (retired code) (retired code) -> Quechua (Bolivia) */ + {"cqu", 0x51555a20}, /* Chilean Quechua (retired code) (retired code) -> Quechua */ + {"cr", 0x43524520}, /* Cree [macrolanguage] */ + {"crh", 0x43525420}, /* Crimean Tatar */ + {"cri", 0x43505020}, /* Sãotomense -> Creoles */ + {"crj", 0x45435220}, /* Southern East Cree -> Eastern Cree */ + {"crj", 0x59435220}, /* Southern East Cree -> Y-Cree */ + {"crj", 0x43524520}, /* Southern East Cree -> Cree */ + {"crk", 0x57435220}, /* Plains Cree -> West-Cree */ + {"crk", 0x59435220}, /* Plains Cree -> Y-Cree */ + {"crk", 0x43524520}, /* Plains Cree -> Cree */ + {"crl", 0x45435220}, /* Northern East Cree -> Eastern Cree */ + {"crl", 0x59435220}, /* Northern East Cree -> Y-Cree */ + {"crl", 0x43524520}, /* Northern East Cree -> Cree */ + {"crm", 0x4d435220}, /* Moose Cree */ + {"crm", 0x4c435220}, /* Moose Cree -> L-Cree */ + {"crm", 0x43524520}, /* Moose Cree -> Cree */ + {"crp", 0x43505020}, /* Creoles and pidgins [collection] -> Creoles */ + {"crr", 0}, /* Carolina Algonquian != Carrier */ + {"crs", 0x43505020}, /* Seselwa Creole French -> Creoles */ + {"crt", 0}, /* Iyojwa'ja Chorote != Crimean Tatar */ + {"crx", 0x43525220}, /* Carrier */ + {"crx", 0x41544820}, /* Carrier -> Athapaskan */ + {"cs", 0x43535920}, /* Czech */ + {"csa", 0x4343484e}, /* Chiltepec Chinantec -> Chinantec */ + /*{"csb", 0x43534220},*/ /* Kashubian */ + {"csh", 0x51494e20}, /* Asho Chin -> Chin */ + {"csj", 0x51494e20}, /* Songlai Chin -> Chin */ + {"csl", 0}, /* Chinese Sign Language != Church Slavonic */ + {"cso", 0x4343484e}, /* Sochiapam Chinantec -> Chinantec */ + {"csp", 0x5a485320}, /* Southern Ping Chinese -> Chinese, Simplified */ + {"csv", 0x51494e20}, /* Sumtu Chin -> Chin */ + {"csw", 0x4e435220}, /* Swampy Cree -> N-Cree */ + {"csw", 0x4e484320}, /* Swampy Cree -> Norway House Cree */ + {"csw", 0x43524520}, /* Swampy Cree -> Cree */ + {"csy", 0x51494e20}, /* Siyin Chin -> Chin */ + {"ctc", 0x41544820}, /* Chetco -> Athapaskan */ + {"ctd", 0x51494e20}, /* Tedim Chin -> Chin */ + {"cte", 0x4343484e}, /* Tepinapa Chinantec -> Chinantec */ + /*{"ctg", 0x43544720},*/ /* Chittagonian */ + {"cth", 0x51494e20}, /* Thaiphum Chin -> Chin */ + {"ctl", 0x4343484e}, /* Tlacoatzintepec Chinantec -> Chinantec */ + {"cts", 0x42494b20}, /* Northern Catanduanes Bikol -> Bikol */ + /*{"ctt", 0x43545420},*/ /* Wayanad Chetti */ + {"ctu", 0x4d594e20}, /* Chol -> Mayan */ + {"cu", 0x43534c20}, /* Church Slavonic */ + {"cuc", 0x4343484e}, /* Usila Chinantec -> Chinantec */ + /*{"cuk", 0x43554b20},*/ /* San Blas Kuna */ + {"cv", 0x43485520}, /* Chuvash */ + {"cvn", 0x4343484e}, /* Valle Nacional Chinantec -> Chinantec */ + {"cwd", 0x44435220}, /* Woods Cree */ + {"cwd", 0x54435220}, /* Woods Cree -> TH-Cree */ + {"cwd", 0x43524520}, /* Woods Cree -> Cree */ + {"cy", 0x57454c20}, /* Welsh */ + {"czh", 0x5a485320}, /* Huizhou Chinese -> Chinese, Simplified */ + {"czo", 0x5a485320}, /* Min Zhong Chinese -> Chinese, Simplified */ + {"czt", 0x51494e20}, /* Zotung Chin -> Chin */ + {"da", 0x44414e20}, /* Danish */ + /*{"dag", 0x44414720},*/ /* Dagbani */ + {"dao", 0x51494e20}, /* Daai Chin -> Chin */ + {"dap", 0x4e495320}, /* Nisi (India) (retired code) (retired code) */ + /*{"dar", 0x44415220},*/ /* Dargwa */ + /*{"dax", 0x44415820},*/ /* Dayi */ + {"dcr", 0x43505020}, /* Negerhollands -> Creoles */ + {"de", 0x44455520}, /* German */ + {"den", 0x534c4120}, /* Slave (Athapascan) [macrolanguage] -> Slavey */ + {"den", 0x41544820}, /* Slave (Athapascan) [macrolanguage] -> Athapaskan */ + {"dep", 0x43505020}, /* Pidgin Delaware -> Creoles */ + {"dgo", 0x44474f20}, /* Dogri (individual language) */ + {"dgo", 0x44475220}, /* Dogri (macrolanguage) */ + {"dgr", 0x41544820}, /* Dogrib -> Athapaskan */ + {"dhd", 0x4d415720}, /* Dhundari -> Marwari */ + /*{"dhg", 0x44484720},*/ /* Dhangu */ + {"dhv", 0}, /* Dehu != Divehi (Dhivehi, Maldivian) (deprecated) */ + {"dib", 0x444e4b20}, /* South Central Dinka -> Dinka */ + {"dik", 0x444e4b20}, /* Southwestern Dinka -> Dinka */ + {"din", 0x444e4b20}, /* Dinka [macrolanguage] */ + {"dip", 0x444e4b20}, /* Northeastern Dinka -> Dinka */ + {"diq", 0x44495120}, /* Dimli */ + {"diq", 0x5a5a4120}, /* Dimli -> Zazaki */ + {"diw", 0x444e4b20}, /* Northwestern Dinka -> Dinka */ + {"dje", 0x444a5220}, /* Zarma */ + {"djk", 0x43505020}, /* Eastern Maroon Creole -> Creoles */ + {"djr", 0x444a5230}, /* Djambarrpuyngu */ + {"dks", 0x444e4b20}, /* Southeastern Dinka -> Dinka */ + {"dng", 0x44554e20}, /* Dungan */ + /*{"dnj", 0x444e4a20},*/ /* Dan */ + {"dnk", 0}, /* Dengka != Dinka */ + {"doi", 0x44475220}, /* Dogri (macrolanguage) [macrolanguage] */ + {"drh", 0x4d4e4720}, /* Darkhat (retired code) (retired code) -> Mongolian */ + {"dri", 0}, /* C'Lela != Dari */ + {"drw", 0x44524920}, /* Darwazi (retired code) (retired code) -> Dari */ + {"drw", 0x46415220}, /* Darwazi (retired code) (retired code) -> Persian */ + {"dsb", 0x4c534220}, /* Lower Sorbian */ + {"dty", 0x4e455020}, /* Dotyali -> Nepali */ + /*{"duj", 0x44554a20},*/ /* Dhuwal (retired code) (retired code) */ + {"dun", 0}, /* Dusun Deyah != Dungan */ + {"dup", 0x4d4c5920}, /* Duano -> Malay */ + {"dv", 0x44495620}, /* Divehi (Dhivehi, Maldivian) */ + {"dv", 0x44485620}, /* Divehi (Dhivehi, Maldivian) (deprecated) */ + {"dwk", 0x4b554920}, /* Dawik Kui -> Kui */ + {"dwu", 0x44554a20}, /* Dhuwal */ + {"dwy", 0x44554a20}, /* Dhuwaya -> Dhuwal */ + {"dyu", 0x4a554c20}, /* Dyula -> Jula */ + {"dz", 0x445a4e20}, /* Dzongkha */ + {"dzn", 0}, /* Dzando != Dzongkha */ + {"ecr", 0}, /* Eteocretan != Eastern Cree */ + {"ee", 0x45574520}, /* Ewe */ + /*{"efi", 0x45464920},*/ /* Efik */ + {"ekk", 0x45544920}, /* Standard Estonian -> Estonian */ + {"eky", 0x4b524e20}, /* Eastern Kayah -> Karen */ + {"el", 0x454c4c20}, /* Modern Greek (1453-) -> Greek */ + {"emk", 0x454d4b20}, /* Eastern Maninkakan */ + {"emk", 0x4d4e4b20}, /* Eastern Maninkakan -> Maninka */ + {"emy", 0x4d594e20}, /* Epigraphic Mayan -> Mayan */ + {"en", 0x454e4720}, /* English */ + {"enb", 0x4b414c20}, /* Markweeta -> Kalenjin */ + {"enf", 0x464e4520}, /* Forest Enets */ + {"enh", 0x544e4520}, /* Tundra Enets */ + {"eo", 0x4e544f20}, /* Esperanto */ + {"es", 0x45535020}, /* Spanish */ + {"esg", 0x474f4e20}, /* Aheri Gondi -> Gondi */ + {"esi", 0x49504b20}, /* North Alaskan Inupiatun -> Inupiat */ + {"esk", 0x49504b20}, /* Northwest Alaska Inupiatun -> Inupiat */ + /*{"esu", 0x45535520},*/ /* Central Yupik */ + {"et", 0x45544920}, /* Estonian [macrolanguage] */ + {"eto", 0x42544920}, /* Eton (Cameroon) -> Beti */ + {"eu", 0x45555120}, /* Basque */ + {"euq", 0}, /* Basque [collection] != Basque */ + {"eve", 0x45564e20}, /* Even */ + {"evn", 0x45564b20}, /* Evenki */ + {"ewo", 0x42544920}, /* Ewondo -> Beti */ + {"eyo", 0x4b414c20}, /* Keiyo -> Kalenjin */ + {"fa", 0x46415220}, /* Persian [macrolanguage] */ + {"fab", 0x43505020}, /* Fa d'Ambu -> Creoles */ + {"fan", 0x46414e30}, /* Fang (Equatorial Guinea) */ + {"fan", 0x42544920}, /* Fang (Equatorial Guinea) -> Beti */ + {"far", 0}, /* Fataleka != Persian */ + {"fat", 0x46415420}, /* Fanti */ + {"fat", 0x414b4120}, /* Fanti -> Akan */ + {"fbl", 0x42494b20}, /* West Albay Bikol -> Bikol */ + {"ff", 0x46554c20}, /* Fulah [macrolanguage] */ + {"ffm", 0x46554c20}, /* Maasina Fulfulde -> Fulah */ + {"fi", 0x46494e20}, /* Finnish */ + {"fil", 0x50494c20}, /* Filipino */ + {"fj", 0x464a4920}, /* Fijian */ + {"flm", 0x48414c20}, /* Halam (Falam Chin) (retired code) */ + {"flm", 0x51494e20}, /* Falam Chin (retired code) -> Chin */ + {"fmp", 0x464d5020}, /* Fe’fe’ */ + {"fmp", 0x424d4c20}, /* Fe'fe' -> Bamileke */ + {"fng", 0x43505020}, /* Fanagalo -> Creoles */ + {"fo", 0x464f5320}, /* Faroese */ + /*{"fon", 0x464f4e20},*/ /* Fon */ + {"fos", 0}, /* Siraya != Faroese */ + {"fpe", 0x43505020}, /* Fernando Po Creole English -> Creoles */ + {"fr", 0x46524120}, /* French */ + /*{"frc", 0x46524320},*/ /* Cajun French */ + /*{"frp", 0x46525020},*/ /* Arpitan */ + {"fub", 0x46554c20}, /* Adamawa Fulfulde -> Fulah */ + {"fuc", 0x46554c20}, /* Pulaar -> Fulah */ + {"fue", 0x46554c20}, /* Borgu Fulfulde -> Fulah */ + {"fuf", 0x46544120}, /* Pular -> Futa */ + {"fuf", 0x46554c20}, /* Pular -> Fulah */ + {"fuh", 0x46554c20}, /* Western Niger Fulfulde -> Fulah */ + {"fui", 0x46554c20}, /* Bagirmi Fulfulde -> Fulah */ + {"fuq", 0x46554c20}, /* Central-Eastern Niger Fulfulde -> Fulah */ + {"fur", 0x46524c20}, /* Friulian */ + {"fuv", 0x46555620}, /* Nigerian Fulfulde */ + {"fuv", 0x46554c20}, /* Nigerian Fulfulde -> Fulah */ + {"fy", 0x46524920}, /* Western Frisian -> Frisian */ + {"ga", 0x49524920}, /* Irish */ + {"gaa", 0x47414420}, /* Ga */ + {"gac", 0x43505020}, /* Mixed Great Andamanese -> Creoles */ + {"gad", 0}, /* Gaddang != Ga */ + {"gae", 0}, /* Guarequena != Scottish Gaelic (Gaelic) */ + /*{"gag", 0x47414720},*/ /* Gagauz */ + {"gal", 0}, /* Galolen != Galician */ + {"gan", 0x5a485320}, /* Gan Chinese -> Chinese, Simplified */ + {"gaw", 0}, /* Nobonob != Garhwali */ + {"gax", 0x4f524f20}, /* Borana-Arsi-Guji Oromo -> Oromo */ + {"gaz", 0x4f524f20}, /* West Central Oromo -> Oromo */ + {"gbm", 0x47415720}, /* Garhwali */ + {"gce", 0x41544820}, /* Galice -> Athapaskan */ + {"gcf", 0x43505020}, /* Guadeloupean Creole French -> Creoles */ + {"gcl", 0x43505020}, /* Grenadian Creole English -> Creoles */ + {"gcr", 0x43505020}, /* Guianese Creole French -> Creoles */ + {"gd", 0x47414520}, /* Scottish Gaelic (Gaelic) */ + {"gda", 0x52414a20}, /* Gade Lohar -> Rajasthani */ + /*{"gez", 0x47455a20},*/ /* Geez */ + {"ggo", 0x474f4e20}, /* Southern Gondi (retired code) (retired code) -> Gondi */ + {"gha", 0x42425220}, /* Ghadamès -> Berber */ + {"ghk", 0x4b524e20}, /* Geko Karen -> Karen */ + {"gho", 0x42425220}, /* Ghomara -> Berber */ + {"gib", 0x43505020}, /* Gibanawa -> Creoles */ + /*{"gih", 0x47494820},*/ /* Githabul */ + {"gil", 0x47494c30}, /* Kiribati (Gilbertese) */ + {"gju", 0x52414a20}, /* Gujari -> Rajasthani */ + {"gkp", 0x474b5020}, /* Guinea Kpelle -> Kpelle (Guinea) */ + {"gkp", 0x4b504c20}, /* Guinea Kpelle -> Kpelle */ + {"gl", 0x47414c20}, /* Galician */ + {"gld", 0x4e414e20}, /* Nanai */ + /*{"glk", 0x474c4b20},*/ /* Gilaki */ + {"gmz", 0}, /* Mgbolizhia != Gumuz */ + {"gn", 0x47554120}, /* Guarani [macrolanguage] */ + {"gnb", 0x51494e20}, /* Gangte -> Chin */ + /*{"gnn", 0x474e4e20},*/ /* Gumatj */ + {"gno", 0x474f4e20}, /* Northern Gondi -> Gondi */ + {"gnw", 0x47554120}, /* Western Bolivian Guaraní -> Guarani */ + /*{"gog", 0x474f4720},*/ /* Gogo */ + {"gom", 0x4b4f4b20}, /* Goan Konkani -> Konkani */ + /*{"gon", 0x474f4e20},*/ /* Gondi [macrolanguage] */ + {"goq", 0x43505020}, /* Gorap -> Creoles */ + {"gox", 0x42414430}, /* Gobu -> Banda */ + {"gpe", 0x43505020}, /* Ghanaian Pidgin English -> Creoles */ + {"gro", 0}, /* Groma != Garo */ + {"grr", 0x42425220}, /* Taznatit -> Berber */ + {"grt", 0x47524f20}, /* Garo */ + {"gru", 0x534f4720}, /* Kistane -> Sodo Gurage */ + {"gsw", 0x414c5320}, /* Alsatian */ + {"gu", 0x47554a20}, /* Gujarati */ + {"gua", 0}, /* Shiki != Guarani */ + /*{"guc", 0x47554320},*/ /* Wayuu */ + /*{"guf", 0x47554620},*/ /* Gupapuyngu */ + {"gug", 0x47554120}, /* Paraguayan Guaraní -> Guarani */ + {"gui", 0x47554120}, /* Eastern Bolivian Guaraní -> Guarani */ + {"guk", 0x474d5a20}, /* Gumuz */ + {"gul", 0x43505020}, /* Sea Island Creole English -> Creoles */ + {"gun", 0x47554120}, /* Mbyá Guaraní -> Guarani */ + /*{"guz", 0x47555a20},*/ /* Gusii */ + {"gv", 0x4d4e5820}, /* Manx */ + {"gwi", 0x41544820}, /* Gwichʼin -> Athapaskan */ + {"gyn", 0x43505020}, /* Guyanese Creole English -> Creoles */ + {"ha", 0x48415520}, /* Hausa */ + {"haa", 0x41544820}, /* Han -> Athapaskan */ + {"hae", 0x4f524f20}, /* Eastern Oromo -> Oromo */ + {"hai", 0x48414930}, /* Haida [macrolanguage] */ + {"hak", 0x5a485320}, /* Hakka Chinese -> Chinese, Simplified */ + {"hal", 0}, /* Halang != Halam (Falam Chin) */ + {"har", 0x48524920}, /* Harari */ + /*{"haw", 0x48415720},*/ /* Hawaiian */ + {"hax", 0x48414930}, /* Southern Haida -> Haida */ + /*{"hay", 0x48415920},*/ /* Haya */ + /*{"haz", 0x48415a20},*/ /* Hazaragi */ + {"hbn", 0}, /* Heiban != Hammer-Banna */ + {"hca", 0x43505020}, /* Andaman Creole Hindi -> Creoles */ + {"hdn", 0x48414930}, /* Northern Haida -> Haida */ + {"he", 0x49575220}, /* Hebrew */ + {"hea", 0x484d4e20}, /* Northern Qiandong Miao -> Hmong */ + /*{"hei", 0x48454920},*/ /* Heiltsuk */ + {"hi", 0x48494e20}, /* Hindi */ + /*{"hil", 0x48494c20},*/ /* Hiligaynon */ + {"hji", 0x4d4c5920}, /* Haji -> Malay */ + {"hlt", 0x51494e20}, /* Matu Chin -> Chin */ + {"hma", 0x484d4e20}, /* Southern Mashan Hmong -> Hmong */ + {"hmc", 0x484d4e20}, /* Central Huishui Hmong -> Hmong */ + {"hmd", 0x484d4420}, /* Large Flowery Miao -> A-Hmao */ + {"hmd", 0x484d4e20}, /* Large Flowery Miao -> Hmong */ + {"hme", 0x484d4e20}, /* Eastern Huishui Hmong -> Hmong */ + {"hmg", 0x484d4e20}, /* Southwestern Guiyang Hmong -> Hmong */ + {"hmh", 0x484d4e20}, /* Southwestern Huishui Hmong -> Hmong */ + {"hmi", 0x484d4e20}, /* Northern Huishui Hmong -> Hmong */ + {"hmj", 0x484d4e20}, /* Ge -> Hmong */ + {"hml", 0x484d4e20}, /* Luopohe Hmong -> Hmong */ + {"hmm", 0x484d4e20}, /* Central Mashan Hmong -> Hmong */ + /*{"hmn", 0x484d4e20},*/ /* Hmong [macrolanguage] */ + {"hmp", 0x484d4e20}, /* Northern Mashan Hmong -> Hmong */ + {"hmq", 0x484d4e20}, /* Eastern Qiandong Miao -> Hmong */ + {"hmr", 0x51494e20}, /* Hmar -> Chin */ + {"hms", 0x484d4e20}, /* Southern Qiandong Miao -> Hmong */ + {"hmw", 0x484d4e20}, /* Western Mashan Hmong -> Hmong */ + {"hmy", 0x484d4e20}, /* Southern Guiyang Hmong -> Hmong */ + {"hmz", 0x484d5a20}, /* Hmong Shua -> Hmong Shuat */ + {"hmz", 0x484d4e20}, /* Hmong Shua -> Hmong */ + /*{"hnd", 0x484e4420},*/ /* Southern Hindko -> Hindko */ + {"hne", 0x43484820}, /* Chhattisgarhi -> Chattisgarhi */ + {"hnj", 0x484d4e20}, /* Hmong Njua -> Hmong */ + {"hno", 0x484e4420}, /* Northern Hindko -> Hindko */ + {"ho", 0x484d4f20}, /* Hiri Motu */ + {"ho", 0x43505020}, /* Hiri Motu -> Creoles */ + {"hoc", 0x484f2020}, /* Ho */ + {"hoi", 0x41544820}, /* Holikachuk -> Athapaskan */ + {"hoj", 0x48415220}, /* Hadothi -> Harauti */ + {"hoj", 0x52414a20}, /* Hadothi -> Rajasthani */ + {"hr", 0x48525620}, /* Croatian */ + {"hra", 0x51494e20}, /* Hrangkhol -> Chin */ + {"hrm", 0x484d4e20}, /* Horned Miao -> Hmong */ + {"hsb", 0x55534220}, /* Upper Sorbian */ + {"hsn", 0x5a485320}, /* Xiang Chinese -> Chinese, Simplified */ + {"ht", 0x48414920}, /* Haitian (Haitian Creole) */ + {"ht", 0x43505020}, /* Haitian -> Creoles */ + {"hu", 0x48554e20}, /* Hungarian */ + {"huj", 0x484d4e20}, /* Northern Guiyang Hmong -> Hmong */ + {"hup", 0x41544820}, /* Hupa -> Athapaskan */ + {"hus", 0x4d594e20}, /* Huastec -> Mayan */ + {"hwc", 0x43505020}, /* Hawai'i Creole English -> Creoles */ + {"hy", 0x48594530}, /* Armenian -> Armenian East */ + {"hy", 0x48594520}, /* Armenian */ + {"hyw", 0x48594520}, /* Western Armenian -> Armenian */ + {"hz", 0x48455220}, /* Herero */ + {"ia", 0x494e4120}, /* Interlingua (International Auxiliary Language Association) */ + /*{"iba", 0x49424120},*/ /* Iban */ + /*{"ibb", 0x49424220},*/ /* Ibibio */ + {"iby", 0x494a4f20}, /* Ibani -> Ijo */ + {"icr", 0x43505020}, /* Islander Creole English -> Creoles */ + {"id", 0x494e4420}, /* Indonesian */ + {"id", 0x4d4c5920}, /* Indonesian -> Malay */ + {"ida", 0x4c554820}, /* Idakho-Isukha-Tiriki -> Luyia */ + {"idb", 0x43505020}, /* Indo-Portuguese -> Creoles */ + {"ie", 0x494c4520}, /* Interlingue */ + {"ig", 0x49424f20}, /* Igbo */ + {"igb", 0x45424920}, /* Ebira */ + {"ihb", 0x43505020}, /* Iha Based Pidgin -> Creoles */ + {"ii", 0x59494d20}, /* Sichuan Yi -> Yi Modern */ + {"ijc", 0x494a4f20}, /* Izon -> Ijo */ + {"ije", 0x494a4f20}, /* Biseni -> Ijo */ + {"ijn", 0x494a4f20}, /* Kalabari -> Ijo */ + /*{"ijo", 0x494a4f20},*/ /* Ijo [collection] */ + {"ijs", 0x494a4f20}, /* Southeast Ijo -> Ijo */ + {"ik", 0x49504b20}, /* Inupiaq [macrolanguage] -> Inupiat */ + {"ike", 0x494e5520}, /* Eastern Canadian Inuktitut -> Inuktitut */ + {"ike", 0x494e554b}, /* Eastern Canadian Inuktitut -> Nunavik Inuktitut */ + {"ikt", 0x494e5520}, /* Inuinnaqtun -> Inuktitut */ + {"ikt", 0x494e554b}, /* Inuinnaqtun -> Nunavik Inuktitut */ + /*{"ilo", 0x494c4f20},*/ /* Iloko -> Ilokano */ + {"in", 0x494e4420}, /* Indonesian (retired code) (retired code) */ + {"in", 0x4d4c5920}, /* Indonesian (retired code) (retired code) -> Malay */ + {"ing", 0x41544820}, /* Degexit'an -> Athapaskan */ + {"inh", 0x494e4720}, /* Ingush */ + {"io", 0x49444f20}, /* Ido */ + {"iri", 0}, /* Rigwe != Irish */ + /*{"iru", 0x49525520},*/ /* Irula */ + {"is", 0x49534c20}, /* Icelandic */ + {"ism", 0}, /* Masimasi != Inari Sami */ + {"it", 0x49544120}, /* Italian */ + {"itz", 0x4d594e20}, /* Itzá -> Mayan */ + {"iu", 0x494e5520}, /* Inuktitut [macrolanguage] */ + {"iu", 0x494e554b}, /* Inuktitut [macrolanguage] -> Nunavik Inuktitut */ + {"iw", 0x49575220}, /* Hebrew (retired code) (retired code) */ + {"ixl", 0x4d594e20}, /* Ixil -> Mayan */ + {"ja", 0x4a414e20}, /* Japanese */ + {"jac", 0x4d594e20}, /* Popti' -> Mayan */ + {"jak", 0x4d4c5920}, /* Jakun -> Malay */ + {"jam", 0x4a414d20}, /* Jamaican Creole English -> Jamaican Creole */ + {"jam", 0x43505020}, /* Jamaican Creole English -> Creoles */ + {"jan", 0}, /* Jandai != Japanese */ + {"jax", 0x4d4c5920}, /* Jambi Malay -> Malay */ + {"jbe", 0x42425220}, /* Judeo-Berber -> Berber */ + {"jbn", 0x42425220}, /* Nafusi -> Berber */ + /*{"jbo", 0x4a424f20},*/ /* Lojban */ + /*{"jct", 0x4a435420},*/ /* Krymchak */ + {"jgo", 0x424d4c20}, /* Ngomba -> Bamileke */ + {"ji", 0x4a494920}, /* Yiddish (retired code) (retired code) */ + {"jii", 0}, /* Jiiddu != Yiddish */ + {"jkm", 0x4b524e20}, /* Mobwa Karen -> Karen */ + {"jkp", 0x4b524e20}, /* Paku Karen -> Karen */ + {"jud", 0}, /* Worodougou != Ladino */ + {"jul", 0}, /* Jirel != Jula */ + {"jv", 0x4a415620}, /* Javanese */ + {"jvd", 0x43505020}, /* Javindo -> Creoles */ + {"jw", 0x4a415620}, /* Javanese (retired code) (retired code) */ + {"ka", 0x4b415420}, /* Georgian */ + {"kaa", 0x4b524b20}, /* Karakalpak */ + {"kab", 0x4b414230}, /* Kabyle */ + {"kab", 0x42425220}, /* Kabyle -> Berber */ + {"kac", 0}, /* Kachin != Kachchi */ + {"kam", 0x4b4d4220}, /* Kamba (Kenya) */ + {"kar", 0x4b524e20}, /* Karen [collection] */ + /*{"kaw", 0x4b415720},*/ /* Kawi (Old Javanese) */ + {"kbd", 0x4b414220}, /* Kabardian */ + {"kby", 0x4b4e5220}, /* Manga Kanuri -> Kanuri */ + {"kca", 0x4b484b20}, /* Khanty -> Khanty-Kazim */ + {"kca", 0x4b485320}, /* Khanty -> Khanty-Shurishkar */ + {"kca", 0x4b485620}, /* Khanty -> Khanty-Vakhi */ + {"kcn", 0x43505020}, /* Nubi -> Creoles */ + /*{"kde", 0x4b444520},*/ /* Makonde */ + {"kdr", 0x4b524d20}, /* Karaim */ + {"kdt", 0x4b555920}, /* Kuy */ + {"kea", 0x4b454120}, /* Kabuverdianu (Crioulo) */ + {"kea", 0x43505020}, /* Kabuverdianu -> Creoles */ + {"keb", 0}, /* Kélé != Kebena */ + {"kek", 0x4b454b20}, /* Kekchí */ + {"kek", 0x4d594e20}, /* Kekchí -> Mayan */ + {"kex", 0x4b4b4e20}, /* Kukna -> Kokni */ + {"kfa", 0x4b4f4420}, /* Kodava -> Kodagu */ + {"kfr", 0x4b414320}, /* Kachhi -> Kachchi */ + {"kfx", 0x4b554c20}, /* Kullu Pahari -> Kulvi */ + {"kfy", 0x4b4d4e20}, /* Kumaoni */ + {"kg", 0x4b4f4e30}, /* Kongo [macrolanguage] */ + {"kge", 0}, /* Komering != Khutsuri Georgian */ + {"kha", 0x4b534920}, /* Khasi */ + {"khb", 0x58424420}, /* Lü */ + {"khk", 0x4d4e4720}, /* Halh Mongolian -> Mongolian */ + {"khn", 0}, /* Khandesi != Khamti Shan (Microsoft fonts) */ + {"khs", 0}, /* Kasua != Khanty-Shurishkar */ + {"kht", 0x4b485420}, /* Khamti -> Khamti Shan */ + {"kht", 0x4b484e20}, /* Khamti -> Khamti Shan (Microsoft fonts) */ + {"khv", 0}, /* Khvarshi != Khanty-Vakhi */ + /*{"khw", 0x4b485720},*/ /* Khowar */ + {"ki", 0x4b494b20}, /* Kikuyu (Gikuyu) */ + {"kis", 0}, /* Kis != Kisii */ + {"kiu", 0x4b495520}, /* Kirmanjki */ + {"kiu", 0x5a5a4120}, /* Kirmanjki -> Zazaki */ + {"kj", 0x4b554120}, /* Kuanyama */ + {"kjb", 0x4d594e20}, /* Q'anjob'al -> Mayan */ + /*{"kjd", 0x4b4a4420},*/ /* Southern Kiwai */ + {"kjh", 0x4b484120}, /* Khakas -> Khakass */ + {"kjp", 0x4b4a5020}, /* Pwo Eastern Karen -> Eastern Pwo Karen */ + {"kjp", 0x4b524e20}, /* Pwo Eastern Karen -> Karen */ + {"kjt", 0x4b524e20}, /* Phrae Pwo Karen -> Karen */ + /*{"kjz", 0x4b4a5a20},*/ /* Bumthangkha */ + {"kk", 0x4b415a20}, /* Kazakh */ + {"kkn", 0}, /* Kon Keu != Kokni */ + {"kkz", 0x41544820}, /* Kaska -> Athapaskan */ + {"kl", 0x47524e20}, /* Greenlandic */ + {"klm", 0}, /* Migum != Kalmyk */ + {"kln", 0x4b414c20}, /* Kalenjin [macrolanguage] */ + {"km", 0x4b484d20}, /* Khmer */ + {"kmb", 0x4d424e20}, /* Kimbundu -> Mbundu */ + {"kmn", 0}, /* Awtuw != Kumaoni */ + {"kmo", 0}, /* Kwoma != Komo */ + {"kmr", 0x4b555220}, /* Northern Kurdish -> Kurdish */ + {"kms", 0}, /* Kamasau != Komso */ + {"kmv", 0x43505020}, /* Karipúna Creole French -> Creoles */ + {"kmw", 0x4b4d4f20}, /* Komo (Democratic Republic of Congo) */ + /*{"kmz", 0x4b4d5a20},*/ /* Khorasani Turkish -> Khorasani Turkic */ + {"kn", 0x4b414e20}, /* Kannada */ + {"knc", 0x4b4e5220}, /* Central Kanuri -> Kanuri */ + {"kng", 0x4b4f4e30}, /* Koongo -> Kongo */ + {"knj", 0x4d594e20}, /* Western Kanjobal -> Mayan */ + {"knn", 0x4b4f4b20}, /* Konkani */ + {"knr", 0}, /* Kaningra != Kanuri */ + {"ko", 0x4b4f5220}, /* Korean */ + {"ko", 0x4b4f4820}, /* Korean -> Korean Old Hangul */ + {"kod", 0}, /* Kodi != Kodagu */ + {"koh", 0}, /* Koyo != Korean Old Hangul */ + {"koi", 0x4b4f5020}, /* Komi-Permyak */ + {"koi", 0x4b4f4d20}, /* Komi-Permyak -> Komi */ + /*{"kok", 0x4b4f4b20},*/ /* Konkani [macrolanguage] */ + {"kop", 0}, /* Waube != Komi-Permyak */ + /*{"kos", 0x4b4f5320},*/ /* Kosraean */ + {"koy", 0x41544820}, /* Koyukon -> Athapaskan */ + {"koz", 0}, /* Korak != Komi-Zyrian */ + {"kpe", 0x4b504c20}, /* Kpelle [macrolanguage] */ + {"kpl", 0}, /* Kpala != Kpelle */ + {"kpp", 0x4b524e20}, /* Paku Karen (retired code) (retired code) -> Karen */ + {"kpv", 0x4b4f5a20}, /* Komi-Zyrian */ + {"kpv", 0x4b4f4d20}, /* Komi-Zyrian -> Komi */ + {"kpy", 0x4b594b20}, /* Koryak */ + {"kqs", 0x4b495320}, /* Northern Kissi -> Kisii */ + {"kqy", 0x4b525420}, /* Koorete */ + {"kr", 0x4b4e5220}, /* Kanuri [macrolanguage] */ + {"krc", 0x4b415220}, /* Karachay-Balkar -> Karachay */ + {"krc", 0x42414c20}, /* Karachay-Balkar -> Balkar */ + {"kri", 0x4b524920}, /* Krio */ + {"kri", 0x43505020}, /* Krio -> Creoles */ + {"krk", 0}, /* Kerek != Karakalpak */ + /*{"krl", 0x4b524c20},*/ /* Karelian */ + {"krm", 0}, /* Krim (retired code) (retired code) != Karaim */ + {"krn", 0}, /* Sapo != Karen */ + {"krt", 0x4b4e5220}, /* Tumari Kanuri -> Kanuri */ + {"kru", 0x4b555520}, /* Kurukh */ + {"ks", 0x4b534820}, /* Kashmiri */ + {"ksh", 0x4b534830}, /* Kölsch -> Ripuarian */ + {"ksi", 0}, /* Krisa != Khasi */ + {"ksm", 0}, /* Kumba != Kildin Sami */ + {"kss", 0x4b495320}, /* Southern Kisi -> Kisii */ + {"ksw", 0x4b535720}, /* S’gaw Karen */ + {"ksw", 0x4b524e20}, /* S'gaw Karen -> Karen */ + {"ktb", 0x4b454220}, /* Kambaata -> Kebena */ + {"ktu", 0x4b4f4e20}, /* Kituba (Democratic Republic of Congo) -> Kikongo */ + {"ktw", 0x41544820}, /* Kato -> Athapaskan */ + {"ku", 0x4b555220}, /* Kurdish [macrolanguage] */ + {"kui", 0}, /* Kuikúro-Kalapálo != Kui */ + {"kul", 0}, /* Kulere != Kulvi */ + /*{"kum", 0x4b554d20},*/ /* Kumyk */ + {"kuu", 0x41544820}, /* Upper Kuskokwim -> Athapaskan */ + {"kuw", 0x42414430}, /* Kpagua -> Banda */ + {"kuy", 0}, /* Kuuku-Ya'u != Kuy */ + {"kv", 0x4b4f4d20}, /* Komi [macrolanguage] */ + {"kvb", 0x4d4c5920}, /* Kubu -> Malay */ + {"kvl", 0x4b524e20}, /* Kayaw -> Karen */ + {"kvq", 0x4b524e20}, /* Geba Karen -> Karen */ + {"kvr", 0x4d4c5920}, /* Kerinci -> Malay */ + {"kvt", 0x4b524e20}, /* Lahta Karen -> Karen */ + {"kvu", 0x4b524e20}, /* Yinbaw Karen -> Karen */ + {"kvy", 0x4b524e20}, /* Yintale Karen -> Karen */ + {"kw", 0x434f5220}, /* Cornish */ + /*{"kwk", 0x4b574b20},*/ /* Kwakiutl -> Kwakʼwala */ + {"kww", 0x43505020}, /* Kwinti -> Creoles */ + {"kwy", 0x4b4f4e30}, /* San Salvador Kongo -> Kongo */ + {"kxc", 0x4b4d5320}, /* Konso -> Komso */ + {"kxd", 0x4d4c5920}, /* Brunei -> Malay */ + {"kxf", 0x4b524e20}, /* Manumanaw Karen -> Karen */ + {"kxk", 0x4b524e20}, /* Zayein Karen -> Karen */ + {"kxl", 0x4b555520}, /* Nepali Kurux (retired code) (retired code) -> Kurukh */ + {"kxu", 0x4b554920}, /* Kui (India) (retired code) (retired code) */ + {"ky", 0x4b495220}, /* Kirghiz (Kyrgyz) */ + {"kyk", 0}, /* Kamayo != Koryak */ + {"kyu", 0x4b595520}, /* Western Kayah */ + {"kyu", 0x4b524e20}, /* Western Kayah -> Karen */ + {"la", 0x4c415420}, /* Latin */ + {"lac", 0x4d594e20}, /* Lacandon -> Mayan */ + {"lad", 0x4a554420}, /* Ladino */ + {"lah", 0}, /* Lahnda [macrolanguage] != Lahuli */ + {"lak", 0}, /* Laka (Nigeria) (retired code) (retired code) != Lak */ + {"lam", 0}, /* Lamba != Lambani */ + {"laz", 0}, /* Aribwatsa != Laz */ + {"lb", 0x4c545a20}, /* Luxembourgish */ + {"lbe", 0x4c414b20}, /* Lak */ + {"lbj", 0x4c444b20}, /* Ladakhi */ + {"lbl", 0x42494b20}, /* Libon Bikol -> Bikol */ + {"lce", 0x4d4c5920}, /* Loncong -> Malay */ + {"lcf", 0x4d4c5920}, /* Lubu -> Malay */ + {"ldi", 0x4b4f4e30}, /* Laari -> Kongo */ + {"ldk", 0}, /* Leelau != Ladakhi */ + /*{"lef", 0x4c454620},*/ /* Lelemi */ + /*{"lez", 0x4c455a20},*/ /* Lezghian -> Lezgi */ + {"lg", 0x4c554720}, /* Ganda */ + {"li", 0x4c494d20}, /* Limburgish */ + {"lif", 0x4c4d4220}, /* Limbu */ + /*{"lij", 0x4c494a20},*/ /* Ligurian */ + {"lir", 0x43505020}, /* Liberian English -> Creoles */ + /*{"lis", 0x4c495320},*/ /* Lisu */ + {"liw", 0x4d4c5920}, /* Col -> Malay */ + {"liy", 0x42414430}, /* Banda-Bambari -> Banda */ + /*{"ljp", 0x4c4a5020},*/ /* Lampung Api -> Lampung */ + {"lkb", 0x4c554820}, /* Kabras -> Luyia */ + /*{"lki", 0x4c4b4920},*/ /* Laki */ + {"lko", 0x4c554820}, /* Khayo -> Luyia */ + {"lks", 0x4c554820}, /* Kisa -> Luyia */ + {"lld", 0x4c414420}, /* Ladin */ + {"lma", 0}, /* East Limba != Low Mari */ + {"lmb", 0}, /* Merei != Limbu */ + {"lmn", 0x4c414d20}, /* Lambadi -> Lambani */ + /*{"lmo", 0x4c4d4f20},*/ /* Lombard */ + {"lmw", 0}, /* Lake Miwok != Lomwe */ + {"ln", 0x4c494e20}, /* Lingala */ + {"lna", 0x42414430}, /* Langbashe -> Banda */ + {"lnl", 0x42414430}, /* South Central Banda -> Banda */ + {"lo", 0x4c414f20}, /* Lao */ + /*{"lom", 0x4c4f4d20},*/ /* Loma (Liberia) */ + {"lou", 0x43505020}, /* Louisiana Creole -> Creoles */ + /*{"lpo", 0x4c504f20},*/ /* Lipo */ + /*{"lrc", 0x4c524320},*/ /* Northern Luri -> Luri */ + {"lri", 0x4c554820}, /* Marachi -> Luyia */ + {"lrm", 0x4c554820}, /* Marama -> Luyia */ + {"lrt", 0x43505020}, /* Larantuka Malay -> Creoles */ + {"lsb", 0}, /* Burundian Sign Language != Lower Sorbian */ + {"lsm", 0x4c554820}, /* Saamia -> Luyia */ + {"lt", 0x4c544820}, /* Lithuanian */ + {"ltg", 0x4c564920}, /* Latgalian -> Latvian */ + {"lth", 0}, /* Thur != Lithuanian */ + {"lto", 0x4c554820}, /* Tsotso -> Luyia */ + {"lts", 0x4c554820}, /* Tachoni -> Luyia */ + {"lu", 0x4c554220}, /* Luba-Katanga */ + /*{"lua", 0x4c554120},*/ /* Luba-Lulua */ + /*{"luo", 0x4c554f20},*/ /* Luo (Kenya and Tanzania) */ + {"lus", 0x4d495a20}, /* Lushai -> Mizo */ + {"lus", 0x51494e20}, /* Lushai -> Chin */ + {"luy", 0x4c554820}, /* Luyia [macrolanguage] */ + {"luz", 0x4c524320}, /* Southern Luri -> Luri */ + {"lv", 0x4c564920}, /* Latvian [macrolanguage] */ + {"lvi", 0}, /* Lavi != Latvian */ + {"lvs", 0x4c564920}, /* Standard Latvian -> Latvian */ + {"lwg", 0x4c554820}, /* Wanga -> Luyia */ + {"lzh", 0x5a485420}, /* Literary Chinese -> Chinese, Traditional */ + {"lzz", 0x4c415a20}, /* Laz */ + /*{"mad", 0x4d414420},*/ /* Madurese -> Madura */ + /*{"mag", 0x4d414720},*/ /* Magahi */ + {"mai", 0x4d544820}, /* Maithili */ + {"maj", 0}, /* Jalapa De Díaz Mazatec != Majang */ + {"mak", 0x4d4b5220}, /* Makasar */ + {"mam", 0x4d414d20}, /* Mam */ + {"mam", 0x4d594e20}, /* Mam -> Mayan */ + {"man", 0x4d4e4b20}, /* Mandingo [macrolanguage] -> Maninka */ + {"map", 0}, /* Austronesian [collection] != Mapudungun */ + {"maw", 0}, /* Mampruli != Marwari */ + {"max", 0x4d4c5920}, /* North Moluccan Malay -> Malay */ + {"max", 0x43505020}, /* North Moluccan Malay -> Creoles */ + {"mbf", 0x43505020}, /* Baba Malay -> Creoles */ + {"mbn", 0}, /* Macaguán != Mbundu */ + /*{"mbo", 0x4d424f20},*/ /* Mbo (Cameroon) */ + {"mch", 0}, /* Maquiritari != Manchu */ + {"mcm", 0x43505020}, /* Malaccan Creole Portuguese -> Creoles */ + {"mcr", 0}, /* Menya != Moose Cree */ + {"mct", 0x42544920}, /* Mengisa -> Beti */ + {"mde", 0}, /* Maba (Chad) != Mende */ + {"mdf", 0x4d4f4b20}, /* Moksha */ + /*{"mdr", 0x4d445220},*/ /* Mandar */ + {"mdy", 0x4d4c4520}, /* Male (Ethiopia) */ + {"men", 0x4d444520}, /* Mende (Sierra Leone) */ + {"meo", 0x4d4c5920}, /* Kedah Malay -> Malay */ + /*{"mer", 0x4d455220},*/ /* Meru */ + {"mfa", 0x4d464120}, /* Pattani Malay */ + {"mfa", 0x4d4c5920}, /* Pattani Malay -> Malay */ + {"mfb", 0x4d4c5920}, /* Bangka -> Malay */ + {"mfe", 0x4d464520}, /* Morisyen */ + {"mfe", 0x43505020}, /* Morisyen -> Creoles */ + {"mfp", 0x43505020}, /* Makassar Malay -> Creoles */ + {"mg", 0x4d4c4720}, /* Malagasy [macrolanguage] */ + {"mh", 0x4d414820}, /* Marshallese */ + {"mhc", 0x4d594e20}, /* Mocho -> Mayan */ + {"mhr", 0x4c4d4120}, /* Eastern Mari -> Low Mari */ + {"mhv", 0x41524b20}, /* Arakanese (retired code) -> Rakhine */ + {"mi", 0x4d524920}, /* Maori */ + {"min", 0x4d494e20}, /* Minangkabau */ + {"min", 0x4d4c5920}, /* Minangkabau -> Malay */ + {"miz", 0}, /* Coatzospan Mixtec != Mizo */ + {"mk", 0x4d4b4420}, /* Macedonian */ + {"mkn", 0x43505020}, /* Kupang Malay -> Creoles */ + {"mkr", 0}, /* Malas != Makasar */ + {"mku", 0x4d4e4b20}, /* Konyanka Maninka -> Maninka */ + /*{"mkw", 0x4d4b5720},*/ /* Kituba (Congo) */ + {"ml", 0x4d414c20}, /* Malayalam -> Malayalam Traditional */ + {"ml", 0x4d4c5220}, /* Malayalam -> Malayalam Reformed */ + {"mle", 0}, /* Manambu != Male */ + {"mln", 0}, /* Malango != Malinke */ + {"mlq", 0x4d4c4e20}, /* Western Maninkakan -> Malinke */ + {"mlq", 0x4d4e4b20}, /* Western Maninkakan -> Maninka */ + {"mlr", 0}, /* Vame != Malayalam Reformed */ + {"mmr", 0x484d4e20}, /* Western Xiangxi Miao -> Hmong */ + {"mn", 0x4d4e4720}, /* Mongolian [macrolanguage] */ + {"mnc", 0x4d434820}, /* Manchu */ + {"mnd", 0}, /* Mondé != Mandinka */ + {"mng", 0}, /* Eastern Mnong != Mongolian */ + {"mnh", 0x42414430}, /* Mono (Democratic Republic of Congo) -> Banda */ + /*{"mni", 0x4d4e4920},*/ /* Manipuri */ + {"mnk", 0x4d4e4420}, /* Mandinka */ + {"mnk", 0x4d4e4b20}, /* Mandinka -> Maninka */ + {"mnp", 0x5a485320}, /* Min Bei Chinese -> Chinese, Simplified */ + {"mns", 0x4d414e20}, /* Mansi */ + {"mnw", 0x4d4f4e20}, /* Mon */ + {"mnw", 0x4d4f4e54}, /* Mon -> Thailand Mon */ + {"mnx", 0}, /* Manikion != Manx */ + {"mo", 0x4d4f4c20}, /* Moldavian (retired code) (retired code) */ + {"mo", 0x524f4d20}, /* Moldavian (retired code) (retired code) -> Romanian */ + {"mod", 0x43505020}, /* Mobilian -> Creoles */ + /*{"moh", 0x4d4f4820},*/ /* Mohawk */ + {"mok", 0}, /* Morori != Moksha */ + {"mop", 0x4d594e20}, /* Mopán Maya -> Mayan */ + /*{"mos", 0x4d4f5320},*/ /* Mossi */ + {"mpe", 0x4d414a20}, /* Majang */ + {"mqg", 0x4d4c5920}, /* Kota Bangun Kutai Malay -> Malay */ + {"mr", 0x4d415220}, /* Marathi */ + {"mrh", 0x51494e20}, /* Mara Chin -> Chin */ + {"mrj", 0x484d4120}, /* Western Mari -> High Mari */ + {"ms", 0x4d4c5920}, /* Malay [macrolanguage] */ + {"msc", 0x4d4e4b20}, /* Sankaran Maninka -> Maninka */ + {"msh", 0x4d4c4720}, /* Masikoro Malagasy -> Malagasy */ + {"msi", 0x4d4c5920}, /* Sabah Malay -> Malay */ + {"msi", 0x43505020}, /* Sabah Malay -> Creoles */ + {"mt", 0x4d545320}, /* Maltese */ + {"mth", 0}, /* Munggui != Maithili */ + {"mtr", 0x4d415720}, /* Mewari -> Marwari */ + {"mts", 0}, /* Yora != Maltese */ + {"mud", 0x43505020}, /* Mednyj Aleut -> Creoles */ + {"mui", 0x4d4c5920}, /* Musi -> Malay */ + {"mun", 0}, /* Munda [collection] != Mundari */ + {"mup", 0x52414a20}, /* Malvi -> Rajasthani */ + {"muq", 0x484d4e20}, /* Eastern Xiangxi Miao -> Hmong */ + /*{"mus", 0x4d555320},*/ /* Creek -> Muscogee */ + {"mvb", 0x41544820}, /* Mattole -> Athapaskan */ + {"mve", 0x4d415720}, /* Marwari (Pakistan) */ + {"mvf", 0x4d4e4720}, /* Peripheral Mongolian -> Mongolian */ + {"mwk", 0x4d4e4b20}, /* Kita Maninkakan -> Maninka */ + /*{"mwl", 0x4d574c20},*/ /* Mirandese */ + {"mwq", 0x51494e20}, /* Mün Chin -> Chin */ + {"mwr", 0x4d415720}, /* Marwari [macrolanguage] */ + {"mww", 0x4d575720}, /* Hmong Daw */ + {"mww", 0x484d4e20}, /* Hmong Daw -> Hmong */ + {"my", 0x42524d20}, /* Burmese */ + {"mym", 0x4d454e20}, /* Me’en */ + /*{"myn", 0x4d594e20},*/ /* Mayan [collection] */ + {"myq", 0x4d4e4b20}, /* Forest Maninka (retired code) (retired code) -> Maninka */ + {"myv", 0x45525a20}, /* Erzya */ + {"mzb", 0x42425220}, /* Tumzabt -> Berber */ + /*{"mzn", 0x4d5a4e20},*/ /* Mazanderani */ + {"mzs", 0x43505020}, /* Macanese -> Creoles */ + {"na", 0x4e415520}, /* Nauru -> Nauruan */ + {"nag", 0x4e414720}, /* Naga Pidgin -> Naga-Assamese */ + {"nag", 0x43505020}, /* Naga Pidgin -> Creoles */ + /*{"nah", 0x4e414820},*/ /* Nahuatl [collection] */ + {"nan", 0x5a485320}, /* Min Nan Chinese -> Chinese, Simplified */ + /*{"nap", 0x4e415020},*/ /* Neapolitan */ + {"nas", 0}, /* Naasioi != Naskapi */ + {"naz", 0x4e414820}, /* Coatepec Nahuatl -> Nahuatl */ + {"nb", 0x4e4f5220}, /* Norwegian Bokmål -> Norwegian */ + {"nch", 0x4e414820}, /* Central Huasteca Nahuatl -> Nahuatl */ + {"nci", 0x4e414820}, /* Classical Nahuatl -> Nahuatl */ + {"ncj", 0x4e414820}, /* Northern Puebla Nahuatl -> Nahuatl */ + {"ncl", 0x4e414820}, /* Michoacán Nahuatl -> Nahuatl */ + {"ncr", 0}, /* Ncane != N-Cree */ + {"ncx", 0x4e414820}, /* Central Puebla Nahuatl -> Nahuatl */ + {"nd", 0x4e444220}, /* North Ndebele -> Ndebele */ + {"ndb", 0}, /* Kenswei Nsei != Ndebele */ + /*{"ndc", 0x4e444320},*/ /* Ndau */ + {"ndg", 0}, /* Ndengereko != Ndonga */ + /*{"nds", 0x4e445320},*/ /* Low Saxon */ + {"ne", 0x4e455020}, /* Nepali [macrolanguage] */ + {"nef", 0x43505020}, /* Nefamese -> Creoles */ + /*{"new", 0x4e455720},*/ /* Newari */ + {"ng", 0x4e444720}, /* Ndonga */ + /*{"nga", 0x4e474120},*/ /* Ngbaka */ + {"ngl", 0x4c4d5720}, /* Lomwe */ + {"ngm", 0x43505020}, /* Ngatik Men's Creole -> Creoles */ + {"ngo", 0x53585420}, /* Ngoni (retired code) (retired code) -> Sutu */ + {"ngu", 0x4e414820}, /* Guerrero Nahuatl -> Nahuatl */ + {"nhc", 0x4e414820}, /* Tabasco Nahuatl -> Nahuatl */ + {"nhd", 0x47554120}, /* Chiripá -> Guarani */ + {"nhe", 0x4e414820}, /* Eastern Huasteca Nahuatl -> Nahuatl */ + {"nhg", 0x4e414820}, /* Tetelcingo Nahuatl -> Nahuatl */ + {"nhi", 0x4e414820}, /* Zacatlán-Ahuacatlán-Tepetzintla Nahuatl -> Nahuatl */ + {"nhk", 0x4e414820}, /* Isthmus-Cosoleacaque Nahuatl -> Nahuatl */ + {"nhm", 0x4e414820}, /* Morelos Nahuatl -> Nahuatl */ + {"nhn", 0x4e414820}, /* Central Nahuatl -> Nahuatl */ + {"nhp", 0x4e414820}, /* Isthmus-Pajapan Nahuatl -> Nahuatl */ + {"nhq", 0x4e414820}, /* Huaxcaleca Nahuatl -> Nahuatl */ + {"nht", 0x4e414820}, /* Ometepec Nahuatl -> Nahuatl */ + {"nhv", 0x4e414820}, /* Temascaltepec Nahuatl -> Nahuatl */ + {"nhw", 0x4e414820}, /* Western Huasteca Nahuatl -> Nahuatl */ + {"nhx", 0x4e414820}, /* Isthmus-Mecayapan Nahuatl -> Nahuatl */ + {"nhy", 0x4e414820}, /* Northern Oaxaca Nahuatl -> Nahuatl */ + {"nhz", 0x4e414820}, /* Santa María La Alta Nahuatl -> Nahuatl */ + {"niq", 0x4b414c20}, /* Nandi -> Kalenjin */ + {"nis", 0}, /* Nimi != Nisi */ + /*{"niu", 0x4e495520},*/ /* Niuean */ + {"niv", 0x47494c20}, /* Gilyak */ + {"njt", 0x43505020}, /* Ndyuka-Trio Pidgin -> Creoles */ + {"njz", 0x4e495320}, /* Nyishi -> Nisi */ + {"nko", 0}, /* Nkonya != N’Ko */ + {"nkx", 0x494a4f20}, /* Nkoroo -> Ijo */ + {"nl", 0x4e4c4420}, /* Dutch */ + {"nla", 0x424d4c20}, /* Ngombale -> Bamileke */ + {"nle", 0x4c554820}, /* East Nyala -> Luyia */ + {"nln", 0x4e414820}, /* Durango Nahuatl (retired code) (retired code) -> Nahuatl */ + {"nlv", 0x4e414820}, /* Orizaba Nahuatl -> Nahuatl */ + {"nn", 0x4e594e20}, /* Norwegian Nynorsk (Nynorsk, Norwegian) */ + {"nn", 0x4e4f5220}, /* Norwegian Nynorsk -> Norwegian */ + {"nnh", 0x424d4c20}, /* Ngiemboon -> Bamileke */ + {"nnz", 0x424d4c20}, /* Nda'nda' -> Bamileke */ + {"no", 0x4e4f5220}, /* Norwegian [macrolanguage] */ + {"nod", 0x4e544120}, /* Northern Thai -> Northern Tai */ + /*{"noe", 0x4e4f4520},*/ /* Nimadi */ + /*{"nog", 0x4e4f4720},*/ /* Nogai */ + /*{"nov", 0x4e4f5620},*/ /* Novial */ + {"npi", 0x4e455020}, /* Nepali */ + {"npl", 0x4e414820}, /* Southeastern Puebla Nahuatl -> Nahuatl */ + {"nqo", 0x4e4b4f20}, /* N’Ko */ + {"nr", 0x4e444220}, /* South Ndebele -> Ndebele */ + {"nsk", 0x4e415320}, /* Naskapi */ + {"nsm", 0}, /* Sumi Naga != Northern Sami */ + /*{"nso", 0x4e534f20},*/ /* Northern Sotho */ + {"nsu", 0x4e414820}, /* Sierra Negra Nahuatl -> Nahuatl */ + {"nto", 0}, /* Ntomba != Esperanto */ + {"nue", 0x42414430}, /* Ngundu -> Banda */ + {"nuu", 0x42414430}, /* Ngbundu -> Banda */ + {"nuz", 0x4e414820}, /* Tlamacazapa Nahuatl -> Nahuatl */ + {"nv", 0x4e415620}, /* Navajo */ + {"nv", 0x41544820}, /* Navajo -> Athapaskan */ + {"nwe", 0x424d4c20}, /* Ngwe -> Bamileke */ + {"ny", 0x43484920}, /* Chichewa (Chewa, Nyanja) */ + {"nyd", 0x4c554820}, /* Nyore -> Luyia */ + /*{"nym", 0x4e594d20},*/ /* Nyamwezi */ + {"nyn", 0x4e4b4c20}, /* Nyankole */ + /*{"nza", 0x4e5a4120},*/ /* Tigon Mbembe -> Mbembe Tigon */ + {"oc", 0x4f434920}, /* Occitan (post 1500) */ + {"oj", 0x4f4a4220}, /* Ojibwa [macrolanguage] -> Ojibway */ + /*{"ojb", 0x4f4a4220},*/ /* Northwestern Ojibwa -> Ojibway */ + {"ojc", 0x4f4a4220}, /* Central Ojibwa -> Ojibway */ + {"ojg", 0x4f4a4220}, /* Eastern Ojibwa -> Ojibway */ + {"ojs", 0x4f435220}, /* Severn Ojibwa -> Oji-Cree */ + {"ojs", 0x4f4a4220}, /* Severn Ojibwa -> Ojibway */ + {"ojw", 0x4f4a4220}, /* Western Ojibwa -> Ojibway */ + {"okd", 0x494a4f20}, /* Okodia -> Ijo */ + {"oki", 0x4b414c20}, /* Okiek -> Kalenjin */ + {"okm", 0x4b4f4820}, /* Middle Korean (10th-16th cent.) -> Korean Old Hangul */ + {"okr", 0x494a4f20}, /* Kirike -> Ijo */ + {"om", 0x4f524f20}, /* Oromo [macrolanguage] */ + {"onx", 0x43505020}, /* Onin Based Pidgin -> Creoles */ + {"oor", 0x43505020}, /* Oorlams -> Creoles */ + {"orc", 0x4f524f20}, /* Orma -> Oromo */ + {"orn", 0x4d4c5920}, /* Orang Kanaq -> Malay */ + {"oro", 0}, /* Orokolo != Oromo */ + {"orr", 0x494a4f20}, /* Oruma -> Ijo */ + {"ors", 0x4d4c5920}, /* Orang Seletar -> Malay */ + {"os", 0x4f535320}, /* Ossetian */ + {"otw", 0x4f4a4220}, /* Ottawa -> Ojibway */ + {"oua", 0x42425220}, /* Tagargrent -> Berber */ + {"pa", 0x50414e20}, /* Punjabi */ + {"paa", 0}, /* Papuan [collection] != Palestinian Aramaic */ + /*{"pag", 0x50414720},*/ /* Pangasinan */ + {"pal", 0}, /* Pahlavi != Pali */ + /*{"pam", 0x50414d20},*/ /* Pampanga -> Pampangan */ + {"pap", 0x50415030}, /* Papiamento -> Papiamentu */ + {"pap", 0x43505020}, /* Papiamento -> Creoles */ + {"pas", 0}, /* Papasena != Pashto */ + /*{"pau", 0x50415520},*/ /* Palauan */ + {"pbt", 0x50415320}, /* Southern Pashto -> Pashto */ + {"pbu", 0x50415320}, /* Northern Pashto -> Pashto */ + /*{"pcc", 0x50434320},*/ /* Bouyei */ + /*{"pcd", 0x50434420},*/ /* Picard */ + {"pce", 0x504c4720}, /* Ruching Palaung -> Palaung */ + {"pck", 0x51494e20}, /* Paite Chin -> Chin */ + {"pcm", 0x43505020}, /* Nigerian Pidgin -> Creoles */ + /*{"pdc", 0x50444320},*/ /* Pennsylvania German */ + {"pdu", 0x4b524e20}, /* Kayan -> Karen */ + {"pea", 0x43505020}, /* Peranakan Indonesian -> Creoles */ + {"pel", 0x4d4c5920}, /* Pekal -> Malay */ + {"pes", 0x46415220}, /* Iranian Persian -> Persian */ + {"pey", 0x43505020}, /* Petjo -> Creoles */ + {"pga", 0x41524120}, /* Sudanese Creole Arabic -> Arabic */ + {"pga", 0x43505020}, /* Sudanese Creole Arabic -> Creoles */ + /*{"phk", 0x50484b20},*/ /* Phake */ + {"pi", 0x50414c20}, /* Pali */ + {"pih", 0x50494820}, /* Pitcairn-Norfolk -> Norfolk */ + {"pih", 0x43505020}, /* Pitcairn-Norfolk -> Creoles */ + {"pil", 0}, /* Yom != Filipino */ + {"pis", 0x43505020}, /* Pijin -> Creoles */ + {"pkh", 0x51494e20}, /* Pankhu -> Chin */ + {"pko", 0x4b414c20}, /* Pökoot -> Kalenjin */ + {"pl", 0x504c4b20}, /* Polish */ + {"plg", 0}, /* Pilagá != Palaung */ + {"plk", 0}, /* Kohistani Shina != Polish */ + {"pll", 0x504c4720}, /* Shwe Palaung -> Palaung */ + {"pln", 0x43505020}, /* Palenquero -> Creoles */ + {"plp", 0x50415020}, /* Palpa (retired code) (retired code) */ + {"plt", 0x4d4c4720}, /* Plateau Malagasy -> Malagasy */ + {"pml", 0x43505020}, /* Lingua Franca -> Creoles */ + /*{"pms", 0x504d5320},*/ /* Piemontese */ + {"pmy", 0x43505020}, /* Papuan Malay -> Creoles */ + /*{"pnb", 0x504e4220},*/ /* Western Panjabi */ + {"poc", 0x4d594e20}, /* Poqomam -> Mayan */ + {"poh", 0x504f4820}, /* Poqomchi' -> Pocomchi */ + {"poh", 0x4d594e20}, /* Poqomchi' -> Mayan */ + /*{"pon", 0x504f4e20},*/ /* Pohnpeian */ + {"pov", 0x43505020}, /* Upper Guinea Crioulo -> Creoles */ + {"ppa", 0x42414720}, /* Pao (retired code) (retired code) -> Baghelkhandi */ + {"pre", 0x43505020}, /* Principense -> Creoles */ + /*{"pro", 0x50524f20},*/ /* Old Provençal (to 1500) -> Provençal / Old Provençal */ + {"prp", 0x47554a20}, /* Parsi (retired code) (retired code) -> Gujarati */ + {"prs", 0x44524920}, /* Dari */ + {"prs", 0x46415220}, /* Dari -> Persian */ + {"ps", 0x50415320}, /* Pashto [macrolanguage] */ + {"pse", 0x4d4c5920}, /* Central Malay -> Malay */ + {"pst", 0x50415320}, /* Central Pashto -> Pashto */ + {"pt", 0x50544720}, /* Portuguese */ + {"pub", 0x51494e20}, /* Purum -> Chin */ + {"puz", 0x51494e20}, /* Purum Naga (retired code) (retired code) -> Chin */ + {"pwo", 0x50574f20}, /* Pwo Western Karen -> Western Pwo Karen */ + {"pwo", 0x4b524e20}, /* Pwo Western Karen -> Karen */ + {"pww", 0x4b524e20}, /* Pwo Northern Karen -> Karen */ + {"qu", 0x51555a20}, /* Quechua [macrolanguage] */ + {"qub", 0x51574820}, /* Huallaga Huánuco Quechua -> Quechua (Peru) */ + {"qub", 0x51555a20}, /* Huallaga Huánuco Quechua -> Quechua */ + {"quc", 0x51554320}, /* K’iche’ */ + {"quc", 0x4d594e20}, /* K'iche' -> Mayan */ + {"qud", 0x51564920}, /* Calderón Highland Quichua -> Quechua (Ecuador) */ + {"qud", 0x51555a20}, /* Calderón Highland Quichua -> Quechua */ + {"quf", 0x51555a20}, /* Lambayeque Quechua -> Quechua */ + {"qug", 0x51564920}, /* Chimborazo Highland Quichua -> Quechua (Ecuador) */ + {"qug", 0x51555a20}, /* Chimborazo Highland Quichua -> Quechua */ + {"quh", 0x51554820}, /* South Bolivian Quechua -> Quechua (Bolivia) */ + {"quh", 0x51555a20}, /* South Bolivian Quechua -> Quechua */ + {"quk", 0x51555a20}, /* Chachapoyas Quechua -> Quechua */ + {"qul", 0x51554820}, /* North Bolivian Quechua -> Quechua (Bolivia) */ + {"qul", 0x51555a20}, /* North Bolivian Quechua -> Quechua */ + {"qum", 0x4d594e20}, /* Sipacapense -> Mayan */ + {"qup", 0x51564920}, /* Southern Pastaza Quechua -> Quechua (Ecuador) */ + {"qup", 0x51555a20}, /* Southern Pastaza Quechua -> Quechua */ + {"qur", 0x51574820}, /* Yanahuanca Pasco Quechua -> Quechua (Peru) */ + {"qur", 0x51555a20}, /* Yanahuanca Pasco Quechua -> Quechua */ + {"qus", 0x51554820}, /* Santiago del Estero Quichua -> Quechua (Bolivia) */ + {"qus", 0x51555a20}, /* Santiago del Estero Quichua -> Quechua */ + {"quv", 0x4d594e20}, /* Sacapulteco -> Mayan */ + {"quw", 0x51564920}, /* Tena Lowland Quichua -> Quechua (Ecuador) */ + {"quw", 0x51555a20}, /* Tena Lowland Quichua -> Quechua */ + {"qux", 0x51574820}, /* Yauyos Quechua -> Quechua (Peru) */ + {"qux", 0x51555a20}, /* Yauyos Quechua -> Quechua */ + {"quy", 0x51555a20}, /* Ayacucho Quechua -> Quechua */ + /*{"quz", 0x51555a20},*/ /* Cusco Quechua -> Quechua */ + {"qva", 0x51574820}, /* Ambo-Pasco Quechua -> Quechua (Peru) */ + {"qva", 0x51555a20}, /* Ambo-Pasco Quechua -> Quechua */ + {"qvc", 0x51555a20}, /* Cajamarca Quechua -> Quechua */ + {"qve", 0x51555a20}, /* Eastern Apurímac Quechua -> Quechua */ + {"qvh", 0x51574820}, /* Huamalíes-Dos de Mayo Huánuco Quechua -> Quechua (Peru) */ + {"qvh", 0x51555a20}, /* Huamalíes-Dos de Mayo Huánuco Quechua -> Quechua */ + {"qvi", 0x51564920}, /* Imbabura Highland Quichua -> Quechua (Ecuador) */ + {"qvi", 0x51555a20}, /* Imbabura Highland Quichua -> Quechua */ + {"qvj", 0x51564920}, /* Loja Highland Quichua -> Quechua (Ecuador) */ + {"qvj", 0x51555a20}, /* Loja Highland Quichua -> Quechua */ + {"qvl", 0x51574820}, /* Cajatambo North Lima Quechua -> Quechua (Peru) */ + {"qvl", 0x51555a20}, /* Cajatambo North Lima Quechua -> Quechua */ + {"qvm", 0x51574820}, /* Margos-Yarowilca-Lauricocha Quechua -> Quechua (Peru) */ + {"qvm", 0x51555a20}, /* Margos-Yarowilca-Lauricocha Quechua -> Quechua */ + {"qvn", 0x51574820}, /* North Junín Quechua -> Quechua (Peru) */ + {"qvn", 0x51555a20}, /* North Junín Quechua -> Quechua */ + {"qvo", 0x51564920}, /* Napo Lowland Quechua -> Quechua (Ecuador) */ + {"qvo", 0x51555a20}, /* Napo Lowland Quechua -> Quechua */ + {"qvp", 0x51574820}, /* Pacaraos Quechua -> Quechua (Peru) */ + {"qvp", 0x51555a20}, /* Pacaraos Quechua -> Quechua */ + {"qvs", 0x51555a20}, /* San Martín Quechua -> Quechua */ + {"qvw", 0x51574820}, /* Huaylla Wanca Quechua -> Quechua (Peru) */ + {"qvw", 0x51555a20}, /* Huaylla Wanca Quechua -> Quechua */ + {"qvz", 0x51564920}, /* Northern Pastaza Quichua -> Quechua (Ecuador) */ + {"qvz", 0x51555a20}, /* Northern Pastaza Quichua -> Quechua */ + {"qwa", 0x51574820}, /* Corongo Ancash Quechua -> Quechua (Peru) */ + {"qwa", 0x51555a20}, /* Corongo Ancash Quechua -> Quechua */ + {"qwc", 0x51555a20}, /* Classical Quechua -> Quechua */ + {"qwh", 0x51574820}, /* Huaylas Ancash Quechua -> Quechua (Peru) */ + {"qwh", 0x51555a20}, /* Huaylas Ancash Quechua -> Quechua */ + {"qws", 0x51574820}, /* Sihuas Ancash Quechua -> Quechua (Peru) */ + {"qws", 0x51555a20}, /* Sihuas Ancash Quechua -> Quechua */ + {"qwt", 0x41544820}, /* Kwalhioqua-Tlatskanai -> Athapaskan */ + {"qxa", 0x51574820}, /* Chiquián Ancash Quechua -> Quechua (Peru) */ + {"qxa", 0x51555a20}, /* Chiquián Ancash Quechua -> Quechua */ + {"qxc", 0x51574820}, /* Chincha Quechua -> Quechua (Peru) */ + {"qxc", 0x51555a20}, /* Chincha Quechua -> Quechua */ + {"qxh", 0x51574820}, /* Panao Huánuco Quechua -> Quechua (Peru) */ + {"qxh", 0x51555a20}, /* Panao Huánuco Quechua -> Quechua */ + {"qxl", 0x51564920}, /* Salasaca Highland Quichua -> Quechua (Ecuador) */ + {"qxl", 0x51555a20}, /* Salasaca Highland Quichua -> Quechua */ + {"qxn", 0x51574820}, /* Northern Conchucos Ancash Quechua -> Quechua (Peru) */ + {"qxn", 0x51555a20}, /* Northern Conchucos Ancash Quechua -> Quechua */ + {"qxo", 0x51574820}, /* Southern Conchucos Ancash Quechua -> Quechua (Peru) */ + {"qxo", 0x51555a20}, /* Southern Conchucos Ancash Quechua -> Quechua */ + {"qxp", 0x51555a20}, /* Puno Quechua -> Quechua */ + {"qxr", 0x51564920}, /* Cañar Highland Quichua -> Quechua (Ecuador) */ + {"qxr", 0x51555a20}, /* Cañar Highland Quichua -> Quechua */ + {"qxt", 0x51574820}, /* Santa Ana de Tusi Pasco Quechua -> Quechua (Peru) */ + {"qxt", 0x51555a20}, /* Santa Ana de Tusi Pasco Quechua -> Quechua */ + {"qxu", 0x51555a20}, /* Arequipa-La Unión Quechua -> Quechua */ + {"qxw", 0x51574820}, /* Jauja Wanca Quechua -> Quechua (Peru) */ + {"qxw", 0x51555a20}, /* Jauja Wanca Quechua -> Quechua */ + {"rag", 0x4c554820}, /* Logooli -> Luyia */ + /*{"raj", 0x52414a20},*/ /* Rajasthani [macrolanguage] */ + {"ral", 0x51494e20}, /* Ralte -> Chin */ + /*{"rar", 0x52415220},*/ /* Rarotongan */ + {"rbb", 0x504c4720}, /* Rumai Palaung -> Palaung */ + {"rbl", 0x42494b20}, /* Miraya Bikol -> Bikol */ + {"rcf", 0x43505020}, /* Réunion Creole French -> Creoles */ + /*{"rej", 0x52454a20},*/ /* Rejang */ + /*{"rhg", 0x52484720},*/ /* Rohingya */ + /*{"ria", 0x52494120},*/ /* Riang (India) */ + {"rif", 0x52494620}, /* Tarifit */ + {"rif", 0x42425220}, /* Tarifit -> Berber */ + /*{"rit", 0x52495420},*/ /* Ritharrngu -> Ritarungo */ + {"rki", 0x41524b20}, /* Rakhine */ + /*{"rkw", 0x524b5720},*/ /* Arakwal */ + {"rm", 0x524d5320}, /* Romansh */ + {"rmc", 0x524f5920}, /* Carpathian Romani -> Romany */ + {"rmf", 0x524f5920}, /* Kalo Finnish Romani -> Romany */ + {"rml", 0x524f5920}, /* Baltic Romani -> Romany */ + {"rmn", 0x524f5920}, /* Balkan Romani -> Romany */ + {"rmo", 0x524f5920}, /* Sinte Romani -> Romany */ + {"rms", 0}, /* Romanian Sign Language != Romansh */ + {"rmw", 0x524f5920}, /* Welsh Romani -> Romany */ + {"rmy", 0x524d5920}, /* Vlax Romani */ + {"rmy", 0x524f5920}, /* Vlax Romani -> Romany */ + {"rmz", 0x41524b20}, /* Marma -> Rakhine */ + {"rn", 0x52554e20}, /* Rundi */ + {"ro", 0x524f4d20}, /* Romanian */ + {"rom", 0x524f5920}, /* Romany [macrolanguage] */ + {"rop", 0x43505020}, /* Kriol -> Creoles */ + {"rtc", 0x51494e20}, /* Rungtu Chin -> Chin */ + /*{"rtm", 0x52544d20},*/ /* Rotuman */ + {"ru", 0x52555320}, /* Russian */ + {"rue", 0x52535920}, /* Rusyn */ + /*{"rup", 0x52555020},*/ /* Aromanian */ + {"rw", 0x52554120}, /* Kinyarwanda */ + {"rwr", 0x4d415720}, /* Marwari (India) */ + {"sa", 0x53414e20}, /* Sanskrit */ + {"sad", 0}, /* Sandawe != Sadri */ + {"sah", 0x59414b20}, /* Yakut -> Sakha */ + {"sam", 0x50414120}, /* Samaritan Aramaic -> Palestinian Aramaic */ + /*{"sas", 0x53415320},*/ /* Sasak */ + /*{"sat", 0x53415420},*/ /* Santali */ + {"say", 0}, /* Saya != Sayisi */ + {"sc", 0x53524420}, /* Sardinian [macrolanguage] */ + {"scf", 0x43505020}, /* San Miguel Creole French -> Creoles */ + {"sch", 0x51494e20}, /* Sakachep -> Chin */ + {"sci", 0x43505020}, /* Sri Lankan Creole Malay -> Creoles */ + {"sck", 0x53414420}, /* Sadri */ + /*{"scn", 0x53434e20},*/ /* Sicilian */ + /*{"sco", 0x53434f20},*/ /* Scots */ + {"scs", 0x53435320}, /* North Slavey */ + {"scs", 0x534c4120}, /* North Slavey -> Slavey */ + {"scs", 0x41544820}, /* North Slavey -> Athapaskan */ + {"sd", 0x534e4420}, /* Sindhi */ + {"sdc", 0x53524420}, /* Sassarese Sardinian -> Sardinian */ + {"sdh", 0x4b555220}, /* Southern Kurdish -> Kurdish */ + {"sdn", 0x53524420}, /* Gallurese Sardinian -> Sardinian */ + {"sds", 0x42425220}, /* Sened -> Berber */ + {"se", 0x4e534d20}, /* Northern Sami */ + {"seh", 0x534e4120}, /* Sena */ + {"sek", 0x41544820}, /* Sekani -> Athapaskan */ + /*{"sel", 0x53454c20},*/ /* Selkup */ + {"sez", 0x51494e20}, /* Senthang Chin -> Chin */ + {"sfm", 0x53464d20}, /* Small Flowery Miao */ + {"sfm", 0x484d4e20}, /* Small Flowery Miao -> Hmong */ + {"sg", 0x53474f20}, /* Sango */ + /*{"sga", 0x53474120},*/ /* Old Irish (to 900) */ + {"sgc", 0x4b414c20}, /* Kipsigis -> Kalenjin */ + {"sgo", 0}, /* Songa (retired code) (retired code) != Sango */ + /*{"sgs", 0x53475320},*/ /* Samogitian */ + {"sgw", 0x43484720}, /* Sebat Bet Gurage -> Chaha Gurage */ + {"sh", 0x424f5320}, /* Serbo-Croatian [macrolanguage] -> Bosnian */ + {"sh", 0x48525620}, /* Serbo-Croatian [macrolanguage] -> Croatian */ + {"sh", 0x53524220}, /* Serbo-Croatian [macrolanguage] -> Serbian */ + {"shi", 0x53484920}, /* Tachelhit */ + {"shi", 0x42425220}, /* Tachelhit -> Berber */ + {"shl", 0x51494e20}, /* Shendu -> Chin */ + /*{"shn", 0x53484e20},*/ /* Shan */ + {"shu", 0x41524120}, /* Chadian Arabic -> Arabic */ + {"shy", 0x42425220}, /* Tachawit -> Berber */ + {"si", 0x534e4820}, /* Sinhala (Sinhalese) */ + {"sib", 0}, /* Sebop != Sibe */ + /*{"sid", 0x53494420},*/ /* Sidamo */ + {"sig", 0}, /* Paasaal != Silte Gurage */ + {"siz", 0x42425220}, /* Siwi -> Berber */ + {"sjd", 0x4b534d20}, /* Kildin Sami */ + {"sjo", 0x53494220}, /* Xibe -> Sibe */ + {"sjs", 0x42425220}, /* Senhaja De Srair -> Berber */ + {"sk", 0x534b5920}, /* Slovak */ + {"skg", 0x4d4c4720}, /* Sakalava Malagasy -> Malagasy */ + {"skr", 0x53524b20}, /* Saraiki */ + {"sks", 0}, /* Maia != Skolt Sami */ + {"skw", 0x43505020}, /* Skepi Creole Dutch -> Creoles */ + {"sky", 0}, /* Sikaiana != Slovak */ + {"sl", 0x534c5620}, /* Slovenian */ + {"sla", 0}, /* Slavic [collection] != Slavey */ + {"sm", 0x534d4f20}, /* Samoan */ + {"sma", 0x53534d20}, /* Southern Sami */ + {"smd", 0x4d424e20}, /* Sama (retired code) (retired code) -> Mbundu */ + {"smj", 0x4c534d20}, /* Lule Sami */ + {"sml", 0}, /* Central Sama != Somali */ + {"smn", 0x49534d20}, /* Inari Sami */ + {"sms", 0x534b5320}, /* Skolt Sami */ + {"smt", 0x51494e20}, /* Simte -> Chin */ + {"sn", 0x534e4130}, /* Shona */ + {"snb", 0x49424120}, /* Sebuyau (retired code) (retired code) -> Iban */ + {"snh", 0}, /* Shinabo (retired code) (retired code) != Sinhala (Sinhalese) */ + /*{"snk", 0x534e4b20},*/ /* Soninke */ + {"so", 0x534d4c20}, /* Somali */ + {"sog", 0}, /* Sogdian != Sodo Gurage */ + /*{"sop", 0x534f5020},*/ /* Songe */ + {"spy", 0x4b414c20}, /* Sabaot -> Kalenjin */ + {"sq", 0x53514920}, /* Albanian [macrolanguage] */ + {"sr", 0x53524220}, /* Serbian */ + {"srb", 0}, /* Sora != Serbian */ + {"src", 0x53524420}, /* Logudorese Sardinian -> Sardinian */ + {"srk", 0}, /* Serudung Murut != Saraiki */ + {"srm", 0x43505020}, /* Saramaccan -> Creoles */ + {"srn", 0x43505020}, /* Sranan Tongo -> Creoles */ + {"sro", 0x53524420}, /* Campidanese Sardinian -> Sardinian */ + /*{"srr", 0x53525220},*/ /* Serer */ + {"srs", 0x41544820}, /* Sarsi -> Athapaskan */ + {"ss", 0x53575a20}, /* Swati */ + {"ssh", 0x41524120}, /* Shihhi Arabic -> Arabic */ + {"ssl", 0}, /* Western Sisaala != South Slavey */ + {"ssm", 0}, /* Semnam != Southern Sami */ + {"st", 0x534f5420}, /* Southern Sotho */ + {"sta", 0x43505020}, /* Settla -> Creoles */ + /*{"stq", 0x53545120},*/ /* Saterfriesisch -> Saterland Frisian */ + {"stv", 0x53494720}, /* Silt'e -> Silte Gurage */ + {"su", 0x53554e20}, /* Sundanese */ + /*{"suk", 0x53554b20},*/ /* Sukuma */ + {"suq", 0x53555220}, /* Suri */ + {"sur", 0}, /* Mwaghavul != Suri */ + {"sv", 0x53564520}, /* Swedish */ + /*{"sva", 0x53564120},*/ /* Svan */ + {"svc", 0x43505020}, /* Vincentian Creole English -> Creoles */ + {"sve", 0}, /* Serili != Swedish */ + {"sw", 0x53574b20}, /* Swahili [macrolanguage] */ + {"swb", 0x434d5220}, /* Maore Comorian -> Comorian */ + {"swc", 0x53574b20}, /* Congo Swahili -> Swahili */ + {"swh", 0x53574b20}, /* Swahili */ + {"swk", 0}, /* Malawi Sena != Swahili */ + {"swn", 0x42425220}, /* Sawknah -> Berber */ + {"swv", 0x4d415720}, /* Shekhawati -> Marwari */ + /*{"sxu", 0x53585520},*/ /* Upper Saxon */ + {"syc", 0x53595220}, /* Classical Syriac -> Syriac */ + /*{"syl", 0x53594c20},*/ /* Sylheti */ + /*{"syr", 0x53595220},*/ /* Syriac [macrolanguage] */ + /*{"szl", 0x535a4c20},*/ /* Silesian */ + {"ta", 0x54414d20}, /* Tamil */ + {"taa", 0x41544820}, /* Lower Tanana -> Athapaskan */ + /*{"tab", 0x54414220},*/ /* Tabassaran -> Tabasaran */ + {"taj", 0}, /* Eastern Tamang != Tajiki */ + {"taq", 0x544d4820}, /* Tamasheq -> Tamashek */ + {"taq", 0x42425220}, /* Tamasheq -> Berber */ + {"tas", 0x43505020}, /* Tay Boi -> Creoles */ + {"tau", 0x41544820}, /* Upper Tanana -> Athapaskan */ + {"tcb", 0x41544820}, /* Tanacross -> Athapaskan */ + {"tce", 0x41544820}, /* Southern Tutchone -> Athapaskan */ + {"tch", 0x43505020}, /* Turks And Caicos Creole English -> Creoles */ + {"tcp", 0x51494e20}, /* Tawr Chin -> Chin */ + {"tcs", 0x43505020}, /* Torres Strait Creole -> Creoles */ + {"tcy", 0x54554c20}, /* Tulu */ + {"tcz", 0x51494e20}, /* Thado Chin -> Chin */ + /*{"tdd", 0x54444420},*/ /* Tai Nüa -> Dehong Dai */ + {"tdx", 0x4d4c4720}, /* Tandroy-Mahafaly Malagasy -> Malagasy */ + {"te", 0x54454c20}, /* Telugu */ + {"tec", 0x4b414c20}, /* Terik -> Kalenjin */ + {"tem", 0x544d4e20}, /* Timne -> Temne */ + /*{"tet", 0x54455420},*/ /* Tetum */ + {"tez", 0x42425220}, /* Tetserret -> Berber */ + {"tfn", 0x41544820}, /* Tanaina -> Athapaskan */ + {"tg", 0x54414a20}, /* Tajik -> Tajiki */ + {"tgh", 0x43505020}, /* Tobagonian Creole English -> Creoles */ + {"tgj", 0x4e495320}, /* Tagin -> Nisi */ + {"tgn", 0}, /* Tandaganon != Tongan */ + {"tgr", 0}, /* Tareng != Tigre */ + {"tgx", 0x41544820}, /* Tagish -> Athapaskan */ + {"tgy", 0}, /* Togoyo != Tigrinya */ + {"th", 0x54484120}, /* Thai */ + {"tht", 0x41544820}, /* Tahltan -> Athapaskan */ + {"thv", 0x544d4820}, /* Tahaggart Tamahaq -> Tamashek */ + {"thv", 0x42425220}, /* Tahaggart Tamahaq -> Berber */ + {"thz", 0x544d4820}, /* Tayart Tamajeq -> Tamashek */ + {"thz", 0x42425220}, /* Tayart Tamajeq -> Berber */ + {"ti", 0x54475920}, /* Tigrinya */ + {"tia", 0x42425220}, /* Tidikelt Tamazight -> Berber */ + {"tig", 0x54475220}, /* Tigre */ + /*{"tiv", 0x54495620},*/ /* Tiv */ + /*{"tjl", 0x544a4c20},*/ /* Tai Laing */ + {"tjo", 0x42425220}, /* Temacine Tamazight -> Berber */ + {"tk", 0x544b4d20}, /* Turkmen */ + {"tkg", 0x4d4c4720}, /* Tesaka Malagasy -> Malagasy */ + {"tkm", 0}, /* Takelma != Turkmen */ + {"tl", 0x54474c20}, /* Tagalog */ + /*{"tli", 0x544c4920},*/ /* Tlingit */ + {"tmg", 0x43505020}, /* Ternateño -> Creoles */ + {"tmh", 0x544d4820}, /* Tamashek [macrolanguage] */ + {"tmh", 0x42425220}, /* Tamashek [macrolanguage] -> Berber */ + {"tmn", 0}, /* Taman (Indonesia) != Temne */ + {"tmw", 0x4d4c5920}, /* Temuan -> Malay */ + {"tn", 0x544e4120}, /* Tswana */ + {"tna", 0}, /* Tacana != Tswana */ + {"tne", 0}, /* Tinoc Kallahan (retired code) (retired code) != Tundra Enets */ + {"tnf", 0x44524920}, /* Tangshewi (retired code) (retired code) -> Dari */ + {"tnf", 0x46415220}, /* Tangshewi (retired code) (retired code) -> Persian */ + {"tng", 0}, /* Tobanga != Tonga */ + {"to", 0x54474e20}, /* Tonga (Tonga Islands) -> Tongan */ + {"tod", 0x544f4430}, /* Toma */ + {"toi", 0x544e4720}, /* Tonga (Zambia) */ + {"toj", 0x4d594e20}, /* Tojolabal -> Mayan */ + {"tol", 0x41544820}, /* Tolowa -> Athapaskan */ + {"tor", 0x42414430}, /* Togbo-Vara Banda -> Banda */ + {"tpi", 0x54504920}, /* Tok Pisin */ + {"tpi", 0x43505020}, /* Tok Pisin -> Creoles */ + {"tr", 0x54524b20}, /* Turkish */ + {"trf", 0x43505020}, /* Trinidadian Creole English -> Creoles */ + {"trk", 0}, /* Turkic [collection] != Turkish */ + {"tru", 0x54554120}, /* Turoyo -> Turoyo Aramaic */ + {"tru", 0x53595220}, /* Turoyo -> Syriac */ + {"ts", 0x54534720}, /* Tsonga */ + {"tsg", 0}, /* Tausug != Tsonga */ + /*{"tsj", 0x54534a20},*/ /* Tshangla */ + {"tt", 0x54415420}, /* Tatar */ + {"ttc", 0x4d594e20}, /* Tektiteko -> Mayan */ + {"ttm", 0x41544820}, /* Northern Tutchone -> Athapaskan */ + {"ttq", 0x544d4820}, /* Tawallammat Tamajaq -> Tamashek */ + {"ttq", 0x42425220}, /* Tawallammat Tamajaq -> Berber */ + {"tua", 0}, /* Wiarumus != Turoyo Aramaic */ + {"tul", 0}, /* Tula != Tulu */ + /*{"tum", 0x54554d20},*/ /* Tumbuka */ + {"tuu", 0x41544820}, /* Tututni -> Athapaskan */ + {"tuv", 0}, /* Turkana != Tuvin */ + {"tuy", 0x4b414c20}, /* Tugen -> Kalenjin */ + /*{"tvl", 0x54564c20},*/ /* Tuvalu */ + {"tvy", 0x43505020}, /* Timor Pidgin -> Creoles */ + {"tw", 0x54574920}, /* Twi */ + {"tw", 0x414b4120}, /* Twi -> Akan */ + {"txc", 0x41544820}, /* Tsetsaut -> Athapaskan */ + {"txy", 0x4d4c4720}, /* Tanosy Malagasy -> Malagasy */ + {"ty", 0x54485420}, /* Tahitian */ + {"tyv", 0x54555620}, /* Tuvinian -> Tuvin */ + /*{"tyz", 0x54595a20},*/ /* Tày */ + {"tzh", 0x4d594e20}, /* Tzeltal -> Mayan */ + {"tzj", 0x4d594e20}, /* Tz'utujil -> Mayan */ + {"tzm", 0x545a4d20}, /* Central Atlas Tamazight -> Tamazight */ + {"tzm", 0x42425220}, /* Central Atlas Tamazight -> Berber */ + {"tzo", 0x545a4f20}, /* Tzotzil */ + {"tzo", 0x4d594e20}, /* Tzotzil -> Mayan */ + {"ubl", 0x42494b20}, /* Buhi'non Bikol -> Bikol */ + /*{"udm", 0x55444d20},*/ /* Udmurt */ + {"ug", 0x55594720}, /* Uyghur */ + {"uk", 0x554b5220}, /* Ukrainian */ + {"uki", 0x4b554920}, /* Kui (India) */ + {"uln", 0x43505020}, /* Unserdeutsch -> Creoles */ + /*{"umb", 0x554d4220},*/ /* Umbundu */ + {"unr", 0x4d554e20}, /* Mundari */ + {"ur", 0x55524420}, /* Urdu */ + {"urk", 0x4d4c5920}, /* Urak Lawoi' -> Malay */ + {"usp", 0x4d594e20}, /* Uspanteco -> Mayan */ + {"uz", 0x555a4220}, /* Uzbek [macrolanguage] */ + {"uzn", 0x555a4220}, /* Northern Uzbek -> Uzbek */ + {"uzs", 0x555a4220}, /* Southern Uzbek -> Uzbek */ + {"vap", 0x51494e20}, /* Vaiphei -> Chin */ + {"ve", 0x56454e20}, /* Venda */ + /*{"vec", 0x56454320},*/ /* Venetian */ + {"vi", 0x56495420}, /* Vietnamese */ + {"vic", 0x43505020}, /* Virgin Islands Creole English -> Creoles */ + {"vit", 0}, /* Viti != Vietnamese */ + {"vkk", 0x4d4c5920}, /* Kaur -> Malay */ + {"vkp", 0x43505020}, /* Korlai Creole Portuguese -> Creoles */ + {"vkt", 0x4d4c5920}, /* Tenggarong Kutai Malay -> Malay */ + {"vls", 0x464c4520}, /* Vlaams -> Dutch (Flemish) */ + {"vmw", 0x4d414b20}, /* Makhuwa */ + {"vo", 0x564f4c20}, /* Volapük */ + /*{"vro", 0x56524f20},*/ /* Võro */ + {"wa", 0x574c4e20}, /* Walloon */ + {"wag", 0}, /* Wa'ema != Wagdi */ + /*{"war", 0x57415220},*/ /* Waray (Philippines) -> Waray-Waray */ + {"wbm", 0x57412020}, /* Wa */ + {"wbr", 0x57414720}, /* Wagdi */ + {"wbr", 0x52414a20}, /* Wagdi -> Rajasthani */ + /*{"wci", 0x57434920},*/ /* Waci Gbe */ + {"wea", 0x4b524e20}, /* Wewaw -> Karen */ + {"wes", 0x43505020}, /* Cameroon Pidgin -> Creoles */ + {"weu", 0x51494e20}, /* Rawngtu Chin -> Chin */ + {"wlc", 0x434d5220}, /* Mwali Comorian -> Comorian */ + {"wle", 0x53494720}, /* Wolane -> Silte Gurage */ + {"wlk", 0x41544820}, /* Wailaki -> Athapaskan */ + {"wni", 0x434d5220}, /* Ndzwani Comorian -> Comorian */ + {"wo", 0x574c4620}, /* Wolof */ + {"wry", 0x4d415720}, /* Merwari -> Marwari */ + {"wsg", 0x474f4e20}, /* Adilabad Gondi -> Gondi */ + /*{"wtm", 0x57544d20},*/ /* Mewati */ + {"wuu", 0x5a485320}, /* Wu Chinese -> Chinese, Simplified */ + {"xal", 0x4b4c4d20}, /* Kalmyk */ + {"xal", 0x544f4420}, /* Kalmyk -> Todo */ + {"xan", 0x53454b20}, /* Xamtanga -> Sekota */ + {"xbd", 0}, /* Bindal != Lü */ + {"xh", 0x58485320}, /* Xhosa */ + /*{"xjb", 0x584a4220},*/ /* Minjungbal -> Minjangbal */ + /*{"xkf", 0x584b4620},*/ /* Khengkha */ + {"xmg", 0x424d4c20}, /* Mengaka -> Bamileke */ + {"xmm", 0x4d4c5920}, /* Manado Malay -> Malay */ + {"xmm", 0x43505020}, /* Manado Malay -> Creoles */ + {"xmv", 0x4d4c4720}, /* Antankarana Malagasy -> Malagasy */ + {"xmw", 0x4d4c4720}, /* Tsimihety Malagasy -> Malagasy */ + {"xnj", 0x53585420}, /* Ngoni (Tanzania) -> Sutu */ + {"xnq", 0x53585420}, /* Ngoni (Mozambique) -> Sutu */ + {"xnr", 0x44475220}, /* Kangri -> Dogri (macrolanguage) */ + /*{"xog", 0x584f4720},*/ /* Soga */ + {"xpe", 0x58504520}, /* Liberia Kpelle -> Kpelle (Liberia) */ + {"xpe", 0x4b504c20}, /* Liberia Kpelle -> Kpelle */ + {"xsl", 0x53534c20}, /* South Slavey */ + {"xsl", 0x534c4120}, /* South Slavey -> Slavey */ + {"xsl", 0x41544820}, /* South Slavey -> Athapaskan */ + {"xst", 0x53494720}, /* Silt'e (retired code) -> Silte Gurage */ + /*{"xub", 0x58554220},*/ /* Betta Kurumba -> Bette Kuruma */ + /*{"xuj", 0x58554a20},*/ /* Jennu Kurumba -> Jennu Kuruma */ + {"xup", 0x41544820}, /* Upper Umpqua -> Athapaskan */ + {"xwo", 0x544f4420}, /* Written Oirat -> Todo */ + {"yaj", 0x42414430}, /* Banda-Yangere -> Banda */ + {"yak", 0}, /* Yakama != Sakha */ + /*{"yao", 0x59414f20},*/ /* Yao */ + /*{"yap", 0x59415020},*/ /* Yapese */ + {"yba", 0}, /* Yala != Yoruba */ + {"ybb", 0x424d4c20}, /* Yemba -> Bamileke */ + {"ybd", 0x41524b20}, /* Yangbye (retired code) (retired code) -> Rakhine */ + {"ycr", 0}, /* Yilan Creole != Y-Cree */ + {"ydd", 0x4a494920}, /* Eastern Yiddish -> Yiddish */ + /*{"ygp", 0x59475020},*/ /* Gepo */ + {"yi", 0x4a494920}, /* Yiddish [macrolanguage] */ + {"yih", 0x4a494920}, /* Western Yiddish -> Yiddish */ + {"yim", 0}, /* Yimchungru Naga != Yi Modern */ + /*{"yna", 0x594e4120},*/ /* Aluo */ + {"yo", 0x59424120}, /* Yoruba */ + {"yos", 0x51494e20}, /* Yos (retired code) (retired code) -> Chin */ + {"yua", 0x4d594e20}, /* Yucateco -> Mayan */ + {"yue", 0x5a484820}, /* Yue Chinese -> Chinese, Traditional, Hong Kong SAR */ + /*{"ywq", 0x59575120},*/ /* Wuding-Luquan Yi */ + {"za", 0x5a484120}, /* Zhuang [macrolanguage] */ + {"zch", 0x5a484120}, /* Central Hongshuihe Zhuang -> Zhuang */ + {"zdj", 0x434d5220}, /* Ngazidja Comorian -> Comorian */ + /*{"zea", 0x5a454120},*/ /* Zeeuws -> Zealandic */ + {"zeh", 0x5a484120}, /* Eastern Hongshuihe Zhuang -> Zhuang */ + {"zen", 0x42425220}, /* Zenaga -> Berber */ + {"zgb", 0x5a484120}, /* Guibei Zhuang -> Zhuang */ + {"zgh", 0x5a474820}, /* Standard Moroccan Tamazight */ + {"zgh", 0x42425220}, /* Standard Moroccan Tamazight -> Berber */ + {"zgm", 0x5a484120}, /* Minz Zhuang -> Zhuang */ + {"zgn", 0x5a484120}, /* Guibian Zhuang -> Zhuang */ + {"zh", 0x5a485320}, /* Chinese, Simplified [macrolanguage] */ + {"zhd", 0x5a484120}, /* Dai Zhuang -> Zhuang */ + {"zhn", 0x5a484120}, /* Nong Zhuang -> Zhuang */ + {"zkb", 0x4b484120}, /* Koibal (retired code) (retired code) -> Khakass */ + {"zlj", 0x5a484120}, /* Liujiang Zhuang -> Zhuang */ + {"zlm", 0x4d4c5920}, /* Malay */ + {"zln", 0x5a484120}, /* Lianshan Zhuang -> Zhuang */ + {"zlq", 0x5a484120}, /* Liuqian Zhuang -> Zhuang */ + {"zmi", 0x4d4c5920}, /* Negeri Sembilan Malay -> Malay */ + {"zmz", 0x42414430}, /* Mbandja -> Banda */ + {"znd", 0}, /* Zande [collection] != Zande */ + {"zne", 0x5a4e4420}, /* Zande */ + {"zom", 0x51494e20}, /* Zou -> Chin */ + {"zqe", 0x5a484120}, /* Qiubei Zhuang -> Zhuang */ + {"zsm", 0x4d4c5920}, /* Standard Malay -> Malay */ + {"zu", 0x5a554c20}, /* Zulu */ + {"zum", 0x4c524320}, /* Kumzari -> Luri */ + {"zyb", 0x5a484120}, /* Yongbei Zhuang -> Zhuang */ + {"zyg", 0x5a484120}, /* Yang Zhuang -> Zhuang */ + {"zyj", 0x5a484120}, /* Youjiang Zhuang -> Zhuang */ + {"zyn", 0x5a484120}, /* Yongnan Zhuang -> Zhuang */ + {"zyp", 0x51494e20}, /* Zyphe Chin -> Chin */ + /*{"zza", 0x5a5a4120},*/ /* Zazaki [macrolanguage] */ + {"zzj", 0x5a484120}, /* Zuojiang Zhuang -> Zhuang */ + {"||", 0x4f524920}, /* -> Odia (formerly Oriya) */ +} + +// Converts a multi-subtag BCP 47 language tag to language tags. +func tagsFromComplexLanguage(langStr string) []ot.Tag { + if subtagMatches(langStr, "fonnapa") { + /* Undetermined; North American Phonetic Alphabet */ + + return []ot.Tag{0x41505048} /* */ + } + if subtagMatches(langStr, "fonipa") { + /* Undetermined; International Phonetic Alphabet */ + + return []ot.Tag{0x49505048} /* */ + } + if subtagMatches(langStr, "geok") { + /* Undetermined; */ + + return []ot.Tag{0x4b474520} /* Khutsuri Georgian */ + } + if subtagMatches(langStr, "syre") { + /* Undetermined; */ + + return []ot.Tag{0x53595245} /* Syriac, Estrangela script-variant (equivalent to ISO 15924 'Syre') */ + } + if subtagMatches(langStr, "syrj") { + /* Undetermined; */ + + return []ot.Tag{0x5359524a} /* Syriac, Western script-variant (equivalent to ISO 15924 'Syrj') */ + } + if subtagMatches(langStr, "syrn") { + /* Undetermined; */ + + return []ot.Tag{0x5359524e} /* Syriac, Eastern script-variant (equivalent to ISO 15924 'Syrn') */ + } + + switch langStr[0] { + case 'a': + if langStr[1:] == "rt-lojban" { + /* Lojban (retired code) (retired code) */ + return []ot.Tag{0x4a424f20} /* Lojban */ + } + + case 'c': + if langMatches(langStr[1:], "do-hant-hk") { + /* Min Dong Chinese; ; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if langMatches(langStr[1:], "do-hant-mo") { + /* Min Dong Chinese; ; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if langMatches(langStr[1:], "jy-hant-hk") { + /* Jinyu Chinese; ; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if langMatches(langStr[1:], "jy-hant-mo") { + /* Jinyu Chinese; ; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if langMatches(langStr[1:], "mn-hant-hk") { + /* Mandarin Chinese; ; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if langMatches(langStr[1:], "mn-hant-mo") { + /* Mandarin Chinese; ; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if langMatches(langStr[1:], "np-hant-hk") { + /* Northern Ping Chinese; ; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if langMatches(langStr[1:], "np-hant-mo") { + /* Northern Ping Chinese; ; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if langMatches(langStr[1:], "px-hant-hk") { + /* Pu-Xian Chinese; ; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if langMatches(langStr[1:], "px-hant-mo") { + /* Pu-Xian Chinese; ; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if langMatches(langStr[1:], "sp-hant-hk") { + /* Southern Ping Chinese; ; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if langMatches(langStr[1:], "sp-hant-mo") { + /* Southern Ping Chinese; ; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if langMatches(langStr[1:], "zh-hant-hk") { + /* Huizhou Chinese; ; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if langMatches(langStr[1:], "zh-hant-mo") { + /* Huizhou Chinese; ; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if langMatches(langStr[1:], "zo-hant-hk") { + /* Min Zhong Chinese; ; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if langMatches(langStr[1:], "zo-hant-mo") { + /* Min Zhong Chinese; ; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if langMatches(langStr[1:], "do-hans") { + /* Min Dong Chinese; */ + return []ot.Tag{0x5a485320} /* Chinese, Simplified */ + } + if langMatches(langStr[1:], "do-hant") { + /* Min Dong Chinese; */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if langMatches(langStr[1:], "jy-hans") { + /* Jinyu Chinese; */ + return []ot.Tag{0x5a485320} /* Chinese, Simplified */ + } + if langMatches(langStr[1:], "jy-hant") { + /* Jinyu Chinese; */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if langMatches(langStr[1:], "mn-hans") { + /* Mandarin Chinese; */ + return []ot.Tag{0x5a485320} /* Chinese, Simplified */ + } + if langMatches(langStr[1:], "mn-hant") { + /* Mandarin Chinese; */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if langMatches(langStr[1:], "np-hans") { + /* Northern Ping Chinese; */ + return []ot.Tag{0x5a485320} /* Chinese, Simplified */ + } + if langMatches(langStr[1:], "np-hant") { + /* Northern Ping Chinese; */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if langMatches(langStr[1:], "px-hans") { + /* Pu-Xian Chinese; */ + return []ot.Tag{0x5a485320} /* Chinese, Simplified */ + } + if langMatches(langStr[1:], "px-hant") { + /* Pu-Xian Chinese; */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if langMatches(langStr[1:], "sp-hans") { + /* Southern Ping Chinese; */ + return []ot.Tag{0x5a485320} /* Chinese, Simplified */ + } + if langMatches(langStr[1:], "sp-hant") { + /* Southern Ping Chinese; */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if langMatches(langStr[1:], "zh-hans") { + /* Huizhou Chinese; */ + return []ot.Tag{0x5a485320} /* Chinese, Simplified */ + } + if langMatches(langStr[1:], "zh-hant") { + /* Huizhou Chinese; */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if langMatches(langStr[1:], "zo-hans") { + /* Min Zhong Chinese; */ + return []ot.Tag{0x5a485320} /* Chinese, Simplified */ + } + if langMatches(langStr[1:], "zo-hant") { + /* Min Zhong Chinese; */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if strings.HasPrefix(langStr[1:], "do-") && + subtagMatches(langStr, "hk") { + /* Min Dong Chinese; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if strings.HasPrefix(langStr[1:], "do-") && + subtagMatches(langStr, "mo") { + /* Min Dong Chinese; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if strings.HasPrefix(langStr[1:], "do-") && + subtagMatches(langStr, "tw") { + /* Min Dong Chinese; Taiwan, Province of China */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if strings.HasPrefix(langStr[1:], "jy-") && + subtagMatches(langStr, "hk") { + /* Jinyu Chinese; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if strings.HasPrefix(langStr[1:], "jy-") && + subtagMatches(langStr, "mo") { + /* Jinyu Chinese; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if strings.HasPrefix(langStr[1:], "jy-") && + subtagMatches(langStr, "tw") { + /* Jinyu Chinese; Taiwan, Province of China */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if strings.HasPrefix(langStr[1:], "mn-") && + subtagMatches(langStr, "hk") { + /* Mandarin Chinese; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if strings.HasPrefix(langStr[1:], "mn-") && + subtagMatches(langStr, "mo") { + /* Mandarin Chinese; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if strings.HasPrefix(langStr[1:], "mn-") && + subtagMatches(langStr, "tw") { + /* Mandarin Chinese; Taiwan, Province of China */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if strings.HasPrefix(langStr[1:], "np-") && + subtagMatches(langStr, "hk") { + /* Northern Ping Chinese; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if strings.HasPrefix(langStr[1:], "np-") && + subtagMatches(langStr, "mo") { + /* Northern Ping Chinese; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if strings.HasPrefix(langStr[1:], "np-") && + subtagMatches(langStr, "tw") { + /* Northern Ping Chinese; Taiwan, Province of China */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if strings.HasPrefix(langStr[1:], "px-") && + subtagMatches(langStr, "hk") { + /* Pu-Xian Chinese; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if strings.HasPrefix(langStr[1:], "px-") && + subtagMatches(langStr, "mo") { + /* Pu-Xian Chinese; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if strings.HasPrefix(langStr[1:], "px-") && + subtagMatches(langStr, "tw") { + /* Pu-Xian Chinese; Taiwan, Province of China */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if strings.HasPrefix(langStr[1:], "sp-") && + subtagMatches(langStr, "hk") { + /* Southern Ping Chinese; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if strings.HasPrefix(langStr[1:], "sp-") && + subtagMatches(langStr, "mo") { + /* Southern Ping Chinese; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if strings.HasPrefix(langStr[1:], "sp-") && + subtagMatches(langStr, "tw") { + /* Southern Ping Chinese; Taiwan, Province of China */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if strings.HasPrefix(langStr[1:], "zh-") && + subtagMatches(langStr, "hk") { + /* Huizhou Chinese; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if strings.HasPrefix(langStr[1:], "zh-") && + subtagMatches(langStr, "mo") { + /* Huizhou Chinese; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if strings.HasPrefix(langStr[1:], "zh-") && + subtagMatches(langStr, "tw") { + /* Huizhou Chinese; Taiwan, Province of China */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if strings.HasPrefix(langStr[1:], "zo-") && + subtagMatches(langStr, "hk") { + /* Min Zhong Chinese; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if strings.HasPrefix(langStr[1:], "zo-") && + subtagMatches(langStr, "mo") { + /* Min Zhong Chinese; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if strings.HasPrefix(langStr[1:], "zo-") && + subtagMatches(langStr, "tw") { + /* Min Zhong Chinese; Taiwan, Province of China */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + + case 'e': + if strings.HasPrefix(langStr[1:], "l-") && + subtagMatches(langStr, "polyton") { + /* Modern Greek (1453-); Polytonic Greek */ + return []ot.Tag{0x50475220} /* Polytonic Greek */ + } + + case 'g': + if langMatches(langStr[1:], "an-hant-hk") { + /* Gan Chinese; ; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if langMatches(langStr[1:], "an-hant-mo") { + /* Gan Chinese; ; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if langMatches(langStr[1:], "an-hans") { + /* Gan Chinese; */ + return []ot.Tag{0x5a485320} /* Chinese, Simplified */ + } + if langMatches(langStr[1:], "an-hant") { + /* Gan Chinese; */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if langMatches(langStr[1:], "a-latg") { + /* Irish; */ + return []ot.Tag{0x49525420} /* Irish Traditional */ + } + if strings.HasPrefix(langStr[1:], "an-") && + subtagMatches(langStr, "hk") { + /* Gan Chinese; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if strings.HasPrefix(langStr[1:], "an-") && + subtagMatches(langStr, "mo") { + /* Gan Chinese; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if strings.HasPrefix(langStr[1:], "an-") && + subtagMatches(langStr, "tw") { + /* Gan Chinese; Taiwan, Province of China */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + + case 'h': + if langMatches(langStr[1:], "ak-hant-hk") { + /* Hakka Chinese; ; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if langMatches(langStr[1:], "ak-hant-mo") { + /* Hakka Chinese; ; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if langMatches(langStr[1:], "sn-hant-hk") { + /* Xiang Chinese; ; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if langMatches(langStr[1:], "sn-hant-mo") { + /* Xiang Chinese; ; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if strings.HasPrefix(langStr[1:], "y-") && + subtagMatches(langStr, "arevmda") { + /* Armenian; Western Armenian */ + return []ot.Tag{0x48594520} /* Armenian */ + } + if langMatches(langStr[1:], "ak-hans") { + /* Hakka Chinese; */ + return []ot.Tag{0x5a485320} /* Chinese, Simplified */ + } + if langMatches(langStr[1:], "ak-hant") { + /* Hakka Chinese; */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if langMatches(langStr[1:], "sn-hans") { + /* Xiang Chinese; */ + return []ot.Tag{0x5a485320} /* Chinese, Simplified */ + } + if langMatches(langStr[1:], "sn-hant") { + /* Xiang Chinese; */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if strings.HasPrefix(langStr[1:], "ak-") && + subtagMatches(langStr, "hk") { + /* Hakka Chinese; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if strings.HasPrefix(langStr[1:], "ak-") && + subtagMatches(langStr, "mo") { + /* Hakka Chinese; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if strings.HasPrefix(langStr[1:], "ak-") && + subtagMatches(langStr, "tw") { + /* Hakka Chinese; Taiwan, Province of China */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if strings.HasPrefix(langStr[1:], "sn-") && + subtagMatches(langStr, "hk") { + /* Xiang Chinese; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if strings.HasPrefix(langStr[1:], "sn-") && + subtagMatches(langStr, "mo") { + /* Xiang Chinese; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if strings.HasPrefix(langStr[1:], "sn-") && + subtagMatches(langStr, "tw") { + /* Xiang Chinese; Taiwan, Province of China */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + + case 'i': + if langStr[1:] == "-navajo" { + /* Navajo (retired code) (retired code) */ + return []ot.Tag{ + 0x4e415620, /* Navajo */ + 0x41544820, /* Athapaskan */ + } + } + if langStr[1:] == "-hak" { + /* Hakka (retired code) (retired code) */ + return []ot.Tag{0x5a485320} /* Chinese, Simplified */ + } + if langStr[1:] == "-lux" { + /* Luxembourgish (retired code) (retired code) */ + return []ot.Tag{0x4c545a20} /* Luxembourgish */ + } + + case 'l': + if langMatches(langStr[1:], "zh-hans") { + /* Literary Chinese; */ + return []ot.Tag{0x5a485320} /* Chinese, Simplified */ + } + + case 'm': + if langMatches(langStr[1:], "np-hant-hk") { + /* Min Bei Chinese; ; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if langMatches(langStr[1:], "np-hant-mo") { + /* Min Bei Chinese; ; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if langMatches(langStr[1:], "np-hans") { + /* Min Bei Chinese; */ + return []ot.Tag{0x5a485320} /* Chinese, Simplified */ + } + if langMatches(langStr[1:], "np-hant") { + /* Min Bei Chinese; */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if strings.HasPrefix(langStr[1:], "np-") && + subtagMatches(langStr, "hk") { + /* Min Bei Chinese; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if strings.HasPrefix(langStr[1:], "np-") && + subtagMatches(langStr, "mo") { + /* Min Bei Chinese; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if strings.HasPrefix(langStr[1:], "np-") && + subtagMatches(langStr, "tw") { + /* Min Bei Chinese; Taiwan, Province of China */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if strings.HasPrefix(langStr[1:], "nw-") && + subtagMatches(langStr, "th") { + /* Mon; Thailand */ + return []ot.Tag{0x4d4f4e54} /* Thailand Mon */ + } + + case 'n': + if langMatches(langStr[1:], "an-hant-hk") { + /* Min Nan Chinese; ; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if langMatches(langStr[1:], "an-hant-mo") { + /* Min Nan Chinese; ; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if langMatches(langStr[1:], "an-hans") { + /* Min Nan Chinese; */ + return []ot.Tag{0x5a485320} /* Chinese, Simplified */ + } + if langMatches(langStr[1:], "an-hant") { + /* Min Nan Chinese; */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if strings.HasPrefix(langStr[1:], "an-") && + subtagMatches(langStr, "hk") { + /* Min Nan Chinese; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if strings.HasPrefix(langStr[1:], "an-") && + subtagMatches(langStr, "mo") { + /* Min Nan Chinese; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if strings.HasPrefix(langStr[1:], "an-") && + subtagMatches(langStr, "tw") { + /* Min Nan Chinese; Taiwan, Province of China */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if langStr[1:] == "o-bok" { + /* Norwegian Bokmal (retired code) (retired code) */ + return []ot.Tag{0x4e4f5220} /* Norwegian */ + } + if langStr[1:] == "o-nyn" { + /* Norwegian Nynorsk (retired code) (retired code) */ + return []ot.Tag{ + 0x4e594e20, /* Norwegian Nynorsk (Nynorsk, Norwegian) */ + 0x4e4f5220, /* Norwegian */ + } + } + + case 'o': + if strings.HasPrefix(langStr[1:], "c-") && + subtagMatches(langStr, "provenc") { + /* Occitan (post 1500); Provençal */ + return []ot.Tag{0x50524f20} /* Provençal / Old Provençal */ + } + + case 'r': + if strings.HasPrefix(langStr[1:], "o-") && + subtagMatches(langStr, "md") { + /* Romanian; Moldova */ + return []ot.Tag{0x4d4f4c20} /* Moldavian */ + } + + case 'w': + if langMatches(langStr[1:], "uu-hant-hk") { + /* Wu Chinese; ; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if langMatches(langStr[1:], "uu-hant-mo") { + /* Wu Chinese; ; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if langMatches(langStr[1:], "uu-hans") { + /* Wu Chinese; */ + return []ot.Tag{0x5a485320} /* Chinese, Simplified */ + } + if langMatches(langStr[1:], "uu-hant") { + /* Wu Chinese; */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if strings.HasPrefix(langStr[1:], "uu-") && + subtagMatches(langStr, "hk") { + /* Wu Chinese; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if strings.HasPrefix(langStr[1:], "uu-") && + subtagMatches(langStr, "mo") { + /* Wu Chinese; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if strings.HasPrefix(langStr[1:], "uu-") && + subtagMatches(langStr, "tw") { + /* Wu Chinese; Taiwan, Province of China */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + + case 'y': + if langMatches(langStr[1:], "ue-hans") { + /* Yue Chinese; */ + return []ot.Tag{0x5a485320} /* Chinese, Simplified */ + } + + case 'z': + if langMatches(langStr[1:], "h-hant-hk") { + /* Chinese [macrolanguage]; ; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if langMatches(langStr[1:], "h-hant-mo") { + /* Chinese [macrolanguage]; ; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if langStr[1:] == "h-min-nan" { + /* Minnan, Hokkien, Amoy, Taiwanese, Southern Min, Southern Fujian, Hoklo, Southern Fukien, Ho-lo (retired code) (retired code) */ + return []ot.Tag{0x5a485320} /* Chinese, Simplified */ + } + if langMatches(langStr[1:], "h-hans") { + /* Chinese [macrolanguage]; */ + return []ot.Tag{0x5a485320} /* Chinese, Simplified */ + } + if langMatches(langStr[1:], "h-hant") { + /* Chinese [macrolanguage]; */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + if langStr[1:] == "h-min" { + /* Min, Fuzhou, Hokkien, Amoy, or Taiwanese (retired code) (retired code) */ + return []ot.Tag{0x5a485320} /* Chinese, Simplified */ + } + if strings.HasPrefix(langStr[1:], "h-") && + subtagMatches(langStr, "hk") { + /* Chinese [macrolanguage]; Hong Kong */ + return []ot.Tag{0x5a484820} /* Chinese, Traditional, Hong Kong SAR */ + } + if strings.HasPrefix(langStr[1:], "h-") && + subtagMatches(langStr, "mo") { + /* Chinese [macrolanguage]; Macao */ + return []ot.Tag{ + 0x5a48544d, /* Chinese, Traditional, Macao SAR */ + 0x5a484820, /* Chinese, Traditional, Hong Kong SAR */ + } + } + if strings.HasPrefix(langStr[1:], "h-") && + subtagMatches(langStr, "tw") { + /* Chinese [macrolanguage]; Taiwan, Province of China */ + return []ot.Tag{0x5a485420} /* Chinese, Traditional */ + } + + } + return nil +} + +// Converts 'tag' to a BCP 47 language tag if it is ambiguous (it corresponds to +// many language tags) and the best tag is not the alphabetically first, or if +// the best tag consists of multiple subtags, or if the best tag does not appear +// in 'otLanguages'. +func ambiguousTagToLanguage(tag ot.Tag) language.Language { + switch tag { + case 0x414c5420: /* Altai */ + return "alt" /* language.NewLanguage("alt") Southern Altai */ + case 0x41505048: /* */ + return "und-fonnapa" /* language.NewLanguage("und-fonnapa") Undetermined; North American Phonetic Alphabet */ + case 0x41524120: /* Arabic */ + return "ar" /* language.NewLanguage("ar") Arabic [macrolanguage] */ + case 0x41524b20: /* Rakhine */ + return "rki" /* language.NewLanguage("rki") Rakhine */ + case 0x41544820: /* Athapaskan */ + return "ath" /* language.NewLanguage("ath") Athapascan [collection] */ + case 0x42425220: /* Berber */ + return "ber" /* language.NewLanguage("ber") Berber [collection] */ + case 0x42494b20: /* Bikol */ + return "bik" /* language.NewLanguage("bik") Bikol [macrolanguage] */ + case 0x42544b20: /* Batak */ + return "btk" /* language.NewLanguage("btk") Batak [collection] */ + case 0x43505020: /* Creoles */ + return "crp" /* language.NewLanguage("crp") Creoles and pidgins [collection] */ + case 0x43525220: /* Carrier */ + return "crx" /* language.NewLanguage("crx") Carrier */ + case 0x44475220: /* Dogri (macrolanguage) */ + return "doi" /* language.NewLanguage("doi") Dogri [macrolanguage] */ + case 0x444e4b20: /* Dinka */ + return "din" /* language.NewLanguage("din") Dinka [macrolanguage] */ + case 0x44524920: /* Dari */ + return "prs" /* language.NewLanguage("prs") Dari */ + case 0x445a4e20: /* Dzongkha */ + return "dz" /* language.NewLanguage("dz") Dzongkha */ + case 0x45544920: /* Estonian */ + return "et" /* language.NewLanguage("et") Estonian [macrolanguage] */ + case 0x46415220: /* Persian */ + return "fa" /* language.NewLanguage("fa") Persian [macrolanguage] */ + case 0x474f4e20: /* Gondi */ + return "gon" /* language.NewLanguage("gon") Gondi [macrolanguage] */ + case 0x484d4120: /* High Mari */ + return "mrj" /* language.NewLanguage("mrj") Western Mari */ + case 0x484d4e20: /* Hmong */ + return "hmn" /* language.NewLanguage("hmn") Hmong [macrolanguage] */ + case 0x484e4420: /* Hindko */ + return "hnd" /* language.NewLanguage("hnd") Southern Hindko */ + case 0x48594520: /* Armenian */ + return "hyw" /* language.NewLanguage("hyw") Western Armenian */ + case 0x49424120: /* Iban */ + return "iba" /* language.NewLanguage("iba") Iban */ + case 0x494a4f20: /* Ijo */ + return "ijo" /* language.NewLanguage("ijo") Ijo [collection] */ + case 0x494e5520: /* Inuktitut */ + return "iu" /* language.NewLanguage("iu") Inuktitut [macrolanguage] */ + case 0x49504b20: /* Inupiat */ + return "ik" /* language.NewLanguage("ik") Inupiaq [macrolanguage] */ + case 0x49505048: /* */ + return "und-fonipa" /* language.NewLanguage("und-fonipa") Undetermined; International Phonetic Alphabet */ + case 0x49525420: /* Irish Traditional */ + return "ga-latg" /* language.NewLanguage("ga-Latg") Irish; */ + case 0x4a494920: /* Yiddish */ + return "yi" /* language.NewLanguage("yi") Yiddish [macrolanguage] */ + case 0x4b414c20: /* Kalenjin */ + return "kln" /* language.NewLanguage("kln") Kalenjin [macrolanguage] */ + case 0x4b474520: /* Khutsuri Georgian */ + return "und-geok" /* language.NewLanguage("und-Geok") Undetermined; */ + case 0x4b4e5220: /* Kanuri */ + return "kr" /* language.NewLanguage("kr") Kanuri [macrolanguage] */ + case 0x4b4f4820: /* Korean Old Hangul */ + return "okm" /* language.NewLanguage("okm") Middle Korean (10th-16th cent.) */ + case 0x4b4f4b20: /* Konkani */ + return "kok" /* language.NewLanguage("kok") Konkani [macrolanguage] */ + case 0x4b4f4d20: /* Komi */ + return "kv" /* language.NewLanguage("kv") Komi [macrolanguage] */ + case 0x4b504c20: /* Kpelle */ + return "kpe" /* language.NewLanguage("kpe") Kpelle [macrolanguage] */ + case 0x4b524e20: /* Karen */ + return "kar" /* language.NewLanguage("kar") Karen [collection] */ + case 0x4b554920: /* Kui */ + return "uki" /* language.NewLanguage("uki") Kui (India) */ + case 0x4b555220: /* Kurdish */ + return "ku" /* language.NewLanguage("ku") Kurdish [macrolanguage] */ + case 0x4c4d4120: /* Low Mari */ + return "mhr" /* language.NewLanguage("mhr") Eastern Mari */ + case 0x4c554820: /* Luyia */ + return "luy" /* language.NewLanguage("luy") Luyia [macrolanguage] */ + case 0x4c564920: /* Latvian */ + return "lv" /* language.NewLanguage("lv") Latvian [macrolanguage] */ + case 0x4d415720: /* Marwari */ + return "mwr" /* language.NewLanguage("mwr") Marwari [macrolanguage] */ + case 0x4d4c4720: /* Malagasy */ + return "mg" /* language.NewLanguage("mg") Malagasy [macrolanguage] */ + case 0x4d4c5920: /* Malay */ + return "ms" /* language.NewLanguage("ms") Malay [macrolanguage] */ + case 0x4d4e4720: /* Mongolian */ + return "mn" /* language.NewLanguage("mn") Mongolian [macrolanguage] */ + case 0x4d4e4b20: /* Maninka */ + return "man" /* language.NewLanguage("man") Mandingo [macrolanguage] */ + case 0x4d4f4c20: /* Moldavian */ + return "ro-md" /* language.NewLanguage("ro-MD") Romanian; Moldova */ + case 0x4d4f4e54: /* Thailand Mon */ + return "mnw-th" /* language.NewLanguage("mnw-TH") Mon; Thailand */ + case 0x4d594e20: /* Mayan */ + return "myn" /* language.NewLanguage("myn") Mayan [collection] */ + case 0x4e414820: /* Nahuatl */ + return "nah" /* language.NewLanguage("nah") Nahuatl [collection] */ + case 0x4e455020: /* Nepali */ + return "ne" /* language.NewLanguage("ne") Nepali [macrolanguage] */ + case 0x4e495320: /* Nisi */ + return "njz" /* language.NewLanguage("njz") Nyishi */ + case 0x4e4f5220: /* Norwegian */ + return "no" /* language.NewLanguage("no") Norwegian [macrolanguage] */ + case 0x4f4a4220: /* Ojibway */ + return "oj" /* language.NewLanguage("oj") Ojibwa [macrolanguage] */ + case 0x4f524f20: /* Oromo */ + return "om" /* language.NewLanguage("om") Oromo [macrolanguage] */ + case 0x50415320: /* Pashto */ + return "ps" /* language.NewLanguage("ps") Pashto [macrolanguage] */ + case 0x50475220: /* Polytonic Greek */ + return "el-polyton" /* language.NewLanguage("el-polyton") Modern Greek (1453-); Polytonic Greek */ + case 0x50524f20: /* Provençal / Old Provençal */ + return "pro" /* language.NewLanguage("pro") Old Provençal (to 1500) */ + case 0x51554820: /* Quechua (Bolivia) */ + return "quh" /* language.NewLanguage("quh") South Bolivian Quechua */ + case 0x51555a20: /* Quechua */ + return "qu" /* language.NewLanguage("qu") Quechua [macrolanguage] */ + case 0x51564920: /* Quechua (Ecuador) */ + return "qvi" /* language.NewLanguage("qvi") Imbabura Highland Quichua */ + case 0x51574820: /* Quechua (Peru) */ + return "qwh" /* language.NewLanguage("qwh") Huaylas Ancash Quechua */ + case 0x52414a20: /* Rajasthani */ + return "raj" /* language.NewLanguage("raj") Rajasthani [macrolanguage] */ + case 0x524f4d20: /* Romanian */ + return "ro" /* language.NewLanguage("ro") Romanian */ + case 0x524f5920: /* Romany */ + return "rom" /* language.NewLanguage("rom") Romany [macrolanguage] */ + case 0x53514920: /* Albanian */ + return "sq" /* language.NewLanguage("sq") Albanian [macrolanguage] */ + case 0x53524220: /* Serbian */ + return "sr" /* language.NewLanguage("sr") Serbian */ + case 0x53585420: /* Sutu */ + return "xnj" /* language.NewLanguage("xnj") Ngoni (Tanzania) */ + case 0x53595220: /* Syriac */ + return "syr" /* language.NewLanguage("syr") Syriac [macrolanguage] */ + case 0x53595245: /* Syriac, Estrangela script-variant (equivalent to ISO 15924 'Syre') */ + return "und-syre" /* language.NewLanguage("und-Syre") Undetermined; */ + case 0x5359524a: /* Syriac, Western script-variant (equivalent to ISO 15924 'Syrj') */ + return "und-syrj" /* language.NewLanguage("und-Syrj") Undetermined; */ + case 0x5359524e: /* Syriac, Eastern script-variant (equivalent to ISO 15924 'Syrn') */ + return "und-syrn" /* language.NewLanguage("und-Syrn") Undetermined; */ + case 0x544d4820: /* Tamashek */ + return "tmh" /* language.NewLanguage("tmh") Tamashek [macrolanguage] */ + case 0x544f4420: /* Todo */ + return "xwo" /* language.NewLanguage("xwo") Written Oirat */ + case 0x5a484820: /* Chinese, Traditional, Hong Kong SAR */ + return "zh-hk" /* language.NewLanguage("zh-HK") Chinese [macrolanguage]; Hong Kong */ + case 0x5a485320: /* Chinese, Simplified */ + return "zh-hans" /* language.NewLanguage("zh-Hans") Chinese [macrolanguage]; */ + case 0x5a485420: /* Chinese, Traditional */ + return "zh-hant" /* language.NewLanguage("zh-Hant") Chinese [macrolanguage]; */ + case 0x5a48544d: /* Chinese, Traditional, Macao SAR */ + return "zh-mo" /* language.NewLanguage("zh-MO") Chinese [macrolanguage]; Macao */ + case 0x5a5a4120: /* Zazaki */ + return "zza" /* language.NewLanguage("zza") Zazaki [macrolanguage] */ + default: + return "" + } +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_layout.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_layout.go new file mode 100644 index 0000000..8456800 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_layout.go @@ -0,0 +1,373 @@ +package harfbuzz + +import ( + "github.com/go-text/typesetting/font" + ot "github.com/go-text/typesetting/font/opentype" + "github.com/go-text/typesetting/font/opentype/tables" +) + +// ported from src/hb-ot-layout.cc, hb-ot-layout.hh +// Copyright © 1998-2004 David Turner and Werner Lemberg +// Copyright © 2006 2007,2008,2009 Red Hat, Inc. 2012,2013 Google, Inc. Behdad Esfahbod + +const ( + // This bit relates only to the correct processing of + // the cursive attachment lookup type (GPOS lookup type 3). + // When this bit is set, the last glyph in a given sequence to + // which the cursive attachment lookup is applied, will be positioned on the baseline. + otRightToLeft uint16 = 1 << iota + otIgnoreBaseGlyphs // If set, skips over base glyphs + otIgnoreLigatures // If set, skips over ligatures + otIgnoreMarks // If set, skips over all combining marks + // If set, indicates that the lookup table structure + // is followed by a MarkFilteringSet field. + // The layout engine skips over all mark glyphs not in the mark filtering set indicated. + _ + _ uint16 = 0x00E0 // For future use (Set to zero) + // If not zero, skips over all marks of attachment + // type different from specified. + otMarkAttachmentType uint16 = 0xFF00 +) + +// /** +// * SECTION:hb-ot-layout +// * @title: hb-ot-layout +// * @short_description: OpenType Layout +// * @include: hb-ot.h +// * +// * Functions for querying OpenType Layout features in the font face. +// **/ + +const maxNestingLevel = 6 + +func (c *otApplyContext) applyString(proxy otProxyMeta, accel *otLayoutLookupAccelerator) { + buffer := c.buffer + lookup := accel.lookup + + if len(buffer.Info) == 0 || c.lookupMask == 0 { + return + } + c.setLookupProps(lookup.Props()) + if !lookup.isReverse() { + // in/out forward substitution/positioning + if !proxy.inplace { + buffer.clearOutput() + } + buffer.idx = 0 + + c.applyForward(accel) + if !proxy.inplace { + buffer.swapBuffers() + } + } else { + /* in-place backward substitution/positioning */ + // assert (!buffer->have_output); + + buffer.idx = len(buffer.Info) - 1 + + c.applyBackward(accel) + } +} + +func (c *otApplyContext) applyForward(accel *otLayoutLookupAccelerator) bool { + ret := false + buffer := c.buffer + for buffer.idx < len(buffer.Info) { + applied := false + if accel.digest.mayHave(gID(buffer.cur(0).Glyph)) && + (buffer.cur(0).Mask&c.lookupMask) != 0 && + c.checkGlyphProperty(buffer.cur(0), c.lookupProps) { + applied = accel.apply(c) + } + + if applied { + ret = true + } else { + buffer.nextGlyph() + } + } + return ret +} + +func (c *otApplyContext) applyBackward(accel *otLayoutLookupAccelerator) bool { + ret := false + buffer := c.buffer + for do := true; do; do = buffer.idx >= 0 { + if accel.digest.mayHave(gID(buffer.cur(0).Glyph)) && + (buffer.cur(0).Mask&c.lookupMask != 0) && + c.checkGlyphProperty(buffer.cur(0), c.lookupProps) { + applied := accel.apply(c) + ret = ret || applied + } + + // the reverse lookup doesn't "advance" cursor (for good reason). + buffer.idx-- + + } + return ret +} + +/* + * kern + */ + +// tests whether a face includes any state-machine kerning in the 'kern' table. +// +// Does NOT examine the GPOS table. +func hasMachineKerning(kern font.Kernx) bool { + for _, subtable := range kern { + if _, isType1 := subtable.Data.(font.Kern1); isType1 { + return true + } + } + return false +} + +// tests whether a face has any cross-stream kerning (i.e., kerns +// that make adjustments perpendicular to the direction of the text +// flow: Y adjustments in horizontal text or X adjustments in +// vertical text) in the 'kern' table. +// +// Does NOT examine the GPOS table. +func hasCrossKerning(kern font.Kernx) bool { + for _, subtable := range kern { + if subtable.IsCrossStream() { + return true + } + } + return false +} + +func (sp *otShapePlan) otLayoutKern(font *Font, buffer *Buffer) { + kern := font.face.Kern + c := newAatApplyContext(sp, font, buffer) + c.applyKernx(kern) +} + +var otTagLatinScript = ot.NewTag('l', 'a', 't', 'n') + +// selectScript selects an OpenType script from the `scriptTags` array, +// returning its index in the Scripts slice and the script tag. +// +// If `table` does not have any of the requested scripts, then `DFLT`, +// `dflt`, and `latn` tags are tried in that order. If the table still does not +// have any of these scripts, NoScriptIndex is returned. +// +// An additional boolean if returned : it is `true` if one of the requested scripts is selected, or `false` if a fallback +// script is selected or if no scripts are selected. +func selectScript(table *font.Layout, scriptTags []tables.Tag) (int, tables.Tag, bool) { + for _, tag := range scriptTags { + if scriptIndex := table.FindScript(tag); scriptIndex != -1 { + return scriptIndex, tag, true + } + } + + // try finding 'DFLT' + if scriptIndex := table.FindScript(tagDefaultScript); scriptIndex != -1 { + return scriptIndex, tagDefaultScript, false + } + + // try with 'dflt'; MS site has had typos and many fonts use it now :( + if scriptIndex := table.FindScript(tagDefaultLanguage); scriptIndex != -1 { + return scriptIndex, tagDefaultLanguage, false + } + + // try with 'latn'; some old fonts put their features there even though + // they're really trying to support Thai, for example :( + if scriptIndex := table.FindScript(otTagLatinScript); scriptIndex != -1 { + return scriptIndex, otTagLatinScript, false + } + + return NoScriptIndex, NoScriptIndex, false +} + +// selectLanguage fetches the index of the first language tag from `languageTags` in the specified layout table, +// underneath `scriptIndex`. +// It not found, the `dflt` language tag is searched. +// Return `true` if the requested language tag is found, `false` otherwise. +// If `scriptIndex` is `NoScriptIndex` or if no language is found, `DefaultLanguageIndex` is returned. +func selectLanguage(table *font.Layout, scriptIndex int, languageTags []tables.Tag) (int, bool) { + if scriptIndex == NoScriptIndex { + return DefaultLanguageIndex, false + } + + s := table.Scripts[scriptIndex] + + for _, lang := range languageTags { + if languageIndex := s.FindLanguage(lang); languageIndex != -1 { + return languageIndex, true + } + } + + // try finding 'dflt' + if languageIndex := s.FindLanguage(tagDefaultLanguage); languageIndex != -1 { + return languageIndex, false + } + + return DefaultLanguageIndex, false +} + +func findFeature(g *font.Layout, featureTag tables.Tag) uint16 { + if index, ok := g.FindFeatureIndex(featureTag); ok { + return index + } + return NoFeatureIndex +} + +// Fetches the index of a given feature tag in the specified face's GSUB table +// or GPOS table, underneath the specified script and language. +// Return `NoFeatureIndex` it the the feature is not found. +func findFeatureForLang(table *font.Layout, scriptIndex, languageIndex int, featureTag tables.Tag) uint16 { + if scriptIndex == NoScriptIndex { + return NoFeatureIndex + } + + l := table.Scripts[scriptIndex].GetLangSys(uint16(languageIndex)) + for _, fIndex := range l.FeatureIndices { + if featureTag == table.Features[fIndex].Tag { + return fIndex + } + } + + return NoFeatureIndex +} + +// Fetches the tag of a requested feature index in the given layout table, +// underneath the specified script and language. Returns -1 if no feature is requested. +func getRequiredFeature(g *font.Layout, scriptIndex, languageIndex int) (uint16, tables.Tag) { + if scriptIndex == NoScriptIndex { + return NoFeatureIndex, 0 + } + + l := g.Scripts[scriptIndex].GetLangSys(uint16(languageIndex)) + if l.RequiredFeatureIndex == 0xFFFF { + return NoFeatureIndex, 0 + } + index := l.RequiredFeatureIndex + return index, g.Features[index].Tag +} + +// getFeatureLookupsWithVar fetches a list of all lookups enumerated for the specified feature, in +// the given table, enabled at the specified variations index. +// it returns the basic feature if `variationsIndex == noVariationsIndex` +func getFeatureLookupsWithVar(table *font.Layout, featureIndex uint16, variationsIndex int) []uint16 { + if featureIndex == NoFeatureIndex { + return nil + } + + if variationsIndex == noVariationsIndex { // just fetch the feature + return table.Features[featureIndex].LookupListIndices + } + + // hook the variations + subs := table.FeatureVariations[variationsIndex].Substitutions.Substitutions + for _, sub := range subs { + if sub.FeatureIndex == featureIndex { + return sub.AlternateFeature.LookupListIndices + } + } + return nil +} + +// tests whether a specified lookup index in the specified face would +// trigger a substitution on the given glyph sequence. +// zeroContext indicating whether substitutions should be context-free. +func otLayoutLookupWouldSubstitute(font *Font, lookupIndex uint16, glyphs []GID, zeroContext bool) bool { + gsub := font.face.GSUB + if int(lookupIndex) >= len(gsub.Lookups) { + return false + } + c := wouldApplyContext{glyphs, nil, zeroContext} + + l := lookupGSUB(gsub.Lookups[lookupIndex]) + return l.wouldApply(&c, &font.gsubAccels[lookupIndex]) +} + +// Called before substitution lookups are performed, to ensure that glyph +// class and other properties are set on the glyphs in the buffer. +func layoutSubstituteStart(font *Font, buffer *Buffer) { + gdef := font.face.GDEF + hasClass := gdef.GlyphClassDef != nil + for i := range buffer.Info { + if hasClass { + buffer.Info[i].glyphProps = gdef.GlyphProps(gID(buffer.Info[i].Glyph)) + } + buffer.Info[i].ligProps = 0 + buffer.Info[i].syllable = 0 + } +} + +func otLayoutDeleteGlyphsInplace(buffer *Buffer, filter func(*GlyphInfo) bool) { + // Merge clusters and delete filtered glyphs. + var ( + j int + info = buffer.Info + pos = buffer.Pos + ) + for i := range info { + if filter(&info[i]) { + /* Merge clusters. + * Same logic as buffer.delete_glyph(), but for in-place removal. */ + + cluster := info[i].Cluster + if i+1 < len(buffer.Info) && cluster == info[i+1].Cluster { + /* Cluster survives; do nothing. */ + continue + } + + if j != 0 { + /* Merge cluster backward. */ + if cluster < info[j-1].Cluster { + mask := info[i].Mask + oldCluster := info[j-1].Cluster + for k := j; k != 0 && info[k-1].Cluster == oldCluster; k-- { + info[k-1].setCluster(cluster, mask) + } + } + continue + } + + if i+1 < len(buffer.Info) { + /* Merge cluster forward. */ + buffer.mergeClusters(i, i+2) + } + + continue + } + + if j != i { + info[j] = info[i] + pos[j] = pos[i] + } + j++ + } + buffer.Info = buffer.Info[:j] + buffer.Pos = buffer.Pos[:j] +} + +// Called before positioning lookups are performed, to ensure that glyph +// attachment types and glyph-attachment chains are set for the glyphs in the buffer. +func otLayoutPositionStart(_ *Font, buffer *Buffer) { + positionStartGPOS(buffer) +} + +// Called after positioning lookups are performed, to finish glyph offsets. +func otLayoutPositionFinishOffsets(_ *Font, buffer *Buffer) { + positionFinishOffsetsGPOS(buffer) +} + +func glyphInfoSubstituted(info *GlyphInfo) bool { + return (info.glyphProps & substituted) != 0 +} + +func clearSubstitutionFlags(_ *otShapePlan, _ *Font, buffer *Buffer) bool { + info := buffer.Info + for i := range info { + info[i].glyphProps &= ^substituted + } + return false +} + +func reverseGraphemes(b *Buffer) { + b.reverseGroups(func(_, gi2 *GlyphInfo) bool { return gi2.isContinuation() }, b.ClusterLevel == MonotoneGraphemes) +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_layout_gpos.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_layout_gpos.go new file mode 100644 index 0000000..4af2321 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_layout_gpos.go @@ -0,0 +1,683 @@ +package harfbuzz + +import ( + "fmt" + + "github.com/go-text/typesetting/font" + "github.com/go-text/typesetting/font/opentype/tables" +) + +// ported from harfbuzz/src/hb-ot-layout-gpos-table.hh Copyright © 2007,2008,2009,2010 Red Hat, Inc.; 2010,2012,2013 Google, Inc. Behdad Esfahbod + +var _ layoutLookup = lookupGPOS{} + +// implements layoutLookup +type lookupGPOS font.GPOSLookup + +func (l lookupGPOS) Props() uint32 { return l.LookupOptions.Props() } + +func (l lookupGPOS) collectCoverage(dst *setDigest) { + for _, table := range l.Subtables { + dst.collectCoverage(table.Cov()) + } +} + +func (l lookupGPOS) dispatchSubtables(ctx *getSubtablesContext) { + for _, table := range l.Subtables { + *ctx = append(*ctx, newGPOSApplicable(table)) + } +} + +func (l lookupGPOS) dispatchApply(ctx *otApplyContext) bool { + for _, table := range l.Subtables { + if ctx.applyGPOS(table) { + return true + } + } + return false +} + +func (lookupGPOS) isReverse() bool { return false } + +// attach_type_t +const ( + attachTypeNone = 0x00 + + /* Each attachment should be either a mark or a cursive; can't be both. */ + attachTypeMark = 0x01 + attachTypeCursive = 0x02 +) + +func positionStartGPOS(buffer *Buffer) { + for i := range buffer.Pos { + buffer.Pos[i].attachChain = 0 + buffer.Pos[i].attachType = 0 + } +} + +func propagateAttachmentOffsets(pos []GlyphPosition, i int, direction Direction) { + /* Adjusts offsets of attached glyphs (both cursive and mark) to accumulate + * offset of glyph they are attached to. */ + chain, type_ := pos[i].attachChain, pos[i].attachType + if chain == 0 { + return + } + + pos[i].attachChain = 0 + + j := i + int(chain) + + if j >= len(pos) { + return + } + + propagateAttachmentOffsets(pos, j, direction) + + // assert (!!(type_ & attachTypeMark) ^ !!(type_ & attachTypeCursive)); + + if (type_ & attachTypeCursive) != 0 { + if direction.isHorizontal() { + pos[i].YOffset += pos[j].YOffset + } else { + pos[i].XOffset += pos[j].XOffset + } + } else /*if (type_ & attachTypeMark)*/ { + pos[i].XOffset += pos[j].XOffset + pos[i].YOffset += pos[j].YOffset + + // assert (j < i); + if direction.isForward() { + for _, p := range pos[j:i] { + pos[i].XOffset -= p.XAdvance + pos[i].YOffset -= p.YAdvance + } + } else { + for _, p := range pos[j+1 : i+1] { + pos[i].XOffset += p.XAdvance + pos[i].YOffset += p.YAdvance + } + } + } +} + +func positionFinishOffsetsGPOS(buffer *Buffer) { + pos := buffer.Pos + direction := buffer.Props.Direction + + /* Handle attachments */ + if buffer.scratchFlags&bsfHasGPOSAttachment != 0 { + + if debugMode { + fmt.Println("POSITION - handling attachments") + } + + for i := range pos { + propagateAttachmentOffsets(pos, i, direction) + } + } +} + +func applyRecurseGPOS(c *otApplyContext, lookupIndex uint16) bool { + gpos := c.font.face.GPOS + l := lookupGPOS(gpos.Lookups[lookupIndex]) + return c.applyRecurseLookup(lookupIndex, l) +} + +// return `true` is the positionning found a match and was applied +func (c *otApplyContext) applyGPOS(table tables.GPOSLookup) bool { + buffer := c.buffer + glyphID := buffer.cur(0).Glyph + glyphPos := buffer.curPos(0) + index, ok := table.Cov().Index(gID(glyphID)) + if !ok { + return false + } + + if debugMode { + fmt.Printf("\tAPPLY - type %T at index %d\n", table, c.buffer.idx) + } + + switch data := table.(type) { + case tables.SinglePos: + switch inner := data.Data.(type) { + case tables.SinglePosData1: + c.applyGPOSValueRecord(inner.ValueFormat, inner.ValueRecord, glyphPos) + case tables.SinglePosData2: + c.applyGPOSValueRecord(inner.ValueFormat, inner.ValueRecords[index], glyphPos) + } + buffer.idx++ + case tables.PairPos: + skippyIter := &c.iterInput + skippyIter.reset(buffer.idx, 1) + if ok, unsafeTo := skippyIter.next(); !ok { + buffer.unsafeToConcat(buffer.idx, unsafeTo) + return false + } + switch inner := data.Data.(type) { + case tables.PairPosData1: + return c.applyGPOSPair1(inner, index) + case tables.PairPosData2: + return c.applyGPOSPair2(inner) + } + + case tables.CursivePos: + return c.applyGPOSCursive(data, index) + case tables.MarkBasePos: + return c.applyGPOSMarkToBase(data, index) + case tables.MarkLigPos: + return c.applyGPOSMarkToLigature(data, index) + case tables.MarkMarkPos: + return c.applyGPOSMarkToMark(data, index) + + case tables.ContextualPos: + switch inner := data.Data.(type) { + case tables.ContextualPos1: + return c.applyLookupContext1(tables.SequenceContextFormat1(inner), index) + case tables.ContextualPos2: + return c.applyLookupContext2(tables.SequenceContextFormat2(inner), index, glyphID) + case tables.ContextualPos3: + return c.applyLookupContext3(tables.SequenceContextFormat3(inner), index) + } + + case tables.ChainedContextualPos: + switch inner := data.Data.(type) { + case tables.ChainedContextualPos1: + return c.applyLookupChainedContext1(tables.ChainedSequenceContextFormat1(inner), index) + case tables.ChainedContextualPos2: + return c.applyLookupChainedContext2(tables.ChainedSequenceContextFormat2(inner), index, glyphID) + case tables.ChainedContextualPos3: + return c.applyLookupChainedContext3(tables.ChainedSequenceContextFormat3(inner), index) + } + } + return true +} + +func (c *otApplyContext) applyGPOSValueRecord(format tables.ValueFormat, v tables.ValueRecord, glyphPos *GlyphPosition) bool { + var ret bool + if format == 0 { + return ret + } + + font := c.font + horizontal := c.direction.isHorizontal() + + if format&tables.XPlacement != 0 { + glyphPos.XOffset += font.emScaleX(v.XPlacement) + ret = ret || v.XPlacement != 0 + } + if format&tables.YPlacement != 0 { + glyphPos.YOffset += font.emScaleY(v.YPlacement) + ret = ret || v.YPlacement != 0 + } + if format&tables.XAdvance != 0 { + if horizontal { + glyphPos.XAdvance += font.emScaleX(v.XAdvance) + ret = ret || v.XAdvance != 0 + } + } + /* YAdvance values grow downward but font-space grows upward, hence negation */ + if format&tables.YAdvance != 0 { + if !horizontal { + glyphPos.YAdvance -= font.emScaleY(v.YAdvance) + ret = ret || v.YAdvance != 0 + } + } + + if format&tables.Devices == 0 { + return ret + } + + xp, yp := font.face.Ppem() + useXDevice := xp != 0 || len(font.varCoords()) != 0 + useYDevice := yp != 0 || len(font.varCoords()) != 0 + + if !useXDevice && !useYDevice { + return ret + } + + if format&tables.XPlaDevice != 0 && useXDevice { + glyphPos.XOffset += font.getXDelta(c.varStore, v.XPlaDevice) + ret = ret || v.XPlaDevice != nil + } + if format&tables.YPlaDevice != 0 && useYDevice { + glyphPos.YOffset += font.getYDelta(c.varStore, v.YPlaDevice) + ret = ret || v.YPlaDevice != nil + } + if format&tables.XAdvDevice != 0 && horizontal && useXDevice { + glyphPos.XAdvance += font.getXDelta(c.varStore, v.XAdvDevice) + ret = ret || v.XAdvDevice != nil + } + if format&tables.YAdvDevice != 0 && !horizontal && useYDevice { + /* YAdvance values grow downward but font-space grows upward, hence negation */ + glyphPos.YAdvance -= font.getYDelta(c.varStore, v.YAdvDevice) + ret = ret || v.YAdvDevice != nil + } + return ret +} + +func reverseCursiveMinorOffset(pos []GlyphPosition, i int, direction Direction, newParent int) { + chain, type_ := pos[i].attachChain, pos[i].attachType + if chain == 0 || type_&attachTypeCursive == 0 { + return + } + + pos[i].attachChain = 0 + + j := i + int(chain) + + // stop if we see new parent in the chain + if j == newParent { + return + } + reverseCursiveMinorOffset(pos, j, direction, newParent) + + if direction.isHorizontal() { + pos[j].YOffset = -pos[i].YOffset + } else { + pos[j].XOffset = -pos[i].XOffset + } + + pos[j].attachChain = -chain + pos[j].attachType = type_ +} + +func (c *otApplyContext) applyGPOSPair1(inner tables.PairPosData1, index int) bool { + buffer := c.buffer + skippyIter := &c.iterInput + pos := skippyIter.idx + set := inner.PairSets[index] + record, ok := set.FindGlyph(gID(buffer.Info[skippyIter.idx].Glyph)) + if !ok { + buffer.unsafeToConcat(buffer.idx, pos+1) + return false + } + + ap1 := c.applyGPOSValueRecord(inner.ValueFormat1, record.ValueRecord1, buffer.curPos(0)) + ap2 := c.applyGPOSValueRecord(inner.ValueFormat2, record.ValueRecord2, &buffer.Pos[pos]) + + if ap1 || ap2 { + buffer.unsafeToBreak(buffer.idx, pos+1) + } + + if inner.ValueFormat2 != 0 { + // https://github.com/harfbuzz/harfbuzz/issues/3824 + // https://github.com/harfbuzz/harfbuzz/issues/3888#issuecomment-1326781116 + pos++ + buffer.unsafeToBreak(buffer.idx, pos+1) + } + buffer.idx = pos + return true +} + +func (c *otApplyContext) applyGPOSPair2(inner tables.PairPosData2) bool { + buffer := c.buffer + skippyIter := &c.iterInput + + glyphID := buffer.cur(0).Glyph + class2, ok2 := inner.ClassDef2.Class(gID(buffer.Info[skippyIter.idx].Glyph)) + if !ok2 { + buffer.unsafeToConcat(buffer.idx, skippyIter.idx+1) + return false + } + + class1, _ := inner.ClassDef1.Class(gID(glyphID)) + vals := inner.Record(class1, class2) + + ap1 := c.applyGPOSValueRecord(inner.ValueFormat1, vals.ValueRecord1, buffer.curPos(0)) + ap2 := c.applyGPOSValueRecord(inner.ValueFormat2, vals.ValueRecord2, &buffer.Pos[skippyIter.idx]) + + if ap1 || ap2 { + buffer.unsafeToBreak(buffer.idx, skippyIter.idx+1) + } else { + buffer.unsafeToConcat(buffer.idx, skippyIter.idx+1) + } + + if inner.ValueFormat2 != 0 { + // https://github.com/harfbuzz/harfbuzz/issues/3824 + // https://github.com/harfbuzz/harfbuzz/issues/3888#issuecomment-1326781116 + skippyIter.idx++ + buffer.unsafeToBreak(buffer.idx, skippyIter.idx+1) + } + buffer.idx = skippyIter.idx + return true +} + +func (c *otApplyContext) applyGPOSCursive(data tables.CursivePos, covIndex int) bool { + buffer := c.buffer + + thisRecord := data.EntryExits[covIndex] + if thisRecord.EntryAnchor == nil { + return false + } + + skippyIter := &c.iterInput + skippyIter.reset(buffer.idx, 1) + if ok, unsafeFrom := skippyIter.prev(); !ok { + buffer.unsafeToConcatFromOutbuffer(unsafeFrom, buffer.idx+1) + return false + } + + prevIndex, ok := data.Cov().Index(gID(buffer.Info[skippyIter.idx].Glyph)) + if !ok { + buffer.unsafeToConcatFromOutbuffer(skippyIter.idx, buffer.idx+1) + return false + } + prevRecord := data.EntryExits[prevIndex] + if prevRecord.ExitAnchor == nil { + buffer.unsafeToConcatFromOutbuffer(skippyIter.idx, buffer.idx+1) + return false + } + + i := skippyIter.idx + j := buffer.idx + + buffer.unsafeToBreak(i, j+1) + exitX, exitY := c.getAnchor(prevRecord.ExitAnchor, buffer.Info[i].Glyph) + entryX, entryY := c.getAnchor(thisRecord.EntryAnchor, buffer.Info[j].Glyph) + + pos := buffer.Pos + + var d Position + /* Main-direction adjustment */ + switch c.direction { + case LeftToRight: + pos[i].XAdvance = roundf(exitX) + pos[i].XOffset + + d = roundf(entryX) + pos[j].XOffset + pos[j].XAdvance -= d + pos[j].XOffset -= d + case RightToLeft: + d = roundf(exitX) + pos[i].XOffset + pos[i].XAdvance -= d + pos[i].XOffset -= d + + pos[j].XAdvance = roundf(entryX) + pos[j].XOffset + case TopToBottom: + pos[i].YAdvance = roundf(exitY) + pos[i].YOffset + + d = roundf(entryY) + pos[j].YOffset + pos[j].YAdvance -= d + pos[j].YOffset -= d + case BottomToTop: + d = roundf(exitY) + pos[i].YOffset + pos[i].YAdvance -= d + pos[i].YOffset -= d + + pos[j].YAdvance = roundf(entryY) + } + + /* Cross-direction adjustment */ + + /* We attach child to parent (think graph theory and rooted trees whereas + * the root stays on baseline and each node aligns itself against its + * parent. + * + * Optimize things for the case of RightToLeft, as that's most common in + * Arabic. */ + child := i + parent := j + xOffset := Position(entryX - exitX) + yOffset := Position(entryY - exitY) + if uint16(c.lookupProps)&otRightToLeft == 0 { + k := child + child = parent + parent = k + xOffset = -xOffset + yOffset = -yOffset + } + + /* If child was already connected to someone else, walk through its old + * chain and reverse the link direction, such that the whole tree of its + * previous connection now attaches to new parent. Watch out for case + * where new parent is on the path from old chain... + */ + reverseCursiveMinorOffset(pos, child, c.direction, parent) + + pos[child].attachType = attachTypeCursive + pos[child].attachChain = int16(parent - child) + buffer.scratchFlags |= bsfHasGPOSAttachment + if c.direction.isHorizontal() { + pos[child].YOffset = yOffset + } else { + pos[child].XOffset = xOffset + } + + /* If parent was attached to child, separate them. + * https://github.com/harfbuzz/harfbuzz/issues/2469 */ + if pos[parent].attachChain == -pos[child].attachChain { + pos[parent].attachChain = 0 + if c.direction.isHorizontal() { + pos[parent].YOffset = 0 + } else { + pos[parent].XOffset = 0 + } + } + + buffer.idx++ + return true +} + +// panic if anchor is nil +func (c *otApplyContext) getAnchor(anchor tables.Anchor, glyph GID) (x, y float32) { + font := c.font + switch anchor := anchor.(type) { + case tables.AnchorFormat1: + return font.emFscaleX(anchor.XCoordinate), font.emFscaleY(anchor.YCoordinate) + case tables.AnchorFormat2: + xPpem, yPpem := font.face.Ppem() + var cx, cy Position + ret := xPpem != 0 || yPpem != 0 + if ret { + cx, cy, ret = font.getGlyphContourPointForOrigin(glyph, anchor.AnchorPoint, LeftToRight) + } + if ret && xPpem != 0 { + x = float32(cx) + } else { + x = font.emFscaleX(anchor.XCoordinate) + } + if ret && yPpem != 0 { + y = float32(cy) + } else { + y = font.emFscaleY(anchor.YCoordinate) + } + return x, y + case tables.AnchorFormat3: + xPpem, yPpem := font.face.Ppem() + x, y = font.emFscaleX(anchor.XCoordinate), font.emFscaleY(anchor.YCoordinate) + if xPpem != 0 || len(font.varCoords()) != 0 { + x += float32(font.getXDelta(c.varStore, anchor.XDevice)) + } + if yPpem != 0 || len(font.varCoords()) != 0 { + y += float32(font.getYDelta(c.varStore, anchor.YDevice)) + } + return x, y + default: + panic("exhaustive switch") + } +} + +func (c *otApplyContext) applyGPOSMarks(marks tables.MarkArray, markIndex, glyphIndex int, anchors tables.AnchorMatrix, glyphPos int) bool { + buffer := c.buffer + markClass := marks.MarkRecords[markIndex].MarkClass + markAnchor := marks.MarkAnchors[markIndex] + + glyphAnchor := anchors.Anchor(glyphIndex, int(markClass)) + // If this subtable doesn't have an anchor for this base and this class, + // return false such that the subsequent subtables have a chance at it. + if glyphAnchor == nil { + return false + } + + buffer.unsafeToBreak(glyphPos, buffer.idx+1) + markX, markY := c.getAnchor(markAnchor, buffer.cur(0).Glyph) + baseX, baseY := c.getAnchor(glyphAnchor, buffer.Info[glyphPos].Glyph) + + o := buffer.curPos(0) + o.XOffset = roundf(baseX - markX) + o.YOffset = roundf(baseY - markY) + o.attachType = attachTypeMark + o.attachChain = int16(glyphPos - buffer.idx) + buffer.scratchFlags |= bsfHasGPOSAttachment + + buffer.idx++ + return true +} + +func (c *otApplyContext) applyGPOSMarkToBase(data tables.MarkBasePos, markIndex int) bool { + buffer := c.buffer + + // Now we search backwards for a non-mark glyph. + // We don't use skippy_iter.prev() to avoid O(n^2) behavior. + + skippyIter := &c.iterInput + skippyIter.matcher.lookupProps = uint32(otIgnoreMarks) + + if c.lastBaseUntil > buffer.idx { + c.lastBaseUntil = 0 + c.lastBase = -1 + } + + for j := buffer.idx; j > c.lastBaseUntil; j-- { + ma := skippyIter.match(&buffer.Info[j-1]) + if ma == match { + // https://github.com/harfbuzz/harfbuzz/issues/4124 + + // We only want to attach to the first of a MultipleSubst sequence. + // https://github.com/harfbuzz/harfbuzz/issues/740 + // Reject others... + // ...but stop if we find a mark in the MultipleSubst sequence: + // https://github.com/harfbuzz/harfbuzz/issues/1020 + idx := j - 1 + accept := !buffer.Info[idx].multiplied() || buffer.Info[idx].getLigComp() == 0 || + idx == 0 || buffer.Info[idx-1].isMark() || + buffer.Info[idx].getLigID() != buffer.Info[idx-1].getLigID() || + buffer.Info[idx].getLigComp() != buffer.Info[idx-1].getLigComp()+1 + + _, covered := data.BaseCoverage.Index(gID(buffer.Info[idx].Glyph)) + if !accept && !covered { + ma = skip + } + } + if ma == match { + c.lastBase = j - 1 + break + } + } + + c.lastBaseUntil = buffer.idx + if c.lastBase == -1 { + buffer.unsafeToConcatFromOutbuffer(0, buffer.idx+1) + return false + } + + idx := c.lastBase + baseIndex, ok := data.BaseCoverage.Index(gID(buffer.Info[idx].Glyph)) + if !ok { + buffer.unsafeToConcatFromOutbuffer(idx, buffer.idx+1) + return false + } + + return c.applyGPOSMarks(data.MarkArray, markIndex, baseIndex, data.BaseArray.Anchors(), idx) +} + +func (c *otApplyContext) applyGPOSMarkToLigature(data tables.MarkLigPos, markIndex int) bool { + buffer := c.buffer + + // now we search backwards for a non-mark glyph + skippyIter := &c.iterInput + skippyIter.matcher.lookupProps = uint32(otIgnoreMarks) + if c.lastBaseUntil > buffer.idx { + c.lastBaseUntil = 0 + c.lastBase = -1 + } + + for j := buffer.idx; j > c.lastBaseUntil; j-- { + ma := skippyIter.match(&buffer.Info[j-1]) + if ma == match { + c.lastBase = j - 1 + break + } + } + c.lastBaseUntil = buffer.idx + if c.lastBase == -1 { + c.buffer.unsafeToConcatFromOutbuffer(0, buffer.idx+1) + return false + } + + idx := c.lastBase + ligIndex, ok := data.LigatureCoverage.Index(gID(buffer.Info[idx].Glyph)) + if !ok { + c.buffer.unsafeToConcatFromOutbuffer(idx, c.buffer.idx+1) + return false + } + + ligAttach := data.LigatureArray.LigatureAttachs[ligIndex].Anchors() + + // Find component to attach to + compCount := ligAttach.Len() + if compCount == 0 { + return false + } + + // We must now check whether the ligature ID of the current mark glyph + // is identical to the ligature ID of the found ligature. If yes, we + // can directly use the component index. If not, we attach the mark + // glyph to the last component of the ligature. + ligID := buffer.Info[idx].getLigID() + markID := buffer.cur(0).getLigID() + markComp := buffer.cur(0).getLigComp() + compIndex := compCount - 1 + if ligID != 0 && ligID == markID && markComp > 0 { + compIndex = min(compCount, int(buffer.cur(0).getLigComp())) - 1 + } + + return c.applyGPOSMarks(data.MarkArray, markIndex, compIndex, ligAttach, idx) +} + +func (c *otApplyContext) applyGPOSMarkToMark(data tables.MarkMarkPos, mark1Index int) bool { + buffer := c.buffer + + // now we search backwards for a suitable mark glyph until a non-mark glyph + skippyIter := &c.iterInput + skippyIter.reset(buffer.idx, 1) + skippyIter.matcher.lookupProps = c.lookupProps &^ uint32(ignoreFlags) + if ok, _ := skippyIter.prev(); !ok { + return false + } + + if !buffer.Info[skippyIter.idx].isMark() { + return false + } + + j := skippyIter.idx + + id1 := buffer.cur(0).getLigID() + id2 := buffer.Info[j].getLigID() + comp1 := buffer.cur(0).getLigComp() + comp2 := buffer.Info[j].getLigComp() + + if id1 == id2 { + if id1 == 0 { /* Marks belonging to the same base. */ + goto good + } else if comp1 == comp2 { /* Marks belonging to the same ligature component. */ + goto good + } + } else { + /* If ligature ids don't match, it may be the case that one of the marks + * itself is a ligature. In which case match. */ + if (id1 > 0 && comp1 == 0) || (id2 > 0 && comp2 == 0) { + goto good + } + } + + /* Didn't match. */ + return false + +good: + mark2Index, ok := data.Mark2Coverage.Index(gID(buffer.Info[j].Glyph)) + if !ok { + return false + } + + return c.applyGPOSMarks(data.Mark1Array, mark1Index, mark2Index, data.Mark2Array.Anchors(), j) +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_layout_gsub.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_layout_gsub.go new file mode 100644 index 0000000..b27365b --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_layout_gsub.go @@ -0,0 +1,298 @@ +package harfbuzz + +import ( + "fmt" + "math/bits" + + "github.com/go-text/typesetting/font" + "github.com/go-text/typesetting/font/opentype/tables" +) + +const maxContextLength = 64 + +var _ layoutLookup = lookupGSUB{} + +// implements layoutLookup +type lookupGSUB font.GSUBLookup + +func (l lookupGSUB) Props() uint32 { return l.LookupOptions.Props() } + +func (l lookupGSUB) collectCoverage(dst *setDigest) { + for _, table := range l.Subtables { + dst.collectCoverage(table.Cov()) + } +} + +func (l lookupGSUB) dispatchSubtables(ctx *getSubtablesContext) { + for _, table := range l.Subtables { + *ctx = append(*ctx, newGSUBApplicable(table)) + } +} + +func (l lookupGSUB) dispatchApply(ctx *otApplyContext) bool { + for _, table := range l.Subtables { + if ctx.applyGSUB(table) { + return true + } + } + return false +} + +func (l lookupGSUB) wouldApply(ctx *wouldApplyContext, accel *otLayoutLookupAccelerator) bool { + if len(ctx.glyphs) == 0 { + return false + } + if !accel.digest.mayHave(gID(ctx.glyphs[0])) { + return false + } + // dispatch on subtables + for _, table := range l.Subtables { + if ctx.wouldApplyGSUB(table) { + return true + } + } + return false +} + +func (l lookupGSUB) isReverse() bool { + if len(l.Subtables) == 0 { + return false + } + _, is := l.Subtables[0].(tables.ReverseChainSingleSubs) + return is +} + +func applyRecurseGSUB(c *otApplyContext, lookupIndex uint16) bool { + gsub := c.font.face.GSUB + l := lookupGSUB(gsub.Lookups[lookupIndex]) + return c.applyRecurseLookup(lookupIndex, l) +} + +// matchesLigature tests if the ligature should be applied on `glyphsFromSecond`, +// which starts from the second glyph. +func matchesLigature(l tables.Ligature, glyphsFromSecond []GID) bool { + if len(glyphsFromSecond) != len(l.ComponentGlyphIDs) { + return false + } + for i, g := range glyphsFromSecond { + if g != GID(l.ComponentGlyphIDs[i]) { + return false + } + } + return true +} + +// return `true` is we should apply this lookup to the glyphs in `c`, +// which are assumed to be non empty +func (c *wouldApplyContext) wouldApplyGSUB(table tables.GSUBLookup) bool { + index, ok := table.Cov().Index(gID(c.glyphs[0])) + switch data := table.(type) { + case tables.SingleSubs, tables.MultipleSubs, tables.AlternateSubs, tables.ReverseChainSingleSubs: + return len(c.glyphs) == 1 && ok + + case tables.LigatureSubs: + if !ok { + return false + } + ligatureSet := data.LigatureSets[index].Ligatures + glyphsFromSecond := c.glyphs[1:] + for _, ligature := range ligatureSet { + if matchesLigature(ligature, glyphsFromSecond) { + return true + } + } + return false + + case tables.ContextualSubs: + switch inner := data.Data.(type) { + case tables.ContextualSubs1: + return c.wouldApplyLookupContext1(tables.SequenceContextFormat1(inner), index) + case tables.ContextualSubs2: + return c.wouldApplyLookupContext2(tables.SequenceContextFormat2(inner), index, c.glyphs[0]) + case tables.ContextualSubs3: + return c.wouldApplyLookupContext3(tables.SequenceContextFormat3(inner), index) + } + + case tables.ChainedContextualSubs: + switch inner := data.Data.(type) { + case tables.ChainedContextualSubs1: + return c.wouldApplyLookupChainedContext1(tables.ChainedSequenceContextFormat1(inner), index) + case tables.ChainedContextualSubs2: + return c.wouldApplyLookupChainedContext2(tables.ChainedSequenceContextFormat2(inner), index, c.glyphs[0]) + case tables.ChainedContextualSubs3: + return c.wouldApplyLookupChainedContext3(tables.ChainedSequenceContextFormat3(inner), index) + } + + } + return false +} + +// return `true` is the subsitution found a match and was applied +func (c *otApplyContext) applyGSUB(table tables.GSUBLookup) bool { + glyph := c.buffer.cur(0) + glyphID := glyph.Glyph + index, ok := table.Cov().Index(gID(glyphID)) + if !ok { + return false + } + + if debugMode { + fmt.Printf("\tAPPLY - type %T at index %d\n", table, c.buffer.idx) + } + + switch data := table.(type) { + case tables.SingleSubs: + switch inner := data.Data.(type) { + case tables.SingleSubstData1: + /* According to the Adobe Annotated OpenType Suite, result is always + * limited to 16bit. */ + glyphID = GID(uint16(int(glyphID) + int(inner.DeltaGlyphID))) + c.replaceGlyph(glyphID) + case tables.SingleSubstData2: + if index >= len(inner.SubstituteGlyphIDs) { // index is not sanitized in tables.Parse + return false + } + c.replaceGlyph(GID(inner.SubstituteGlyphIDs[index])) + } + + case tables.MultipleSubs: + c.applySubsSequence(data.Sequences[index].SubstituteGlyphIDs) + + case tables.AlternateSubs: + alternates := data.AlternateSets[index].AlternateGlyphIDs + return c.applySubsAlternate(alternates) + + case tables.LigatureSubs: + ligatureSet := data.LigatureSets[index].Ligatures + return c.applySubsLigature(ligatureSet) + + case tables.ContextualSubs: + switch inner := data.Data.(type) { + case tables.ContextualSubs1: + return c.applyLookupContext1(tables.SequenceContextFormat1(inner), index) + case tables.ContextualSubs2: + return c.applyLookupContext2(tables.SequenceContextFormat2(inner), index, glyphID) + case tables.ContextualSubs3: + return c.applyLookupContext3(tables.SequenceContextFormat3(inner), index) + } + + case tables.ChainedContextualSubs: + switch inner := data.Data.(type) { + case tables.ChainedContextualSubs1: + return c.applyLookupChainedContext1(tables.ChainedSequenceContextFormat1(inner), index) + case tables.ChainedContextualSubs2: + return c.applyLookupChainedContext2(tables.ChainedSequenceContextFormat2(inner), index, glyphID) + case tables.ChainedContextualSubs3: + return c.applyLookupChainedContext3(tables.ChainedSequenceContextFormat3(inner), index) + } + + case tables.ReverseChainSingleSubs: + if c.nestingLevelLeft != maxNestingLevel { + return false // no chaining to this type + } + lB, lL := len(data.BacktrackCoverages), len(data.LookaheadCoverages) + + hasMatch, startIndex := c.matchBacktrack(get1N(&c.indices, 0, lB), matchCoverage(data.BacktrackCoverages)) + if !hasMatch { + return false + } + + hasMatch, endIndex := c.matchLookahead(get1N(&c.indices, 0, lL), matchCoverage(data.LookaheadCoverages), c.buffer.idx+1) + if !hasMatch { + return false + } + + c.buffer.unsafeToBreakFromOutbuffer(startIndex, endIndex) + c.setGlyphClass(GID(data.SubstituteGlyphIDs[index])) + c.buffer.cur(0).Glyph = GID(data.SubstituteGlyphIDs[index]) + // Note: We DON'T decrease buffer.idx. The main loop does it + // for us. This is useful for preventing surprises if someone + // calls us through a Context lookup. + } + + return true +} + +func (c *otApplyContext) applySubsSequence(seq []gID) { + /* Special-case to make it in-place and not consider this + * as a "multiplied" substitution. */ + switch len(seq) { + case 1: + c.replaceGlyph(GID(seq[0])) + case 0: + /* Spec disallows this, but Uniscribe allows it. + * https://github.com/harfbuzz/harfbuzz/issues/253 */ + c.buffer.deleteGlyph() + default: + var klass uint16 + if c.buffer.cur(0).isLigature() { + klass = tables.GPBaseGlyph + } + ligID := c.buffer.cur(0).getLigID() + for i, g := range seq { + // If is attached to a ligature, don't disturb that. + // https://github.com/harfbuzz/harfbuzz/issues/3069 + if ligID == 0 { + c.buffer.cur(0).setLigPropsForMark(0, uint8(i)) + } + c.setGlyphClassExt(GID(g), klass, false, true) + c.buffer.outputGlyphIndex(GID(g)) + } + c.buffer.skipGlyph() + } +} + +func (c *otApplyContext) applySubsAlternate(alternates []gID) bool { + count := uint32(len(alternates)) + if count == 0 { + return false + } + + glyphMask := c.buffer.cur(0).Mask + lookupMask := c.lookupMask + + /* Note: This breaks badly if two features enabled this lookup together. */ + + shift := bits.TrailingZeros32(lookupMask) + altIndex := (lookupMask & glyphMask) >> shift + + /* If altIndex is MAX_VALUE, randomize feature if it is the rand feature. */ + if altIndex == otMapMaxValue && c.random { + // Maybe we can do better than unsafe-to-break all; but since we are + // changing random state, it would be hard to track that. Good 'nough. + c.buffer.unsafeToBreak(0, len(c.buffer.Info)) + altIndex = c.randomNumber()%count + 1 + } + + if altIndex > count || altIndex == 0 { + return false + } + + c.replaceGlyph(GID(alternates[altIndex-1])) + return true +} + +func (c *otApplyContext) applySubsLigature(ligatureSet []tables.Ligature) bool { + for _, lig := range ligatureSet { + count := len(lig.ComponentGlyphIDs) + 1 + + // Special-case to make it in-place and not consider this + // as a "ligated" substitution. + if count == 1 { + c.replaceGlyph(GID(lig.LigatureGlyph)) + return true + } + + var matchPositions [maxContextLength]int + + ok, matchEnd, totalComponentCount := c.matchInput(lig.ComponentGlyphIDs, matchGlyph, &matchPositions) + if !ok { + c.buffer.unsafeToConcat(c.buffer.idx, matchEnd) + continue + } + c.ligateInput(count, matchPositions, matchEnd, lig.LigatureGlyph, totalComponentCount) + + return true + } + return false +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_layout_gsubgpos.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_layout_gsubgpos.go new file mode 100644 index 0000000..e613bdc --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_layout_gsubgpos.go @@ -0,0 +1,1102 @@ +package harfbuzz + +import ( + "fmt" + "math" + + "github.com/go-text/typesetting/font" + "github.com/go-text/typesetting/font/opentype/tables" +) + +// ported from harfbuzz/src/hb-ot-layout-gsubgpos.hh Copyright © 2007,2008,2009,2010 Red Hat, Inc. 2010,2012 Google, Inc. Behdad Esfahbod + +// GSUB or GPOS lookup +type layoutLookup interface { + // accumulate the subtables coverage into the diggest + collectCoverage(*setDigest) + // walk the subtables to add them to the context + dispatchSubtables(*getSubtablesContext) + + // walk the subtables and apply the sub/pos + dispatchApply(ctx *otApplyContext) bool + + Props() uint32 + isReverse() bool +} + +/* + * GSUB/GPOS Common + */ + +const ignoreFlags = otIgnoreBaseGlyphs | otIgnoreLigatures | otIgnoreMarks + +// use a digest to speedup match +type otLayoutLookupAccelerator struct { + lookup layoutLookup + subtables getSubtablesContext + digest setDigest +} + +func (ac *otLayoutLookupAccelerator) init(lookup layoutLookup) { + ac.lookup = lookup + ac.digest = setDigest{} + lookup.collectCoverage(&ac.digest) + ac.subtables = nil + lookup.dispatchSubtables(&ac.subtables) +} + +// apply the subtables and stops at the first success. +func (ac *otLayoutLookupAccelerator) apply(c *otApplyContext) bool { + for _, table := range ac.subtables { + if table.apply(c) { + return true + } + } + return false +} + +// represents one layout subtable, with its own coverage +type applicable struct { + objApply func(c *otApplyContext) bool + + digest setDigest +} + +func newGSUBApplicable(table tables.GSUBLookup) applicable { + ap := applicable{objApply: func(c *otApplyContext) bool { return c.applyGSUB(table) }} + ap.digest.collectCoverage(table.Cov()) + return ap +} + +func newGPOSApplicable(table tables.GPOSLookup) applicable { + ap := applicable{objApply: func(c *otApplyContext) bool { return c.applyGPOS(table) }} + ap.digest.collectCoverage(table.Cov()) + return ap +} + +func (ap applicable) apply(c *otApplyContext) bool { + return ap.digest.mayHave(gID(c.buffer.cur(0).Glyph)) && ap.objApply(c) +} + +type getSubtablesContext []applicable + +// one for GSUB, one for GPOS (known at compile time) +type otProxyMeta struct { + recurseFunc recurseFunc + tableIndex uint8 // 0 for GSUB, 1 for GPOS + inplace bool +} + +var ( + proxyGSUB = otProxyMeta{tableIndex: 0, inplace: false, recurseFunc: applyRecurseGSUB} + proxyGPOS = otProxyMeta{tableIndex: 1, inplace: true, recurseFunc: applyRecurseGPOS} +) + +type otProxy struct { + otProxyMeta + accels []otLayoutLookupAccelerator +} + +type wouldApplyContext struct { + glyphs []GID + indices []uint16 // see get1N + zeroContext bool +} + +// `value` interpretation is dictated by the context +type matcherFunc = func(gid gID, value uint16) bool + +// interprets `value` as a Glyph +func matchGlyph(gid gID, value uint16) bool { return gid == gID(value) } + +// interprets `value` as a Class +func matchClass(class tables.ClassDef) matcherFunc { + return func(gid gID, value uint16) bool { + c, _ := class.Class(gid) + return uint16(c) == value + } +} + +// interprets `value` as an index in coverage array +func matchCoverage(covs []tables.Coverage) matcherFunc { + return func(gid gID, value uint16) bool { + _, covered := covs[value].Index(gid) + return covered + } +} + +const ( + no uint8 = iota + yes + maybe +) + +type otApplyContextMatcher struct { + matchFunc matcherFunc + lookupProps uint32 + mask GlyphMask + ignoreZWNJ bool + ignoreZWJ bool + perSyllable bool + syllable uint8 +} + +func (m *otApplyContextMatcher) setSyllable(syllable uint8) { + if m.perSyllable { + m.syllable = syllable + } else { + m.syllable = 0 + } +} + +func (m otApplyContextMatcher) mayMatch(info *GlyphInfo, glyphData []uint16) uint8 { + if info.Mask&m.mask == 0 || (m.syllable != 0 && m.syllable != info.syllable) { + return no + } + + if m.matchFunc != nil { + if m.matchFunc(gID(info.Glyph), glyphData[0]) { + return yes + } + return no + } + + return maybe +} + +func (m otApplyContextMatcher) maySkip(c *otApplyContext, info *GlyphInfo) uint8 { + if !c.checkGlyphProperty(info, m.lookupProps) { + return yes + } + + if info.isDefaultIgnorableAndNotHidden() && (m.ignoreZWNJ || !info.isZwnj()) && + (m.ignoreZWJ || !info.isZwj()) { + return maybe + } + + return no +} + +type skippingIterator struct { + c *otApplyContext + matcher otApplyContextMatcher + + matchGlyphDataArray []uint16 + matchGlyphDataStart int // start as index in match_glyph_data_array + + idx int + numItems int + end int +} + +func (it *skippingIterator) init(c *otApplyContext, contextMatch bool) { + it.c = c + it.setMatchFunc(nil, nil) + it.matcher.matchFunc = nil + it.matcher.lookupProps = c.lookupProps + /* Ignore ZWNJ if we are matching GPOS, or matching GSUB context and asked to. */ + it.matcher.ignoreZWNJ = c.tableIndex == 1 || (contextMatch && c.autoZWNJ) + /* Ignore ZWJ if we are matching context, or asked to. */ + it.matcher.ignoreZWJ = contextMatch || c.autoZWJ + if contextMatch { + it.matcher.mask = math.MaxUint32 + } else { + it.matcher.mask = c.lookupMask + } + // Per syllable matching is only for GSUB. + it.matcher.perSyllable = c.tableIndex == 0 && c.perSyllable + it.matcher.setSyllable(0) +} + +func (it *skippingIterator) setMatchFunc(matchFunc matcherFunc, glyphData []uint16) { + it.matcher.matchFunc = matchFunc + it.matchGlyphDataArray = glyphData + it.matchGlyphDataStart = 0 +} + +func (it *skippingIterator) reset(startIndex, numItems int) { + it.idx = startIndex + it.numItems = numItems + it.end = len(it.c.buffer.Info) + if startIndex == it.c.buffer.idx { + it.matcher.setSyllable(it.c.buffer.cur(0).syllable) + } else { + it.matcher.setSyllable(0) + } +} + +func (it *skippingIterator) maySkip(info *GlyphInfo) uint8 { return it.matcher.maySkip(it.c, info) } + +type matchRes uint8 + +const ( + match matchRes = iota + notMatch + skip +) + +func (it *skippingIterator) match(info *GlyphInfo) matchRes { + skipR := it.matcher.maySkip(it.c, info) + if skipR == yes { + return skip + } + + matchR := it.matcher.mayMatch(info, it.matchGlyphDataArray[it.matchGlyphDataStart:]) + if matchR == yes || (matchR == maybe && skipR == no) { + return match + } + + if skipR == no { + return notMatch + } + + return skip +} + +func (it *skippingIterator) next() (_ bool, unsafeTo int) { + // The alternate condition below is faster at string boundaries, + // but produces subpar "unsafe-to-concat" values. + stop := it.end - it.numItems + if (it.c.buffer.Flags & ProduceUnsafeToConcat) != 0 { + stop = it.end - 1 + } + + for it.idx < stop { + it.idx++ + info := &it.c.buffer.Info[it.idx] + switch it.match(info) { + case match: + it.numItems-- + if len(it.matchGlyphDataArray) != 0 { + it.matchGlyphDataStart++ + } + return true, 0 + case notMatch: + return false, it.idx + 1 + case skip: + continue + } + } + return false, it.end +} + +func (it *skippingIterator) prev() (_ bool, unsafeFrom int) { + // The alternate condition below is faster at string boundaries, + // but produces subpar "unsafe-to-concat" values. + stop := it.numItems - 1 + if (it.c.buffer.Flags & ProduceUnsafeToConcat) != 0 { + stop = 0 + } + + L := len(it.c.buffer.outInfo) + for it.idx > stop { + it.idx-- + var info *GlyphInfo + if it.idx < L { + info = &it.c.buffer.outInfo[it.idx] + } else { + // we are in "position mode" : outInfo is not used anymore + // in the C implementation, outInfo and info now are sharing the same storage + info = &it.c.buffer.Info[it.idx] + } + + switch it.match(info) { + case match: + it.numItems-- + if len(it.matchGlyphDataArray) != 0 { + it.matchGlyphDataStart++ + } + return true, 0 + case notMatch: + return false, max(1, it.idx) - 1 + case skip: + continue + } + } + return false, 0 +} + +type recurseFunc = func(c *otApplyContext, lookupIndex uint16) bool + +type otApplyContext struct { + font *Font + buffer *Buffer + + recurseFunc recurseFunc + gdef tables.GDEF + varStore tables.ItemVarStore + indices []uint16 // see get1N() + + digest setDigest + + iterContext skippingIterator + iterInput skippingIterator + + nestingLevelLeft int + tableIndex uint8 // 0 for GSUB, 1 for GPOS + lookupMask GlyphMask + lookupProps uint32 + randomState uint32 + lookupIndex uint16 + direction Direction + + hasGlyphClasses bool + autoZWNJ bool + autoZWJ bool + perSyllable bool + newSyllables uint8 // 0xFF for undefined + random bool + + lastBase int // GPOS uses + lastBaseUntil int // GPOS uses +} + +func (c *otApplyContext) reset(tableIndex uint8, font *Font, buffer *Buffer) { + c.font = font + c.buffer = buffer + + c.recurseFunc = nil + c.gdef = font.face.GDEF + c.varStore = c.gdef.ItemVarStore + c.indices = c.indices[:0] + + c.digest = buffer.digest() + + c.nestingLevelLeft = maxNestingLevel + c.tableIndex = tableIndex + c.lookupMask = 1 + c.lookupProps = 0 + c.randomState = 1 + c.lookupIndex = 0 + c.direction = buffer.Props.Direction + + c.hasGlyphClasses = c.gdef.GlyphClassDef != nil + c.autoZWNJ = true + c.autoZWJ = true + c.perSyllable = false + c.newSyllables = 0xFF + c.random = false + + c.lastBase = -1 + c.lastBaseUntil = 0 + + // iterContext + // iterInput + c.initIters() +} + +func (c *otApplyContext) initIters() { + c.iterInput.init(c, false) + c.iterContext.init(c, true) +} + +func (c *otApplyContext) setLookupMask(mask GlyphMask) { + c.lookupMask = mask + c.initIters() +} + +func (c *otApplyContext) setLookupProps(lookupProps uint32) { + c.lookupProps = lookupProps + c.initIters() +} + +func (c *otApplyContext) applyRecurseLookup(lookupIndex uint16, l layoutLookup) bool { + savedLookupProps := c.lookupProps + savedLookupIndex := c.lookupIndex + + c.lookupIndex = lookupIndex + c.setLookupProps(l.Props()) + + ret := l.dispatchApply(c) + + c.lookupIndex = savedLookupIndex + c.setLookupProps(savedLookupProps) + return ret +} + +func (c *otApplyContext) substituteLookup(accel *otLayoutLookupAccelerator) { + c.applyString(proxyGSUB, accel) +} + +func (c *otApplyContext) checkGlyphProperty(info *GlyphInfo, matchProps uint32) bool { + glyphProps := info.glyphProps + + /* Not covered, if, for example, glyph class is ligature and + * matchProps includes LookupFlags::IgnoreLigatures */ + if (glyphProps & uint16(matchProps) & ignoreFlags) != 0 { + return false + } + + if glyphProps&tables.GPMark != 0 { + return c.matchPropertiesMark(info.Glyph, glyphProps, matchProps) + } + + return true +} + +func (c *otApplyContext) matchPropertiesMark(glyph GID, glyphProps uint16, matchProps uint32) bool { + /* If using mark filtering sets, the high uint16 of + * matchProps has the set index. */ + if uint16(matchProps)&font.UseMarkFilteringSet != 0 { + _, has := c.gdef.MarkGlyphSetsDef.Coverages[matchProps>>16].Index(gID(glyph)) + return has + } + + /* The second byte of matchProps has the meaning + * "ignore marks of attachment type different than + * the attachment type specified." */ + if uint16(matchProps)&otMarkAttachmentType != 0 { + return uint16(matchProps)&otMarkAttachmentType == (glyphProps & otMarkAttachmentType) + } + + return true +} + +func (c *otApplyContext) setGlyphClass(glyphIndex GID) { + c.setGlyphClassExt(glyphIndex, 0, false, false) +} + +func (c *otApplyContext) setGlyphClassExt(glyphIndex_ GID, classGuess uint16, ligature, component bool) { + glyphIndex := gID(glyphIndex_) + + c.digest.add(glyphIndex) + + if c.newSyllables != 0xFF { + c.buffer.cur(0).syllable = c.newSyllables + } + + props := c.buffer.cur(0).glyphProps | substituted + if ligature { + props |= ligated + // In the only place that the MULTIPLIED bit is used, Uniscribe + // seems to only care about the "last" transformation between + // Ligature and Multiple substitutions. Ie. if you ligate, expand, + // and ligate again, it forgives the multiplication and acts as + // if only ligation happened. As such, clear MULTIPLIED bit. + props &= ^multiplied + } + if component { + props |= multiplied + } + if c.hasGlyphClasses { + props &= preserve + c.buffer.cur(0).glyphProps = props | c.gdef.GlyphProps(glyphIndex) + } else if classGuess != 0 { + props &= preserve + c.buffer.cur(0).glyphProps = props | classGuess + } else { + c.buffer.cur(0).glyphProps = props + } +} + +func (c *otApplyContext) replaceGlyph(glyphIndex GID) { + c.setGlyphClass(glyphIndex) + c.buffer.replaceGlyphIndex(glyphIndex) +} + +func (c *otApplyContext) randomNumber() uint32 { + /* http://www.cplusplus.com/reference/random/minstd_rand/ */ + c.randomState = c.randomState * 48271 % 2147483647 + return c.randomState +} + +func (c *otApplyContext) applyRuleSet(ruleSet tables.SequenceRuleSet, match matcherFunc) bool { + for _, rule := range ruleSet.SeqRule { + // the first which match is applied + applied := c.contextApplyLookup(rule.InputSequence, rule.SeqLookupRecords, match) + if applied { + return true + } + } + return false +} + +func (c *otApplyContext) applyChainRuleSet(ruleSet tables.ChainedClassSequenceRuleSet, match [3]matcherFunc) bool { + for i, rule := range ruleSet.ChainedSeqRules { + + if debugMode { + fmt.Println("APPLY - chain rule number", i) + } + + b := c.chainContextApplyLookup(rule.BacktrackSequence, rule.InputSequence, rule.LookaheadSequence, rule.SeqLookupRecords, match) + if b { // stop at the first application + return true + } + } + return false +} + +// `input` starts with second glyph (`inputCount` = len(input)+1) +func (c *otApplyContext) contextApplyLookup(input []uint16, lookupRecord []tables.SequenceLookupRecord, lookupContext matcherFunc) bool { + matchEnd := 0 + var matchPositions [maxContextLength]int + hasMatch, matchEnd, _ := c.matchInput(input, lookupContext, &matchPositions) + if hasMatch { + c.buffer.unsafeToBreak(c.buffer.idx, matchEnd) + c.applyLookup(len(input)+1, &matchPositions, lookupRecord, matchEnd) + return true + } else { + c.buffer.unsafeToConcat(c.buffer.idx, matchEnd) + return false + } +} + +// `input` starts with second glyph (`inputCount` = len(input)+1) +// +// lookupsContexts : backtrack, input, lookahead +func (c *otApplyContext) chainContextApplyLookup(backtrack, input, lookahead []uint16, + lookupRecord []tables.SequenceLookupRecord, lookupContexts [3]matcherFunc, +) bool { + var matchPositions [maxContextLength]int + + hasMatch, matchEnd, _ := c.matchInput(input, lookupContexts[1], &matchPositions) + endIndex := matchEnd + if !(hasMatch && endIndex != 0) { + c.buffer.unsafeToConcat(c.buffer.idx, endIndex) + return false + } + + hasMatch, endIndex = c.matchLookahead(lookahead, lookupContexts[2], matchEnd) + if !hasMatch { + c.buffer.unsafeToConcat(c.buffer.idx, endIndex) + return false + } + + hasMatch, startIndex := c.matchBacktrack(backtrack, lookupContexts[0]) + if !hasMatch { + c.buffer.unsafeToConcatFromOutbuffer(startIndex, endIndex) + return false + } + + c.buffer.unsafeToBreakFromOutbuffer(startIndex, endIndex) + c.applyLookup(len(input)+1, &matchPositions, lookupRecord, matchEnd) + return true +} + +func (c *wouldApplyContext) wouldApplyLookupContext1(data tables.SequenceContextFormat1, index int) bool { + if index >= len(data.SeqRuleSet) { // index is not sanitized in tt.Parse + return false + } + ruleSet := data.SeqRuleSet[index] + return c.wouldApplyRuleSet(ruleSet, matchGlyph) +} + +func (c *wouldApplyContext) wouldApplyLookupContext2(data tables.SequenceContextFormat2, index int, glyphID GID) bool { + class, _ := data.ClassDef.Class(gID(glyphID)) + ruleSet := data.ClassSeqRuleSet[class] + return c.wouldApplyRuleSet(ruleSet, matchClass(data.ClassDef)) +} + +func (c *wouldApplyContext) wouldApplyLookupContext3(data tables.SequenceContextFormat3, index int) bool { + covIndices := get1N(&c.indices, 1, len(data.Coverages)) + return c.wouldMatchInput(covIndices, matchCoverage(data.Coverages)) +} + +func (c *wouldApplyContext) wouldApplyRuleSet(ruleSet tables.SequenceRuleSet, match matcherFunc) bool { + for _, rule := range ruleSet.SeqRule { + if c.wouldMatchInput(rule.InputSequence, match) { + return true + } + } + return false +} + +func (c *wouldApplyContext) wouldApplyChainRuleSet(ruleSet tables.ChainedSequenceRuleSet, inputMatch matcherFunc) bool { + for _, rule := range ruleSet.ChainedSeqRules { + if c.wouldApplyChainLookup(rule.BacktrackSequence, rule.InputSequence, rule.LookaheadSequence, inputMatch) { + return true + } + } + return false +} + +func (c *wouldApplyContext) wouldApplyLookupChainedContext1(data tables.ChainedSequenceContextFormat1, index int) bool { + if index >= len(data.ChainedSeqRuleSet) { // index is not sanitized in tt.Parse + return false + } + ruleSet := data.ChainedSeqRuleSet[index] + return c.wouldApplyChainRuleSet(ruleSet, matchGlyph) +} + +func (c *wouldApplyContext) wouldApplyLookupChainedContext2(data tables.ChainedSequenceContextFormat2, index int, glyphID GID) bool { + class, _ := data.InputClassDef.Class(gID(glyphID)) + ruleSet := data.ChainedClassSeqRuleSet[class] + return c.wouldApplyChainRuleSet(ruleSet, matchClass(data.InputClassDef)) +} + +func (c *wouldApplyContext) wouldApplyLookupChainedContext3(data tables.ChainedSequenceContextFormat3, index int) bool { + lB, lI, lL := len(data.BacktrackCoverages), len(data.InputCoverages), len(data.LookaheadCoverages) + return c.wouldApplyChainLookup(get1N(&c.indices, 0, lB), get1N(&c.indices, 1, lI), get1N(&c.indices, 0, lL), + matchCoverage(data.InputCoverages)) +} + +// `input` starts with second glyph (`inputCount` = len(input)+1) +// only the input lookupsContext is needed +func (c *wouldApplyContext) wouldApplyChainLookup(backtrack, input, lookahead []uint16, inputLookupContext matcherFunc) bool { + contextOk := true + if c.zeroContext { + contextOk = len(backtrack) == 0 && len(lookahead) == 0 + } + return contextOk && c.wouldMatchInput(input, inputLookupContext) +} + +// `input` starts with second glyph (`count` = len(input)+1) +func (c *wouldApplyContext) wouldMatchInput(input []uint16, matchFunc matcherFunc) bool { + if len(c.glyphs) != len(input)+1 { + return false + } + + for i, glyph := range input { + if !matchFunc(gID(c.glyphs[i+1]), glyph) { + return false + } + } + + return true +} + +// `input` starts with second glyph (`inputCount` = len(input)+1) +func (c *otApplyContext) matchInput(input []uint16, matchFunc matcherFunc, + matchPositions *[maxContextLength]int, +) (_ bool, endPosition int, totalComponentCount uint8) { + count := len(input) + 1 + if count > maxContextLength { + return false, 0, 0 + } + buffer := c.buffer + skippyIter := &c.iterInput + skippyIter.reset(buffer.idx, count-1) + skippyIter.setMatchFunc(matchFunc, input) + + /* + * This is perhaps the trickiest part of OpenType... Remarks: + * + * - If all components of the ligature were marks, we call this a mark ligature. + * + * - If there is no GDEF, and the ligature is NOT a mark ligature, we categorize + * it as a ligature glyph. + * + * - Ligatures cannot be formed across glyphs attached to different components + * of previous ligatures. Eg. the sequence is LAM,SHADDA,LAM,FATHA,HEH, and + * LAM,LAM,HEH form a ligature, leaving SHADDA,FATHA next to eachother. + * However, it would be wrong to ligate that SHADDA,FATHA sequence. + * There are a couple of exceptions to this: + * + * o If a ligature tries ligating with marks that belong to it itself, go ahead, + * assuming that the font designer knows what they are doing (otherwise it can + * break Indic stuff when a matra wants to ligate with a conjunct, + * + * o If two marks want to ligate and they belong to different components of the + * same ligature glyph, and said ligature glyph is to be ignored according to + * mark-filtering rules, then allow. + * https://github.com/harfbuzz/harfbuzz/issues/545 + */ + + firstLigID := buffer.cur(0).getLigID() + firstLigComp := buffer.cur(0).getLigComp() + + const ( + ligbaseNotChecked = iota + ligbaseMayNotSkip + ligbaseMaySkip + ) + ligbase := ligbaseNotChecked + for i := 1; i < count; i++ { + if ok, unsafeTo := skippyIter.next(); !ok { + return false, unsafeTo, 0 + } + + matchPositions[i] = skippyIter.idx + + thisLigID := buffer.Info[skippyIter.idx].getLigID() + thisLigComp := buffer.Info[skippyIter.idx].getLigComp() + if firstLigID != 0 && firstLigComp != 0 { + /* If first component was attached to a previous ligature component, + * all subsequent components should be attached to the same ligature + * component, otherwise we shouldn't ligate them... */ + if firstLigID != thisLigID || firstLigComp != thisLigComp { + /* ...unless, we are attached to a base ligature and that base + * ligature is ignorable. */ + if ligbase == ligbaseNotChecked { + found := false + out := buffer.outInfo + j := len(out) + for j != 0 && out[j-1].getLigID() == firstLigID { + if out[j-1].getLigComp() == 0 { + j-- + found = true + break + } + j-- + } + + if found && skippyIter.maySkip(&out[j]) == yes { + ligbase = ligbaseMaySkip + } else { + ligbase = ligbaseMayNotSkip + } + } + + if ligbase == ligbaseMayNotSkip { + return false, 0, 0 + } + } + } else { + /* If first component was NOT attached to a previous ligature component, + * all subsequent components should also NOT be attached to any ligature + * component, unless they are attached to the first component itself! */ + if thisLigID != 0 && thisLigComp != 0 && (thisLigID != firstLigID) { + return false, 0, 0 + } + } + + totalComponentCount += buffer.Info[skippyIter.idx].getLigNumComps() + } + + endPosition = skippyIter.idx + 1 + totalComponentCount += buffer.cur(0).getLigNumComps() + matchPositions[0] = buffer.idx + + return true, endPosition, totalComponentCount +} + +// `count` and `matchPositions` include the first glyph +func (c *otApplyContext) ligateInput(count int, matchPositions [maxContextLength]int, + matchEnd int, ligGlyph gID, totalComponentCount uint8, +) { + buffer := c.buffer + + buffer.mergeClusters(buffer.idx, matchEnd) + + /* - If a base and one or more marks ligate, consider that as a base, NOT + * ligature, such that all following marks can still attach to it. + * https://github.com/harfbuzz/harfbuzz/issues/1109 + * + * - If all components of the ligature were marks, we call this a mark ligature. + * If it *is* a mark ligature, we don't allocate a new ligature id, and leave + * the ligature to keep its old ligature id. This will allow it to attach to + * a base ligature in GPOS. Eg. if the sequence is: LAM,LAM,SHADDA,FATHA,HEH, + * and LAM,LAM,HEH for a ligature, they will leave SHADDA and FATHA with a + * ligature id and component value of 2. Then if SHADDA,FATHA form a ligature + * later, we don't want them to lose their ligature id/component, otherwise + * GPOS will fail to correctly position the mark ligature on top of the + * LAM,LAM,HEH ligature. See: + * https://bugzilla.gnome.org/show_bug.cgi?id=676343 + * + * - If a ligature is formed of components that some of which are also ligatures + * themselves, and those ligature components had marks attached to *their* + * components, we have to attach the marks to the new ligature component + * positions! Now *that*'s tricky! And these marks may be following the + * last component of the whole sequence, so we should loop forward looking + * for them and update them. + * + * Eg. the sequence is LAM,LAM,SHADDA,FATHA,HEH, and the font first forms a + * 'calt' ligature of LAM,HEH, leaving the SHADDA and FATHA with a ligature + * id and component == 1. Now, during 'liga', the LAM and the LAM-HEH ligature + * form a LAM-LAM-HEH ligature. We need to reassign the SHADDA and FATHA to + * the new ligature with a component value of 2. + * + * This in fact happened to a font... See: + * https://bugzilla.gnome.org/show_bug.cgi?id=437633 + */ + + isBaseLigature := buffer.Info[matchPositions[0]].isBaseGlyph() + isMarkLigature := buffer.Info[matchPositions[0]].isMark() + for i := 1; i < count; i++ { + if !buffer.Info[matchPositions[i]].isMark() { + isBaseLigature = false + isMarkLigature = false + break + } + } + isLigature := !isBaseLigature && !isMarkLigature + + klass, ligID := uint16(0), uint8(0) + if isLigature { + klass = tables.GPLigature + ligID = buffer.allocateLigID() + } + lastLigID := buffer.cur(0).getLigID() + lastNumComponents := buffer.cur(0).getLigNumComps() + componentsSoFar := lastNumComponents + + if isLigature { + buffer.cur(0).setLigPropsForLigature(ligID, totalComponentCount) + if buffer.cur(0).unicode.generalCategory() == nonSpacingMark { + buffer.cur(0).setGeneralCategory(otherLetter) + } + } + + // ReplaceGlyph_with_ligature + c.setGlyphClassExt(GID(ligGlyph), klass, true, false) + buffer.replaceGlyphIndex(GID(ligGlyph)) + + for i := 1; i < count; i++ { + for buffer.idx < matchPositions[i] { + if isLigature { + thisComp := buffer.cur(0).getLigComp() + if thisComp == 0 { + thisComp = lastNumComponents + } + newLigComp := componentsSoFar - lastNumComponents + + min8(thisComp, lastNumComponents) + buffer.cur(0).setLigPropsForMark(ligID, newLigComp) + } + buffer.nextGlyph() + } + + lastLigID = buffer.cur(0).getLigID() + lastNumComponents = buffer.cur(0).getLigNumComps() + componentsSoFar += lastNumComponents + + /* Skip the base glyph */ + buffer.skipGlyph() + } + + if !isMarkLigature && lastLigID != 0 { + /* Re-adjust components for any marks following. */ + for i := buffer.idx; i < len(buffer.Info); i++ { + if lastLigID != buffer.Info[i].getLigID() { + break + } + + thisComp := buffer.Info[i].getLigComp() + if thisComp == 0 { + break + } + + newLigComp := componentsSoFar - lastNumComponents + + min8(thisComp, lastNumComponents) + buffer.Info[i].setLigPropsForMark(ligID, newLigComp) + } + } +} + +func (c *otApplyContext) recurse(subLookupIndex uint16) bool { + if c.nestingLevelLeft == 0 || c.recurseFunc == nil || c.buffer.maxOps <= 0 { + if c.buffer.maxOps <= 0 { + c.buffer.maxOps-- + return false + } + c.buffer.maxOps-- + } + + c.nestingLevelLeft-- + ret := c.recurseFunc(c, subLookupIndex) + c.nestingLevelLeft++ + return ret +} + +// `count` and `matchPositions` include the first glyph +// `lookupRecord` is in design order +func (c *otApplyContext) applyLookup(count int, matchPositions *[maxContextLength]int, + lookupRecord []tables.SequenceLookupRecord, matchLength int, +) { + buffer := c.buffer + var end int + + /* All positions are distance from beginning of *output* buffer. + * Adjust. */ + { + bl := buffer.backtrackLen() + end = bl + matchLength - buffer.idx + + delta := bl - buffer.idx + /* Convert positions to new indexing. */ + for j := 0; j < count; j++ { + matchPositions[j] += delta + } + } + + for _, lk := range lookupRecord { + idx := int(lk.SequenceIndex) + if idx >= count { // invalid, ignored + continue + } + + origLen := buffer.backtrackLen() + buffer.lookaheadLen() + + // This can happen if earlier recursed lookups deleted many entries. + if matchPositions[idx] >= origLen { + continue + } + + buffer.moveTo(matchPositions[idx]) + + if buffer.maxOps <= 0 { + break + } + + if debugMode { + fmt.Printf("\t\tAPPLY nested lookup %d\n", lk.LookupListIndex) + } + + if !c.recurse(lk.LookupListIndex) { + continue + } + + newLen := buffer.backtrackLen() + buffer.lookaheadLen() + delta := newLen - origLen + + if delta == 0 { + continue + } + + // Recursed lookup changed buffer len. Adjust. + // + // TODO: + // + // Right now, if buffer length increased by n, we assume n new glyphs + // were added right after the current position, and if buffer length + // was decreased by n, we assume n match positions after the current + // one where removed. The former (buffer length increased) case is + // fine, but the decrease case can be improved in at least two ways, + // both of which are significant: + // + // - If recursed-to lookup is MultipleSubst and buffer length + // decreased, then it's current match position that was deleted, + // NOT the one after it. + // + // - If buffer length was decreased by n, it does not necessarily + // mean that n match positions where removed, as there recursed-to + // lookup might had a different LookupFlag. Here's a constructed + // case of that: + // https://github.com/harfbuzz/harfbuzz/discussions/3538 + // + // It should be possible to construct tests for both of these cases. + // + end += delta + if end < int(matchPositions[idx]) { + // End might end up being smaller than match_positions[idx] if the recursed + // lookup ended up removing many items. + // Just never rewind end beyond start of current position, since that is + // not possible in the recursed lookup. Also adjust delta as such. + // + // https://bugs.chromium.org/p/chromium/issues/detail?id=659496 + // https://github.com/harfbuzz/harfbuzz/issues/1611 + // + delta += matchPositions[idx] - end + end = matchPositions[idx] + } + + next := idx + 1 // next now is the position after the recursed lookup. + + if delta > 0 { + if delta+count > maxContextLength { + break + } + } else { + /* NOTE: delta is negative. */ + delta = max(delta, int(next)-int(count)) + next -= delta + } + + /* Shift! */ + copy(matchPositions[next+delta:], matchPositions[next:count]) + next += delta + count += delta + + /* Fill in new entries. */ + for j := idx + 1; j < next; j++ { + matchPositions[j] = matchPositions[j-1] + 1 + } + + /* And fixup the rest. */ + for ; next < count; next++ { + matchPositions[next] += delta + } + + } + + buffer.moveTo(end) +} + +func (c *otApplyContext) matchBacktrack(backtrack []uint16, matchFunc matcherFunc) (_ bool, matchStart int) { + skippyIter := &c.iterContext + skippyIter.reset(c.buffer.backtrackLen(), len(backtrack)) + skippyIter.setMatchFunc(matchFunc, backtrack) + + for i := 0; i < len(backtrack); i++ { + if ok, unsafeFrom := skippyIter.prev(); !ok { + return false, unsafeFrom + } + } + + return true, skippyIter.idx +} + +func (c *otApplyContext) matchLookahead(lookahead []uint16, matchFunc matcherFunc, startIndex int) (_ bool, endIndex int) { + skippyIter := &c.iterContext + skippyIter.reset(startIndex-1, len(lookahead)) + skippyIter.setMatchFunc(matchFunc, lookahead) + + for i := 0; i < len(lookahead); i++ { + if ok, unsafeTo := skippyIter.next(); !ok { + return false, unsafeTo + } + } + + return true, skippyIter.idx + 1 +} + +func (c *otApplyContext) applyLookupContext1(data tables.SequenceContextFormat1, index int) bool { + if index >= len(data.SeqRuleSet) { // index is not sanitized in tt.Parse + return false + } + ruleSet := data.SeqRuleSet[index] + return c.applyRuleSet(ruleSet, matchGlyph) +} + +func (c *otApplyContext) applyLookupContext2(data tables.SequenceContextFormat2, index int, glyphID GID) bool { + class, _ := data.ClassDef.Class(gID(glyphID)) + var ruleSet tables.SequenceRuleSet + if int(class) < len(data.ClassSeqRuleSet) { + ruleSet = data.ClassSeqRuleSet[class] + } + return c.applyRuleSet(ruleSet, matchClass(data.ClassDef)) +} + +// return a slice containing [start, start+1, ..., end-1], +// using `indices` as an internal buffer to avoid allocations +// these indices are used to refer to coverage +func get1N(indices *[]uint16, start, end int) []uint16 { + if end > cap(*indices) { + *indices = make([]uint16, end) + for i := range *indices { + (*indices)[i] = uint16(i) + } + } + return (*indices)[start:end] +} + +func (c *otApplyContext) applyLookupContext3(data tables.SequenceContextFormat3, index int) bool { + covIndices := get1N(&c.indices, 1, len(data.Coverages)) + return c.contextApplyLookup(covIndices, data.SeqLookupRecords, matchCoverage(data.Coverages)) +} + +func (c *otApplyContext) applyLookupChainedContext1(data tables.ChainedSequenceContextFormat1, index int) bool { + if index >= len(data.ChainedSeqRuleSet) { // index is not sanitized in tt.Parse + return false + } + ruleSet := data.ChainedSeqRuleSet[index] + return c.applyChainRuleSet(ruleSet, [3]matcherFunc{matchGlyph, matchGlyph, matchGlyph}) +} + +func (c *otApplyContext) applyLookupChainedContext2(data tables.ChainedSequenceContextFormat2, index int, glyphID GID) bool { + class, _ := data.InputClassDef.Class(gID(glyphID)) + var ruleSet tables.ChainedClassSequenceRuleSet + if int(class) < len(data.ChainedClassSeqRuleSet) { + ruleSet = data.ChainedClassSeqRuleSet[class] + } + return c.applyChainRuleSet(ruleSet, [3]matcherFunc{ + matchClass(data.BacktrackClassDef), matchClass(data.InputClassDef), matchClass(data.LookaheadClassDef), + }) +} + +func (c *otApplyContext) applyLookupChainedContext3(data tables.ChainedSequenceContextFormat3, index int) bool { + lB, lI, lL := len(data.BacktrackCoverages), len(data.InputCoverages), len(data.LookaheadCoverages) + return c.chainContextApplyLookup(get1N(&c.indices, 0, lB), get1N(&c.indices, 1, lI), get1N(&c.indices, 0, lL), + data.SeqLookupRecords, [3]matcherFunc{ + matchCoverage(data.BacktrackCoverages), matchCoverage(data.InputCoverages), matchCoverage(data.LookaheadCoverages), + }) +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_map.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_map.go new file mode 100644 index 0000000..c63a0c5 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_map.go @@ -0,0 +1,550 @@ +package harfbuzz + +import ( + "fmt" + "math" + "math/bits" + "sort" + + "github.com/go-text/typesetting/font" + ot "github.com/go-text/typesetting/font/opentype" + "github.com/go-text/typesetting/font/opentype/tables" +) + +// ported from harfbuzz/src/hb-ot-map.cc, hb-ot-map.hh Copyright © 2009,2010 Red Hat, Inc. 2010,2011,2013 Google, Inc. Behdad Esfahbod + +type otMapFeatureFlags uint8 + +const ( + ffGLOBAL otMapFeatureFlags = 1 << iota /* Feature applies to all characters; results in no mask allocated for it. */ + ffHasFallback /* Has fallback implementation, so include mask bit even if feature not found. */ + ffManualZWNJ /* Don't skip over ZWNJ when matching **context**. */ + ffManualZWJ /* Don't skip over ZWJ when matching **input**. */ + ffGlobalSearch /* If feature not found in LangSys, look for it in global feature list and pick one. */ + ffRandom /* Randomly select a glyph from an AlternateSubstFormat1 subtable. */ + ffPerSyllable /* Contain lookup application to within syllable. */ + + ffNone otMapFeatureFlags = 0 + ffManualJoiners = ffManualZWNJ | ffManualZWJ + ffGlobalManualJoiners = ffGLOBAL | ffManualJoiners + ffGlobalHasFallback = ffGLOBAL | ffHasFallback +) + +const ( + otMapMaxBits = 8 + otMapMaxValue = (1 << otMapMaxBits) - 1 +) + +type otMapFeature struct { + tag tables.Tag + flags otMapFeatureFlags +} + +type featureInfo struct { + Tag tables.Tag + // seq int /* sequence#, used for stable sorting only */ + maxValue uint32 + flags otMapFeatureFlags + defaultValue uint32 /* for non-global features, what should the unset glyphs take */ + stage [2]int /* GSUB/GPOS */ +} + +type stageInfo struct { + pauseFunc pauseFunc + index int +} + +type otMapBuilder struct { + tables *font.Font + props SegmentProperties + stages [2][]stageInfo + featureInfos []featureInfo + scriptIndex [2]int + languageIndex [2]int + currentStage [2]int + chosenScript [2]tables.Tag + foundScript [2]bool +} + +func newOtMapBuilder(tables *font.Font, props SegmentProperties) otMapBuilder { + var out otMapBuilder + + out.tables = tables + out.props = props + + /* Fetch script/language indices for GSUB/GPOS. We need these later to skip + * features not available in either table and not waste precious bits for them. */ + scriptTags, languageTags := newOTTagsFromScriptAndLanguage(props.Script, props.Language) + + out.scriptIndex[0], out.chosenScript[0], out.foundScript[0] = selectScript(&tables.GSUB.Layout, scriptTags) + out.languageIndex[0], _ = selectLanguage(&tables.GSUB.Layout, out.scriptIndex[0], languageTags) + + out.scriptIndex[1], out.chosenScript[1], out.foundScript[1] = selectScript(&tables.GPOS.Layout, scriptTags) + out.languageIndex[1], _ = selectLanguage(&tables.GPOS.Layout, out.scriptIndex[1], languageTags) + + return out +} + +func (mb *otMapBuilder) addFeatureExt(tag tables.Tag, flags otMapFeatureFlags, value uint32) { + var info featureInfo + info.Tag = tag + info.maxValue = value + info.flags = flags + if (flags & ffGLOBAL) != 0 { + info.defaultValue = value + } + info.stage = mb.currentStage + + mb.featureInfos = append(mb.featureInfos, info) +} + +// Pause functions return true if new glyph indices might have been +// added to the buffer. This is used to update buffer digest. +type pauseFunc func(plan *otShapePlan, font *Font, buffer *Buffer) bool + +func (mb *otMapBuilder) addPause(tableIndex int, fn pauseFunc) { + s := stageInfo{ + index: mb.currentStage[tableIndex], + pauseFunc: fn, + } + mb.stages[tableIndex] = append(mb.stages[tableIndex], s) + mb.currentStage[tableIndex]++ +} + +func (mb *otMapBuilder) addGSUBPause(fn pauseFunc) { mb.addPause(0, fn) } +func (mb *otMapBuilder) addGPOSPause(fn pauseFunc) { mb.addPause(1, fn) } + +func (mb *otMapBuilder) enableFeatureExt(tag tables.Tag, flags otMapFeatureFlags, value uint32) { + mb.addFeatureExt(tag, ffGLOBAL|flags, value) +} + +// shortand for enableFeatureExt(tag, None, 1) +func (mb *otMapBuilder) enableFeature(tag tables.Tag) { mb.enableFeatureExt(tag, ffNone, 1) } +func (mb *otMapBuilder) addFeature(tag tables.Tag) { mb.addFeatureExt(tag, ffNone, 1) } +func (mb *otMapBuilder) disableFeature(tag tables.Tag) { mb.addFeatureExt(tag, ffGLOBAL, 0) } + +func (mb *otMapBuilder) compile(m *otMap, key otShapePlanKey) { + const globalBitShift = 8*4 - 1 + const globalBitMask = 1 << globalBitShift + + m.globalMask = globalBitMask + + var ( + requiredFeatureIndex [2]uint16 // HB_OT_LAYOUT_NO_FEATURE_INDEX for empty + requiredFeatureTag [2]tables.Tag + /* We default to applying required feature in stage 0. If the required + * feature has a tag that is known to the shaper, we apply the required feature + * in the stage for that tag. */ + requiredFeatureStage [2]int + ) + + gsub, gpos := mb.tables.GSUB, mb.tables.GPOS + tables := [2]*font.Layout{&gsub.Layout, &gpos.Layout} + + m.chosenScript = mb.chosenScript + m.foundScript = mb.foundScript + requiredFeatureIndex[0], requiredFeatureTag[0] = getRequiredFeature(tables[0], mb.scriptIndex[0], mb.languageIndex[0]) + requiredFeatureIndex[1], requiredFeatureTag[1] = getRequiredFeature(tables[1], mb.scriptIndex[1], mb.languageIndex[1]) + + // sort features and merge duplicates + if len(mb.featureInfos) != 0 { + sort.SliceStable(mb.featureInfos, func(i, j int) bool { + return mb.featureInfos[i].Tag < mb.featureInfos[j].Tag + }) + j := 0 + for i, feat := range mb.featureInfos { + if i == 0 { + continue + } + if feat.Tag != mb.featureInfos[j].Tag { + j++ + mb.featureInfos[j] = feat + continue + } + if feat.flags&ffGLOBAL != 0 { + mb.featureInfos[j].flags |= ffGLOBAL + mb.featureInfos[j].maxValue = feat.maxValue + mb.featureInfos[j].defaultValue = feat.defaultValue + } else { + if mb.featureInfos[j].flags&ffGLOBAL != 0 { + mb.featureInfos[j].flags ^= ffGLOBAL + } + mb.featureInfos[j].maxValue = max32(mb.featureInfos[j].maxValue, feat.maxValue) + // inherit default_value from j + } + mb.featureInfos[j].flags |= (feat.flags & ffHasFallback) + mb.featureInfos[j].stage[0] = min(mb.featureInfos[j].stage[0], feat.stage[0]) + mb.featureInfos[j].stage[1] = min(mb.featureInfos[j].stage[1], feat.stage[1]) + } + mb.featureInfos = mb.featureInfos[0 : j+1] + } + + // allocate bits now + nextBit := bits.OnesCount32(glyphFlagDefined) + 1 + + for _, info := range mb.featureInfos { + + bitsNeeded := 0 + + if (info.flags&ffGLOBAL) != 0 && info.maxValue == 1 { + // uses the global bit + bitsNeeded = 0 + } else { + // limit bits per feature. + bitsNeeded = min(otMapMaxBits, bitStorage(info.maxValue)) + } + + if info.maxValue == 0 || nextBit+bitsNeeded >= globalBitShift { + continue // feature disabled, or not enough bits. + } + + var ( + found = false + featureIndex [2]uint16 + ) + for tableIndex, table := range tables { + if requiredFeatureTag[tableIndex] == info.Tag { + requiredFeatureStage[tableIndex] = info.stage[tableIndex] + } + featureIndex[tableIndex] = findFeatureForLang(table, mb.scriptIndex[tableIndex], mb.languageIndex[tableIndex], info.Tag) + found = found || featureIndex[tableIndex] != NoFeatureIndex + } + if !found && (info.flags&ffGlobalSearch) != 0 { + for tableIndex, table := range tables { + featureIndex[tableIndex] = findFeature(table, info.Tag) + found = found || featureIndex[tableIndex] != NoFeatureIndex + } + } + if !found && info.flags&ffHasFallback == 0 { + continue + } + + var map_ featureMap + map_.tag = info.Tag + map_.index = featureIndex + map_.stage = info.stage + map_.autoZWNJ = info.flags&ffManualZWNJ == 0 + map_.autoZWJ = info.flags&ffManualZWJ == 0 + map_.random = info.flags&ffRandom != 0 + map_.perSyllable = info.flags&ffPerSyllable != 0 + if (info.flags&ffGLOBAL) != 0 && info.maxValue == 1 { + // uses the global bit + map_.shift = globalBitShift + map_.mask = globalBitMask + } else { + map_.shift = nextBit + map_.mask = (1 << (nextBit + bitsNeeded)) - (1 << nextBit) + nextBit += bitsNeeded + m.globalMask |= (info.defaultValue << map_.shift) & map_.mask + } + map_.mask1 = (1 << map_.shift) & map_.mask + map_.needsFallback = !found + + if debugMode { + fmt.Printf("\tMAP - adding feature %s (%d) for stage %v\n", info.Tag, info.Tag, info.stage) + } + + m.features = append(m.features, map_) + } + mb.featureInfos = mb.featureInfos[:0] // done with these + + mb.addGSUBPause(nil) + mb.addGPOSPause(nil) + + // collect lookup indices for features + for tableIndex, table := range tables { + // Collect lookup indices for features + stageIndex := 0 + lastNumLookups := 0 + for stage := 0; stage < mb.currentStage[tableIndex]; stage++ { + if requiredFeatureIndex[tableIndex] != NoFeatureIndex && + requiredFeatureStage[tableIndex] == stage { + const emptyTag = 0x20202020 // (" ") + m.addLookups(table, tableIndex, requiredFeatureIndex[tableIndex], + key[tableIndex], globalBitMask, true, true, false, false, emptyTag) + } + + for _, feat := range m.features { + if feat.stage[tableIndex] == stage { + m.addLookups(table, tableIndex, + feat.index[tableIndex], + key[tableIndex], + feat.mask, + feat.autoZWNJ, + feat.autoZWJ, + feat.random, + feat.perSyllable, + feat.tag, + ) + } + } + // sort lookups and merge duplicates + + if ls := m.lookups[tableIndex]; lastNumLookups < len(ls) { + view := ls[lastNumLookups:] + sort.Slice(view, func(i, j int) bool { return view[i].index < view[j].index }) + + j := lastNumLookups + for i := j + 1; i < len(ls); i++ { + if ls[i].index != ls[j].index { + j++ + ls[j] = ls[i] + } else { + ls[j].mask |= ls[i].mask + ls[j].autoZWNJ = ls[j].autoZWNJ && ls[i].autoZWNJ + ls[j].autoZWJ = ls[j].autoZWJ && ls[i].autoZWJ + } + } + m.lookups[tableIndex] = ls[:j+1] + } + + lastNumLookups = len(m.lookups[tableIndex]) + + if stageIndex < len(mb.stages[tableIndex]) && mb.stages[tableIndex][stageIndex].index == stage { + sm := stageMap{ + lastLookup: lastNumLookups, + pauseFunc: mb.stages[tableIndex][stageIndex].pauseFunc, + } + m.stages[tableIndex] = append(m.stages[tableIndex], sm) + stageIndex++ + } + } + } +} + +func (mb *otMapBuilder) hasFeature(tag ot.Tag) bool { + tables := [2]*font.Layout{&mb.tables.GSUB.Layout, &mb.tables.GPOS.Layout} + + for tableIndex, table := range tables { + if findFeatureForLang(table, mb.scriptIndex[tableIndex], mb.languageIndex[tableIndex], tag) != NoFeatureIndex { + return true + } + } + return false +} + +type featureMap struct { + tag tables.Tag /* should be first for our bsearch to work */ + index [2]uint16 /* GSUB/GPOS */ + stage [2]int /* GSUB/GPOS */ + shift int + mask GlyphMask + mask1 GlyphMask /* mask for value=1, for quick access */ + needsFallback bool // = 1; + autoZWNJ bool // = 1; + autoZWJ bool // = 1; + random bool // = 1; + perSyllable bool +} + +// by tag +func bsearchFeature(features []featureMap, tag tables.Tag) *featureMap { + low, high := 0, len(features) + for low < high { + mid := low + (high-low)/2 // avoid overflow when computing mid + p := features[mid].tag + if tag < p { + high = mid + } else if tag > p { + low = mid + 1 + } else { + return &features[mid] + } + } + return nil +} + +type lookupMap struct { + index uint16 + autoZWNJ bool // = 1; + autoZWJ bool // = 1; + random bool // = 1; + perSyllable bool + featureTag ot.Tag + mask GlyphMask + + // HB_INTERNAL static int cmp (const void *pa, const void *pb) + // { + // const lookup_map_t *a = (const lookup_map_t *) pa; + // const lookup_map_t *b = (const lookup_map_t *) pb; + // return a.index < b.index ? -1 : a.index > b.index ? 1 : 0; + // } +} + +type stageMap struct { + pauseFunc pauseFunc + lastLookup int +} + +type otMap struct { + lookups [2][]lookupMap + stages [2][]stageMap + features []featureMap // sorted + chosenScript [2]tables.Tag + globalMask GlyphMask + foundScript [2]bool + + applyContext otApplyContext // buffer +} + +func (m *otMap) needsFallback(featureTag tables.Tag) bool { + if ma := bsearchFeature(m.features, featureTag); ma != nil { + return ma.needsFallback + } + return false +} + +func (m *otMap) getMask(featureTag tables.Tag) (GlyphMask, int) { + if ma := bsearchFeature(m.features, featureTag); ma != nil { + return ma.mask, ma.shift + } + return 0, 0 +} + +func (m *otMap) getMask1(featureTag tables.Tag) GlyphMask { + if ma := bsearchFeature(m.features, featureTag); ma != nil { + return ma.mask1 + } + return 0 +} + +func (m *otMap) getFeatureIndex(tableIndex int, featureTag tables.Tag) uint16 { + if ma := bsearchFeature(m.features, featureTag); ma != nil { + return ma.index[tableIndex] + } + return NoFeatureIndex +} + +func (m *otMap) getFeatureStage(tableIndex int, featureTag tables.Tag) int { + if ma := bsearchFeature(m.features, featureTag); ma != nil { + return ma.stage[tableIndex] + } + return math.MaxInt32 +} + +func (m *otMap) getStageLookups(tableIndex, stage int) []lookupMap { + if stage > len(m.stages[tableIndex]) { + return nil + } + start, end := 0, len(m.lookups[tableIndex]) + if stage != 0 { + start = m.stages[tableIndex][stage-1].lastLookup + } + if stage < len(m.stages[tableIndex]) { + end = m.stages[tableIndex][stage].lastLookup + } + return m.lookups[tableIndex][start:end] +} + +func (m *otMap) addLookups(table *font.Layout, tableIndex int, featureIndex uint16, variationsIndex int, + mask GlyphMask, autoZwnj, autoZwj, random, perSyllable bool, featureTag ot.Tag, +) { + lookupIndices := getFeatureLookupsWithVar(table, featureIndex, variationsIndex) + for _, lookupInd := range lookupIndices { + lookup := lookupMap{ + mask: mask, + index: lookupInd, + autoZWNJ: autoZwnj, + autoZWJ: autoZwj, + random: random, + perSyllable: perSyllable, + featureTag: featureTag, + } + m.lookups[tableIndex] = append(m.lookups[tableIndex], lookup) + } +} + +// apply the GSUB table +func (m *otMap) substitute(plan *otShapePlan, font *Font, buffer *Buffer) { + if debugMode { + fmt.Println("SUBSTITUTE - start table GSUB") + } + + proxy := otProxy{otProxyMeta: proxyGSUB, accels: font.gsubAccels} + m.apply(proxy, plan, font, buffer) + + if debugMode { + fmt.Println("SUBSTITUTE - end table GSUB") + } +} + +// apply the GPOS table +func (m *otMap) position(plan *otShapePlan, font *Font, buffer *Buffer) { + if debugMode { + fmt.Println("POSITION - start table GPOS") + } + + proxy := otProxy{otProxyMeta: proxyGPOS, accels: font.gposAccels} + m.apply(proxy, plan, font, buffer) + + if debugMode { + fmt.Println("POSITION - end table GPOS") + } +} + +func (m *otMap) apply(proxy otProxy, plan *otShapePlan, font *Font, buffer *Buffer) { + tableIndex := proxy.tableIndex + i := 0 + c := &m.applyContext + + c.reset(tableIndex, font, buffer) + c.recurseFunc = proxy.recurseFunc + + for stageI, stage := range m.stages[tableIndex] { + + if debugMode { + fmt.Printf("\tAPPLY - stage %d\n", stageI) + } + + for ; i < stage.lastLookup; i++ { + lookup := m.lookups[tableIndex][i] + lookupIndex := lookup.index + + if debugMode { + fmt.Printf("\t\tLookup %d start\n", lookupIndex) + } + + // c.digest is a digest of all the current glyphs in the buffer + // (plus some past glyphs). + // + // Only try applying the lookup if there is any overlap. */ + accel := &proxy.accels[lookupIndex] + if accel.digest.mayHaveDigest(c.digest) { + + c.lookupIndex = lookupIndex + c.lookupMask = lookup.mask + c.autoZWJ = lookup.autoZWJ + c.autoZWNJ = lookup.autoZWNJ + c.random = lookup.random + c.perSyllable = lookup.perSyllable + + // pathological cases + if len(c.buffer.Info) > c.buffer.maxLen { + return + } + c.applyString(proxy.otProxyMeta, accel) + } + + if debugMode { + fmt.Print("\t\tLookup end : ") + if proxy.tableIndex == 0 { + fmt.Println(c.buffer.Info) + } else { + fmt.Println(c.buffer.Pos) + } + } + + } + + if stage.pauseFunc != nil { + if debugMode { + fmt.Println("\t\tExecuting pause function") + } + + if stage.pauseFunc(plan, font, buffer) { + // Refresh working buffer digest since buffer changed. + c.digest = buffer.digest() + } + } + } +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_myanmar.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_myanmar.go new file mode 100644 index 0000000..c3b2b56 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_myanmar.go @@ -0,0 +1,265 @@ +package harfbuzz + +import ( + "fmt" + + ot "github.com/go-text/typesetting/font/opentype" + "github.com/go-text/typesetting/font/opentype/tables" +) + +// ported from harfbuzz/src/hb-ot-shape-complex-myanmar.cc, .hh Copyright © 2011,2012,2013 Google, Inc. Behdad Esfahbod + +// Myanmar shaper. +type complexShaperMyanmar struct { + complexShaperNil +} + +var _ otComplexShaper = complexShaperMyanmar{} + +func setMyanmarProperties(info *GlyphInfo) { + u := info.codepoint + type_ := indicGetCategories(u) + cat := uint8(type_ & 0xFF) + // pos := uint8(type_ >> 8) + + info.complexCategory = cat + // info.complexAux = pos +} + +/* Note: + * + * We treat Vowels and placeholders as if they were consonants. This is safe because Vowels + * cannot happen in a consonant syllable. The plus side however is, we can call the + * consonant syllable logic from the vowel syllable function and get it all right! + * + * Keep in sync with consonant_categories in the generator. */ +const consonantFlagsMyanmar = (1 << myaSM_ex_C) | 1< 0; _nacts-- { + _acts++ + switch _myaSM_actions[_acts-1] { + case 1: + ts = p + + } + } + + _keys = int(_myaSM_key_offsets[cs]) + _trans = int(_myaSM_index_offsets[cs]) + + _klen = int(_myaSM_single_lengths[cs]) + if _klen > 0 { + _lower := int(_keys) + var _mid int + _upper := int(_keys + _klen - 1) + for { + if _upper < _lower { + break + } + + _mid = _lower + ((_upper - _lower) >> 1) + switch { + case (info[p].complexCategory) < _myaSM_trans_keys[_mid]: + _upper = _mid - 1 + case (info[p].complexCategory) > _myaSM_trans_keys[_mid]: + _lower = _mid + 1 + default: + _trans += int(_mid - int(_keys)) + goto _match + } + } + _keys += _klen + _trans += _klen + } + + _klen = int(_myaSM_range_lengths[cs]) + if _klen > 0 { + _lower := int(_keys) + var _mid int + _upper := int(_keys + (_klen << 1) - 2) + for { + if _upper < _lower { + break + } + + _mid = _lower + (((_upper - _lower) >> 1) & ^1) + switch { + case (info[p].complexCategory) < _myaSM_trans_keys[_mid]: + _upper = _mid - 2 + case (info[p].complexCategory) > _myaSM_trans_keys[_mid+1]: + _lower = _mid + 2 + default: + _trans += int((_mid - int(_keys)) >> 1) + goto _match + } + } + _trans += _klen + } + + _match: + _trans = int(_myaSM_indicies[_trans]) + _eof_trans: + cs = int(_myaSM_trans_targs[_trans]) + + if _myaSM_trans_actions[_trans] == 0 { + goto _again + } + + _acts = int(_myaSM_trans_actions[_trans]) + _nacts = uint(_myaSM_actions[_acts]) + _acts++ + for ; _nacts > 0; _nacts-- { + _acts++ + switch _myaSM_actions[_acts-1] { + case 2: + te = p + 1 + { + foundSyllableMyanmar(myanmarConsonantSyllable, ts, te, info, &syllableSerial) + } + case 3: + te = p + 1 + { + foundSyllableMyanmar(myanmarNonMyanmarCluster, ts, te, info, &syllableSerial) + } + case 4: + te = p + 1 + { + foundSyllableMyanmar(myanmarBrokenCluster, ts, te, info, &syllableSerial) + buffer.scratchFlags |= bsfHasBrokenSyllable + } + case 5: + te = p + 1 + { + foundSyllableMyanmar(myanmarNonMyanmarCluster, ts, te, info, &syllableSerial) + } + case 6: + te = p + p-- + { + foundSyllableMyanmar(myanmarConsonantSyllable, ts, te, info, &syllableSerial) + } + case 7: + te = p + p-- + { + foundSyllableMyanmar(myanmarBrokenCluster, ts, te, info, &syllableSerial) + buffer.scratchFlags |= bsfHasBrokenSyllable + } + case 8: + te = p + p-- + { + foundSyllableMyanmar(myanmarNonMyanmarCluster, ts, te, info, &syllableSerial) + } + } + } + + _again: + _acts = int(_myaSM_to_state_actions[cs]) + _nacts = uint(_myaSM_actions[_acts]) + _acts++ + for ; _nacts > 0; _nacts-- { + _acts++ + switch _myaSM_actions[_acts-1] { + case 0: + ts = 0 + + } + } + + p++ + if p != pe { + goto _resume + } + _test_eof: + { + } + if p == eof { + if _myaSM_eof_trans[cs] > 0 { + _trans = int(_myaSM_eof_trans[cs] - 1) + goto _eof_trans + } + } + + } + + _ = act // needed by Ragel, but unused +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_myanmar_machine.rl b/vendor/github.com/go-text/typesetting/harfbuzz/ot_myanmar_machine.rl new file mode 100644 index 0000000..3ae6e7f --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_myanmar_machine.rl @@ -0,0 +1,99 @@ +package harfbuzz + +// Code generated with ragel -Z -o ot_myanmar_machine.go ot_myanmar_machine.rl ; sed -i '/^\/\/line/ d' ot_myanmar_machine.go ; goimports -w ot_myanmar_machine.go DO NOT EDIT. + +// ported from harfbuzz/src/hb-ot-shape-complex-myanmar-machine.rl Copyright © 2015 Mozilla Foundation. Google, Inc. Behdad Esfahbod + +// myanmar_syllable_type_t +const ( + myanmarConsonantSyllable = iota + myanmarBrokenCluster + myanmarNonMyanmarCluster +) + +%%{ + machine myaSM; + alphtype byte; + write exports; + write data; +}%% + +%%{ + +# Spec category D is folded into GB; D0 is not implemented by Uniscribe and as such folded into D +# Spec category P is folded into GB + +export C = 1; +export IV = 2; +export DB = 3; # Dot below = OT_N +export H = 4; +export ZWNJ = 5; +export ZWJ = 6; +export SM = 8; # Visarga and Shan tones +export GB = 10; # = OT_PLACEHOLDER +export DOTTEDCIRCLE = 11; +export A = 9; +export Ra = 15; +export CS = 18; + +export VAbv = 20; +export VBlw = 21; +export VPre = 22; +export VPst = 23; + +# 32+ are for Myanmar-specific values +export As = 32; # Asat +export MH = 35; # Medial Ha +export MR = 36; # Medial Ra +export MW = 37; # Medial Wa, Shan Wa +export MY = 38; # Medial Ya, Mon Na, Mon Ma +export PT = 39; # Pwo and other tones +export VS = 40; # Variation selectors +export ML = 41; # Medial Mon La + +j = ZWJ|ZWNJ; # Joiners +k = (Ra As H); # Kinzi + +c = C|Ra; # is_consonant + +medial_group = MY? As? MR? ((MW MH? ML? | MH ML? | ML) As?)?; +main_vowel_group = (VPre.VS?)* VAbv* VBlw* A* (DB As?)?; +post_vowel_group = VPst MH? ML? As* VAbv* A* (DB As?)?; +pwo_tone_group = PT A* DB? As?; + +complex_syllable_tail = As* medial_group main_vowel_group post_vowel_group* pwo_tone_group* SM* j?; +syllable_tail = (H (c|IV).VS?)* (H | complex_syllable_tail); + +consonant_syllable = (k|CS)? (c|IV|GB|DOTTEDCIRCLE).VS? syllable_tail; +broken_cluster = k? VS? syllable_tail; +other = any; + +main := |* + consonant_syllable => { foundSyllableMyanmar (myanmarConsonantSyllable, ts, te, info, &syllableSerial); }; + j => { foundSyllableMyanmar (myanmarNonMyanmarCluster, ts, te, info, &syllableSerial); }; + broken_cluster => { foundSyllableMyanmar (myanmarBrokenCluster, ts, te, info, &syllableSerial); buffer.scratchFlags |= bsfHasBrokenSyllable }; + other => { foundSyllableMyanmar (myanmarNonMyanmarCluster, ts, te, info, &syllableSerial); }; +*|; + + +}%% + + +func findSyllablesMyanmar (buffer *Buffer){ + var p, ts, te, act, cs int + info := buffer.Info; + %%{ + write init; + getkey info[p].complexCategory; + }%% + + pe := len(info) + eof := pe + + var syllableSerial uint8 = 1; + %%{ + write exec; + }%% + _ = act // needed by Ragel, but unused +} + diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_shape_complex.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_shape_complex.go new file mode 100644 index 0000000..63d6703 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_shape_complex.go @@ -0,0 +1,251 @@ +package harfbuzz + +import ( + ot "github.com/go-text/typesetting/font/opentype" + "github.com/go-text/typesetting/font/opentype/tables" + "github.com/go-text/typesetting/language" +) + +type zeroWidthMarks uint8 + +const ( + zeroWidthMarksNone zeroWidthMarks = iota + zeroWidthMarksByGdefEarly + zeroWidthMarksByGdefLate +) + +// implements the specialisation for a script +type otComplexShaper interface { + marksBehavior() (zwm zeroWidthMarks, fallbackPosition bool) + normalizationPreference() normalizationMode + // If not 0, then must match found GPOS script tag for + // GPOS to be applied. Otherwise, fallback positioning will be used. + gposTag() tables.Tag + + // collectFeatures is alled during shape_plan(). + // Shapers should use plan.map to add their features and callbacks. + collectFeatures(plan *otShapePlanner) + + // overrideFeatures is called during shape_plan(). + // Shapers should use plan.map to override features and add callbacks after + // common features are added. + overrideFeatures(plan *otShapePlanner) + + // dataCreate is called at the end of shape_plan(). + dataCreate(plan *otShapePlan) + + // called during shape(), shapers can use to modify text before shaping starts. + preprocessText(plan *otShapePlan, buffer *Buffer, font *Font) + + // called during shape()'s normalization: may use decompose_unicode as fallback + decompose(c *otNormalizeContext, ab rune) (a, b rune, ok bool) + + // called during shape()'s normalization: may use compose_unicode as fallback + compose(c *otNormalizeContext, a, b rune) (ab rune, ok bool) + + // called during shape(), shapers should use map to get feature masks and set on buffer. + // Shapers may NOT modify characters. + setupMasks(plan *otShapePlan, buffer *Buffer, font *Font) + + // called during shape(), shapers can use to modify ordering of combining marks. + reorderMarks(plan *otShapePlan, buffer *Buffer, start, end int) + + // called during shape(), shapers can use to modify glyphs after shaping ends. + postprocessGlyphs(plan *otShapePlan, buffer *Buffer, font *Font) +} + +/* + * For lack of a better place, put Zawgyi script hack here. + * https://github.com/harfbuzz/harfbuzz/issues/1162 + */ +var scriptMyanmarZawgyi = language.Script(ot.NewTag('Q', 'a', 'a', 'g')) + +func (planner *otShapePlanner) categorizeComplex() otComplexShaper { + switch planner.props.Script { + case language.Arabic, language.Syriac: + /* For Arabic script, use the Arabic shaper even if no OT script tag was found. + * This is because we do fallback shaping for Arabic script (and not others). + * But note that Arabic shaping is applicable only to horizontal layout; for + * vertical text, just use the generic shaper instead. */ + if (planner.map_.chosenScript[0] != tagDefaultScript || + planner.props.Script == language.Arabic) && + planner.props.Direction.isHorizontal() { + return &complexShaperArabic{} + } + return complexShaperDefault{} + case language.Thai, language.Lao: + return complexShaperThai{} + case language.Hangul: + return &complexShaperHangul{} + case language.Hebrew: + return complexShaperHebrew{} + case language.Bengali, language.Devanagari, language.Gujarati, language.Gurmukhi, language.Kannada, + language.Malayalam, language.Oriya, language.Tamil, language.Telugu: + /* If the designer designed the font for the 'DFLT' script, + * (or we ended up arbitrarily pick 'latn'), use the default shaper. + * Otherwise, use the specific shaper. + * + * If it's indy3 tag, send to USE. */ + if planner.map_.chosenScript[0] == ot.NewTag('D', 'F', 'L', 'T') || + planner.map_.chosenScript[0] == ot.NewTag('l', 'a', 't', 'n') { + return complexShaperDefault{} + } else if (planner.map_.chosenScript[0] & 0x000000FF) == '3' { + return &complexShaperUSE{} + } + return &complexShaperIndic{} + case language.Khmer: + return &complexShaperKhmer{} + case language.Myanmar: + /* If the designer designed the font for the 'DFLT' script, + * (or we ended up arbitrarily pick 'latn'), use the default shaper. + * Otherwise, use the specific shaper. + * + * If designer designed for 'mymr' tag, also send to default + * shaper. That's tag used from before Myanmar shaping spec + * was developed. The shaping spec uses 'mym2' tag. */ + if planner.map_.chosenScript[0] == ot.NewTag('D', 'F', 'L', 'T') || + planner.map_.chosenScript[0] == ot.NewTag('l', 'a', 't', 'n') || + planner.map_.chosenScript[0] == ot.NewTag('m', 'y', 'm', 'r') { + return complexShaperDefault{} + } + return complexShaperMyanmar{} + + case scriptMyanmarZawgyi: + /* Ugly Zawgyi encoding. + * Disable all auto processing. + * https://github.com/harfbuzz/harfbuzz/issues/1162 */ + return complexShaperDefault{dumb: true, disableNorm: true} + case language.Tibetan, + language.Mongolian, language.Sinhala, + language.Buhid, language.Hanunoo, language.Tagalog, language.Tagbanwa, + language.Limbu, language.Tai_Le, + language.Buginese, language.Kharoshthi, language.Syloti_Nagri, language.Tifinagh, + language.Balinese, language.Nko, language.Phags_Pa, language.Cham, language.Kayah_Li, + language.Lepcha, language.Rejang, language.Saurashtra, language.Sundanese, + language.Egyptian_Hieroglyphs, language.Javanese, language.Kaithi, + language.Meetei_Mayek, language.Tai_Tham, language.Tai_Viet, language.Batak, + language.Brahmi, language.Mandaic, language.Chakma, language.Miao, language.Sharada, + language.Takri, language.Duployan, language.Grantha, language.Khojki, language.Khudawadi, + language.Mahajani, language.Manichaean, language.Modi, language.Pahawh_Hmong, + language.Psalter_Pahlavi, language.Siddham, language.Tirhuta, language.Ahom, language.Multani, + language.Adlam, language.Bhaiksuki, language.Marchen, language.Newa, language.Masaram_Gondi, + language.Soyombo, language.Zanabazar_Square, language.Dogra, language.Gunjala_Gondi, + language.Hanifi_Rohingya, language.Makasar, language.Medefaidrin, language.Old_Sogdian, + language.Sogdian, language.Elymaic, language.Nandinagari, language.Nyiakeng_Puachue_Hmong, + language.Wancho, + language.Chorasmian, language.Dives_Akuru, language.Khitan_Small_Script, language.Yezidi: + + /* If the designer designed the font for the 'DFLT' script, + * (or we ended up arbitrarily pick 'latn'), use the default shaper. + * Otherwise, use the specific shaper. + * Note that for some simple scripts, there may not be *any* + * GSUB/GPOS needed, so there may be no scripts found! */ + if planner.map_.chosenScript[0] == ot.NewTag('D', 'F', 'L', 'T') || + planner.map_.chosenScript[0] == ot.NewTag('l', 'a', 't', 'n') { + return complexShaperDefault{} + } + return &complexShaperUSE{} + default: + return complexShaperDefault{} + } +} + +// zero byte struct providing no-ops, used to reduced boilerplate +type complexShaperNil struct{} + +func (complexShaperNil) gposTag() tables.Tag { return 0 } + +func (complexShaperNil) collectFeatures(plan *otShapePlanner) {} +func (complexShaperNil) overrideFeatures(plan *otShapePlanner) {} +func (complexShaperNil) dataCreate(plan *otShapePlan) {} +func (complexShaperNil) decompose(_ *otNormalizeContext, ab rune) (a, b rune, ok bool) { + return uni.decompose(ab) +} + +func (complexShaperNil) compose(_ *otNormalizeContext, a, b rune) (ab rune, ok bool) { + return uni.compose(a, b) +} +func (complexShaperNil) preprocessText(*otShapePlan, *Buffer, *Font) {} +func (complexShaperNil) postprocessGlyphs(*otShapePlan, *Buffer, *Font) { +} +func (complexShaperNil) setupMasks(*otShapePlan, *Buffer, *Font) {} +func (complexShaperNil) reorderMarks(*otShapePlan, *Buffer, int, int) {} + +type complexShaperDefault struct { + complexShaperNil + + /* if true, no mark advance zeroing / fallback positioning. + * Dumbest shaper ever, basically. */ + dumb bool + disableNorm bool +} + +func (cs complexShaperDefault) marksBehavior() (zeroWidthMarks, bool) { + if cs.dumb { + return zeroWidthMarksNone, false + } + return zeroWidthMarksByGdefLate, true +} + +func (cs complexShaperDefault) normalizationPreference() normalizationMode { + if cs.disableNorm { + return nmNone + } + return nmDefault +} + +func syllabicInsertDottedCircles(font *Font, buffer *Buffer, brokenSyllableType, + dottedcircleCategory uint8, rephaCategory, dottedCirclePosition int, +) bool { + if (buffer.Flags & DoNotinsertDottedCircle) != 0 { + return false + } + + if (buffer.scratchFlags & bsfHasBrokenSyllable) == 0 { + return false + } + + dottedcircleGlyph, ok := font.face.NominalGlyph(0x25CC) + if !ok { + return false + } + + dottedcircle := GlyphInfo{ + Glyph: dottedcircleGlyph, + complexCategory: dottedcircleCategory, + } + + if dottedCirclePosition != -1 { + dottedcircle.complexAux = uint8(dottedCirclePosition) + } + + buffer.clearOutput() + + buffer.idx = 0 + var lastSyllable uint8 + for buffer.idx < len(buffer.Info) { + syllable := buffer.cur(0).syllable + if lastSyllable != syllable && (syllable&0x0F) == brokenSyllableType { + lastSyllable = syllable + + ginfo := dottedcircle + ginfo.Cluster = buffer.cur(0).Cluster + ginfo.Mask = buffer.cur(0).Mask + ginfo.syllable = buffer.cur(0).syllable + + /* Insert dottedcircle after possible Repha. */ + if rephaCategory != -1 { + for buffer.idx < len(buffer.Info) && + lastSyllable == buffer.cur(0).syllable && + buffer.cur(0).complexCategory == uint8(rephaCategory) { + buffer.nextGlyph() + } + } + buffer.outInfo = append(buffer.outInfo, ginfo) + } else { + buffer.nextGlyph() + } + } + buffer.swapBuffers() + return true +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_shape_fallback.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_shape_fallback.go new file mode 100644 index 0000000..11c9757 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_shape_fallback.go @@ -0,0 +1,429 @@ +package harfbuzz + +import "fmt" + +// ported from harfbuzz/src/hb-ot-shape-fallback.cc Copyright © 2011,2012 Google, Inc. Behdad Esfahbod + +const ( + combiningClassAttachedBelowLeft = 200 + combiningClassAttachedBelow = 202 + combiningClassAttachedAbove = 214 + combiningClassAttachedAboveRight = 216 + combiningClassBelowLeft = 218 + combiningClassBelow = 220 + combiningClassBelowRight = 222 + combiningClassLeft = 224 + combiningClassRight = 226 + combiningClassAboveLeft = 228 + combiningClassAbove = 230 + combiningClassAboveRight = 232 + combiningClassDoubleBelow = 233 + combiningClassDoubleAbove = 234 +) + +func recategorizeCombiningClass(u rune, klass uint8) uint8 { + if klass >= 200 { + return klass + } + + /* Thai / Lao need some per-character work. */ + if (u & ^0xFF) == 0x0E00 { + if klass == 0 { + switch u { + case 0x0E31, 0x0E34, 0x0E35, 0x0E36, 0x0E37, 0x0E47, 0x0E4C, 0x0E4D, 0x0E4E: + klass = combiningClassAboveRight + case 0x0EB1, 0x0EB4, 0x0EB5, 0x0EB6, 0x0EB7, 0x0EBB, 0x0ECC, 0x0ECD: + klass = combiningClassAbove + case 0x0EBC: + klass = combiningClassBelow + } + } else { + /* Thai virama is below-right */ + if u == 0x0E3A { + klass = combiningClassBelowRight + } + } + } + + switch klass { + + /* Hebrew */ + case mcc10, /* sheva */ + mcc11, /* hataf segol */ + mcc12, /* hataf patah */ + mcc13, /* hataf qamats */ + mcc14, /* hiriq */ + mcc15, /* tsere */ + mcc16, /* segol */ + mcc17, /* patah */ + mcc18, /* qamats & qamats qatan */ + mcc20, /* qubuts */ + mcc22: /* meteg */ + return combiningClassBelow + + case mcc23: /* rafe */ + return combiningClassAttachedAbove + + case mcc24: /* shin dot */ + return combiningClassAboveRight + + case mcc25, /* sin dot */ + mcc19: /* holam & holam haser for vav*/ + return combiningClassAboveLeft + + case mcc26: /* point varika */ + return combiningClassAbove + + case mcc21: /* dagesh */ + + /* Arabic and Syriac */ + + case mcc27, /* fathatan */ + mcc28, /* dammatan */ + mcc30, /* fatha */ + mcc31, /* damma */ + mcc33, /* shadda */ + mcc34, /* sukun */ + mcc35, /* superscript alef */ + mcc36: /* superscript alaph */ + return combiningClassAbove + + case mcc29, /* kasratan */ + mcc32: /* kasra */ + return combiningClassBelow + + /* Thai */ + + case mcc103: /* sara u / sara uu */ + return combiningClassBelowRight + + case mcc107: /* mai */ + return combiningClassAboveRight + + /* Lao */ + + case mcc118: /* sign u / sign uu */ + return combiningClassBelow + + case mcc122: /* mai */ + return combiningClassAbove + + /* Tibetan */ + + case mcc129: /* sign aa */ + return combiningClassBelow + + case mcc130: /* sign i*/ + return combiningClassAbove + + case mcc132: /* sign u */ + return combiningClassBelow + + } + + return klass +} + +func fallbackMarkPositionRecategorizeMarks(buffer *Buffer) { + for i, info := range buffer.Info { + if info.unicode.generalCategory() == nonSpacingMark { + combiningClass := info.getModifiedCombiningClass() + combiningClass = recategorizeCombiningClass(info.codepoint, combiningClass) + buffer.Info[i].setModifiedCombiningClass(combiningClass) + } + } +} + +func zeroMarkAdvances(buffer *Buffer, start, end int, adjustOffsetsWhenZeroing bool) { + info := buffer.Info + for i := start; i < end; i++ { + if info[i].unicode.generalCategory() != nonSpacingMark { + continue + } + if adjustOffsetsWhenZeroing { + buffer.Pos[i].XOffset -= buffer.Pos[i].XAdvance + buffer.Pos[i].YOffset -= buffer.Pos[i].YAdvance + } + buffer.Pos[i].XAdvance = 0 + buffer.Pos[i].YAdvance = 0 + } +} + +func positionMark(font *Font, buffer *Buffer, baseExtents *GlyphExtents, + i int, combiningClass uint8, +) { + markExtents, ok := font.GlyphExtents(buffer.Info[i].Glyph) + if !ok { + return + } + + yGap := font.YScale / 16 + + pos := &buffer.Pos[i] + pos.XOffset = 0 + pos.YOffset = 0 + + // we don't position LEFT and RIGHT marks. + + // X positioning + switch combiningClass { + case combiningClassAttachedBelowLeft, combiningClassBelowLeft, combiningClassAboveLeft: + /* Left align. */ + pos.XOffset += baseExtents.XBearing - markExtents.XBearing + + case combiningClassAttachedAboveRight, combiningClassBelowRight, combiningClassAboveRight: + /* Right align. */ + pos.XOffset += baseExtents.XBearing + baseExtents.Width - markExtents.Width - markExtents.XBearing + case combiningClassDoubleBelow, combiningClassDoubleAbove: + if buffer.Props.Direction == LeftToRight { + pos.XOffset += baseExtents.XBearing + baseExtents.Width - markExtents.Width/2 - markExtents.XBearing + break + } else if buffer.Props.Direction == RightToLeft { + pos.XOffset += baseExtents.XBearing - markExtents.Width/2 - markExtents.XBearing + break + } + fallthrough + case combiningClassAttachedBelow, combiningClassAttachedAbove, combiningClassBelow, combiningClassAbove: + fallthrough + default: + /* Center align. */ + pos.XOffset += baseExtents.XBearing + (baseExtents.Width-markExtents.Width)/2 - markExtents.XBearing + } + + /* Y positioning */ + switch combiningClass { + case combiningClassDoubleBelow, combiningClassBelowLeft, combiningClassBelow, combiningClassBelowRight: + /* Add gap, fall-through. */ + baseExtents.Height -= yGap + fallthrough + + case combiningClassAttachedBelowLeft, combiningClassAttachedBelow: + pos.YOffset = baseExtents.YBearing + baseExtents.Height - markExtents.YBearing + /* Never shift up "below" marks. */ + if (yGap > 0) == (pos.YOffset > 0) { + baseExtents.Height -= pos.YOffset + pos.YOffset = 0 + } + baseExtents.Height += markExtents.Height + + case combiningClassDoubleAbove, combiningClassAboveLeft, combiningClassAbove, combiningClassAboveRight: + /* Add gap, fall-through. */ + baseExtents.YBearing += yGap + baseExtents.Height -= yGap + fallthrough + case combiningClassAttachedAbove, combiningClassAttachedAboveRight: + pos.YOffset = baseExtents.YBearing - (markExtents.YBearing + markExtents.Height) + /* Don't shift down "above" marks too much. */ + if (yGap > 0) != (pos.YOffset > 0) { + correction := -pos.YOffset / 2 + baseExtents.YBearing += correction + baseExtents.Height -= correction + pos.YOffset += correction + } + baseExtents.YBearing -= markExtents.Height + baseExtents.Height += markExtents.Height + } +} + +func positionAroundBase(plan *otShapePlan, font *Font, buffer *Buffer, + base, end int, adjustOffsetsWhenZeroing bool, +) { + buffer.unsafeToBreak(base, end) + + baseExtents, ok := font.GlyphExtents(buffer.Info[base].Glyph) + if !ok { + // if extents don't work, zero marks and go home. + zeroMarkAdvances(buffer, base+1, end, adjustOffsetsWhenZeroing) + return + } + baseExtents.YBearing += buffer.Pos[base].YOffset + /* Use horizontal advance for horizontal positioning. + * Generally a better idea. Also works for zero-ink glyphs. See: + * https://github.com/harfbuzz/harfbuzz/issues/1532 */ + baseExtents.XBearing = 0 + baseExtents.Width = font.GlyphHAdvance(buffer.Info[base].Glyph) + + ligID := buffer.Info[base].getLigID() + numLigComponents := int32(buffer.Info[base].getLigNumComps()) + + var xOffset, yOffset Position + if buffer.Props.Direction.isForward() { + xOffset -= buffer.Pos[base].XAdvance + yOffset -= buffer.Pos[base].YAdvance + } + + var horizDir Direction + componentExtents := baseExtents + lastLigComponent := int32(-1) + lastCombiningClass := uint8(255) + clusterExtents := baseExtents + info := buffer.Info + for i := base + 1; i < end; i++ { + thisCombiningClass := info[i].getModifiedCombiningClass() + + if thisCombiningClass != 0 { + if numLigComponents > 1 { + thisLigID := info[i].getLigID() + thisLigComponent := int32(info[i].getLigComp() - 1) + // conditions for attaching to the last component. + if ligID == 0 || ligID != thisLigID || thisLigComponent >= numLigComponents { + thisLigComponent = numLigComponents - 1 + } + if lastLigComponent != thisLigComponent { + lastLigComponent = thisLigComponent + lastCombiningClass = 255 + componentExtents = baseExtents + if horizDir == 0 { + if plan.props.Direction.isHorizontal() { + horizDir = plan.props.Direction + } else { + horizDir = getHorizontalDirection(plan.props.Script) + } + } + if horizDir == LeftToRight { + componentExtents.XBearing += (thisLigComponent * componentExtents.Width) / numLigComponents + } else { + componentExtents.XBearing += ((numLigComponents - 1 - thisLigComponent) * componentExtents.Width) / numLigComponents + } + componentExtents.Width /= numLigComponents + } + } + + if lastCombiningClass != thisCombiningClass { + lastCombiningClass = thisCombiningClass + clusterExtents = componentExtents + } + + positionMark(font, buffer, &clusterExtents, i, thisCombiningClass) + + buffer.Pos[i].XAdvance = 0 + buffer.Pos[i].YAdvance = 0 + buffer.Pos[i].XOffset += xOffset + buffer.Pos[i].YOffset += yOffset + + } else { + if buffer.Props.Direction.isForward() { + xOffset -= buffer.Pos[i].XAdvance + yOffset -= buffer.Pos[i].YAdvance + } else { + xOffset += buffer.Pos[i].XAdvance + yOffset += buffer.Pos[i].YAdvance + } + } + } +} + +func positionCluster(plan *otShapePlan, font *Font, buffer *Buffer, + start, end int, adjustOffsetsWhenZeroing bool, +) { + if end-start < 2 { + return + } + + // find the base glyph + info := buffer.Info + for i := start; i < end; i++ { + if !info[i].isUnicodeMark() { + // find mark glyphs + var j int + for j = i + 1; j < end; j++ { + if !info[j].isUnicodeMark() { + break + } + } + + positionAroundBase(plan, font, buffer, i, j, adjustOffsetsWhenZeroing) + + i = j - 1 + } + } +} + +func fallbackMarkPosition(plan *otShapePlan, font *Font, buffer *Buffer, + adjustOffsetsWhenZeroing bool, +) { + var start int + info := buffer.Info + for i := 1; i < len(info); i++ { + if !info[i].isUnicodeMark() { + positionCluster(plan, font, buffer, start, i, adjustOffsetsWhenZeroing) + start = i + } + } + positionCluster(plan, font, buffer, start, len(info), adjustOffsetsWhenZeroing) +} + +// adjusts width of various spaces. +func fallbackSpaces(font *Font, buffer *Buffer) { + if debugMode { + fmt.Println("POSITION - applying fallback spaces") + } + info := buffer.Info + pos := buffer.Pos + horizontal := buffer.Props.Direction.isHorizontal() + for i, inf := range info { + if !inf.isUnicodeSpace() || inf.ligated() { + continue + } + + // If font had no ASCII space and we used the invisible glyph, give it a 1/4 EM default advance. + if buffer.Invisible != 0 && info[i].Glyph == buffer.Invisible { + if horizontal { + pos[i].XAdvance = +font.XScale / 4 + } else { + pos[i].YAdvance = -font.YScale / 4 + } + } + + spaceType := inf.getUnicodeSpaceFallbackType() + + switch spaceType { + case notSpace, space: // shouldn't happen + case spaceEM, spaceEM2, spaceEM3, spaceEM4, spaceEM5, spaceEM6, spaceEM16: + if horizontal { + pos[i].XAdvance = +(font.XScale + int32(spaceType)/2) / int32(spaceType) + } else { + pos[i].YAdvance = -(font.YScale + int32(spaceType)/2) / int32(spaceType) + } + case space4EM18: + if horizontal { + pos[i].XAdvance = +font.XScale * 4 / 18 + } else { + pos[i].YAdvance = -font.YScale * 4 / 18 + } + case spaceFigure: + for u := '0'; u <= '9'; u++ { + if glyph, ok := font.face.NominalGlyph(u); ok { + if horizontal { + pos[i].XAdvance = font.GlyphHAdvance(glyph) + } else { + pos[i].YAdvance = font.getGlyphVAdvance(glyph) + } + } + } + case spacePunctuation: + glyph, ok := font.face.NominalGlyph('.') + if !ok { + glyph, ok = font.face.NominalGlyph(',') + } + if ok { + if horizontal { + pos[i].XAdvance = font.GlyphHAdvance(glyph) + } else { + pos[i].YAdvance = font.getGlyphVAdvance(glyph) + } + } + case spaceNarrow: + /* Half-space? + * Unicode doc https://unicode.org/charts/PDF/U2000.pdf says ~1/4 or 1/5 of EM. + * However, in my testing, many fonts have their regular space being about that + * size. To me, a percentage of the space width makes more sense. Half is as + * good as any. */ + if horizontal { + pos[i].XAdvance /= 2 + } else { + pos[i].YAdvance /= 2 + } + } + } +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_shape_normalize.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_shape_normalize.go new file mode 100644 index 0000000..a49add3 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_shape_normalize.go @@ -0,0 +1,431 @@ +package harfbuzz + +import ( + "fmt" +) + +// ported from harfbuzz/src/hb-ot-shape-normalize.cc Copyright © 2011,2012 Google, Inc. Behdad Esfahbod + +/* + * HIGHLEVEL DESIGN: + * + * This file exports one main function: otShapeNormalize(). + * + * This function closely reflects the Unicode Normalization Algorithm, + * yet it's different. + * + * Each shaper specifies whether it prefers decomposed (NFD) or composed (NFC). + * The logic however tries to use whatever the font can support. + * + * In general what happens is that: each grapheme is decomposed in a chain + * of 1:2 decompositions, marks reordered, and then recomposed if desired, + * so far it's like Unicode Normalization. However, the decomposition and + * recomposition only happens if the font supports the resulting characters. + * + * The goals are: + * + * - Try to render all canonically equivalent strings similarly. To really + * achieve this we have to always do the full decomposition and then + * selectively recompose from there. It's kinda too expensive though, so + * we skip some cases. For example, if composed is desired, we simply + * don't touch 1-character clusters that are supported by the font, even + * though their NFC may be different. + * + * - When a font has a precomposed character for a sequence but the 'ccmp' + * feature in the font is not adequate, use the precomposed character + * which typically has better mark positioning. + * + * - When a font does not support a combining mark, but supports it precomposed + * with previous base, use that. This needs the itemizer to have this + * knowledge too. We need to provide assistance to the itemizer. + * + * - When a font does not support a character but supports its canonical + * decomposition, well, use the decomposition. + * + * - The complex shapers can customize the compose and decompose functions to + * offload some of their requirements to the normalizer. For example, the + * Indic shaper may want to disallow recomposing of two matras. + */ + +const shapeComplexMaxCombiningMarks = 32 + +type normalizationMode uint8 + +const ( + nmNone normalizationMode = iota + nmDecomposed + nmComposedDiacritics // never composes base-to-base + nmComposedDiacriticsNoShortCircuit // always fully decomposes and then recompose back + + nmAuto // see below for logic. + nmDefault = nmAuto +) + +type otNormalizeContext struct { + plan *otShapePlan + buffer *Buffer + font *Font + // hb_unicode_funcs_t *unicode; + decompose func(c *otNormalizeContext, ab rune) (a, b rune, ok bool) + compose func(c *otNormalizeContext, a, b rune) (ab rune, ok bool) +} + +func setGlyph(info *GlyphInfo, font *Font) { + info.Glyph, _ = font.face.NominalGlyph(info.codepoint) +} + +func outputChar(buffer *Buffer, unichar rune, glyph GID) { + buffer.cur(0).Glyph = glyph + buffer.outputRune(unichar) // this is very confusing indeed. + buffer.prev().setUnicodeProps(buffer) +} + +func nextChar(buffer *Buffer, glyph GID) { + buffer.cur(0).Glyph = glyph + buffer.nextGlyph() +} + +// returns 0 if didn't decompose, number of resulting characters otherwise. +func decompose(c *otNormalizeContext, shortest bool, ab rune) int { + var aGlyph, bGlyph GID + buffer := c.buffer + font := c.font + a, b, ok := c.decompose(c, ab) + if !ok { + return 0 + } + bGlyph, ok = font.face.NominalGlyph(b) + if b != 0 && !ok { + return 0 + } + + aGlyph, hasA := font.face.NominalGlyph(a) + if shortest && hasA { + /// output a and b + outputChar(buffer, a, aGlyph) + if b != 0 { + outputChar(buffer, b, bGlyph) + return 2 + } + return 1 + } + + if ret := decompose(c, shortest, a); ret != 0 { + if b != 0 { + outputChar(buffer, b, bGlyph) + return ret + 1 + } + return ret + } + + if hasA { + outputChar(buffer, a, aGlyph) + if b != 0 { + outputChar(buffer, b, bGlyph) + return 2 + } + return 1 + } + + return 0 +} + +func (c *otNormalizeContext) decomposeCurrentCharacter(shortest bool) { + buffer := c.buffer + u := buffer.cur(0).codepoint + glyph, ok := c.font.nominalGlyph(u, c.buffer.NotFound) + + if shortest && ok { + nextChar(buffer, glyph) + return + } + + if decompose(c, shortest, u) != 0 { + buffer.skipGlyph() + return + } + + if !shortest && ok { + nextChar(buffer, glyph) + return + } + + if buffer.cur(0).isUnicodeSpace() { + spaceType := uni.spaceFallbackType(u) + if spaceGlyph, ok := c.font.face.NominalGlyph(0x0020); spaceType != notSpace && (ok || buffer.Invisible != 0) { + if !ok { + spaceGlyph = buffer.Invisible + } + buffer.cur(0).setUnicodeSpaceFallbackType(spaceType) + nextChar(buffer, spaceGlyph) + buffer.scratchFlags |= bsfHasSpaceFallback + return + } + } + + if u == 0x2011 { + /* U+2011 is the only sensible character that is a no-break version of another character + * and not a space. The space ones are handled already. Handle this lone one. */ + if otherGlyph, ok := c.font.face.NominalGlyph(0x2010); ok { + nextChar(buffer, otherGlyph) + return + } + } + + nextChar(buffer, glyph) +} + +func (c *otNormalizeContext) handleVariationSelectorCluster(end int) { + /* Currently if there's a variation-selector we give-up on normalization, it's just too hard. */ + buffer := c.buffer + if debugMode { + fmt.Printf("NORMALIZE - variation selector cluster at index %d\n", buffer.idx) + } + font := c.font + for buffer.idx < end-1 { + if uni.isVariationSelector(buffer.cur(+1).codepoint) { + var ok bool + buffer.cur(0).Glyph, ok = font.face.VariationGlyph(buffer.cur(0).codepoint, buffer.cur(+1).codepoint) + if ok { + r := buffer.cur(0).codepoint + buffer.replaceGlyphs(2, []rune{r}, nil) + } else { + // Just pass on the two characters separately, let GSUB do its magic. + setGlyph(buffer.cur(0), font) + buffer.nextGlyph() + setGlyph(buffer.cur(0), font) + buffer.nextGlyph() + } + // skip any further variation selectors. + for buffer.idx < end && uni.isVariationSelector(buffer.cur(0).codepoint) { + setGlyph(buffer.cur(0), font) + buffer.nextGlyph() + } + } else { + setGlyph(buffer.cur(0), font) + buffer.nextGlyph() + } + } + if buffer.idx < end { + setGlyph(buffer.cur(0), font) + buffer.nextGlyph() + } +} + +func (c *otNormalizeContext) decomposeMultiCharCluster(end int, shortCircuit bool) { + buffer := c.buffer + if debugMode { + fmt.Printf("NORMALIZE - decompose multi char cluster at index %d\n", buffer.idx) + } + + for i := buffer.idx; i < end; i++ { + if uni.isVariationSelector(buffer.Info[i].codepoint) { + c.handleVariationSelectorCluster(end) + return + } + } + for buffer.idx < end { + c.decomposeCurrentCharacter(shortCircuit) + } +} + +func compareCombiningClass(pa, pb *GlyphInfo) int { + a := pa.getModifiedCombiningClass() + b := pb.getModifiedCombiningClass() + if a < b { + return -1 + } else if a == b { + return 0 + } + return 1 +} + +func otShapeNormalize(plan *otShapePlan, buffer *Buffer, font *Font) { + if len(buffer.Info) == 0 { + return + } + + mode := plan.shaper.normalizationPreference() + if mode == nmAuto { + if plan.hasGposMark { + // https://github.com/harfbuzz/harfbuzz/issues/653#issuecomment-423905920 + mode = nmComposedDiacritics + } else { + mode = nmComposedDiacritics + } + } + c := otNormalizeContext{ + plan, + buffer, + font, + plan.shaper.decompose, + plan.shaper.compose, + } + + alwaysShortCircuit := mode == nmNone + mightShortCircuit := alwaysShortCircuit || + (mode != nmDecomposed && + mode != nmComposedDiacriticsNoShortCircuit) + + /* We do a fairly straightforward yet custom normalization process in three + * separate rounds: decompose, reorder, recompose (if desired). Currently + * this makes two buffer swaps. We can make it faster by moving the last + * two rounds into the inner loop for the first round, but it's more readable + * this way. */ + + /* First round, decompose */ + + allSimple := true + buffer.clearOutput() + count := len(buffer.Info) + buffer.idx = 0 + var end int + for do := true; do; do = buffer.idx < count { + for end = buffer.idx + 1; end < count; end++ { + if buffer.Info[end].isUnicodeMark() { + break + } + } + + if end < count { + end-- // leave one base for the marks to cluster with. + } + // from idx to end are simple clusters. + if mightShortCircuit { + var ( + i int + ok bool + ) + for i = buffer.idx; i < end; i++ { + buffer.Info[i].Glyph, ok = font.face.NominalGlyph(buffer.Info[i].codepoint) + if !ok { + break + } + } + buffer.nextGlyphs(i - buffer.idx) + } + for buffer.idx < end { + c.decomposeCurrentCharacter(mightShortCircuit) + } + + if buffer.idx == count { + break + } + + allSimple = false + + // find all the marks now. + for end = buffer.idx + 1; end < count; end++ { + if !buffer.Info[end].isUnicodeMark() { + break + } + } + + // idx to end is one non-simple cluster. + c.decomposeMultiCharCluster(end, alwaysShortCircuit) + } + + buffer.swapBuffers() + /* Second round, reorder (inplace) */ + + if !allSimple { + if debugMode { + fmt.Println("NORMALIZE - start reorder") + } + count = len(buffer.Info) + for i := 0; i < count; i++ { + if buffer.Info[i].getModifiedCombiningClass() == 0 { + continue + } + + var end int + for end = i + 1; end < count; end++ { + if buffer.Info[end].getModifiedCombiningClass() == 0 { + break + } + } + + // we are going to do a O(n^2). Only do this if the sequence is short. + if end-i > shapeComplexMaxCombiningMarks { + i = end + continue + } + + buffer.sort(i, end, compareCombiningClass) + + plan.shaper.reorderMarks(plan, buffer, i, end) + + i = end + } + if debugMode { + fmt.Println("NORMALIZE - end reorder") + } + } + + if buffer.scratchFlags&bsfHasCGJ != 0 { + /* For all CGJ, check if it prevented any reordering at all. + * If it did NOT, then make it skippable. + * https://github.com/harfbuzz/harfbuzz/issues/554 */ + for i := 1; i+1 < len(buffer.Info); i++ { + if buffer.Info[i].codepoint == 0x034F /*CGJ*/ && + (buffer.Info[i+1].getModifiedCombiningClass() == 0 || buffer.Info[i-1].getModifiedCombiningClass() <= buffer.Info[i+1].getModifiedCombiningClass()) { + buffer.Info[i].unhide() + } + } + } + + /* Third round, recompose */ + + if !allSimple && + (mode == nmComposedDiacritics || + mode == nmComposedDiacriticsNoShortCircuit) { + + if debugMode { + fmt.Println("NORMALIZE - recompose") + } + + /* As noted in the comment earlier, we don't try to combine + * ccc=0 chars with their previous Starter. */ + + buffer.clearOutput() + count = len(buffer.Info) + starter := 0 + buffer.nextGlyph() + for buffer.idx < count { + /* We don't try to compose a non-mark character with it's preceding starter. + * This is both an optimization to avoid trying to compose every two neighboring + * glyphs in most scripts AND a desired feature for Hangul. Apparently Hangul + * fonts are not designed to mix-and-match pre-composed syllables and Jamo. */ + if buffer.cur(0).isUnicodeMark() { + /* If there's anything between the starter and this char, they should have CCC + * smaller than this character's. */ + if starter == len(buffer.outInfo)-1 || + buffer.prev().getModifiedCombiningClass() < buffer.cur(0).getModifiedCombiningClass() { + /* And compose. */ + composed, ok := c.compose(&c, buffer.outInfo[starter].codepoint, buffer.cur(0).codepoint) + if ok { // And the font has glyph for the composite. + glyph, ok := font.face.NominalGlyph(composed) /* Composes. */ + if ok { + buffer.nextGlyph() /* Copy to out-buffer. */ + buffer.mergeOutClusters(starter, len(buffer.outInfo)) + buffer.outInfo = buffer.outInfo[:len(buffer.outInfo)-1] // remove the second composable. + /* Modify starter and carry on. */ + buffer.outInfo[starter].codepoint = composed + buffer.outInfo[starter].Glyph = glyph + buffer.outInfo[starter].setUnicodeProps(buffer) + continue + } + } + } + } + + /* Blocked, or doesn't compose. */ + buffer.nextGlyph() + + if buffer.prev().getModifiedCombiningClass() == 0 { + starter = len(buffer.outInfo) - 1 + } + } + buffer.swapBuffers() + } +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_shaper.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_shaper.go new file mode 100644 index 0000000..9bcd998 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_shaper.go @@ -0,0 +1,833 @@ +package harfbuzz + +import ( + "fmt" + + "github.com/go-text/typesetting/font" + ot "github.com/go-text/typesetting/font/opentype" + "github.com/go-text/typesetting/font/opentype/tables" +) + +// Support functions for OpenType shaping related queries. +// ported from src/hb-ot-shape.cc Copyright © 2009,2010 Red Hat, Inc. 2010,2011,2012 Google, Inc. Behdad Esfahbod + +/* + * GSUB/GPOS feature query and enumeration interface + */ + +const ( + // Special value for script index indicating unsupported script. + NoScriptIndex = 0xFFFF + // Special value for feature index indicating unsupported feature. + NoFeatureIndex = 0xFFFF + // Special value for language index indicating default or unsupported language. + DefaultLanguageIndex = 0xFFFF + // Special value for variations index indicating unsupported variation. + noVariationsIndex = -1 +) + +type otShapePlanner struct { + shaper otComplexShaper + props SegmentProperties + tables *font.Font // also used by the map builders + map_ otMapBuilder + applyMorx bool + scriptZeroMarks bool + scriptFallbackMarkPositioning bool +} + +func newOtShapePlanner(tables *font.Font, props SegmentProperties) *otShapePlanner { + var out otShapePlanner + out.props = props + out.tables = tables + out.map_ = newOtMapBuilder(tables, props) + + /* https://github.com/harfbuzz/harfbuzz/issues/2124 */ + out.applyMorx = len(tables.Morx) != 0 && (props.Direction.isHorizontal() || len(tables.GSUB.Lookups) == 0) + + out.shaper = out.categorizeComplex() + + zwm, fb := out.shaper.marksBehavior() + out.scriptZeroMarks = zwm != zeroWidthMarksNone + out.scriptFallbackMarkPositioning = fb + + /* https://github.com/harfbuzz/harfbuzz/issues/1528 */ + if _, isDefault := out.shaper.(complexShaperDefault); out.applyMorx && !isDefault { + out.shaper = complexShaperDefault{dumb: true} + } + return &out +} + +func (planner *otShapePlanner) compile(plan *otShapePlan, key otShapePlanKey) { + plan.props = planner.props + plan.shaper = planner.shaper + planner.map_.compile(&plan.map_, key) + + plan.fracMask = plan.map_.getMask1(ot.NewTag('f', 'r', 'a', 'c')) + plan.numrMask = plan.map_.getMask1(ot.NewTag('n', 'u', 'm', 'r')) + plan.dnomMask = plan.map_.getMask1(ot.NewTag('d', 'n', 'o', 'm')) + plan.hasFrac = plan.fracMask != 0 || (plan.numrMask != 0 && plan.dnomMask != 0) + + plan.rtlmMask = plan.map_.getMask1(ot.NewTag('r', 't', 'l', 'm')) + plan.hasVert = plan.map_.getMask1(ot.NewTag('v', 'e', 'r', 't')) != 0 + + kernTag := ot.NewTag('v', 'k', 'r', 'n') + if planner.props.Direction.isHorizontal() { + kernTag = ot.NewTag('k', 'e', 'r', 'n') + } + + plan.kernMask, _ = plan.map_.getMask(kernTag) + plan.requestedKerning = plan.kernMask != 0 + plan.trakMask, _ = plan.map_.getMask(ot.NewTag('t', 'r', 'a', 'k')) + plan.requestedTracking = plan.trakMask != 0 + + hasGposKern := plan.map_.getFeatureIndex(1, kernTag) != NoFeatureIndex + disableGpos := plan.shaper.gposTag() != 0 && plan.shaper.gposTag() != plan.map_.chosenScript[1] + + // Decide who provides glyph classes. GDEF or Unicode. + if planner.tables.GDEF.GlyphClassDef == nil { + plan.fallbackGlyphClasses = true + } + + // Decide who does substitutions. GSUB, morx, or fallback. + plan.applyMorx = planner.applyMorx + + // Decide who does positioning. GPOS, kerx, kern, or fallback. + hasKerx := planner.tables.Kerx != nil + hasGSUB := !plan.applyMorx && planner.tables.GSUB.Lookups != nil + hasGPOS := !disableGpos && planner.tables.GPOS.Lookups != nil + + if hasKerx && !(hasGSUB && hasGPOS) { + plan.applyKerx = true + } else if hasGPOS { + plan.applyGpos = true + } + + if !plan.applyKerx && (!hasGposKern || !plan.applyGpos) { + // apparently Apple applies kerx if GPOS kern was not applied. + if hasKerx { + plan.applyKerx = true + } else if planner.tables.Kern != nil { + plan.applyKern = true + } + } + + plan.applyFallbackKern = !(plan.applyGpos || plan.applyKerx || plan.applyKern) + + plan.zeroMarks = planner.scriptZeroMarks && !plan.applyKerx && + (!plan.applyKern || !hasMachineKerning(planner.tables.Kern)) + plan.hasGposMark = plan.map_.getMask1(ot.NewTag('m', 'a', 'r', 'k')) != 0 + + plan.adjustMarkPositioningWhenZeroing = !plan.applyGpos && !plan.applyKerx && + (!plan.applyKern || !hasCrossKerning(planner.tables.Kern)) + + plan.fallbackMarkPositioning = plan.adjustMarkPositioningWhenZeroing && planner.scriptFallbackMarkPositioning + + // If we're using morx shaping, we cancel mark position adjustment because + // Apple Color Emoji assumes this will NOT be done when forming emoji sequences; + // https://github.com/harfbuzz/harfbuzz/issues/2967. + if plan.applyMorx { + plan.adjustMarkPositioningWhenZeroing = false + } + + // currently we always apply trak. + plan.applyTrak = plan.requestedTracking && !planner.tables.Trak.IsEmpty() +} + +type otShapePlan struct { + shaper otComplexShaper + props SegmentProperties + + map_ otMap + + fracMask GlyphMask + numrMask GlyphMask + dnomMask GlyphMask + rtlmMask GlyphMask + kernMask GlyphMask + trakMask GlyphMask + + hasFrac bool + requestedTracking bool + requestedKerning bool + hasVert bool + hasGposMark bool + zeroMarks bool + fallbackGlyphClasses bool + fallbackMarkPositioning bool + adjustMarkPositioningWhenZeroing bool + + applyGpos bool + applyFallbackKern bool + applyKern bool + applyKerx bool + applyMorx bool + applyTrak bool +} + +func (sp *otShapePlan) init0(tables *font.Font, props SegmentProperties, userFeatures []Feature, otKey otShapePlanKey) { + planner := newOtShapePlanner(tables, props) + + planner.collectFeatures(userFeatures) + + planner.compile(sp, otKey) + + sp.shaper.dataCreate(sp) +} + +func (sp *otShapePlan) substitute(font *Font, buffer *Buffer) { + sp.map_.substitute(sp, font, buffer) +} + +func (sp *otShapePlan) position(font *Font, buffer *Buffer) { + if sp.applyGpos { + sp.map_.position(sp, font, buffer) + } else if sp.applyKerx { + sp.aatLayoutPosition(font, buffer) + } + + if sp.applyKern { + sp.otLayoutKern(font, buffer) + } else if sp.applyFallbackKern { + sp.otApplyFallbackKern(font, buffer) + } + + if sp.applyTrak { + sp.aatLayoutTrack(font, buffer) + } +} + +var ( + commonFeatures = [...]otMapFeature{ + {ot.NewTag('a', 'b', 'v', 'm'), ffGLOBAL}, + {ot.NewTag('b', 'l', 'w', 'm'), ffGLOBAL}, + {ot.NewTag('c', 'c', 'm', 'p'), ffGLOBAL}, + {ot.NewTag('l', 'o', 'c', 'l'), ffGLOBAL}, + {ot.NewTag('m', 'a', 'r', 'k'), ffGlobalManualJoiners}, + {ot.NewTag('m', 'k', 'm', 'k'), ffGlobalManualJoiners}, + {ot.NewTag('r', 'l', 'i', 'g'), ffGLOBAL}, + } + + horizontalFeatures = [...]otMapFeature{ + {ot.NewTag('c', 'a', 'l', 't'), ffGLOBAL}, + {ot.NewTag('c', 'l', 'i', 'g'), ffGLOBAL}, + {ot.NewTag('c', 'u', 'r', 's'), ffGLOBAL}, + {ot.NewTag('d', 'i', 's', 't'), ffGLOBAL}, + {ot.NewTag('k', 'e', 'r', 'n'), ffGlobalHasFallback}, + {ot.NewTag('l', 'i', 'g', 'a'), ffGLOBAL}, + {ot.NewTag('r', 'c', 'l', 't'), ffGLOBAL}, + } +) + +func (planner *otShapePlanner) collectFeatures(userFeatures []Feature) { + map_ := &planner.map_ + + map_.enableFeature(ot.NewTag('r', 'v', 'r', 'n')) + map_.addGSUBPause(nil) + + switch planner.props.Direction { + case LeftToRight: + map_.enableFeature(ot.NewTag('l', 't', 'r', 'a')) + map_.enableFeature(ot.NewTag('l', 't', 'r', 'm')) + case RightToLeft: + map_.enableFeature(ot.NewTag('r', 't', 'l', 'a')) + map_.addFeature(ot.NewTag('r', 't', 'l', 'm')) + } + + /* Automatic fractions. */ + map_.addFeature(ot.NewTag('f', 'r', 'a', 'c')) + map_.addFeature(ot.NewTag('n', 'u', 'm', 'r')) + map_.addFeature(ot.NewTag('d', 'n', 'o', 'm')) + + /* Random! */ + map_.enableFeatureExt(ot.NewTag('r', 'a', 'n', 'd'), ffRandom, otMapMaxValue) + + /* Tracking. We enable dummy feature here just to allow disabling + * AAT 'trak' table using features. + * https://github.com/harfbuzz/harfbuzz/issues/1303 */ + map_.enableFeatureExt(ot.NewTag('t', 'r', 'a', 'k'), ffHasFallback, 1) + + map_.enableFeature(ot.NewTag('H', 'a', 'r', 'f')) /* Considered required. */ + map_.enableFeature(ot.NewTag('H', 'A', 'R', 'F')) /* Considered discretionary. */ + + planner.shaper.collectFeatures(planner) + + map_.enableFeature(ot.NewTag('B', 'u', 'z', 'z')) /* Considered required. */ + map_.enableFeature(ot.NewTag('B', 'U', 'Z', 'Z')) /* Considered discretionary. */ + + for _, feat := range commonFeatures { + map_.addFeatureExt(feat.tag, feat.flags, 1) + } + + if planner.props.Direction.isHorizontal() { + for _, feat := range horizontalFeatures { + map_.addFeatureExt(feat.tag, feat.flags, 1) + } + } else { + /* We really want to find a 'vert' feature if there's any in the font, no + * matter which script/langsys it is listed (or not) under. + * See various bugs referenced from: + * https://github.com/harfbuzz/harfbuzz/issues/63 */ + map_.enableFeatureExt(ot.NewTag('v', 'e', 'r', 't'), ffGlobalSearch, 1) + } + + for _, f := range userFeatures { + ftag := ffNone + if f.Start == FeatureGlobalStart && f.End == FeatureGlobalEnd { + ftag = ffGLOBAL + } + map_.addFeatureExt(f.Tag, ftag, f.Value) + } + + planner.shaper.overrideFeatures(planner) +} + +/* + * shaper + */ + +type otContext struct { + plan *otShapePlan + font *Font + buffer *Buffer + userFeatures []Feature + + // transient stuff + targetDirection Direction +} + +/* Main shaper */ + +/* + * Substitute + */ + +func vertCharFor(u rune) rune { + switch u >> 8 { + case 0x20: + switch u { + case 0x2013: + return 0xfe32 // EN DASH + case 0x2014: + return 0xfe31 // EM DASH + case 0x2025: + return 0xfe30 // TWO DOT LEADER + case 0x2026: + return 0xfe19 // HORIZONTAL ELLIPSIS + } + case 0x30: + switch u { + case 0x3001: + return 0xfe11 // IDEOGRAPHIC COMMA + case 0x3002: + return 0xfe12 // IDEOGRAPHIC FULL STOP + case 0x3008: + return 0xfe3f // LEFT ANGLE BRACKET + case 0x3009: + return 0xfe40 // RIGHT ANGLE BRACKET + case 0x300a: + return 0xfe3d // LEFT DOUBLE ANGLE BRACKET + case 0x300b: + return 0xfe3e // RIGHT DOUBLE ANGLE BRACKET + case 0x300c: + return 0xfe41 // LEFT CORNER BRACKET + case 0x300d: + return 0xfe42 // RIGHT CORNER BRACKET + case 0x300e: + return 0xfe43 // LEFT WHITE CORNER BRACKET + case 0x300f: + return 0xfe44 // RIGHT WHITE CORNER BRACKET + case 0x3010: + return 0xfe3b // LEFT BLACK LENTICULAR BRACKET + case 0x3011: + return 0xfe3c // RIGHT BLACK LENTICULAR BRACKET + case 0x3014: + return 0xfe39 // LEFT TORTOISE SHELL BRACKET + case 0x3015: + return 0xfe3a // RIGHT TORTOISE SHELL BRACKET + case 0x3016: + return 0xfe17 // LEFT WHITE LENTICULAR BRACKET + case 0x3017: + return 0xfe18 // RIGHT WHITE LENTICULAR BRACKET + } + case 0xfe: + switch u { + case 0xfe4f: + return 0xfe34 // WAVY LOW LINE + } + case 0xff: + switch u { + case 0xff01: + return 0xfe15 // FULLWIDTH EXCLAMATION MARK + case 0xff08: + return 0xfe35 // FULLWIDTH LEFT PARENTHESIS + case 0xff09: + return 0xfe36 // FULLWIDTH RIGHT PARENTHESIS + case 0xff0c: + return 0xfe10 // FULLWIDTH COMMA + case 0xff1a: + return 0xfe13 // FULLWIDTH COLON + case 0xff1b: + return 0xfe14 // FULLWIDTH SEMICOLON + case 0xff1f: + return 0xfe16 // FULLWIDTH QUESTION MARK + case 0xff3b: + return 0xfe47 // FULLWIDTH LEFT SQUARE BRACKET + case 0xff3d: + return 0xfe48 // FULLWIDTH RIGHT SQUARE BRACKET + case 0xff3f: + return 0xfe33 // FULLWIDTH LOW LINE + case 0xff5b: + return 0xfe37 // FULLWIDTH LEFT CURLY BRACKET + case 0xff5d: + return 0xfe38 // FULLWIDTH RIGHT CURLY BRACKET + } + } + + return u +} + +func (c *otContext) otRotateChars() { + info := c.buffer.Info + + if c.targetDirection.isBackward() { + rtlmMask := c.plan.rtlmMask + + for i := range info { + codepoint := uni.mirroring(info[i].codepoint) + if codepoint != info[i].codepoint && c.font.hasGlyph(codepoint) { + info[i].codepoint = codepoint + } else { + info[i].Mask |= rtlmMask + } + } + } + + if c.targetDirection.isVertical() && !c.plan.hasVert { + for i := range info { + codepoint := vertCharFor(info[i].codepoint) + if codepoint != info[i].codepoint && c.font.hasGlyph(codepoint) { + info[i].codepoint = codepoint + } + } + } +} + +func (c *otContext) setupMasksFraction() { + if c.buffer.scratchFlags&bsfHasNonASCII == 0 || !c.plan.hasFrac { + return + } + + buffer := c.buffer + + var preMask, postMask GlyphMask + if buffer.Props.Direction.isForward() { + preMask = c.plan.numrMask | c.plan.fracMask + postMask = c.plan.fracMask | c.plan.dnomMask + } else { + preMask = c.plan.fracMask | c.plan.dnomMask + postMask = c.plan.numrMask | c.plan.fracMask + } + + count := len(buffer.Info) + info := buffer.Info + for i := 0; i < count; i++ { + if info[i].codepoint == 0x2044 /* FRACTION SLASH */ { + start, end := i, i+1 + for start != 0 && info[start-1].unicode.generalCategory() == decimalNumber { + start-- + } + for end < count && info[end].unicode.generalCategory() == decimalNumber { + end++ + } + + buffer.unsafeToBreak(start, end) + + for j := start; j < i; j++ { + info[j].Mask |= preMask + } + info[i].Mask |= c.plan.fracMask + for j := i + 1; j < end; j++ { + info[j].Mask |= postMask + } + + i = end - 1 + } + } +} + +func (c *otContext) initializeMasks() { + c.buffer.resetMasks(c.plan.map_.globalMask) +} + +func (c *otContext) setupMasks() { + map_ := &c.plan.map_ + buffer := c.buffer + + c.setupMasksFraction() + + c.plan.shaper.setupMasks(c.plan, buffer, c.font) + + for _, feature := range c.userFeatures { + if !(feature.Start == FeatureGlobalStart && feature.End == FeatureGlobalEnd) { + mask, shift := map_.getMask(feature.Tag) + buffer.setMasks(feature.Value<= 6 { + extlangEnd := strings.IndexByte(langStr[s+1:], '-') + // if there is an extended language tag, use it. + ref := extlangEnd + if extlangEnd == -1 { + ref = len(langStr[s+1:]) + } + if ref == 3 && isAlpha(langStr[s+1]) { + langStr = langStr[s+1:] + } + } + + if tagIdx := bfindLanguage(langStr); tagIdx != -1 { + for tagIdx != 0 && otLanguages[tagIdx].language == otLanguages[tagIdx-1].language { + tagIdx-- + } + var out []tables.Tag + for i := 0; tagIdx+i < len(otLanguages) && + otLanguages[tagIdx+i].tag != 0 && + otLanguages[tagIdx+i].language == otLanguages[tagIdx].language; i++ { + out = append(out, otLanguages[tagIdx+i].tag) + } + return out + } + + if s == -1 { + s = len(langStr) + } + if s == 3 { + // assume it's ISO-639-3 and upper-case and use it. + return []tables.Tag{ot.NewTag(langStr[0], langStr[1], langStr[2], ' ') & ^tables.Tag(0x20202000)} + } + + return nil +} + +// return 0 if no tag +func parsePrivateUseSubtag(privateUseSubtag string, prefix string, normalize func(byte) byte) (tables.Tag, bool) { + s := strings.Index(privateUseSubtag, prefix) + if s == -1 { + return 0, false + } + + var tag [4]byte + L := len(privateUseSubtag) + s += len(prefix) + if s < L && privateUseSubtag[s] == '-' { + s += 1 + if L < s+8 { + return 0, false + } + _, err := hex.Decode(tag[:], []byte(privateUseSubtag[s:s+8])) + if err != nil { + return 0, false + } + } else { + var i int + for ; i < 4 && s+i < L && isAlnum(privateUseSubtag[s+i]); i++ { + tag[i] = normalize(privateUseSubtag[s+i]) + } + if i == 0 { + return 0, false + } + + for ; i < 4; i++ { + tag[i] = ' ' + } + } + out := ot.NewTag(tag[0], tag[1], tag[2], tag[3]) + if (out & 0xDFDFDFDF) == tagDefaultScript { + out ^= ^tables.Tag(0xDFDFDFDF) + } + return out, true +} + +// newOTTagsFromScriptAndLanguage converts a `Script` and a `Language` +// to script and language tags. +func newOTTagsFromScriptAndLanguage(script language.Script, language language.Language) (scriptTags, languageTags []tables.Tag) { + if language != "" { + prefix, privateUseSubtag := language.SplitExtensionTags() + + s, hasScript := parsePrivateUseSubtag(string(privateUseSubtag), "-hbsc", toLower) + if hasScript { + scriptTags = []tables.Tag{s} + } + + l, hasLanguage := parsePrivateUseSubtag(string(privateUseSubtag), "-hbot", toUpper) + if hasLanguage { + languageTags = append(languageTags, l) + } else { + if prefix == "" { // if the language is 'fully private' + prefix = language + } + languageTags = otTagsFromLanguage(string(prefix)) // TODO: + } + } + + if len(scriptTags) == 0 { + scriptTags = allTagsFromScript(script) + } + return +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_thai.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_thai.go new file mode 100644 index 0000000..829eef8 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_thai.go @@ -0,0 +1,354 @@ +package harfbuzz + +import ( + "github.com/go-text/typesetting/language" +) + +// ported from harfbuzz/src/hb-ot-shape-complex-thai.cc Copyright © 2010,2012 Google, Inc. Behdad Esfahbod + +/* Thai / Lao shaper */ + +var _ otComplexShaper = complexShaperThai{} + +type complexShaperThai struct { + complexShaperNil +} + +/* PUA shaping */ + +// thai_consonant_type_t +const ( + tcNC = iota + tcAC + tcRC + tcDC + tcNOTCONSONANT + numConsonantTypes = tcNOTCONSONANT +) + +func getConsonantType(u rune) uint8 { + switch u { + case 0x0E1B, 0x0E1D, 0x0E1F /* , 0x0E2C*/ : + return tcAC + case 0x0E0D, 0x0E10: + return tcRC + case 0x0E0E, 0x0E0F: + return tcDC + } + if 0x0E01 <= u && u <= 0x0E2E { + return tcNC + } + return tcNOTCONSONANT +} + +// thai_mark_type_t +const ( + tmAV = iota + tmBV + tmT + tmNOTMARK + numMarkTypes = tmNOTMARK +) + +func getMarkType(u rune) uint8 { + if u == 0x0E31 || (0x0E34 <= u && u <= 0x0E37) || + u == 0x0E47 || (0x0E4D <= u && u <= 0x0E4E) { + return tmAV + } + if 0x0E38 <= u && u <= 0x0E3A { + return tmBV + } + if 0x0E48 <= u && u <= 0x0E4C { + return tmT + } + return tmNOTMARK +} + +// thai_action_t +const ( + tcNOP = iota + tcSD /* Shift combining-mark down */ + tcSL /* Shift combining-mark left */ + tcSDL /* Shift combining-mark down-left */ + tcRD /* Remove descender from base */ +) + +type thaiPuaMapping struct { + u, winPua, macPua rune +} + +var ( + sdMappings = [...]thaiPuaMapping{ + {0x0E48, 0xF70A, 0xF88B}, /* MAI EK */ + {0x0E49, 0xF70B, 0xF88E}, /* MAI THO */ + {0x0E4A, 0xF70C, 0xF891}, /* MAI TRI */ + {0x0E4B, 0xF70D, 0xF894}, /* MAI CHATTAWA */ + {0x0E4C, 0xF70E, 0xF897}, /* THANTHAKHAT */ + {0x0E38, 0xF718, 0xF89B}, /* SARA U */ + {0x0E39, 0xF719, 0xF89C}, /* SARA UU */ + {0x0E3A, 0xF71A, 0xF89D}, /* PHINTHU */ + {0x0000, 0x0000, 0x0000}, + } + sdlMappings = [...]thaiPuaMapping{ + {0x0E48, 0xF705, 0xF88C}, /* MAI EK */ + {0x0E49, 0xF706, 0xF88F}, /* MAI THO */ + {0x0E4A, 0xF707, 0xF892}, /* MAI TRI */ + {0x0E4B, 0xF708, 0xF895}, /* MAI CHATTAWA */ + {0x0E4C, 0xF709, 0xF898}, /* THANTHAKHAT */ + {0x0000, 0x0000, 0x0000}, + } + slMappings = [...]thaiPuaMapping{ + {0x0E48, 0xF713, 0xF88A}, /* MAI EK */ + {0x0E49, 0xF714, 0xF88D}, /* MAI THO */ + {0x0E4A, 0xF715, 0xF890}, /* MAI TRI */ + {0x0E4B, 0xF716, 0xF893}, /* MAI CHATTAWA */ + {0x0E4C, 0xF717, 0xF896}, /* THANTHAKHAT */ + {0x0E31, 0xF710, 0xF884}, /* MAI HAN-AKAT */ + {0x0E34, 0xF701, 0xF885}, /* SARA I */ + {0x0E35, 0xF702, 0xF886}, /* SARA II */ + {0x0E36, 0xF703, 0xF887}, /* SARA UE */ + {0x0E37, 0xF704, 0xF888}, /* SARA UEE */ + {0x0E47, 0xF712, 0xF889}, /* MAITAIKHU */ + {0x0E4D, 0xF711, 0xF899}, /* NIKHAHIT */ + {0x0000, 0x0000, 0x0000}, + } + rdMappings = [...]thaiPuaMapping{ + {0x0E0D, 0xF70F, 0xF89A}, /* YO YING */ + {0x0E10, 0xF700, 0xF89E}, /* THO THAN */ + {0x0000, 0x0000, 0x0000}, + } +) + +func thaiPuaShape(u rune, action uint8, font *Font) rune { + var puaMappings []thaiPuaMapping + switch action { + case tcNOP: + return u + case tcSD: + puaMappings = sdMappings[:] + case tcSDL: + puaMappings = sdlMappings[:] + case tcSL: + puaMappings = slMappings[:] + case tcRD: + puaMappings = rdMappings[:] + } + for _, pua := range puaMappings { + if pua.u == u { + _, ok := font.face.NominalGlyph(pua.winPua) + if ok { + return pua.winPua + } + _, ok = font.face.NominalGlyph(pua.macPua) + if ok { + return pua.macPua + } + break + } + } + return u +} + +const ( + /* Cluster above looks like: */ + tcT0 = iota /* ⣤ */ + tcT1 /* ⣼ */ + tcT2 /* ⣾ */ + tcT3 /* ⣿ */ + numAboveStates +) + +var thaiAboveStartState = [numConsonantTypes + 1] /* For NOT_CONSONANT */ uint8{ + tcT0, /* NC */ + tcT1, /* AC */ + tcT0, /* RC */ + tcT0, /* DC */ + tcT3, /* NOT_CONSONANT */ +} + +var thaiAboveStateMachine = [numAboveStates][numMarkTypes]struct { + action uint8 + nextState uint8 +}{ /*AV*/ /*BV*/ /*T*/ + /*T0*/ {{tcNOP, tcT3}, {tcNOP, tcT0}, {tcSD, tcT3}}, + /*T1*/ {{tcSL, tcT2}, {tcNOP, tcT1}, {tcSDL, tcT2}}, + /*T2*/ {{tcNOP, tcT3}, {tcNOP, tcT2}, {tcSL, tcT3}}, + /*T3*/ {{tcNOP, tcT3}, {tcNOP, tcT3}, {tcNOP, tcT3}}, +} + +// thai_below_state_t +const ( + tbB0 = iota /* No descender */ + tbB1 /* Removable descender */ + tbB2 /* Strict descender */ + numBelowStates +) + +var thaiBelowStartState = [numConsonantTypes + 1] /* For NOT_CONSONANT */ uint8{ + tbB0, /* NC */ + tbB0, /* AC */ + tbB1, /* RC */ + tbB2, /* DC */ + tbB2, /* NOT_CONSONANT */ +} + +var thaiBelowStateMachine = [numBelowStates][numMarkTypes]struct { + action uint8 + nextState uint8 +}{ /*AV*/ /*BV*/ /*T*/ + /*B0*/ {{tcNOP, tbB0}, {tcNOP, tbB2}, {tcNOP, tbB0}}, + /*B1*/ {{tcNOP, tbB1}, {tcRD, tbB2}, {tcNOP, tbB1}}, + /*B2*/ {{tcNOP, tbB2}, {tcSD, tbB2}, {tcNOP, tbB2}}, +} + +func doThaiPuaShaping(buffer *Buffer, font *Font) { + aboveState := thaiAboveStartState[tcNOTCONSONANT] + belowState := thaiBelowStartState[tcNOTCONSONANT] + base := 0 + + info := buffer.Info + // unsigned int count = buffer.len; + for i := range info { + mt := getMarkType(info[i].codepoint) + + if mt == tmNOTMARK { + ct := getConsonantType(info[i].codepoint) + aboveState = thaiAboveStartState[ct] + belowState = thaiBelowStartState[ct] + base = i + continue + } + + aboveEdge := &thaiAboveStateMachine[aboveState][mt] + belowEdge := &thaiBelowStateMachine[belowState][mt] + aboveState = aboveEdge.nextState + belowState = belowEdge.nextState + + // at least one of the above/below actions is NOP. + action := belowEdge.action + if aboveEdge.action != tcNOP { + action = aboveEdge.action + } + + buffer.unsafeToBreak(base, i) + if action == tcRD { + info[base].codepoint = thaiPuaShape(info[base].codepoint, action, font) + } else { + info[i].codepoint = thaiPuaShape(info[i].codepoint, action, font) + } + } +} + +/* We only get one script at a time, so a script-agnostic implementation +* is adequate here. */ +func isSaraAm(x rune) bool { return x & ^0x0080 == 0x0E33 } +func nikhahitFromSaraAm(x rune) rune { return x - 0x0E33 + 0x0E4D } +func saraAaFromSaraAm(x rune) rune { return x - 1 } +func isAboveBaseMark(x rune) bool { + u := x & ^0x0080 + return 0x0E34 <= u && u <= 0x0E37 || + 0x0E47 <= u && u <= 0x0E4E || + u == 0x0E31 || + u == 0x0E3B +} + +/* This function implements the shaping logic documented here: + * + * https://linux.thai.net/~thep/th-otf/shaping.html + * + * The first shaping rule listed there is needed even if the font has Thai + * OpenType tables. The rest do fallback positioning based on PUA codepoints. + * We implement that only if there exist no Thai GSUB in the font. + */ +func (complexShaperThai) preprocessText(plan *otShapePlan, buffer *Buffer, font *Font) { + // The following is NOT specified in the MS OT Thai spec, however, it seems + // to be what Uniscribe and other engines implement. According to Eric Muller: + // + // When you have a SARA AM, decompose it in NIKHAHIT + SARA AA, *and* move the + // NIKHAHIT backwards over any above-base marks. + // + // <0E14, 0E4B, 0E33> . <0E14, 0E4D, 0E4B, 0E32> + // + // This reordering is legit only when the NIKHAHIT comes from a SARA AM, not + // when it's there to start with. The string <0E14, 0E4B, 0E4D> is probably + // not what a user wanted, but the rendering is nevertheless nikhahit above + // chattawa. + // + // Same for Lao. + // + // Note: + // + // Uniscribe also does some below-marks reordering. Namely, it positions U+0E3A + // after U+0E38 and U+0E39. We do that by modifying the ccc for U+0E3A. + // See unicode.modified_combining_class (). Lao does NOT have a U+0E3A + // equivalent. + // + + // + // Here are the characters of significance: + // + // Thai Lao + // SARA AM: U+0E33 U+0EB3 + // SARA AA: U+0E32 U+0EB2 + // Nikhahit: U+0E4D U+0ECD + // + // Testing shows that Uniscribe reorder the following marks: + // Thai: <0E31,0E34..0E37, 0E47..0E4E> + // Lao: <0EB1,0EB4..0EB7,0EBB,0EC8..0ECD> + // + // Note how the Lao versions are the same as Thai + 0x80. + // + + buffer.clearOutput() + count := len(buffer.Info) + for buffer.idx = 0; buffer.idx < count; { + u := buffer.cur(0).codepoint + if !isSaraAm(u) { + buffer.nextGlyph() + continue + } + + /* Is SARA AM. Decompose and reorder. */ + buffer.outputRune(nikhahitFromSaraAm(u)) + buffer.prev().setContinuation() + buffer.replaceGlyph(saraAaFromSaraAm(u)) + + /* Make Nikhahit be recognized as a ccc=0 mark when zeroing widths. */ + end := len(buffer.outInfo) + buffer.outInfo[end-2].setGeneralCategory(nonSpacingMark) + + /* Ok, let's see... */ + start := end - 2 + for start > 0 && isAboveBaseMark(buffer.outInfo[start-1].codepoint) { + start-- + } + + if start+2 < end { + /* Move Nikhahit (end-2) to the beginning */ + buffer.mergeOutClusters(start, end) + t := buffer.outInfo[end-2] + copy(buffer.outInfo[start+1:], buffer.outInfo[start:end-2]) + buffer.outInfo[start] = t + } else { + /* Since we decomposed, and NIKHAHIT is combining, merge clusters with the + * previous cluster. */ + if start != 0 && buffer.ClusterLevel == MonotoneGraphemes { + buffer.mergeOutClusters(start-1, end) + } + } + } + buffer.swapBuffers() + + /* If font has Thai GSUB, we are done. */ + if plan.props.Script == language.Thai && !plan.map_.foundScript[0] { + doThaiPuaShaping(buffer, font) + } +} + +func (complexShaperThai) marksBehavior() (zeroWidthMarks, bool) { + return zeroWidthMarksByGdefLate, false +} + +func (complexShaperThai) normalizationPreference() normalizationMode { + return nmDefault +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_use.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_use.go new file mode 100644 index 0000000..75496fb --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_use.go @@ -0,0 +1,388 @@ +package harfbuzz + +import ( + "fmt" + + ot "github.com/go-text/typesetting/font/opentype" + "github.com/go-text/typesetting/font/opentype/tables" +) + +// ported from harfbuzz/src/hb-ot-shape-complex-use.cc Copyright © 2015 Mozilla Foundation. Google, Inc. Jonathan Kew, Behdad Esfahbod + +/* + * Universal Shaping Engine. + * https://docs.microsoft.com/en-us/typography/script-development/use + */ + +var _ otComplexShaper = (*complexShaperUSE)(nil) + +/* + * Basic features. + * These features are applied all at once, before reordering. + */ +var useBasicFeatures = [...]tables.Tag{ + ot.NewTag('r', 'k', 'r', 'f'), + ot.NewTag('a', 'b', 'v', 'f'), + ot.NewTag('b', 'l', 'w', 'f'), + ot.NewTag('h', 'a', 'l', 'f'), + ot.NewTag('p', 's', 't', 'f'), + ot.NewTag('v', 'a', 't', 'u'), + ot.NewTag('c', 'j', 'c', 't'), +} + +var useTopographicalFeatures = [...]tables.Tag{ + ot.NewTag('i', 's', 'o', 'l'), + ot.NewTag('i', 'n', 'i', 't'), + ot.NewTag('m', 'e', 'd', 'i'), + ot.NewTag('f', 'i', 'n', 'a'), +} + +/* Same order as useTopographicalFeatures. */ +const ( + joiningFormIsol = iota + joiningFormInit + joiningFormMedi + joiningFormFina + joiningFormNone +) + +/* + * Other features. + * These features are applied all at once, after reordering and + * clearing syllables. + */ +var useOtherFeatures = [...]tables.Tag{ + ot.NewTag('a', 'b', 'v', 's'), + ot.NewTag('b', 'l', 'w', 's'), + ot.NewTag('h', 'a', 'l', 'n'), + ot.NewTag('p', 'r', 'e', 's'), + ot.NewTag('p', 's', 't', 's'), +} + +type useShapePlan struct { + arabicPlan *arabicShapePlan + rphfMask GlyphMask +} + +type complexShaperUSE struct { + complexShaperNil + + plan useShapePlan +} + +func (cs *complexShaperUSE) collectFeatures(plan *otShapePlanner) { + map_ := &plan.map_ + + /* Do this before any lookups have been applied. */ + map_.addGSUBPause(cs.setupSyllablesUse) + + /* "Default glyph pre-processing group" */ + map_.enableFeatureExt(ot.NewTag('l', 'o', 'c', 'l'), ffPerSyllable, 1) + map_.enableFeatureExt(ot.NewTag('c', 'c', 'm', 'p'), ffPerSyllable, 1) + map_.enableFeatureExt(ot.NewTag('n', 'u', 'k', 't'), ffPerSyllable, 1) + map_.enableFeatureExt(ot.NewTag('a', 'k', 'h', 'n'), ffManualZWJ|ffPerSyllable, 1) + + /* "Reordering group" */ + map_.addGSUBPause(clearSubstitutionFlags) + map_.addFeatureExt(ot.NewTag('r', 'p', 'h', 'f'), ffManualZWJ|ffPerSyllable, 1) + map_.addGSUBPause(cs.recordRphfUse) + map_.addGSUBPause(clearSubstitutionFlags) + map_.enableFeatureExt(ot.NewTag('p', 'r', 'e', 'f'), ffManualZWJ|ffPerSyllable, 1) + map_.addGSUBPause(recordPrefUse) + + /* "Orthographic unit shaping group" */ + for _, basicFeat := range useBasicFeatures { + map_.enableFeatureExt(basicFeat, ffManualZWJ|ffPerSyllable, 1) + } + + map_.addGSUBPause(reorderUse) + map_.addGSUBPause(nil) + + /* "Topographical features" */ + for _, topoFeat := range useTopographicalFeatures { + map_.addFeature(topoFeat) + } + map_.addGSUBPause(nil) + + /* "Standard typographic presentation" */ + for _, otherFeat := range useOtherFeatures { + map_.enableFeatureExt(otherFeat, ffManualZWJ, 1) + } +} + +func (cs *complexShaperUSE) dataCreate(plan *otShapePlan) { + var usePlan useShapePlan + + usePlan.rphfMask = plan.map_.getMask1(ot.NewTag('r', 'p', 'h', 'f')) + + if hasArabicJoining(plan.props.Script) { + pl := newArabicPlan(plan) + usePlan.arabicPlan = &pl + } + + cs.plan = usePlan +} + +func (cs *complexShaperUSE) setupMasks(plan *otShapePlan, buffer *Buffer, _ *Font) { + usePlan := cs.plan + /* Do this before allocating complexCategory. */ + if usePlan.arabicPlan != nil { + usePlan.arabicPlan.setupMasks(buffer, plan.props.Script) + } + + /* We cannot setup masks here. We save information about characters + * and setup masks later on in a pause-callback. */ + + info := buffer.Info + for i := range info { + info[i].complexCategory = getUSECategory(info[i].codepoint) + } +} + +func (cs *complexShaperUSE) setupRphfMask(buffer *Buffer) { + usePlan := cs.plan + + mask := usePlan.rphfMask + if mask == 0 { + return + } + + info := buffer.Info + iter, count := buffer.syllableIterator() + for start, end := iter.next(); start < count; start, end = iter.next() { + limit := 1 + if info[start].complexCategory != useSM_ex_R { + limit = min(3, end-start) + } + for i := start; i < start+limit; i++ { + info[i].Mask |= mask + } + } +} + +func (cs *complexShaperUSE) setupTopographicalMasks(plan *otShapePlan, buffer *Buffer) { + if cs.plan.arabicPlan != nil { + return + } + var ( + masks [4]GlyphMask + allMasks uint32 + ) + for i := range masks { + masks[i] = plan.map_.getMask1(useTopographicalFeatures[i]) + if masks[i] == plan.map_.globalMask { + masks[i] = 0 + } + allMasks |= masks[i] + } + if allMasks == 0 { + return + } + otherMasks := ^allMasks + + lastStart := 0 + lastForm := joiningFormNone + info := buffer.Info + iter, count := buffer.syllableIterator() + for start, end := iter.next(); start < count; start, end = iter.next() { + syllableType := info[start].syllable & 0x0F + switch syllableType { + case useHieroglyphCluster, useNonCluster: + // these don't join. Nothing to do. + lastForm = joiningFormNone + + case useViramaTerminatedCluster, useSakotTerminatedCluster, useStandardCluster, useNumberJoinerTerminatedCluster, + useNumeralCluster, useSymbolCluster, useBrokenCluster: + join := lastForm == joiningFormFina || lastForm == joiningFormIsol + if join { + // fixup previous syllable's form. + if lastForm == joiningFormFina { + lastForm = joiningFormMedi + } else { + lastForm = joiningFormInit + } + for i := lastStart; i < start; i++ { + info[i].Mask = (info[i].Mask & otherMasks) | masks[lastForm] + } + } + + // form for this syllable. + lastForm = joiningFormIsol + if join { + lastForm = joiningFormFina + } + for i := start; i < end; i++ { + info[i].Mask = (info[i].Mask & otherMasks) | masks[lastForm] + } + } + + lastStart = start + } +} + +func (cs *complexShaperUSE) setupSyllablesUse(plan *otShapePlan, _ *Font, buffer *Buffer) bool { + findSyllablesUse(buffer) + iter, count := buffer.syllableIterator() + for start, end := iter.next(); start < count; start, end = iter.next() { + buffer.unsafeToBreak(start, end) + } + cs.setupRphfMask(buffer) + cs.setupTopographicalMasks(plan, buffer) + return false +} + +func (cs *complexShaperUSE) recordRphfUse(plan *otShapePlan, _ *Font, buffer *Buffer) bool { + usePlan := cs.plan + + mask := usePlan.rphfMask + if mask == 0 { + return false + } + info := buffer.Info + + iter, count := buffer.syllableIterator() + for start, end := iter.next(); start < count; start, end = iter.next() { + // mark a substituted repha as USE(R). + for i := start; i < end && (info[i].Mask&mask) != 0; i++ { + if glyphInfoSubstituted(&info[i]) { + info[i].complexCategory = useSM_ex_R + break + } + } + } + return false +} + +func recordPrefUse(_ *otShapePlan, _ *Font, buffer *Buffer) bool { + info := buffer.Info + + iter, count := buffer.syllableIterator() + for start, end := iter.next(); start < count; start, end = iter.next() { + // mark a substituted pref as VPre, as they behave the same way. + for i := start; i < end; i++ { + if glyphInfoSubstituted(&info[i]) { + info[i].complexCategory = useSM_ex_VPre + break + } + } + } + return false +} + +func isHalantUse(info *GlyphInfo) bool { + return (info.complexCategory == useSM_ex_H || info.complexCategory == useSM_ex_HVM || info.complexCategory == useSM_ex_IS) && + !info.ligated() +} + +func reorderSyllableUse(buffer *Buffer, start, end int) { + syllableType := (buffer.Info[start].syllable & 0x0F) + /* Only a few syllable types need reordering. */ + const mask = 1< 1 { + /* Got a repha. Reorder it towards the end, but before the first post-base + * glyph. */ + for i := start + 1; i < end; i++ { + isPostBaseGlyph := (int64(1<<(info[i].complexCategory))&postBaseFlags64) != 0 || + isHalantUse(&info[i]) + if isPostBaseGlyph || i == end-1 { + /* If we hit a post-base glyph, move before it; otherwise move to the + * end. Shift things in between backward. */ + + if isPostBaseGlyph { + i-- + } + + buffer.mergeClusters(start, i+1) + t := info[start] + copy(info[start:i], info[start+1:]) + info[i] = t + + break + } + } + } + + /* Move things back. */ + j := start + for i := start; i < end; i++ { + flag := 1 << (info[i].complexCategory) + if isHalantUse(&info[i]) { + /* If we hit a halant, move after it; otherwise move to the beginning, and + * shift things in between forward. */ + j = i + 1 + } else if flag&(1< 0; _nacts-- { + _acts++ + switch _useSM_actions[_acts-1] { + case 1: + ts = p + + } + } + + _keys = int(_useSM_key_offsets[cs]) + _trans = int(_useSM_index_offsets[cs]) + + _klen = int(_useSM_single_lengths[cs]) + if _klen > 0 { + _lower := int(_keys) + var _mid int + _upper := int(_keys + _klen - 1) + for { + if _upper < _lower { + break + } + + _mid = _lower + ((_upper - _lower) >> 1) + switch { + case ((data[p]).p.v.complexCategory) < _useSM_trans_keys[_mid]: + _upper = _mid - 1 + case ((data[p]).p.v.complexCategory) > _useSM_trans_keys[_mid]: + _lower = _mid + 1 + default: + _trans += int(_mid - int(_keys)) + goto _match + } + } + _keys += _klen + _trans += _klen + } + + _klen = int(_useSM_range_lengths[cs]) + if _klen > 0 { + _lower := int(_keys) + var _mid int + _upper := int(_keys + (_klen << 1) - 2) + for { + if _upper < _lower { + break + } + + _mid = _lower + (((_upper - _lower) >> 1) & ^1) + switch { + case ((data[p]).p.v.complexCategory) < _useSM_trans_keys[_mid]: + _upper = _mid - 2 + case ((data[p]).p.v.complexCategory) > _useSM_trans_keys[_mid+1]: + _lower = _mid + 2 + default: + _trans += int((_mid - int(_keys)) >> 1) + goto _match + } + } + _trans += _klen + } + + _match: + _trans = int(_useSM_indicies[_trans]) + _eof_trans: + cs = int(_useSM_trans_targs[_trans]) + + if _useSM_trans_actions[_trans] == 0 { + goto _again + } + + _acts = int(_useSM_trans_actions[_trans]) + _nacts = uint(_useSM_actions[_acts]) + _acts++ + for ; _nacts > 0; _nacts-- { + _acts++ + switch _useSM_actions[_acts-1] { + case 2: + te = p + 1 + { + foundSyllableUSE(useViramaTerminatedCluster, data, ts, te, info, &syllableSerial) + } + case 3: + te = p + 1 + { + foundSyllableUSE(useSakotTerminatedCluster, data, ts, te, info, &syllableSerial) + } + case 4: + te = p + 1 + { + foundSyllableUSE(useStandardCluster, data, ts, te, info, &syllableSerial) + } + case 5: + te = p + 1 + { + foundSyllableUSE(useNumberJoinerTerminatedCluster, data, ts, te, info, &syllableSerial) + } + case 6: + te = p + 1 + { + foundSyllableUSE(useNumeralCluster, data, ts, te, info, &syllableSerial) + } + case 7: + te = p + 1 + { + foundSyllableUSE(useSymbolCluster, data, ts, te, info, &syllableSerial) + } + case 8: + te = p + 1 + { + foundSyllableUSE(useHieroglyphCluster, data, ts, te, info, &syllableSerial) + } + case 9: + te = p + 1 + { + foundSyllableUSE(useBrokenCluster, data, ts, te, info, &syllableSerial) + buffer.scratchFlags |= bsfHasBrokenSyllable + } + case 10: + te = p + 1 + { + foundSyllableUSE(useNonCluster, data, ts, te, info, &syllableSerial) + } + case 11: + te = p + p-- + { + foundSyllableUSE(useViramaTerminatedCluster, data, ts, te, info, &syllableSerial) + } + case 12: + te = p + p-- + { + foundSyllableUSE(useSakotTerminatedCluster, data, ts, te, info, &syllableSerial) + } + case 13: + te = p + p-- + { + foundSyllableUSE(useStandardCluster, data, ts, te, info, &syllableSerial) + } + case 14: + te = p + p-- + { + foundSyllableUSE(useNumberJoinerTerminatedCluster, data, ts, te, info, &syllableSerial) + } + case 15: + te = p + p-- + { + foundSyllableUSE(useNumeralCluster, data, ts, te, info, &syllableSerial) + } + case 16: + te = p + p-- + { + foundSyllableUSE(useSymbolCluster, data, ts, te, info, &syllableSerial) + } + case 17: + te = p + p-- + { + foundSyllableUSE(useHieroglyphCluster, data, ts, te, info, &syllableSerial) + } + case 18: + te = p + p-- + { + foundSyllableUSE(useBrokenCluster, data, ts, te, info, &syllableSerial) + buffer.scratchFlags |= bsfHasBrokenSyllable + } + case 19: + te = p + p-- + { + foundSyllableUSE(useNonCluster, data, ts, te, info, &syllableSerial) + } + } + } + + _again: + _acts = int(_useSM_to_state_actions[cs]) + _nacts = uint(_useSM_actions[_acts]) + _acts++ + for ; _nacts > 0; _nacts-- { + _acts++ + switch _useSM_actions[_acts-1] { + case 0: + ts = 0 + + } + } + + p++ + if p != pe { + goto _resume + } + _test_eof: + { + } + if p == eof { + if _useSM_eof_trans[cs] > 0 { + _trans = int(_useSM_eof_trans[cs] - 1) + goto _eof_trans + } + } + + } + + _ = act // needed by Ragel, but unused +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_use_machine.rl b/vendor/github.com/go-text/typesetting/harfbuzz/ot_use_machine.rl new file mode 100644 index 0000000..c2ce990 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_use_machine.rl @@ -0,0 +1,167 @@ +package harfbuzz + +// Code generated with ragel -Z -o ot_use_machine.go ot_use_machine.rl ; sed -i '/^\/\/line/ d' ot_use_machine.go ; goimports -w ot_use_machine.go DO NOT EDIT. + +// ported from harfbuzz/src/hb-ot-shape-complex-use-machine.rl Copyright © 2015 Mozilla Foundation. Google, Inc. Jonathan Kew Behdad Esfahbod + +const ( + useViramaTerminatedCluster = iota + useSakotTerminatedCluster + useStandardCluster + useNumberJoinerTerminatedCluster + useNumeralCluster + useSymbolCluster + useHieroglyphCluster + useBrokenCluster + useNonCluster +) + +%%{ + machine useSM; + alphtype byte; + write exports; + write data; +}%% + +%%{ + +# Categories used in the Universal Shaping Engine spec: +# https://docs.microsoft.com/en-us/typography/script-development/use + +export O = 0; # OTHER + +export B = 1; # BASE +export N = 4; # BASE_NUM +export GB = 5; # BASE_OTHER +export CGJ = 6; # CGJ +export SUB = 11; # CONS_SUB +export H = 12; # HALANT + +export HN = 13; # HALANT_NUM +export ZWNJ = 14; # Zero width non-joiner +export WJ = 16; # Word joiner +export R = 18; # REPHA +export CS = 43; # CONS_WITH_STACKER +export IS = 44; # INVISIBLE_STACKER +export Sk = 48; # SAKOT +export G = 49; # HIEROGLYPH +export J = 50; # HIEROGLYPH_JOINER +export SB = 51; # HIEROGLYPH_SEGMENT_BEGIN +export SE = 52; # HIEROGLYPH_SEGMENT_END +export HVM = 53; # HALANT_OR_VOWEL_MODIFIER + +export FAbv = 24; # CONS_FINAL_ABOVE +export FBlw = 25; # CONS_FINAL_BELOW +export FPst = 26; # CONS_FINAL_POST +export MAbv = 27; # CONS_MED_ABOVE +export MBlw = 28; # CONS_MED_BELOW +export MPst = 29; # CONS_MED_POST +export MPre = 30; # CONS_MED_PRE +export CMAbv = 31; # CONS_MOD_ABOVE +export CMBlw = 32; # CONS_MOD_BELOW +export VAbv = 33; # VOWEL_ABOVE / VOWEL_ABOVE_BELOW / VOWEL_ABOVE_BELOW_POST / VOWEL_ABOVE_POST +export VBlw = 34; # VOWEL_BELOW / VOWEL_BELOW_POST +export VPst = 35; # VOWEL_POST UIPC = Right +export VPre = 22; # VOWEL_PRE / VOWEL_PRE_ABOVE / VOWEL_PRE_ABOVE_POST / VOWEL_PRE_POST +export VMAbv = 37; # VOWEL_MOD_ABOVE +export VMBlw = 38; # VOWEL_MOD_BELOW +export VMPst = 39; # VOWEL_MOD_POST +export VMPre = 23; # VOWEL_MOD_PRE +export SMAbv = 41; # SYM_MOD_ABOVE +export SMBlw = 42; # SYM_MOD_BELOW +export FMAbv = 45; # CONS_FINAL_MOD UIPC = Top +export FMBlw = 46; # CONS_FINAL_MOD UIPC = Bottom +export FMPst = 47; # CONS_FINAL_MOD UIPC = Not_Applicable + +h = H | HVM | IS | Sk; + +consonant_modifiers = CMAbv* CMBlw* ((h B | SUB) CMAbv? CMBlw*)*; +medial_consonants = MPre? MAbv? MBlw? MPst?; +dependent_vowels = VPre* VAbv* VBlw* VPst* | H; +vowel_modifiers = HVM? VMPre* VMAbv* VMBlw* VMPst*; +final_consonants = FAbv* FBlw* FPst*; +final_modifiers = FMAbv* FMBlw* | FMPst?; + +complex_syllable_start = (R | CS)? (B | GB); +complex_syllable_middle = + consonant_modifiers + medial_consonants + dependent_vowels + vowel_modifiers + (Sk B)* +; +complex_syllable_tail = + complex_syllable_middle + final_consonants + final_modifiers +; +number_joiner_terminated_cluster_tail = (HN N)* HN; +numeral_cluster_tail = (HN N)+; +symbol_cluster_tail = SMAbv+ SMBlw* | SMBlw+; + +virama_terminated_cluster_tail = + consonant_modifiers + IS +; +virama_terminated_cluster = + complex_syllable_start + virama_terminated_cluster_tail +; +sakot_terminated_cluster_tail = + complex_syllable_middle + Sk +; +sakot_terminated_cluster = + complex_syllable_start + sakot_terminated_cluster_tail +; +standard_cluster = + complex_syllable_start + complex_syllable_tail +; +tail = complex_syllable_tail | sakot_terminated_cluster_tail | symbol_cluster_tail | virama_terminated_cluster_tail; +broken_cluster = + R? + (tail | number_joiner_terminated_cluster_tail | numeral_cluster_tail) +; + +number_joiner_terminated_cluster = N number_joiner_terminated_cluster_tail; +numeral_cluster = N numeral_cluster_tail?; +symbol_cluster = (O | GB) tail?; +hieroglyph_cluster = SB+ | SB* G SE* (J SE* (G SE*)?)*; + +other = any; + +main := |* + virama_terminated_cluster ZWNJ? => { foundSyllableUSE (useViramaTerminatedCluster,data, ts, te, info, &syllableSerial); }; + sakot_terminated_cluster ZWNJ? => { foundSyllableUSE (useSakotTerminatedCluster,data, ts, te, info, &syllableSerial); }; + standard_cluster ZWNJ? => { foundSyllableUSE (useStandardCluster,data, ts, te, info, &syllableSerial); }; + number_joiner_terminated_cluster ZWNJ? => { foundSyllableUSE (useNumberJoinerTerminatedCluster,data, ts, te, info, &syllableSerial); }; + numeral_cluster ZWNJ? => { foundSyllableUSE (useNumeralCluster,data, ts, te, info, &syllableSerial); }; + symbol_cluster ZWNJ? => { foundSyllableUSE (useSymbolCluster,data, ts, te, info, &syllableSerial); }; + hieroglyph_cluster ZWNJ? => { foundSyllableUSE (useHieroglyphCluster,data, ts, te, info, &syllableSerial); }; + broken_cluster ZWNJ? => { foundSyllableUSE (useBrokenCluster,data, ts, te, info, &syllableSerial); buffer.scratchFlags |= bsfHasBrokenSyllable; }; + other => { foundSyllableUSE (useNonCluster,data, ts, te, info, &syllableSerial); }; +*|; + +}%% + +func findSyllablesUse (buffer * Buffer) { + info := buffer.Info + data := preprocessInfoUSE(info) + p, pe := 0, len(data) + eof := pe + var cs, act, ts, te int + %%{ + write init; + getkey (data[p]).p.v.complexCategory; + }%% + + var syllableSerial uint8 = 1; + %%{ + write exec; + }%% + _ = act // needed by Ragel, but unused +} + + diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_use_machine_defs.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_use_machine_defs.go new file mode 100644 index 0000000..68e6d02 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_use_machine_defs.go @@ -0,0 +1,59 @@ +package harfbuzz + +// logic needed by the USE rl parser + +func notCCSDefaultIgnorable(i GlyphInfo) bool { + return i.complexCategory != useSM_ex_CGJ +} + +type pairUSE struct { + i int // index in the original info slice + v GlyphInfo +} + +type machineIndexUSE struct { + j int // index in the filtered slice + p pairUSE +} + +func preprocessInfoUSE(info []GlyphInfo) []machineIndexUSE { + filterMark := func(p pairUSE) bool { + if p.v.complexCategory == useSM_ex_ZWNJ { + for i := p.i + 1; i < len(info); i++ { + if notCCSDefaultIgnorable(info[i]) { + return !info[i].isUnicodeMark() + } + } + } + return true + } + var tmp []pairUSE + for i, v := range info { + if notCCSDefaultIgnorable(v) { + p := pairUSE{i, v} + if filterMark(p) { + tmp = append(tmp, p) + } + } + } + data := make([]machineIndexUSE, len(tmp)) + for j, p := range tmp { + data[j] = machineIndexUSE{j: j, p: p} + } + return data +} + +func foundSyllableUSE(syllableType uint8, data []machineIndexUSE, ts, te int, info []GlyphInfo, syllableSerial *uint8) { + start := data[ts].p.i + end := len(info) // te might right after the end of data + if te < len(data) { + end = data[te].p.i + } + for i := start; i < end; i++ { + info[i].syllable = (*syllableSerial << 4) | syllableType + } + *syllableSerial++ + if *syllableSerial == 16 { + *syllableSerial = 1 + } +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_use_table.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_use_table.go new file mode 100644 index 0000000..5b06a52 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_use_table.go @@ -0,0 +1,1486 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package harfbuzz + +// Code generated by typesettings-utils/generators/unicodedata/cmd/main.go DO NOT EDIT. +const ( + _B = useSM_ex_B + _CGJ = useSM_ex_CGJ + _CS = useSM_ex_CS + _G = useSM_ex_G + _GB = useSM_ex_GB + _H = useSM_ex_H + _HN = useSM_ex_HN + _HVM = useSM_ex_HVM + _IS = useSM_ex_IS + _J = useSM_ex_J + _N = useSM_ex_N + _O = useSM_ex_O + _R = useSM_ex_R + _SB = useSM_ex_SB + _SE = useSM_ex_SE + _SUB = useSM_ex_SUB + _Sk = useSM_ex_Sk + _WJ = useSM_ex_WJ + _ZWNJ = useSM_ex_ZWNJ +) +const ( + _CMAbv = useSM_ex_CMAbv + _CMBlw = useSM_ex_CMBlw + _FAbv = useSM_ex_FAbv + _FBlw = useSM_ex_FBlw + _FPst = useSM_ex_FPst + _FMAbv = useSM_ex_FMAbv + _FMBlw = useSM_ex_FMBlw + _FMPst = useSM_ex_FMPst + _MAbv = useSM_ex_MAbv + _MBlw = useSM_ex_MBlw + _MPre = useSM_ex_MPre + _MPst = useSM_ex_MPst + _SMAbv = useSM_ex_SMAbv + _SMBlw = useSM_ex_SMBlw + _VAbv = useSM_ex_VAbv + _VBlw = useSM_ex_VBlw + _VPre = useSM_ex_VPre + _VPst = useSM_ex_VPst + _VMAbv = useSM_ex_VMAbv + _VMBlw = useSM_ex_VMBlw + _VMPre = useSM_ex_VMPre + _VMPst = useSM_ex_VMPst +) + +var useTable = [...]uint8{ + + /* Basic Latin */ + _O, _O, _O, _O, _O, _GB, _O, _O, + /* 0030 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _O, _O, _O, _O, _O, _O, + + /* Latin-1 Supplement */ + + /* 00A0 */ _GB, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _WJ, _O, _O, + /* 00B0 */ _O, _O, _FMPst, _FMPst, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, + /* 00C0 */ _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, + /* 00D0 */ _O, _O, _O, _O, _O, _O, _O, _GB, + + /* Combining Diacritical Marks */ + _O, _O, _O, _O, _O, _O, _O, _CGJ, + + /* Arabic */ + + /* 0640 */ _B, _O, _O, _O, _O, _O, _O, _O, + + /* NKo */ + _O, _O, _B, _B, _B, _B, _B, _B, + /* 07D0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 07E0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VMAbv, + /* 07F0 */ _VMAbv, _VMAbv, _VMAbv, _VMAbv, _O, _O, _O, _O, + + /* Mandaic */ + + /* 0840 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0850 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _CMBlw, _CMBlw, _CMBlw, _WJ, _WJ, _O, _WJ, + + /* Devanagari */ + + /* 0900 */ _VMAbv, _VMAbv, _VMAbv, _VMPst, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0910 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0920 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0930 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _VAbv, _VPst, _CMBlw, _B, _VPst, _VPre, + /* 0940 */ _VPst, _VBlw, _VBlw, _VBlw, _VBlw, _VAbv, _VAbv, _VAbv, _VAbv, _VPst, _VPst, _VPst, _VPst, _H, _VPre, _VPst, + /* 0950 */ _O, _VMAbv, _VMBlw, _O, _O, _VAbv, _VBlw, _VBlw, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0960 */ _B, _B, _VBlw, _VBlw, _O, _O, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0970 */ _O, _O, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + + /* Bengali */ + + /* 0980 */ _GB, _VMAbv, _VMPst, _VMPst, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _B, + /* 0990 */ _B, _WJ, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 09A0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _B, _B, _B, _B, _B, _B, + /* 09B0 */ _B, _WJ, _B, _WJ, _WJ, _WJ, _B, _B, _B, _B, _WJ, _WJ, _CMBlw, _B, _VPst, _VPre, + /* 09C0 */ _VPst, _VBlw, _VBlw, _VBlw, _VBlw, _WJ, _WJ, _VPre, _VPre, _WJ, _WJ, _VPre, _VPre, _H, _O, _WJ, + /* 09D0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _VPst, _WJ, _WJ, _WJ, _WJ, _B, _B, _WJ, _B, + /* 09E0 */ _B, _B, _VBlw, _VBlw, _WJ, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 09F0 */ _B, _B, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _B, _O, _FMAbv, _WJ, + + /* Gurmukhi */ + + /* 0A00 */ _WJ, _VMAbv, _VMAbv, _VMPst, _WJ, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _B, + /* 0A10 */ _B, _WJ, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0A20 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _B, _B, _B, _B, _B, _B, + /* 0A30 */ _B, _WJ, _B, _B, _WJ, _B, _B, _WJ, _B, _B, _WJ, _WJ, _CMBlw, _WJ, _VPst, _VPre, + /* 0A40 */ _VPst, _VBlw, _VBlw, _WJ, _WJ, _WJ, _WJ, _VAbv, _VAbv, _WJ, _WJ, _VAbv, _VAbv, _H, _WJ, _WJ, + /* 0A50 */ _WJ, _VMBlw, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _B, _B, _B, _B, _WJ, _B, _WJ, + /* 0A60 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0A70 */ _VMAbv, _CMAbv, _GB, _GB, _O, _MBlw, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Gujarati */ + + /* 0A80 */ _WJ, _VMAbv, _VMAbv, _VMPst, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _B, + /* 0A90 */ _B, _B, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0AA0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _B, _B, _B, _B, _B, _B, + /* 0AB0 */ _B, _WJ, _B, _B, _WJ, _B, _B, _B, _B, _B, _WJ, _WJ, _CMBlw, _B, _VPst, _VPre, + /* 0AC0 */ _VPst, _VBlw, _VBlw, _VBlw, _VBlw, _VAbv, _WJ, _VAbv, _VAbv, _VAbv, _WJ, _VPst, _VPst, _H, _WJ, _WJ, + /* 0AD0 */ _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 0AE0 */ _B, _B, _VBlw, _VBlw, _WJ, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0AF0 */ _O, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _B, _VMAbv, _CMAbv, _VMAbv, _CMAbv, _CMAbv, _CMAbv, + /* 0B00 */ _WJ, _VMAbv, _VMPst, _VMPst, _WJ, _B, _B, _B, + + /* Oriya */ + _B, _B, _B, _B, _B, _WJ, _WJ, _B, + /* 0B10 */ _B, _WJ, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0B20 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _B, _B, _B, _B, _B, _B, + /* 0B30 */ _B, _WJ, _B, _B, _WJ, _B, _B, _B, _B, _B, _WJ, _WJ, _CMBlw, _B, _VPst, _VAbv, + /* 0B40 */ _VPst, _VBlw, _VBlw, _VBlw, _VBlw, _WJ, _WJ, _VPre, _VPre, _WJ, _WJ, _VPre, _VPre, _H, _WJ, _WJ, + /* 0B50 */ _WJ, _WJ, _WJ, _WJ, _WJ, _VAbv, _VAbv, _VAbv, _WJ, _WJ, _WJ, _WJ, _B, _B, _WJ, _B, + /* 0B60 */ _B, _B, _VBlw, _VBlw, _WJ, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0B70 */ _O, _B, _O, _O, _O, _O, _O, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Tamil */ + + /* 0B80 */ _WJ, _WJ, _VMAbv, _O, _WJ, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _B, _B, + /* 0B90 */ _B, _WJ, _B, _B, _B, _B, _WJ, _WJ, _WJ, _B, _B, _WJ, _B, _WJ, _B, _B, + /* 0BA0 */ _WJ, _WJ, _WJ, _B, _B, _WJ, _WJ, _WJ, _B, _B, _B, _WJ, _WJ, _WJ, _B, _B, + /* 0BB0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _VPst, _VPst, + /* 0BC0 */ _VAbv, _VPst, _VPst, _WJ, _WJ, _WJ, _VPre, _VPre, _VPre, _WJ, _VPre, _VPre, _VPre, _H, _WJ, _WJ, + /* 0BD0 */ _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _VPst, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 0BE0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0BF0 */ _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Telugu */ + + /* 0C00 */ _VMAbv, _VMPst, _VMPst, _VMPst, _VMAbv, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _B, _B, + /* 0C10 */ _B, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0C20 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _B, _B, _B, _B, _B, _B, + /* 0C30 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _CMBlw, _B, _VAbv, _VAbv, + /* 0C40 */ _VAbv, _VPst, _VPst, _VPst, _VPst, _WJ, _VAbv, _VAbv, _VAbv, _WJ, _VAbv, _VAbv, _VAbv, _H, _WJ, _WJ, + /* 0C50 */ _WJ, _WJ, _WJ, _WJ, _WJ, _VAbv, _VBlw, _WJ, _B, _B, _B, _WJ, _WJ, _O, _WJ, _WJ, + /* 0C60 */ _B, _B, _VBlw, _VBlw, _WJ, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0C70 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _O, _O, _O, _O, _O, _O, _O, _O, _O, + + /* Kannada */ + + /* 0C80 */ _B, _VMAbv, _VMPst, _VMPst, _O, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _B, _B, + /* 0C90 */ _B, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0CA0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _B, _B, _B, _B, _B, _B, + /* 0CB0 */ _B, _B, _B, _B, _WJ, _B, _B, _B, _B, _B, _WJ, _WJ, _CMBlw, _B, _VPst, _VAbv, + /* 0CC0 */ _VAbv, _VPst, _VPst, _VPst, _VPst, _WJ, _VAbv, _VAbv, _VAbv, _WJ, _VAbv, _VAbv, _VAbv, _H, _WJ, _WJ, + /* 0CD0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _VPst, _VPst, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _O, _B, _WJ, + /* 0CE0 */ _B, _B, _VBlw, _VBlw, _WJ, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0CF0 */ _WJ, _CS, _CS, _VMPst, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Malayalam */ + + /* 0D00 */ _VMAbv, _VMAbv, _VMPst, _VMPst, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _B, _B, + /* 0D10 */ _B, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0D20 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0D30 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _VAbv, _VAbv, _B, _VPst, _VPst, + /* 0D40 */ _VPst, _VPst, _VPst, _VBlw, _VBlw, _WJ, _VPre, _VPre, _VPre, _WJ, _VPre, _VPre, _VPre, _H, _R, _O, + /* 0D50 */ _WJ, _WJ, _WJ, _WJ, _O, _O, _O, _VPst, _O, _O, _O, _O, _O, _O, _O, _B, + /* 0D60 */ _B, _B, _VBlw, _VBlw, _WJ, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0D70 */ _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, + + /* Sinhala */ + + /* 0D80 */ _WJ, _VMAbv, _VMPst, _VMPst, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0D90 */ _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _B, _B, _B, _B, _B, _B, + /* 0DA0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0DB0 */ _B, _B, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _B, _WJ, _WJ, + /* 0DC0 */ _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _HVM, _WJ, _WJ, _WJ, _WJ, _VPst, + /* 0DD0 */ _VPst, _VPst, _VAbv, _VAbv, _VBlw, _WJ, _VBlw, _WJ, _VPst, _VPre, _VPre, _VPre, _VPre, _VPre, _VPre, _VPst, + /* 0DE0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0DF0 */ _WJ, _WJ, _VPst, _VPst, _O, _WJ, _WJ, _WJ, + + /* Tibetan */ + + /* 0F00 */ _B, _B, _O, _O, _B, _B, _B, _O, _O, _O, _O, _O, _O, _O, _O, _O, + /* 0F10 */ _O, _O, _O, _O, _O, _O, _O, _O, _VBlw, _VBlw, _O, _O, _O, _O, _O, _O, + /* 0F20 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0F30 */ _B, _B, _B, _B, _O, _FMBlw, _O, _FMBlw, _O, _CMAbv, _O, _O, _O, _O, _VPst, _VPre, + /* 0F40 */ _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _B, _B, _B, _B, _B, _B, _B, + /* 0F50 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 0F60 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, + /* 0F70 */ _WJ, _CMBlw, _VBlw, _VAbv, _VAbv, _VBlw, _VAbv, _VAbv, _VAbv, _VAbv, _VBlw, _VBlw, _VBlw, _VBlw, _VMAbv, _O, + /* 0F80 */ _VBlw, _VAbv, _VMAbv, _VMAbv, _VBlw, _O, _VMAbv, _VMAbv, _B, _B, _B, _B, _B, _SUB, _SUB, _SUB, + /* 0F90 */ _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _WJ, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, + /* 0FA0 */ _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, + /* 0FB0 */ _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _WJ, _O, _O, + + /* Myanmar */ + + /* 1000 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1010 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1020 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _VPst, _VPst, _VAbv, _VAbv, _VBlw, + /* 1030 */ _VBlw, _VPre, _VAbv, _VAbv, _VAbv, _VAbv, _VMAbv, _VMBlw, _VMPst, _IS, _VAbv, _MPst, _MPre, _MBlw, _MBlw, _B, + /* 1040 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _O, _GB, _O, _O, _GB, _O, + /* 1050 */ _B, _B, _B, _B, _B, _B, _VPst, _VPst, _VBlw, _VBlw, _B, _B, _B, _B, _MBlw, _MBlw, + /* 1060 */ _MBlw, _B, _VPst, _VMPst, _VMPst, _B, _B, _VPst, _VPst, _VMPst, _VMPst, _VMPst, _VMPst, _VMPst, _B, _B, + /* 1070 */ _B, _VAbv, _VAbv, _VAbv, _VAbv, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1080 */ _B, _B, _MBlw, _VPst, _VPre, _VAbv, _VAbv, _VMPst, _VMPst, _VMPst, _VMPst, _VMPst, _VMPst, _VMBlw, _B, _VMPst, + /* 1090 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _VMPst, _VMPst, _VPst, _VAbv, _O, _O, + + /* Tagalog */ + + /* 1700 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1710 */ _B, _B, _VAbv, _VBlw, _VBlw, _VPst, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _B, + + /* Hanunoo */ + + /* 1720 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1730 */ _B, _B, _VAbv, _VBlw, _VPst, _O, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Buhid */ + + /* 1740 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1750 */ _B, _B, _VAbv, _VBlw, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Tagbanwa */ + + /* 1760 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _B, _B, + /* 1770 */ _B, _WJ, _VAbv, _VBlw, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Khmer */ + + /* 1780 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1790 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 17A0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 17B0 */ _B, _B, _B, _B, _CGJ, _CGJ, _VPst, _VAbv, _VAbv, _VAbv, _VAbv, _VBlw, _VBlw, _VBlw, _VPre, _VPre, + /* 17C0 */ _VPre, _VPre, _VPre, _VPre, _VPre, _VPre, _VMAbv, _VMPst, _VPst, _VMAbv, _VMAbv, _FMAbv, _FAbv, _CMAbv, _FMAbv, _VMAbv, + /* 17D0 */ _FMAbv, _VAbv, _IS, _FMAbv, _O, _O, _O, _O, _O, _O, _O, _O, _B, _FMAbv, _WJ, _WJ, + /* 17E0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 17F0 */ _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Mongolian */ + + /* 1800 */ _B, _O, _O, _O, _O, _O, _O, _B, _O, _O, _B, _CGJ, _CGJ, _CGJ, _WJ, _CGJ, + /* 1810 */ _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 1820 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1830 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1840 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1850 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1860 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1870 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 1880 */ _GB, _GB, _GB, _GB, _GB, _CMAbv, _CMAbv, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1890 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18A0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _CMBlw, _B, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Limbu */ + + /* 1900 */ _GB, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1910 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, + /* 1920 */ _VAbv, _VAbv, _VBlw, _VPst, _VPst, _VAbv, _VAbv, _VAbv, _VAbv, _SUB, _SUB, _SUB, _WJ, _WJ, _WJ, _WJ, + /* 1930 */ _FPst, _FPst, _VMBlw, _FPst, _FPst, _FPst, _FPst, _FPst, _FPst, _FBlw, _VMAbv, _FMBlw, _WJ, _WJ, _WJ, _WJ, + /* 1940 */ _O, _WJ, _WJ, _WJ, _O, _O, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1950 */ _B, _B, _B, _B, _B, _B, _B, _B, + + /* Tai Le */ + _B, _B, _B, _B, _B, _B, _B, _B, + /* 1960 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, + /* 1970 */ _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* New Tai Lue */ + + /* 1980 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1990 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 19A0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, + /* 19B0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 19C0 */ _B, _B, _B, _B, _B, _B, _B, _B, _VMPst, _VMPst, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 19D0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _O, _O, + /* 19E0 */ _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, + /* 19F0 */ _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, + + /* Buginese */ + + /* 1A00 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1A10 */ _B, _B, _B, _B, _B, _B, _B, _VAbv, _VAbv, _VPre, _VPst, _VAbv, _WJ, _WJ, _O, _O, + /* 1A20 */ _B, _B, _B, _B, _B, _B, _B, _B, + + /* Tai Tham */ + _B, _B, _B, _B, _B, _B, _B, _B, + /* 1A30 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1A40 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1A50 */ _B, _B, _B, _B, _B, _MPre, _MBlw, _SUB, _FAbv, _FAbv, _MAbv, _SUB, _SUB, _SUB, _SUB, _WJ, + /* 1A60 */ _Sk, _VPst, _VAbv, _VPst, _VPst, _VAbv, _VAbv, _VAbv, _VAbv, _VBlw, _VBlw, _VAbv, _VBlw, _VPst, _VPre, _VPre, + /* 1A70 */ _VPre, _VPre, _VPre, _VAbv, _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VAbv, _VMAbv, _VMAbv, _WJ, _WJ, _VMBlw, + /* 1A80 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 1A90 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Balinese */ + + /* 1B00 */ _VMAbv, _VMAbv, _VMAbv, _FAbv, _VMPst, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1B10 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1B20 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1B30 */ _B, _B, _B, _B, _CMAbv, _VPst, _VAbv, _VAbv, _VBlw, _VBlw, _VBlw, _VBlw, _VAbv, _VAbv, _VPre, _VPre, + /* 1B40 */ _VPre, _VPre, _VAbv, _VAbv, _H, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, + /* 1B50 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _O, _O, _O, _O, _O, _O, + /* 1B60 */ _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _SMAbv, _SMBlw, _SMAbv, _SMAbv, _SMAbv, + /* 1B70 */ _SMAbv, _SMAbv, _SMAbv, _SMAbv, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _WJ, + + /* Sundanese */ + + /* 1B80 */ _VMAbv, _FAbv, _VMPst, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1B90 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1BA0 */ _B, _SUB, _SUB, _SUB, _VAbv, _VBlw, _VPre, _VPst, _VAbv, _VAbv, _VPst, _IS, _SUB, _SUB, _B, _B, + /* 1BB0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1BC0 */ _B, _B, _B, _B, _B, _B, _B, _B, + + /* Batak */ + _B, _B, _B, _B, _B, _B, _B, _B, + /* 1BD0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1BE0 */ _B, _B, _B, _B, _B, _B, _CMAbv, _VPst, _VAbv, _VAbv, _VPst, _VPst, _VPst, _VAbv, _VPst, _VAbv, + /* 1BF0 */ _FAbv, _FAbv, _CMBlw, _CMBlw, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _O, _O, _O, _O, + + /* Lepcha */ + + /* 1C00 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1C10 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1C20 */ _B, _B, _B, _B, _SUB, _SUB, _VPst, _VPre, _VPre, _VPre, _VPst, _VPst, _VBlw, _FAbv, _FAbv, _FAbv, + /* 1C30 */ _FAbv, _FAbv, _FAbv, _FAbv, _VMPre, _VMPre, _FMAbv, _CMBlw, _WJ, _WJ, _WJ, _O, _O, _O, _O, _O, + /* 1C40 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _B, _B, _B, + + /* Vedic Extensions */ + + /* 1CD0 */ _VMAbv, _VMAbv, _VMAbv, _O, _VMBlw, _VMBlw, _VMBlw, _VMBlw, _VMBlw, _VMBlw, _VMAbv, _VMAbv, _VMBlw, _VMBlw, _VMBlw, _VMBlw, + /* 1CE0 */ _VMAbv, _VMPst, _VMBlw, _VMBlw, _VMBlw, _VMBlw, _VMBlw, _VMBlw, _VMBlw, _O, _O, _O, _O, _VMBlw, _O, _O, + /* 1CF0 */ _O, _O, _O, _O, _VMAbv, _CS, _CS, _VMPst, _VMAbv, _VMAbv, _GB, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Combining Diacritical Marks Supplement */ + _O, _O, _O, _FMAbv, _O, _O, _O, _O, + + /* General Punctuation */ + _O, _O, _O, _WJ, _ZWNJ, _CGJ, _WJ, _WJ, + /* 2010 */ _GB, _GB, _GB, _GB, _GB, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, + /* 2020 */ _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _O, + /* 2030 */ _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, + /* 2040 */ _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, + /* 2050 */ _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, + /* 2060 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 2070 */ _O, _O, _WJ, _WJ, _FMPst, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, + + /* Superscripts and Subscripts */ + + /* 2080 */ _O, _O, _FMPst, _FMPst, _FMPst, _O, _O, _O, + + /* Combining Diacritical Marks for Symbols */ + + /* 20F0 */ _VMAbv, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Geometric Shapes */ + _O, _O, _O, _O, _B, _O, _O, _O, + + /* Tifinagh */ + + /* 2D30 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 2D40 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 2D50 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 2D60 */ _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _B, + /* 2D70 */ _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _H, + + /* Syloti Nagri */ + + /* A800 */ _B, _B, _VAbv, _B, _B, _B, _H, _B, _B, _B, _B, _VMAbv, _B, _B, _B, _B, + /* A810 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* A820 */ _B, _B, _B, _VPst, _VPst, _VBlw, _VAbv, _VPst, _O, _O, _O, _O, _VBlw, _WJ, _WJ, _WJ, + /* A830 */ _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Phags-pa */ + + /* A840 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* A850 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* A860 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* A870 */ _B, _B, _B, _B, _O, _O, _O, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Saurashtra */ + + /* A880 */ _VMPst, _VMPst, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* A890 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* A8A0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* A8B0 */ _B, _B, _B, _B, _MPst, _VPst, _VPst, _VPst, _VPst, _VPst, _VPst, _VPst, _VPst, _VPst, _VPst, _VPst, + /* A8C0 */ _VPst, _VPst, _VPst, _VPst, _H, _VMAbv, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _O, _O, + /* A8D0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* A8E0 */ _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VMAbv, + + /* Devanagari Extended */ + _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VMAbv, + /* A8F0 */ _VMAbv, _VMAbv, _B, _B, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _B, _VAbv, + + /* Kayah Li */ + + /* A900 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* A910 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* A920 */ _B, _B, _B, _B, _B, _B, _VAbv, _VAbv, _VAbv, _VAbv, _VAbv, _VMBlw, _VMBlw, _VMBlw, _O, _O, + /* A930 */ _B, _B, _B, _B, _B, _B, _B, _B, + + /* Rejang */ + _B, _B, _B, _B, _B, _B, _B, _B, + /* A940 */ _B, _B, _B, _B, _B, _B, _B, _VBlw, _VBlw, _VBlw, _VAbv, _VBlw, _VBlw, _VBlw, _VBlw, _FAbv, + /* A950 */ _FAbv, _FAbv, _FPst, _VPst, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _O, + /* A960 */ _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, + /* A970 */ _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _WJ, _WJ, _WJ, + + /* Javanese */ + + /* A980 */ _VMAbv, _VMAbv, _FAbv, _VMPst, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* A990 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* A9A0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* A9B0 */ _B, _B, _B, _CMAbv, _VPst, _VPst, _VAbv, _VAbv, _VBlw, _VBlw, _VPre, _VPre, _VAbv, _MBlw, _MPst, _MBlw, + /* A9C0 */ _H, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _WJ, _O, + /* A9D0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _O, _O, + /* A9E0 */ _B, _B, _B, _B, _B, _VAbv, _O, _B, + + /* Myanmar Extended-B */ + _B, _B, _B, _B, _B, _B, _B, _B, + /* A9F0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, + /* AA00 */ _B, _B, _B, _B, _B, _B, _B, _B, + + /* Cham */ + _B, _B, _B, _B, _B, _B, _B, _B, + /* AA10 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* AA20 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _VMAbv, _VAbv, _VAbv, _VAbv, _VBlw, _VAbv, _VPre, + /* AA30 */ _VPre, _VAbv, _VBlw, _MPst, _MPre, _MAbv, _MBlw, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* AA40 */ _B, _B, _B, _FAbv, _B, _B, _B, _B, _B, _B, _B, _B, _FAbv, _FPst, _WJ, _WJ, + /* AA50 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _O, _O, _O, _O, + /* AA60 */ _B, _B, _B, _B, _B, _B, _B, _B, + + /* Myanmar Extended-A */ + _B, _B, _B, _B, _B, _B, _B, _B, + /* AA70 */ _O, _B, _B, _B, _GB, _GB, _GB, _O, _O, _O, _B, _VMPst, _VMAbv, _VMPst, _B, _B, + /* AA80 */ _B, _B, _B, _B, _B, _B, _B, _B, + + /* Tai Viet */ + _B, _B, _B, _B, _B, _B, _B, _B, + /* AA90 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* AAA0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* AAB0 */ _VAbv, _B, _VAbv, _VAbv, _VBlw, _B, _B, _VAbv, _VAbv, _B, _B, _B, _B, _B, _VAbv, _VMAbv, + /* AAC0 */ _B, _VMAbv, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* AAD0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _O, _O, _O, _O, _O, + + /* Meetei Mayek Extensions */ + + /* AAE0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _VPre, _VBlw, _VAbv, _VPre, _VPst, + + /* Meetei Mayek */ + + /* ABC0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* ABD0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* ABE0 */ _B, _B, _B, _VPst, _VPst, _VAbv, _VPst, _VPst, _VBlw, _VPst, _VPst, _O, _VMPst, _VBlw, _WJ, _WJ, + /* ABF0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Variation Selectors */ + + /* FE00 */ _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, + + /* Arabic Presentation Forms-B */ + _O, _O, _O, _O, _O, _WJ, _WJ, _WJ, + + /* Specials */ + + /* FFF0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _O, _O, _O, _O, _O, _WJ, _WJ, + + /* Vithkuqi */ + + /* 10570 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _B, _B, _B, _B, + /* 10580 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _B, _B, _B, _B, + /* 10590 */ _B, _B, _B, _WJ, _B, _B, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 105A0 */ _B, _B, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 105B0 */ _B, _B, _WJ, _B, _B, _B, _B, _B, + + /* Kharoshthi */ + + /* 10A00 */ _B, _VBlw, _VBlw, _VBlw, _WJ, _VAbv, _VBlw, _WJ, _WJ, _WJ, _WJ, _WJ, _VPst, _VMBlw, _VMBlw, _VMAbv, + /* 10A10 */ _B, _B, _B, _B, _WJ, _B, _B, _B, _WJ, _B, _B, _B, _B, _B, _B, _B, + /* 10A20 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 10A30 */ _B, _B, _B, _B, _B, _B, _WJ, _WJ, _CMBlw, _CMBlw, _CMBlw, _WJ, _WJ, _WJ, _WJ, _IS, + /* 10A40 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Manichaean */ + + /* 10AC0 */ _B, _B, _B, _B, _B, _B, _B, _B, _O, _B, _B, _B, _B, _B, _B, _B, + /* 10AD0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 10AE0 */ _B, _B, _B, _B, _B, _CMBlw, _CMBlw, _WJ, + + /* Psalter Pahlavi */ + + /* 10B80 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 10B90 */ _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _O, _O, _O, _O, _WJ, _WJ, _WJ, + /* 10BA0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _B, _B, _B, _B, _B, _B, _O, + + /* Hanifi Rohingya */ + + /* 10D00 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 10D10 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 10D20 */ _B, _B, _B, _B, _VMAbv, _VMAbv, _VMAbv, _CMAbv, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 10D30 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Yezidi */ + + /* 10E80 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 10E90 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 10EA0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _VAbv, _VAbv, _O, _WJ, _WJ, + + /* Sogdian */ + + /* 10F30 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 10F40 */ _B, _B, _B, _B, _B, _B, _VMBlw, _VMBlw, _VMBlw, _VMBlw, _VMBlw, _VMBlw, _VMBlw, _VMBlw, _VMBlw, _VMBlw, + /* 10F50 */ _VMBlw, _B, _B, _B, _B, _O, _O, _O, _O, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 10F60 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Old Uyghur */ + + /* 10F70 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 10F80 */ _B, _B, _CMBlw, _CMBlw, _CMBlw, _CMBlw, _O, _O, _O, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 10F90 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 10FA0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Chorasmian */ + + /* 10FB0 */ _B, _O, _B, _B, _B, _B, _B, _O, _B, _B, _B, _B, _B, _B, _B, _B, + /* 10FC0 */ _O, _B, _B, _B, _B, _O, _O, _O, _O, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, + /* 10FD0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 10FE0 */ _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, + /* 10FF0 */ _O, _O, _O, _O, _O, _O, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Brahmi */ + + /* 11000 */ _VMPst, _VMAbv, _VMPst, _CS, _CS, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11010 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11020 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11030 */ _B, _B, _B, _B, _B, _B, _B, _B, _VAbv, _VAbv, _VAbv, _VAbv, _VBlw, _VBlw, _VBlw, _VBlw, + /* 11040 */ _VBlw, _VBlw, _VAbv, _VAbv, _VAbv, _VAbv, _H, _O, _O, _O, _O, _O, _O, _O, _WJ, _WJ, + /* 11050 */ _WJ, _WJ, _N, _N, _N, _N, _N, _N, _N, _N, _N, _N, _N, _N, _N, _N, + /* 11060 */ _N, _N, _N, _N, _N, _N, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11070 */ _VAbv, _B, _B, _VAbv, _VAbv, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _HN, + + /* Kaithi */ + + /* 11080 */ _VMAbv, _VMAbv, _VMPst, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11090 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 110A0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 110B0 */ _VPst, _VPre, _VPst, _VBlw, _VBlw, _VAbv, _VAbv, _VPst, _VPst, _H, _CMBlw, _O, _O, _O, _O, _O, + + /* Chakma */ + + /* 11100 */ _VMAbv, _VMAbv, _VMAbv, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11110 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11120 */ _B, _B, _B, _B, _B, _B, _B, _VBlw, _VBlw, _VBlw, _VAbv, _VAbv, _VPre, _VBlw, _VAbv, _VAbv, + /* 11130 */ _VBlw, _VAbv, _VAbv, _IS, _CMAbv, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11140 */ _O, _O, _O, _O, _B, _VPst, _VPst, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Mahajani */ + + /* 11150 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11160 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11170 */ _B, _B, _B, _CMBlw, _O, _O, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Sharada */ + + /* 11180 */ _VMAbv, _VMAbv, _VMPst, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11190 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 111A0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 111B0 */ _B, _B, _B, _VPst, _VPre, _VPst, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VAbv, _VAbv, _VAbv, _VAbv, + /* 111C0 */ _H, _B, _R, _R, _O, _O, _O, _O, _O, _FMBlw, _CMBlw, _VAbv, _VBlw, _O, _VPre, _VMAbv, + /* 111D0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _O, _O, _O, _O, _O, + /* 111E0 */ _WJ, _B, _B, _B, _B, _B, _B, _B, + + /* Sinhala Archaic Numbers */ + _B, _B, _B, _B, _B, _B, _B, _B, + /* 111F0 */ _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Khojki */ + + /* 11200 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11210 */ _B, _B, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11220 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _VPst, _VPst, _VPst, _VBlw, + /* 11230 */ _VAbv, _VAbv, _VAbv, _VAbv, _VMAbv, _H, _CMAbv, _CMAbv, _O, _O, _O, _O, _O, _O, _VMAbv, _B, + /* 11240 */ _B, _VBlw, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Multani */ + + /* 11280 */ _B, _B, _B, _B, _B, _B, _B, _WJ, _B, _WJ, _B, _B, _B, _B, _WJ, _B, + /* 11290 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _B, + /* 112A0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 112B0 */ _B, _B, _B, _B, _B, _B, _B, _B, + + /* Khudawadi */ + _B, _B, _B, _B, _B, _B, _B, _B, + /* 112C0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 112D0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _VMAbv, + /* 112E0 */ _VPst, _VPre, _VPst, _VBlw, _VBlw, _VAbv, _VAbv, _VAbv, _VAbv, _CMBlw, _VBlw, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 112F0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 11300 */ _VMAbv, _VMAbv, _VMAbv, _VMAbv, _WJ, _B, _B, _B, + + /* Grantha */ + _B, _B, _B, _B, _B, _WJ, _WJ, _B, + /* 11310 */ _B, _WJ, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11320 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _B, _B, _B, _B, _B, _B, + /* 11330 */ _B, _WJ, _B, _B, _WJ, _B, _B, _B, _B, _B, _WJ, _CMBlw, _CMBlw, _B, _VPst, _VPst, + /* 11340 */ _VAbv, _VPst, _VPst, _VPst, _VPst, _WJ, _WJ, _VPre, _VPre, _WJ, _WJ, _VPre, _VPre, _H, _WJ, _WJ, + /* 11350 */ _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _VPst, _WJ, _WJ, _WJ, _WJ, _WJ, _O, _B, _B, + /* 11360 */ _B, _B, _VPst, _VPst, _WJ, _WJ, _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VMAbv, _WJ, _WJ, _WJ, + + /* Newa */ + + /* 11400 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11410 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11420 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11430 */ _B, _B, _B, _B, _B, _VPst, _VPre, _VPst, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VAbv, _VAbv, + /* 11440 */ _VPst, _VPst, _H, _VMAbv, _VMAbv, _VMPst, _CMBlw, _B, _O, _O, _O, _O, _O, _O, _O, _O, + /* 11450 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _O, _O, _WJ, _O, _FMAbv, _B, + /* 11460 */ _CS, _CS, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 11470 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Tirhuta */ + + /* 11480 */ _O, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11490 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 114A0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 114B0 */ _VPst, _VPre, _VPst, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VPre, _VAbv, _VPre, _VPre, _VPst, _VPre, _VMAbv, + /* 114C0 */ _VMAbv, _VMAbv, _H, _CMBlw, _B, _O, _O, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 114D0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Siddham */ + + /* 11580 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11590 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 115A0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _VPst, + /* 115B0 */ _VPre, _VPst, _VBlw, _VBlw, _VBlw, _VBlw, _WJ, _WJ, _VPre, _VPre, _VPre, _VPre, _VMAbv, _VMAbv, _VMPst, _H, + /* 115C0 */ _CMBlw, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, + /* 115D0 */ _O, _O, _O, _O, _O, _O, _O, _O, _B, _B, _B, _B, _VBlw, _VBlw, _WJ, _WJ, + /* 115E0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 115F0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Modi */ + + /* 11600 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11610 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11620 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11630 */ _VPst, _VPst, _VPst, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VAbv, _VAbv, _VPst, _VPst, _VMAbv, _VMPst, _H, + /* 11640 */ _VAbv, _O, _O, _O, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 11650 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 11660 */ _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _WJ, _WJ, _WJ, + /* 11670 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Takri */ + + /* 11680 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11690 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 116A0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _VMAbv, _VMPst, _VAbv, _VPre, _VPst, + /* 116B0 */ _VBlw, _VBlw, _VAbv, _VAbv, _VAbv, _VAbv, _H, _CMBlw, _B, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 116C0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 116D0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 116E0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 116F0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Ahom */ + + /* 11700 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11710 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _MBlw, _MPre, _MAbv, + /* 11720 */ _VPst, _VPst, _VAbv, _VAbv, _VBlw, _VBlw, _VPre, _VAbv, _VBlw, _VAbv, _VAbv, _VAbv, _WJ, _WJ, _WJ, _WJ, + /* 11730 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _O, _O, _O, _O, + + /* Dogra */ + + /* 11800 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11810 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11820 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _VPst, _VPre, _VPst, _VBlw, + /* 11830 */ _VBlw, _VBlw, _VBlw, _VAbv, _VAbv, _VAbv, _VAbv, _VMAbv, _VMPst, _H, _CMBlw, _O, _WJ, _WJ, _WJ, _WJ, + + /* Dives Akuru */ + + /* 11900 */ _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _B, _WJ, _WJ, _B, _B, _B, _B, + /* 11910 */ _B, _B, _B, _B, _WJ, _B, _B, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11920 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11930 */ _VPst, _VPst, _VPst, _VPst, _VPst, _VPre, _WJ, _VPre, _VPre, _WJ, _WJ, _VMAbv, _VMAbv, _VPst, _IS, _R, + /* 11940 */ _MPst, _R, _MPst, _CMBlw, _O, _O, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 11950 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Nandinagari */ + + /* 119A0 */ _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _B, _B, _B, _B, _B, _B, + /* 119B0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 119C0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 119D0 */ _B, _VPst, _VPre, _VPst, _VBlw, _VBlw, _VBlw, _VBlw, _WJ, _WJ, _VAbv, _VAbv, _VPst, _VPst, _VMPst, _VMPst, + /* 119E0 */ _H, _B, _O, _O, _VPre, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 119F0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Zanabazar Square */ + + /* 11A00 */ _B, _VAbv, _VBlw, _VBlw, _VAbv, _VAbv, _VAbv, _VAbv, _VAbv, _VAbv, _VBlw, _B, _B, _B, _B, _B, + /* 11A10 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11A20 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11A30 */ _B, _B, _B, _FMBlw, _VBlw, _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VMPst, _R, _MBlw, _MBlw, _MBlw, _MBlw, _GB, + /* 11A40 */ _O, _O, _O, _O, _O, _GB, _O, _IS, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Soyombo */ + + /* 11A50 */ _B, _VAbv, _VBlw, _VBlw, _VAbv, _VAbv, _VAbv, _VPst, _VPst, _VBlw, _VBlw, _VBlw, _B, _B, _B, _B, + /* 11A60 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11A70 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11A80 */ _B, _B, _B, _B, _R, _R, _R, _R, _R, _R, _FBlw, _FBlw, _FBlw, _FBlw, _FBlw, _FBlw, + /* 11A90 */ _FBlw, _FBlw, _FBlw, _FBlw, _FBlw, _FBlw, _VMAbv, _VMPst, _CMAbv, _IS, _O, _O, _O, _B, _O, _O, + + /* Bhaiksuki */ + + /* 11C00 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _B, _B, _B, _B, _B, _B, + /* 11C10 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11C20 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _VPst, + /* 11C30 */ _VAbv, _VAbv, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _WJ, _VAbv, _VAbv, _VAbv, _VAbv, _VMAbv, _VMAbv, _VMPst, _H, + /* 11C40 */ _B, _O, _O, _O, _O, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 11C50 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11C60 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, + /* 11C70 */ _O, _O, _B, _B, _B, _B, _B, _B, + + /* Marchen */ + _B, _B, _B, _B, _B, _B, _B, _B, + /* 11C80 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11C90 */ _WJ, _WJ, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, + /* 11CA0 */ _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _WJ, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, _SUB, + /* 11CB0 */ _VBlw, _VPre, _VBlw, _VAbv, _VPst, _VMAbv, _VMAbv, _WJ, + + /* Masaram Gondi */ + + /* 11D00 */ _B, _B, _B, _B, _B, _B, _B, _WJ, _B, _B, _WJ, _B, _B, _B, _B, _B, + /* 11D10 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11D20 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11D30 */ _B, _VAbv, _VAbv, _VAbv, _VAbv, _VAbv, _VBlw, _WJ, _WJ, _WJ, _VAbv, _WJ, _VAbv, _VAbv, _WJ, _VAbv, + /* 11D40 */ _VMAbv, _VMAbv, _CMBlw, _VAbv, _VBlw, _IS, _R, _MBlw, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 11D50 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 11D60 */ _B, _B, _B, _B, _B, _B, _WJ, _B, + + /* Gunjala Gondi */ + _B, _WJ, _B, _B, _B, _B, _B, _B, + /* 11D70 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11D80 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _VPst, _VPst, _VPst, _VPst, _VPst, _WJ, + /* 11D90 */ _VAbv, _VAbv, _WJ, _VPst, _VPst, _VMAbv, _VMPst, _IS, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 11DA0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Makasar */ + + /* 11EE0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11EF0 */ _B, _B, _GB, _VAbv, _VBlw, _VPre, _VPst, _O, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Kawi */ + + /* 11F00 */ _VMAbv, _VMAbv, _R, _VMPst, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11F10 */ _B, _WJ, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11F20 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 11F30 */ _B, _B, _B, _B, _VPst, _VPst, _VAbv, _VAbv, _VBlw, _VBlw, _VBlw, _WJ, _WJ, _WJ, _VPre, _VPre, + /* 11F40 */ _VAbv, _VPst, _IS, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, + /* 11F50 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Egyptian Hieroglyphs */ + + /* 13000 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13010 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13020 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13030 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13040 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13050 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13060 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13070 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13080 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13090 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 130A0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 130B0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 130C0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 130D0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 130E0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 130F0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13100 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13110 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13120 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13130 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13140 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13150 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13160 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13170 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13180 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13190 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 131A0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 131B0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 131C0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 131D0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 131E0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 131F0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13200 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13210 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13220 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13230 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13240 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13250 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13260 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13270 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13280 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13290 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 132A0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 132B0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 132C0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 132D0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 132E0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 132F0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13300 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13310 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13320 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13330 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13340 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13350 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13360 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13370 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13380 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13390 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 133A0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 133B0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 133C0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 133D0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 133E0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 133F0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13400 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13410 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13420 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 13430 */ _H, _H, _H, _H, _H, _H, _H, _B, + + /* Egyptian Hieroglyph Format Controls */ + _B, _H, _H, _H, _O, _O, _O, _O, + /* 13440 */ _VMBlw, _B, _B, _B, _B, _B, _B, _VMBlw, _VMBlw, _VMBlw, _VMBlw, _VMBlw, _VMBlw, _VMBlw, _VMBlw, _VMBlw, + /* 13450 */ _VMBlw, _VMBlw, _VMBlw, _VMBlw, _VMBlw, _VMBlw, _WJ, _WJ, + + /* Tangsa */ + + /* 16AC0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 16AD0 */ _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, + /* 16AE0 */ _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _O, _WJ, _WJ, + /* 16AF0 */ _O, _O, _O, _O, _O, _O, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Pahawh Hmong */ + + /* 16B00 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 16B10 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 16B20 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 16B30 */ _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VMAbv, _O, + + /* Miao */ + + /* 16F00 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 16F10 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 16F20 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 16F30 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 16F40 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _CMBlw, + /* 16F50 */ _O, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, + /* 16F60 */ _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, + /* 16F70 */ _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, + /* 16F80 */ _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _VBlw, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _VMBlw, + /* 16F90 */ _VMBlw, _VMBlw, _VMBlw, _O, _O, _O, _O, _O, + + /* Ideographic Symbols and Punctuation */ + + /* 16FE0 */ _O, _O, _O, _O, _B, _WJ, _WJ, _WJ, + + /* Khitan Small Script */ + + /* 18B00 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18B10 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18B20 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18B30 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18B40 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18B50 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18B60 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18B70 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18B80 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18B90 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18BA0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18BB0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18BC0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18BD0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18BE0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18BF0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18C00 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18C10 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18C20 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18C30 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18C40 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18C50 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18C60 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18C70 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18C80 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18C90 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18CA0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18CB0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18CC0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 18CD0 */ _B, _B, _B, _B, _B, _B, _WJ, _WJ, + + /* Duployan */ + + /* 1BC00 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1BC10 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1BC20 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1BC30 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1BC40 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1BC50 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1BC60 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 1BC70 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, + /* 1BC80 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* 1BC90 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _O, _CMBlw, _CMBlw, _O, + + /* Musical Symbols */ + + /* 1D170 */ _O, _O, _O, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Nyiakeng Puachue Hmong */ + + /* 1E100 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1E110 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1E120 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, + /* 1E130 */ _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VMAbv, _VMAbv, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, + /* 1E140 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _B, _B, + + /* Toto */ + + /* 1E290 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1E2A0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _VMAbv, _WJ, + /* 1E2B0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Wancho */ + + /* 1E2C0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1E2D0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1E2E0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _VMAbv, _VMAbv, _VMAbv, _VMAbv, + /* 1E2F0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _O, + + /* Nag Mundari */ + + /* 1E4D0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1E4E0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _VAbv, _VAbv, _VAbv, _VAbv, + /* 1E4F0 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* Adlam */ + + /* 1E900 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1E910 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1E920 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1E930 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, + /* 1E940 */ _B, _B, _B, _B, _CMAbv, _CMAbv, _CMAbv, _CMAbv, _CMAbv, _CMAbv, _CMAbv, _B, _WJ, _WJ, _WJ, _WJ, + /* 1E950 */ _B, _B, _B, _B, _B, _B, _B, _B, _B, _B, _WJ, _WJ, _WJ, _WJ, _O, _O, + + /* Tags */ + + /* E0000 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0010 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0020 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0030 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0040 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0050 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0060 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0070 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0080 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* No_Block */ + _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0090 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E00A0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E00B0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E00C0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E00D0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E00E0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E00F0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0100 */ _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, + + /* Variation Selectors Supplement */ + _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, + /* E0110 */ _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, + /* E0120 */ _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, + /* E0130 */ _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, + /* E0140 */ _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, + /* E0150 */ _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, + /* E0160 */ _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, + /* E0170 */ _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, + /* E0180 */ _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, + /* E0190 */ _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, + /* E01A0 */ _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, + /* E01B0 */ _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, + /* E01C0 */ _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, + /* E01D0 */ _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, + /* E01E0 */ _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, _CGJ, + /* E01F0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + + /* No_Block */ + _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0200 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0210 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0220 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0230 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0240 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0250 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0260 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0270 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0280 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0290 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E02A0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E02B0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E02C0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E02D0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E02E0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E02F0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0300 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0310 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0320 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0330 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0340 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0350 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0360 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0370 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0380 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0390 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E03A0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E03B0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E03C0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E03D0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E03E0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E03F0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0400 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0410 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0420 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0430 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0440 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0450 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0460 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0470 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0480 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0490 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E04A0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E04B0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E04C0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E04D0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E04E0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E04F0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0500 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0510 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0520 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0530 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0540 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0550 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0560 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0570 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0580 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0590 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E05A0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E05B0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E05C0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E05D0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E05E0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E05F0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0600 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0610 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0620 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0630 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0640 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0650 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0660 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0670 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0680 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0690 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E06A0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E06B0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E06C0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E06D0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E06E0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E06F0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0700 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0710 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0720 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0730 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0740 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0750 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0760 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0770 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0780 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0790 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E07A0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E07B0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E07C0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E07D0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E07E0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E07F0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0800 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0810 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0820 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0830 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0840 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0850 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0860 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0870 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0880 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0890 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E08A0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E08B0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E08C0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E08D0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E08E0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E08F0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0900 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0910 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0920 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0930 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0940 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0950 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0960 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0970 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0980 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0990 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E09A0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E09B0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E09C0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E09D0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E09E0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E09F0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0A00 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0A10 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0A20 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0A30 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0A40 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0A50 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0A60 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0A70 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0A80 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0A90 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0AA0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0AB0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0AC0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0AD0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0AE0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0AF0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0B00 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0B10 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0B20 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0B30 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0B40 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0B50 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0B60 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0B70 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0B80 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0B90 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0BA0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0BB0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0BC0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0BD0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0BE0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0BF0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0C00 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0C10 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0C20 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0C30 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0C40 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0C50 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0C60 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0C70 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0C80 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0C90 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0CA0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0CB0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0CC0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0CD0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0CE0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0CF0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0D00 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0D10 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0D20 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0D30 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0D40 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0D50 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0D60 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0D70 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0D80 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0D90 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0DA0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0DB0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0DC0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0DD0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0DE0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0DF0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0E00 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0E10 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0E20 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0E30 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0E40 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0E50 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0E60 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0E70 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0E80 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0E90 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0EA0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0EB0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0EC0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0ED0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0EE0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0EF0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0F00 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0F10 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0F20 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0F30 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0F40 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0F50 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0F60 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0F70 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0F80 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0F90 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0FA0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0FB0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0FC0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0FD0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0FE0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, + /* E0FF0 */ _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, _WJ, +} /* Table items: 13480; occupancy: 84% */ + +const ( + offsetUSE0x0028u = 0 + offsetUSE0x00a0u = 24 + offsetUSE0x0348u = 80 + offsetUSE0x0640u = 88 + offsetUSE0x07c8u = 96 + offsetUSE0x0840u = 144 + offsetUSE0x0900u = 176 + offsetUSE0x0f00u = 1448 + offsetUSE0x1000u = 1640 + offsetUSE0x1700u = 1800 + offsetUSE0x1900u = 2232 + offsetUSE0x1b00u = 2648 + offsetUSE0x1cd0u = 2984 + offsetUSE0x1df8u = 3032 + offsetUSE0x2008u = 3040 + offsetUSE0x20f0u = 3168 + offsetUSE0x25c8u = 3176 + offsetUSE0x2d30u = 3184 + offsetUSE0xa800u = 3264 + offsetUSE0xabc0u = 4016 + offsetUSE0xfe00u = 4080 + offsetUSE0xfef8u = 4096 + offsetUSE0xfff0u = 4104 + offsetUSE0x10570u = 4120 + offsetUSE0x10a00u = 4192 + offsetUSE0x10ac0u = 4272 + offsetUSE0x10b80u = 4312 + offsetUSE0x10d00u = 4360 + offsetUSE0x10e80u = 4424 + offsetUSE0x10f30u = 4472 + offsetUSE0x11100u = 4872 + offsetUSE0x11280u = 5200 + offsetUSE0x11400u = 5440 + offsetUSE0x11580u = 5664 + offsetUSE0x11800u = 6112 + offsetUSE0x11900u = 6176 + offsetUSE0x119a0u = 6272 + offsetUSE0x11c00u = 6528 + offsetUSE0x11d00u = 6712 + offsetUSE0x11ee0u = 6888 + offsetUSE0x13000u = 7016 + offsetUSE0x16ac0u = 8128 + offsetUSE0x16f00u = 8248 + offsetUSE0x16fe0u = 8400 + offsetUSE0x18b00u = 8408 + offsetUSE0x1bc00u = 8880 + offsetUSE0x1d170u = 9040 + offsetUSE0x1e100u = 9048 + offsetUSE0x1e290u = 9128 + offsetUSE0x1e4d0u = 9240 + offsetUSE0x1e900u = 9288 + offsetUSE0xe0000u = 9384 +) + +func getUSECategory(u rune) uint8 { + switch u >> 12 { + case 0x0: + if 0x0028 <= u && u <= 0x003F { + return useTable[u-0x0028+offsetUSE0x0028u] + } + if 0x00A0 <= u && u <= 0x00D7 { + return useTable[u-0x00A0+offsetUSE0x00a0u] + } + if 0x0348 <= u && u <= 0x034F { + return useTable[u-0x0348+offsetUSE0x0348u] + } + if 0x0640 <= u && u <= 0x0647 { + return useTable[u-0x0640+offsetUSE0x0640u] + } + if 0x07C8 <= u && u <= 0x07F7 { + return useTable[u-0x07C8+offsetUSE0x07c8u] + } + if 0x0840 <= u && u <= 0x085F { + return useTable[u-0x0840+offsetUSE0x0840u] + } + if 0x0900 <= u && u <= 0x0DF7 { + return useTable[u-0x0900+offsetUSE0x0900u] + } + if 0x0F00 <= u && u <= 0x0FBF { + return useTable[u-0x0F00+offsetUSE0x0f00u] + } + + case 0x1: + if 0x1000 <= u && u <= 0x109F { + return useTable[u-0x1000+offsetUSE0x1000u] + } + if 0x1700 <= u && u <= 0x18AF { + return useTable[u-0x1700+offsetUSE0x1700u] + } + if 0x1900 <= u && u <= 0x1A9F { + return useTable[u-0x1900+offsetUSE0x1900u] + } + if 0x1B00 <= u && u <= 0x1C4F { + return useTable[u-0x1B00+offsetUSE0x1b00u] + } + if 0x1CD0 <= u && u <= 0x1CFF { + return useTable[u-0x1CD0+offsetUSE0x1cd0u] + } + if 0x1DF8 <= u && u <= 0x1DFF { + return useTable[u-0x1DF8+offsetUSE0x1df8u] + } + + case 0x2: + if 0x2008 <= u && u <= 0x2087 { + return useTable[u-0x2008+offsetUSE0x2008u] + } + if 0x20F0 <= u && u <= 0x20F7 { + return useTable[u-0x20F0+offsetUSE0x20f0u] + } + if 0x25C8 <= u && u <= 0x25CF { + return useTable[u-0x25C8+offsetUSE0x25c8u] + } + if 0x2D30 <= u && u <= 0x2D7F { + return useTable[u-0x2D30+offsetUSE0x2d30u] + } + + case 0xA: + if 0xA800 <= u && u <= 0xAAEF { + return useTable[u-0xA800+offsetUSE0xa800u] + } + if 0xABC0 <= u && u <= 0xABFF { + return useTable[u-0xABC0+offsetUSE0xabc0u] + } + + case 0xF: + if 0xFE00 <= u && u <= 0xFE0F { + return useTable[u-0xFE00+offsetUSE0xfe00u] + } + if 0xFEF8 <= u && u <= 0xFEFF { + return useTable[u-0xFEF8+offsetUSE0xfef8u] + } + if 0xFFF0 <= u && u <= 0xFFFF { + return useTable[u-0xFFF0+offsetUSE0xfff0u] + } + + case 0x10: + if 0xFFF0 <= u && u <= 0xFFFF { + return useTable[u-0xFFF0+offsetUSE0xfff0u] + } + if 0x10570 <= u && u <= 0x105B7 { + return useTable[u-0x10570+offsetUSE0x10570u] + } + if 0x10A00 <= u && u <= 0x10A4F { + return useTable[u-0x10A00+offsetUSE0x10a00u] + } + if 0x10AC0 <= u && u <= 0x10AE7 { + return useTable[u-0x10AC0+offsetUSE0x10ac0u] + } + if 0x10B80 <= u && u <= 0x10BAF { + return useTable[u-0x10B80+offsetUSE0x10b80u] + } + if 0x10D00 <= u && u <= 0x10D3F { + return useTable[u-0x10D00+offsetUSE0x10d00u] + } + if 0x10E80 <= u && u <= 0x10EAF { + return useTable[u-0x10E80+offsetUSE0x10e80u] + } + if 0x10F30 <= u && u <= 0x110BF { + return useTable[u-0x10F30+offsetUSE0x10f30u] + } + + case 0x11: + if 0x10F30 <= u && u <= 0x110BF { + return useTable[u-0x10F30+offsetUSE0x10f30u] + } + if 0x11100 <= u && u <= 0x11247 { + return useTable[u-0x11100+offsetUSE0x11100u] + } + if 0x11280 <= u && u <= 0x1136F { + return useTable[u-0x11280+offsetUSE0x11280u] + } + if 0x11400 <= u && u <= 0x114DF { + return useTable[u-0x11400+offsetUSE0x11400u] + } + if 0x11580 <= u && u <= 0x1173F { + return useTable[u-0x11580+offsetUSE0x11580u] + } + if 0x11800 <= u && u <= 0x1183F { + return useTable[u-0x11800+offsetUSE0x11800u] + } + if 0x11900 <= u && u <= 0x1195F { + return useTable[u-0x11900+offsetUSE0x11900u] + } + if 0x119A0 <= u && u <= 0x11A9F { + return useTable[u-0x119A0+offsetUSE0x119a0u] + } + if 0x11C00 <= u && u <= 0x11CB7 { + return useTable[u-0x11C00+offsetUSE0x11c00u] + } + if 0x11D00 <= u && u <= 0x11DAF { + return useTable[u-0x11D00+offsetUSE0x11d00u] + } + if 0x11EE0 <= u && u <= 0x11F5F { + return useTable[u-0x11EE0+offsetUSE0x11ee0u] + } + + case 0x13: + if 0x13000 <= u && u <= 0x13457 { + return useTable[u-0x13000+offsetUSE0x13000u] + } + + case 0x16: + if 0x16AC0 <= u && u <= 0x16B37 { + return useTable[u-0x16AC0+offsetUSE0x16ac0u] + } + if 0x16F00 <= u && u <= 0x16F97 { + return useTable[u-0x16F00+offsetUSE0x16f00u] + } + if 0x16FE0 <= u && u <= 0x16FE7 { + return useTable[u-0x16FE0+offsetUSE0x16fe0u] + } + + case 0x18: + if 0x18B00 <= u && u <= 0x18CD7 { + return useTable[u-0x18B00+offsetUSE0x18b00u] + } + + case 0x1B: + if 0x1BC00 <= u && u <= 0x1BC9F { + return useTable[u-0x1BC00+offsetUSE0x1bc00u] + } + + case 0x1D: + if 0x1D170 <= u && u <= 0x1D177 { + return useTable[u-0x1D170+offsetUSE0x1d170u] + } + + case 0x1E: + if 0x1E100 <= u && u <= 0x1E14F { + return useTable[u-0x1E100+offsetUSE0x1e100u] + } + if 0x1E290 <= u && u <= 0x1E2FF { + return useTable[u-0x1E290+offsetUSE0x1e290u] + } + if 0x1E4D0 <= u && u <= 0x1E4FF { + return useTable[u-0x1E4D0+offsetUSE0x1e4d0u] + } + if 0x1E900 <= u && u <= 0x1E95F { + return useTable[u-0x1E900+offsetUSE0x1e900u] + } + + case 0xE0: + if 0xE0000 <= u && u <= 0xE0FFF { + return useTable[u-0xE0000+offsetUSE0xe0000u] + } + + case 0xE1: + if 0xE0000 <= u && u <= 0xE0FFF { + return useTable[u-0xE0000+offsetUSE0xe0000u] + } + + } + return useSM_ex_O +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/ot_vowels_constraints.go b/vendor/github.com/go-text/typesetting/harfbuzz/ot_vowels_constraints.go new file mode 100644 index 0000000..3ca9013 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/ot_vowels_constraints.go @@ -0,0 +1,350 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package harfbuzz + +import "github.com/go-text/typesetting/language" + +// Code generated by typesettings-utils/generators/unicodedata/cmd/main.go DO NOT EDIT. + +func outputDottedCircle(buffer *Buffer) { + buffer.outputRune(0x25CC) + buffer.prev().resetContinutation() +} + +func outputWithDottedCircle(buffer *Buffer) { + outputDottedCircle(buffer) + buffer.nextGlyph() +} + +func preprocessTextVowelConstraints(buffer *Buffer) { + if (buffer.Flags & DoNotinsertDottedCircle) != 0 { + return + } + + /* UGLY UGLY UGLY business of adding dotted-circle in the middle of + * vowel-sequences that look like another vowel. Data for each script + * collected from the USE script development spec. + * + * https://github.com/harfbuzz/harfbuzz/issues/1019 + */ + buffer.clearOutput() + count := len(buffer.Info) + switch buffer.Props.Script { + + case language.Devanagari: + for buffer.idx = 0; buffer.idx+1 < count; { + matched := false + switch buffer.cur(0).codepoint { + case 0x0905: + switch buffer.cur(1).codepoint { + case 0x093A, 0x093B, 0x093E, 0x0945, 0x0946, 0x0949, 0x094A, 0x094B, 0x094C, 0x094F, 0x0956, 0x0957: + matched = true + } + case 0x0906: + switch buffer.cur(1).codepoint { + case 0x093A, 0x0945, 0x0946, 0x0947, 0x0948: + matched = true + } + case 0x0909: + matched = 0x0941 == buffer.cur(1).codepoint + case 0x090F: + switch buffer.cur(1).codepoint { + case 0x0945, 0x0946, 0x0947: + matched = true + } + case 0x0930: + if 0x094D == buffer.cur(1).codepoint && + buffer.idx+2 < count && + 0x0907 == buffer.cur(2).codepoint { + buffer.nextGlyph() + matched = true + } + } + + buffer.nextGlyph() + if matched { + outputWithDottedCircle(buffer) + } + } + case language.Bengali: + for buffer.idx = 0; buffer.idx+1 < count; { + matched := false + switch buffer.cur(0).codepoint { + case 0x0985: + matched = 0x09BE == buffer.cur(1).codepoint + case 0x098B: + matched = 0x09C3 == buffer.cur(1).codepoint + case 0x098C: + matched = 0x09E2 == buffer.cur(1).codepoint + } + + buffer.nextGlyph() + if matched { + outputWithDottedCircle(buffer) + } + } + case language.Gurmukhi: + for buffer.idx = 0; buffer.idx+1 < count; { + matched := false + switch buffer.cur(0).codepoint { + case 0x0A05: + switch buffer.cur(1).codepoint { + case 0x0A3E, 0x0A48, 0x0A4C: + matched = true + } + case 0x0A72: + switch buffer.cur(1).codepoint { + case 0x0A3F, 0x0A40, 0x0A47: + matched = true + } + case 0x0A73: + switch buffer.cur(1).codepoint { + case 0x0A41, 0x0A42, 0x0A4B: + matched = true + } + } + + buffer.nextGlyph() + if matched { + outputWithDottedCircle(buffer) + } + } + case language.Gujarati: + for buffer.idx = 0; buffer.idx+1 < count; { + matched := false + switch buffer.cur(0).codepoint { + case 0x0A85: + switch buffer.cur(1).codepoint { + case 0x0ABE, 0x0AC5, 0x0AC7, 0x0AC8, 0x0AC9, 0x0ACB, 0x0ACC: + matched = true + } + case 0x0AC5: + matched = 0x0ABE == buffer.cur(1).codepoint + } + + buffer.nextGlyph() + if matched { + outputWithDottedCircle(buffer) + } + } + case language.Oriya: + for buffer.idx = 0; buffer.idx+1 < count; { + matched := false + switch buffer.cur(0).codepoint { + case 0x0B05: + matched = 0x0B3E == buffer.cur(1).codepoint + case 0x0B0F, 0x0B13: + matched = 0x0B57 == buffer.cur(1).codepoint + } + + buffer.nextGlyph() + if matched { + outputWithDottedCircle(buffer) + } + } + case language.Tamil: + for buffer.idx = 0; buffer.idx+1 < count; { + matched := false + if 0x0B85 == buffer.cur(0).codepoint && + 0x0BC2 == buffer.cur(1).codepoint { + matched = true + } + + buffer.nextGlyph() + if matched { + outputWithDottedCircle(buffer) + } + } + case language.Telugu: + for buffer.idx = 0; buffer.idx+1 < count; { + matched := false + switch buffer.cur(0).codepoint { + case 0x0C12: + switch buffer.cur(1).codepoint { + case 0x0C4C, 0x0C55: + matched = true + } + case 0x0C3F, 0x0C46, 0x0C4A: + matched = 0x0C55 == buffer.cur(1).codepoint + } + + buffer.nextGlyph() + if matched { + outputWithDottedCircle(buffer) + } + } + case language.Kannada: + for buffer.idx = 0; buffer.idx+1 < count; { + matched := false + switch buffer.cur(0).codepoint { + case 0x0C89, 0x0C8B: + matched = 0x0CBE == buffer.cur(1).codepoint + case 0x0C92: + matched = 0x0CCC == buffer.cur(1).codepoint + } + + buffer.nextGlyph() + if matched { + outputWithDottedCircle(buffer) + } + } + case language.Malayalam: + for buffer.idx = 0; buffer.idx+1 < count; { + matched := false + switch buffer.cur(0).codepoint { + case 0x0D07, 0x0D09: + matched = 0x0D57 == buffer.cur(1).codepoint + case 0x0D0E: + matched = 0x0D46 == buffer.cur(1).codepoint + case 0x0D12: + switch buffer.cur(1).codepoint { + case 0x0D3E, 0x0D57: + matched = true + } + } + + buffer.nextGlyph() + if matched { + outputWithDottedCircle(buffer) + } + } + case language.Sinhala: + for buffer.idx = 0; buffer.idx+1 < count; { + matched := false + switch buffer.cur(0).codepoint { + case 0x0D85: + switch buffer.cur(1).codepoint { + case 0x0DCF, 0x0DD0, 0x0DD1: + matched = true + } + case 0x0D8B, 0x0D8F, 0x0D94: + matched = 0x0DDF == buffer.cur(1).codepoint + case 0x0D8D: + matched = 0x0DD8 == buffer.cur(1).codepoint + case 0x0D91: + switch buffer.cur(1).codepoint { + case 0x0DCA, 0x0DD9, 0x0DDA, 0x0DDC, 0x0DDD, 0x0DDE: + matched = true + } + } + + buffer.nextGlyph() + if matched { + outputWithDottedCircle(buffer) + } + } + case language.Brahmi: + for buffer.idx = 0; buffer.idx+1 < count; { + matched := false + switch buffer.cur(0).codepoint { + case 0x11005: + matched = 0x11038 == buffer.cur(1).codepoint + case 0x1100B: + matched = 0x1103E == buffer.cur(1).codepoint + case 0x1100F: + matched = 0x11042 == buffer.cur(1).codepoint + } + + buffer.nextGlyph() + if matched { + outputWithDottedCircle(buffer) + } + } + case language.Khojki: + for buffer.idx = 0; buffer.idx+1 < count; { + matched := false + switch buffer.cur(0).codepoint { + case 0x11200: + switch buffer.cur(1).codepoint { + case 0x1122C, 0x11231, 0x11233: + matched = true + } + case 0x11206: + matched = 0x1122C == buffer.cur(1).codepoint + case 0x1122C: + switch buffer.cur(1).codepoint { + case 0x11230, 0x11231: + matched = true + } + case 0x11240: + matched = 0x1122E == buffer.cur(1).codepoint + } + + buffer.nextGlyph() + if matched { + outputWithDottedCircle(buffer) + } + } + case language.Khudawadi: + for buffer.idx = 0; buffer.idx+1 < count; { + matched := false + switch buffer.cur(0).codepoint { + case 0x112B0: + switch buffer.cur(1).codepoint { + case 0x112E0, 0x112E5, 0x112E6, 0x112E7, 0x112E8: + matched = true + } + } + + buffer.nextGlyph() + if matched { + outputWithDottedCircle(buffer) + } + } + case language.Tirhuta: + for buffer.idx = 0; buffer.idx+1 < count; { + matched := false + switch buffer.cur(0).codepoint { + case 0x11481: + matched = 0x114B0 == buffer.cur(1).codepoint + case 0x1148B, 0x1148D: + matched = 0x114BA == buffer.cur(1).codepoint + case 0x114AA: + switch buffer.cur(1).codepoint { + case 0x114B5, 0x114B6: + matched = true + } + } + + buffer.nextGlyph() + if matched { + outputWithDottedCircle(buffer) + } + } + case language.Modi: + for buffer.idx = 0; buffer.idx+1 < count; { + matched := false + switch buffer.cur(0).codepoint { + case 0x11600, 0x11601: + switch buffer.cur(1).codepoint { + case 0x11639, 0x1163A: + matched = true + } + } + + buffer.nextGlyph() + if matched { + outputWithDottedCircle(buffer) + } + } + case language.Takri: + for buffer.idx = 0; buffer.idx+1 < count; { + matched := false + switch buffer.cur(0).codepoint { + case 0x11680: + switch buffer.cur(1).codepoint { + case 0x116AD, 0x116B4, 0x116B5: + matched = true + } + case 0x11686: + matched = 0x116B2 == buffer.cur(1).codepoint + } + + buffer.nextGlyph() + if matched { + outputWithDottedCircle(buffer) + } + } + } + buffer.swapBuffers() +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/set_digest.go b/vendor/github.com/go-text/typesetting/harfbuzz/set_digest.go new file mode 100644 index 0000000..cec7d16 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/set_digest.go @@ -0,0 +1,117 @@ +package harfbuzz + +import ( + "github.com/go-text/typesetting/font/opentype/tables" +) + +// ported from src/hb-set-digest.hh Copyright © 2012 Google, Inc. Behdad Esfahbod + +const maskBits = 4 * 8 // 4 = size(setDigestLowestBits) + +type setType = gID + +type setBits uint32 + +func maskFor(g setType, shift uint) setBits { + return 1 << ((g >> shift) & (maskBits - 1)) +} + +func (sd *setBits) add(g setType, shift uint) { *sd |= maskFor(g, shift) } + +func (sd *setBits) addRange(a, b setType, shift uint) { + if (b>>shift)-(a>>shift) >= maskBits-1 { + *sd = ^setBits(0) + } else { + mb := maskFor(b, shift) + ma := maskFor(a, shift) + var op setBits + if mb < ma { + op = 1 + } + *sd |= mb + (mb - ma) - op + } +} + +func (sd *setBits) addArray(arr []setType, shift uint) { + for _, v := range arr { + sd.add(v, shift) + } +} + +func (sd setBits) mayHave(g setType, shift uint) bool { + return sd&maskFor(g, shift) != 0 +} + +func (sd setBits) mayHaveSet(g setBits) bool { + return sd&g != 0 +} + +/* This is a combination of digests that performs "best". + * There is not much science to this: it's a result of intuition + * and testing. */ +const ( + shift0 = 4 + shift1 = 0 + shift2 = 9 +) + +// setDigest implement various "filters" that support +// "approximate member query". Conceptually these are like Bloom +// Filter and Quotient Filter, however, much smaller, faster, and +// designed to fit the requirements of our uses for glyph coverage +// queries. +// +// Our filters are highly accurate if the lookup covers fairly local +// set of glyphs, but fully flooded and ineffective if coverage is +// all over the place. +// +// The frozen-set can be used instead of a digest, to trade more +// memory for 100% accuracy, but in practice, that doesn't look like +// an attractive trade-off. +type setDigest [3]setBits + +// add adds the given rune to the set. +func (sd *setDigest) add(g setType) { + sd[0].add(g, shift0) + sd[1].add(g, shift1) + sd[2].add(g, shift2) +} + +// addRange adds the given, inclusive range to the set, +// in an efficient manner. +func (sd *setDigest) addRange(a, b setType) { + sd[0].addRange(a, b, shift0) + sd[1].addRange(a, b, shift1) + sd[2].addRange(a, b, shift2) +} + +// addArray is a convenience method to add +// many runes. +func (sd *setDigest) addArray(arr []setType) { + sd[0].addArray(arr, shift0) + sd[1].addArray(arr, shift1) + sd[2].addArray(arr, shift2) +} + +// mayHave performs an "approximate member query": if the return value +// is `false`, then it is certain that `g` is not in the set. +// Otherwise, we don't kwow, it might be a false positive. +// Note that runes in the set are certain to return `true`. +func (sd setDigest) mayHave(g setType) bool { + return sd[0].mayHave(g, shift0) && sd[1].mayHave(g, shift1) && sd[2].mayHave(g, shift2) +} + +func (sd setDigest) mayHaveDigest(o setDigest) bool { + return sd[0].mayHaveSet(o[0]) && sd[1].mayHaveSet(o[1]) && sd[2].mayHaveSet(o[2]) +} + +func (sd *setDigest) collectCoverage(cov tables.Coverage) { + switch cov := cov.(type) { + case tables.Coverage1: + sd.addArray(cov.Glyphs) + case tables.Coverage2: + for _, r := range cov.Ranges { + sd.addRange(r.StartGlyphID, r.EndGlyphID) + } + } +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/shape.go b/vendor/github.com/go-text/typesetting/harfbuzz/shape.go new file mode 100644 index 0000000..21f33d0 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/shape.go @@ -0,0 +1,156 @@ +package harfbuzz + +import ( + "fmt" + + "github.com/go-text/typesetting/font/opentype/tables" +) + +// ported from harfbuzz/src/hb-shape.cc, harfbuzz/src/hb-shape-plan.cc Copyright © 2009, 2012 Behdad Esfahbod + +/** + * Shaping is the central operation of HarfBuzz. Shaping operates on buffers, + * which are sequences of Unicode characters that use the same font and have + * the same text direction, script, and language. After shaping the buffer + * contains the output glyphs and their positions. + **/ + +// Shape shapes the buffer using `font`, turning its Unicode characters content to +// positioned glyphs. If `features` is not empty, it will be used to control the +// features applied during shaping. If two features have the same tag but +// overlapping ranges the value of the feature with the higher index takes +// precedence. +// +// The shapping plan depends on the font capabilities. See `NewFont` and `Face` and +// its extension interfaces for more details. +// +// It also depends on the properties of the segment of text : the `Props` +// field of the buffer must be set before calling `Shape`. +func (b *Buffer) Shape(font *Font, features []Feature) { + shapePlan := b.newShapePlanCached(font, b.Props, features, font.varCoords()) + shapePlan.execute(font, b, features) +} + +// Shape plans are an internal mechanism. Each plan contains state +// describing how HarfBuzz will shape a particular text segment, based on +// the combination of segment properties and the capabilities in the +// font face in use. +// +// Shape plans are not used for shaping directly, but can be queried to +// access certain information about how shaping will perform, given a set +// of specific input parameters (script, language, direction, features, +// etc.). +// +// Most client programs will not need to deal with shape plans directly. +type shapePlan struct { + shaper shaperOpentype + props SegmentProperties + userFeatures []Feature +} + +func (plan *shapePlan) init(copy bool, font *Font, props SegmentProperties, + userFeatures []Feature, coords []tables.Coord, +) { + plan.props = props + if !copy { + plan.userFeatures = userFeatures + } else { + plan.userFeatures = append([]Feature(nil), userFeatures...) + /* Make start/end uniform to easier catch bugs. */ + for i := range plan.userFeatures { + if plan.userFeatures[i].Start != FeatureGlobalStart { + plan.userFeatures[i].Start = 1 + } + if plan.userFeatures[i].End != FeatureGlobalEnd { + plan.userFeatures[i].End = 2 + } + } + } + + // init shaper + plan.shaper.init(font.face.Font, coords) +} + +func (plan shapePlan) userFeaturesMatch(other shapePlan) bool { + if len(plan.userFeatures) != len(other.userFeatures) { + return false + } + for i, feat := range plan.userFeatures { + if feat.Tag != other.userFeatures[i].Tag || feat.Value != other.userFeatures[i].Value || + (feat.Start == FeatureGlobalStart && feat.End == FeatureGlobalEnd) != + (other.userFeatures[i].Start == FeatureGlobalStart && other.userFeatures[i].End == FeatureGlobalEnd) { + return false + } + } + return true +} + +func (plan shapePlan) equal(other shapePlan) bool { + return plan.props == other.props && plan.userFeaturesMatch(other) +} + +// Constructs a shaping plan for a combination of @face, @userFeatures, @props, +// plus the variation-space coordinates @coords. +// See newShapePlanCached for caching support. +func newShapePlan(font *Font, props SegmentProperties, + userFeatures []Feature, coords []tables.Coord, +) *shapePlan { + if debugMode { + fmt.Printf("NEW SHAPE PLAN: face:%p features:%v coords:%v\n", &font.face, userFeatures, coords) + } + + var sp shapePlan + + sp.init(true, font, props, userFeatures, coords) + + if debugMode { + fmt.Println("NEW SHAPE PLAN - compiling shaper plan") + } + sp.shaper.compile(props, userFeatures) + + return &sp +} + +// Executes the given shaping plan on the specified `buffer`, using +// the given `font` and `features`. +func (sp *shapePlan) execute(font *Font, buffer *Buffer, features []Feature) { + if debugMode { + fmt.Printf("EXECUTE shape plan %p features:%v shaper:%T\n", sp, features, sp.shaper.plan.shaper) + } + + sp.shaper.shape(font, buffer, features) +} + +/* + * Caching + */ + +// creates (or returns) a cached shaping plan suitable for reuse, for a combination +// of `face`, `userFeatures`, `props`, plus the variation-space coordinates `coords`. +func (b *Buffer) newShapePlanCached(font *Font, props SegmentProperties, + userFeatures []Feature, coords []tables.Coord, +) *shapePlan { + var key shapePlan + key.init(false, font, props, userFeatures, coords) + + plans := b.planCache[font.face] + + for _, plan := range plans { + if plan.equal(key) { + if debugMode { + fmt.Printf("\tPLAN %p fulfilled from cache\n", plan) + } + return plan + } + } + plan := newShapePlan(font, props, userFeatures, coords) + + plans = append(plans, plan) + b.planCache[font.face] = plans + + if debugMode { + fmt.Printf("\tPLAN %p inserted into cache\n", plan) + } + + return plan +} diff --git a/vendor/github.com/go-text/typesetting/harfbuzz/unicode.go b/vendor/github.com/go-text/typesetting/harfbuzz/unicode.go new file mode 100644 index 0000000..1baf9ad --- /dev/null +++ b/vendor/github.com/go-text/typesetting/harfbuzz/unicode.go @@ -0,0 +1,639 @@ +package harfbuzz + +import ( + "unicode" + + ucd "github.com/go-text/typesetting/unicodedata" +) + +// uni exposes some lookup functions for Unicode properties. +var uni = unicodeFuncs{} + +// generalCategory is an enum value to allow compact storage (see generalCategories) +type generalCategory uint8 + +const ( + control generalCategory = iota + format + unassigned + privateUse + surrogate + lowercaseLetter + modifierLetter + otherLetter + titlecaseLetter + uppercaseLetter + spacingMark + enclosingMark + nonSpacingMark + decimalNumber + letterNumber + otherNumber + connectPunctuation + dashPunctuation + closePunctuation + finalPunctuation + initialPunctuation + otherPunctuation + openPunctuation + currencySymbol + modifierSymbol + mathSymbol + otherSymbol + lineSeparator + paragraphSeparator + spaceSeparator +) + +// correspondance with *unicode.RangeTable classes +var generalCategories = [...]*unicode.RangeTable{ + control: ucd.Cc, + format: ucd.Cf, + unassigned: nil, + privateUse: ucd.Co, + surrogate: ucd.Cs, + lowercaseLetter: ucd.Ll, + modifierLetter: ucd.Lm, + otherLetter: ucd.Lo, + titlecaseLetter: ucd.Lt, + uppercaseLetter: ucd.Lu, + spacingMark: ucd.Mc, + enclosingMark: ucd.Me, + nonSpacingMark: ucd.Mn, + decimalNumber: ucd.Nd, + letterNumber: ucd.Nl, + otherNumber: ucd.No, + connectPunctuation: ucd.Pc, + dashPunctuation: ucd.Pd, + closePunctuation: ucd.Pe, + finalPunctuation: ucd.Pf, + initialPunctuation: ucd.Pi, + otherPunctuation: ucd.Po, + openPunctuation: ucd.Ps, + currencySymbol: ucd.Sc, + modifierSymbol: ucd.Sk, + mathSymbol: ucd.Sm, + otherSymbol: ucd.So, + lineSeparator: ucd.Zl, + paragraphSeparator: ucd.Zp, + spaceSeparator: ucd.Zs, +} + +func (g generalCategory) isMark() bool { + return g == spacingMark || g == enclosingMark || g == nonSpacingMark +} + +func (g generalCategory) isLetter() bool { + return g == lowercaseLetter || g == modifierLetter || g == otherLetter || + g == titlecaseLetter || g == uppercaseLetter +} + +// Modified combining marks +const ( + /* Hebrew + * + * We permute the "fixed-position" classes 10-26 into the order + * described in the SBL Hebrew manual: + * + * https://www.sbl-site.org/Fonts/SBLHebrewUserManual1.5x.pdf + * + * (as recommended by: + * https://forum.fontlab.com/archive-old-microsoft-volt-group/vista-and-diacritic-ordering/msg22823/) + * + * More details here: + * https://bugzilla.mozilla.org/show_bug.cgi?id=662055 + */ + mcc10 uint8 = 22 /* sheva */ + mcc11 uint8 = 15 /* hataf segol */ + mcc12 uint8 = 16 /* hataf patah */ + mcc13 uint8 = 17 /* hataf qamats */ + mcc14 uint8 = 23 /* hiriq */ + mcc15 uint8 = 18 /* tsere */ + mcc16 uint8 = 19 /* segol */ + mcc17 uint8 = 20 /* patah */ + mcc18 uint8 = 21 /* qamats & qamats qatan */ + mcc19 uint8 = 14 /* holam & holam haser for vav*/ + mcc20 uint8 = 24 /* qubuts */ + mcc21 uint8 = 12 /* dagesh */ + mcc22 uint8 = 25 /* meteg */ + mcc23 uint8 = 13 /* rafe */ + mcc24 uint8 = 10 /* shin dot */ + mcc25 uint8 = 11 /* sin dot */ + mcc26 uint8 = 26 /* point varika */ + + /* + * Arabic + * + * Modify to move Shadda (ccc=33) before other marks. See: + * https://unicode.org/faq/normalization.html#8 + * https://unicode.org/faq/normalization.html#9 + */ + mcc27 uint8 = 28 /* fathatan */ + mcc28 uint8 = 29 /* dammatan */ + mcc29 uint8 = 30 /* kasratan */ + mcc30 uint8 = 31 /* fatha */ + mcc31 uint8 = 32 /* damma */ + mcc32 uint8 = 33 /* kasra */ + mcc33 uint8 = 27 /* shadda */ + mcc34 uint8 = 34 /* sukun */ + mcc35 uint8 = 35 /* superscript alef */ + + /* Syriac */ + mcc36 uint8 = 36 /* superscript alaph */ + + /* Telugu + * + * Modify Telugu length marks (ccc=84, ccc=91). + * These are the only matras in the main Indic scripts range that have + * a non-zero ccc. That makes them reorder with the Halant (ccc=9). + * Assign 4 and 5, which are otherwise unassigned. + */ + mcc84 uint8 = 4 /* length mark */ + mcc91 uint8 = 5 /* ai length mark */ + + /* Thai + * + * Modify U+0E38 and U+0E39 (ccc=103) to be reordered before U+0E3A (ccc=9). + * Assign 3, which is unassigned otherwise. + * Uniscribe does this reordering too. + */ + mcc103 uint8 = 3 /* sara u / sara uu */ + mcc107 uint8 = 107 /* mai * */ + + /* Lao */ + mcc118 uint8 = 118 /* sign u / sign uu */ + mcc122 uint8 = 122 /* mai * */ + + /* Tibetan + * + * In case of multiple vowel-signs, use u first (but after achung) + * this allows Dzongkha multi-vowel shortcuts to render correctly + */ + mcc129 = 129 /* sign aa */ + mcc130 = 132 /* sign i */ + mcc132 = 131 /* sign u */ +) + +var modifiedCombiningClass = [256]uint8{ + 0, /* HB_UNICODE_COMBINING_CLASS_NOT_REORDERED */ + 1, /* HB_UNICODE_COMBINING_CLASS_OVERLAY */ + 2, 3, 4, 5, 6, + 7, /* HB_UNICODE_COMBINING_CLASS_NUKTA */ + 8, /* HB_UNICODE_COMBINING_CLASS_KANA_VOICING */ + 9, /* HB_UNICODE_COMBINING_CLASS_VIRAMA */ + + /* Hebrew */ + mcc10, + mcc11, + mcc12, + mcc13, + mcc14, + mcc15, + mcc16, + mcc17, + mcc18, + mcc19, + mcc20, + mcc21, + mcc22, + mcc23, + mcc24, + mcc25, + mcc26, + + /* Arabic */ + mcc27, + mcc28, + mcc29, + mcc30, + mcc31, + mcc32, + mcc33, + mcc34, + mcc35, + + /* Syriac */ + mcc36, + + 37, 38, 39, + 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, + 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, + 80, 81, 82, 83, + + /* Telugu */ + mcc84, + 85, 86, 87, 88, 89, 90, + mcc91, + 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, + + /* Thai */ + mcc103, + 104, 105, 106, + mcc107, + 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, + + /* Lao */ + mcc118, + 119, 120, 121, + mcc122, + 123, 124, 125, 126, 127, 128, + + /* Tibetan */ + mcc129, + mcc130, + 131, + mcc132, + 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, 195, 196, 197, 198, 199, + + 200, /* HB_UNICODE_COMBINING_CLASS_ATTACHED_BELOW_LEFT */ + 201, + 202, /* HB_UNICODE_COMBINING_CLASS_ATTACHED_BELOW */ + 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, + 214, /* HB_UNICODE_COMBINING_CLASS_ATTACHED_ABOVE */ + 215, + 216, /* HB_UNICODE_COMBINING_CLASS_ATTACHED_ABOVE_RIGHT */ + 217, + 218, /* HB_UNICODE_COMBINING_CLASS_BELOW_LEFT */ + 219, + 220, /* HB_UNICODE_COMBINING_CLASS_BELOW */ + 221, + 222, /* HB_UNICODE_COMBINING_CLASS_BELOW_RIGHT */ + 223, + 224, /* HB_UNICODE_COMBINING_CLASS_LEFT */ + 225, + 226, /* HB_UNICODE_COMBINING_CLASS_RIGHT */ + 227, + 228, /* HB_UNICODE_COMBINING_CLASS_ABOVE_LEFT */ + 229, + 230, /* HB_UNICODE_COMBINING_CLASS_ABOVE */ + 231, + 232, /* HB_UNICODE_COMBINING_CLASS_ABOVE_RIGHT */ + 233, /* HB_UNICODE_COMBINING_CLASS_DOUBLE_BELOW */ + 234, /* HB_UNICODE_COMBINING_CLASS_DOUBLE_ABOVE */ + 235, 236, 237, 238, 239, + 240, /* HB_UNICODE_COMBINING_CLASS_IOTA_SUBSCRIPT */ + 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, + 255, /* HB_UNICODE_COMBINING_CLASS_INVALID */ +} + +type unicodeFuncs struct{} + +func (unicodeFuncs) modifiedCombiningClass(u rune) uint8 { + // Reorder SAKOT to ensure it comes after any tone marks. + if u == 0x1A60 { + return 254 + } + + // Reorder PADMA to ensure it comes after any vowel marks. + if u == 0x0FC6 { + return 254 + } + /* Reorder TSA -PHRU to reorder before U+0F74 */ + if u == 0x0F39 { + return 127 + } + return modifiedCombiningClass[ucd.LookupCombiningClass(u)] +} + +// IsDefaultIgnorable returns `true` for +// codepoints with the Default_Ignorable property +// (as defined in unicode data DerivedCoreProperties.txt) +func IsDefaultIgnorable(ch rune) bool { + // Note: While U+115F, U+1160, U+3164 and U+FFA0 are Default_Ignorable, + // we do NOT want to hide them, as the way Uniscribe has implemented them + // is with regular spacing glyphs, and that's the way fonts are made to work. + // As such, we make exceptions for those four. + // Also ignoring U+1BCA0..1BCA3. https://github.com/harfbuzz/harfbuzz/issues/503 + plane := ch >> 16 + if plane == 0 { + /* BMP */ + page := ch >> 8 + switch page { + case 0x00: + return (ch == 0x00AD) + case 0x03: + return (ch == 0x034F) + case 0x06: + return (ch == 0x061C) + case 0x17: + return 0x17B4 <= ch && ch <= 0x17B5 + case 0x18: + return 0x180B <= ch && ch <= 0x180E + case 0x20: + return 0x200B <= ch && ch <= 0x200F || + 0x202A <= ch && ch <= 0x202E || + 0x2060 <= ch && ch <= 0x206F + case 0xFE: + return 0xFE00 <= ch && ch <= 0xFE0F || ch == 0xFEFF + case 0xFF: + return 0xFFF0 <= ch && ch <= 0xFFF8 + default: + return false + } + } else { + /* Other planes */ + switch plane { + case 0x01: + return 0x1D173 <= ch && ch <= 0x1D17A + case 0x0E: + return 0xE0000 <= ch && ch <= 0xE0FFF + default: + return false + } + } +} + +func (unicodeFuncs) isDefaultIgnorable(ch rune) bool { + return IsDefaultIgnorable(ch) +} + +// retrieves the General Category property for +// a specified Unicode code point, expressed as enumeration value. +func (unicodeFuncs) generalCategory(ch rune) generalCategory { + for i, cat := range generalCategories { + if cat != nil && unicode.Is(cat, ch) { + return generalCategory(i) + } + } + return unassigned +} + +func (unicodeFuncs) isExtendedPictographic(ch rune) bool { + return unicode.Is(ucd.Extended_Pictographic, ch) +} + +// returns the mirroring Glyph code point (for bi-directional +// replacement) of a code point, or itself +func (unicodeFuncs) mirroring(ch rune) rune { + out, _ := ucd.LookupMirrorChar(ch) + return out +} + +/* Space estimates based on: + * https://unicode.org/charts/PDF/U2000.pdf + * https://docs.microsoft.com/en-us/typography/develop/character-design-standards/whitespace + */ +const ( + spaceEM16 = 16 + iota + space4EM18 // 4/18th of an EM! + space + spaceFigure + spacePunctuation + spaceNarrow + notSpace = 0 + spaceEM = 1 + spaceEM2 = 2 + spaceEM3 = 3 + spaceEM4 = 4 + spaceEM5 = 5 + spaceEM6 = 6 +) + +func (unicodeFuncs) spaceFallbackType(u rune) uint8 { + switch u { + // all GC=Zs chars that can use a fallback. + case 0x0020: + return space /* U+0020 SPACE */ + case 0x00A0: + return space /* U+00A0 NO-BREAK SPACE */ + case 0x2000: + return spaceEM2 /* U+2000 EN QUAD */ + case 0x2001: + return spaceEM /* U+2001 EM QUAD */ + case 0x2002: + return spaceEM2 /* U+2002 EN SPACE */ + case 0x2003: + return spaceEM /* U+2003 EM SPACE */ + case 0x2004: + return spaceEM3 /* U+2004 THREE-PER-EM SPACE */ + case 0x2005: + return spaceEM4 /* U+2005 FOUR-PER-EM SPACE */ + case 0x2006: + return spaceEM6 /* U+2006 SIX-PER-EM SPACE */ + case 0x2007: + return spaceFigure /* U+2007 FIGURE SPACE */ + case 0x2008: + return spacePunctuation /* U+2008 PUNCTUATION SPACE */ + case 0x2009: + return spaceEM5 /* U+2009 THIN SPACE */ + case 0x200A: + return spaceEM16 /* U+200A HAIR SPACE */ + case 0x202F: + return spaceNarrow /* U+202F NARROW NO-BREAK SPACE */ + case 0x205F: + return space4EM18 /* U+205F MEDIUM MATHEMATICAL SPACE */ + case 0x3000: + return spaceEM /* U+3000 IDEOGRAPHIC SPACE */ + default: + return notSpace /* U+1680 OGHAM SPACE MARK */ + } +} + +func (unicodeFuncs) isVariationSelector(r rune) bool { + /* U+180B..180D, U+180F MONGOLIAN FREE VARIATION SELECTORs are handled in the + * Arabic shaper. No need to match them here. */ + /* VARIATION SELECTOR-1..16 */ + /* VARIATION SELECTOR-17..256 */ + return (0xFE00 <= r && r <= 0xFE0F) || (0xE0100 <= r && r <= 0xE01EF) +} + +func (unicodeFuncs) decompose(ab rune) (a, b rune, ok bool) { return ucd.Decompose(ab) } +func (unicodeFuncs) compose(a, b rune) (rune, bool) { return ucd.Compose(a, b) } + +/* Prepare */ + +func isRegionalIndicator(r rune) bool { return 0x1F1E6 <= r && r <= 0x1F1FF } + +// Implement enough of Unicode Graphemes here that shaping +// in reverse-direction wouldn't break graphemes. Namely, +// we mark all marks and ZWJ and ZWJ,Extended_Pictographic +// sequences as continuations. The foreach_grapheme() +// macro uses this bit. +// +// https://www.unicode.org/reports/tr29/#Regex_Definitions +func (b *Buffer) setUnicodeProps() { + info := b.Info + for i := 0; i < len(info); i++ { + r := info[i].codepoint + info[i].setUnicodeProps(b) + + /* Marks are already set as continuation by the above line. + * Handle Emoji_Modifier and ZWJ-continuation. */ + if info[i].unicode.generalCategory() == modifierSymbol && (0x1F3FB <= r && r <= 0x1F3FF) { + info[i].setContinuation() + } else if i != 0 && isRegionalIndicator(r) { + /* Regional_Indicators are hairy as hell... + * https://github.com/harfbuzz/harfbuzz/issues/2265 */ + if isRegionalIndicator(info[i-1].codepoint) && !info[i-1].isContinuation() { + info[i].setContinuation() + } + } else if info[i].isZwj() { + info[i].setContinuation() + if i+1 < len(b.Info) && uni.isExtendedPictographic(info[i+1].codepoint) { + i++ + info[i].setUnicodeProps(b) + info[i].setContinuation() + } + } else if (0xFF9E <= r && r <= 0xFF9F) || (0xE0020 <= r && r <= 0xE007F) { + // Or part of the Other_Grapheme_Extend that is not marks. + // As of Unicode 15 that is just: + // + // 200C ; Other_Grapheme_Extend # Cf ZERO WIDTH NON-JOINER + // FF9E..FF9F ; Other_Grapheme_Extend # Lm [2] HALFWIDTH KATAKANA VOICED SOUND MARK..HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK + // E0020..E007F ; Other_Grapheme_Extend # Cf [96] TAG SPACE..CANCEL TAG + // + // ZWNJ is special, we don't want to merge it as there's no need, and keeping + // it separate results in more granular clusters. + // Tags are used for Emoji sub-region flag sequences: + // https://github.com/harfbuzz/harfbuzz/issues/1556 + // Katakana ones were requested: + // https://github.com/harfbuzz/harfbuzz/issues/3844 + info[i].setContinuation() + } + } +} + +func (b *Buffer) insertDottedCircle(font *Font) { + if b.Flags&DoNotinsertDottedCircle != 0 { + return + } + + if b.Flags&Bot == 0 || len(b.context[0]) != 0 || + len(b.Info) == 0 || !b.Info[0].isUnicodeMark() { + return + } + + if !font.hasGlyph(0x25CC) { + return + } + + dottedcircle := GlyphInfo{codepoint: 0x25CC} + dottedcircle.setUnicodeProps(b) + + b.clearOutput() + + b.idx = 0 + dottedcircle.Cluster = b.cur(0).Cluster + dottedcircle.Mask = b.cur(0).Mask + b.outInfo = append(b.outInfo, dottedcircle) + b.swapBuffers() +} + +func (b *Buffer) formClusters() { + if b.scratchFlags&bsfHasNonASCII == 0 { + return + } + + iter, count := b.graphemesIterator() + + if b.ClusterLevel == MonotoneGraphemes { + for start, end := iter.next(); start < count; start, end = iter.next() { + b.mergeClusters(start, end) + } + } else { + for start, end := iter.next(); start < count; start, end = iter.next() { + b.unsafeToBreak(start, end) + } + } +} + +func (b *Buffer) ensureNativeDirection() { + direction := b.Props.Direction + horizDir := getHorizontalDirection(b.Props.Script) + + // Numeric runs in natively-RTL scripts are actually native-LTR, so we reset + // the horiz_dir if the run contains at least one decimal-number char, and no + // letter chars (ideally we should be checking for chars with strong + // directionality but hb-unicode currently lacks bidi categories). + // + // This allows digit sequences in Arabic etc to be shaped in "native" + // direction, so that features like ligatures will work as intended. + // + // https://github.com/harfbuzz/harfbuzz/issues/501 + // + // Similar thing about Regional_Indicators; They are bidi=L, but Script=Common. + // If they are present in a run of natively-RTL text, they get assigned a script + // with natively RTL direction, which would result in wrong shaping if we + // assign such native RTL direction to them then. Detect that as well. + // + // https://github.com/harfbuzz/harfbuzz/issues/3314 + // + + if horizDir == RightToLeft && direction == LeftToRight { + var foundNumber, foundLetter, foundRi bool + for _, info := range b.Info { + gc := info.unicode.generalCategory() + if gc == decimalNumber { + foundNumber = true + } else if gc.isLetter() { + foundLetter = true + break + } else if isRegionalIndicator(info.codepoint) { + foundRi = true + } + } + if (foundNumber || foundRi) && !foundLetter { + horizDir = LeftToRight + } + } + + if (direction.isHorizontal() && direction != horizDir && horizDir != 0) || + (direction.isVertical() && direction != TopToBottom) { + + reverseGraphemes(b) + + b.Props.Direction = b.Props.Direction.Reverse() + } +} + +// the returned flag must be ORed with the current +func computeUnicodeProps(u rune) (unicodeProp, bufferScratchFlags) { + genCat := uni.generalCategory(u) + props := unicodeProp(genCat) + var flags bufferScratchFlags + if u >= 0x80 { + flags |= bsfHasNonASCII + + if uni.isDefaultIgnorable(u) { + flags |= bsfHasDefaultIgnorables + props |= upropsMaskIgnorable + if u == 0x200C { + props |= upropsMaskCfZwnj + } else if u == 0x200D { + props |= upropsMaskCfZwj + } else if (0x180B <= u && u <= 0x180D) || u == 0x180F { + /* Mongolian Free Variation Selectors need to be remembered + * because although we need to hide them like default-ignorables, + * they need to non-ignorable during shaping. This is similar to + * what we do for joiners in Indic-like shapers, but since the + * FVSes are GC=Mn, we have use a separate bit to remember them. + * Fixes: + * https://github.com/harfbuzz/harfbuzz/issues/234 */ + props |= upropsMaskHidden + } else if 0xE0020 <= u && u <= 0xE007F { + /* TAG characters need similar treatment. Fixes: + * https://github.com/harfbuzz/harfbuzz/issues/463 */ + props |= upropsMaskHidden + } else if u == 0x034F { + /* COMBINING GRAPHEME JOINER should not be skipped; at least some times. + * https://github.com/harfbuzz/harfbuzz/issues/554 */ + flags |= bsfHasCGJ + props |= upropsMaskHidden + } + } + + if genCat.isMark() { + props |= upropsMaskContinuation + props |= unicodeProp(uni.modifiedCombiningClass(u)) << 8 + } + } + + return props, flags +} diff --git a/vendor/github.com/go-text/typesetting/language/language.go b/vendor/github.com/go-text/typesetting/language/language.go new file mode 100644 index 0000000..9f34b23 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/language/language.go @@ -0,0 +1,158 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package language + +import ( + "os" + "strings" +) + +var canonMap = [256]byte{ + 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, 0, 0, '-', 0, 0, + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 0, 0, 0, 0, 0, 0, + '-', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 0, 0, 0, 0, '-', + 0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 0, 0, 0, 0, 0, +} + +// Language store the canonicalized BCP 47 tag, +// which has the generic form --... +type Language string + +// NewLanguage canonicalizes the language input (as a BCP 47 language tag), by converting it to +// lowercase, mapping '_' to '-', and stripping all characters other +// than letters, numbers and '-'. +func NewLanguage(language string) Language { + out := make([]byte, 0, len(language)) + for _, r := range language { + if r >= 0xFF { + continue + } + can := canonMap[r] + if can != 0 { + out = append(out, can) + } + } + return Language(out) +} + +// Primary returns the root language of l, that is +// the part before the first '-' separator +func (l Language) Primary() Language { + if index := strings.IndexByte(string(l), '-'); index != -1 { + l = l[:index] + } + return l +} + +// SimpleInheritance returns the list of matching language, using simple truncation inheritance. +// The resulting slice starts with the given whole language. +// See http://www.unicode.org/reports/tr35/#Locale_Inheritance for more information. +func (l Language) SimpleInheritance() []Language { + tags := strings.Split(string(l), "-") + out := make([]Language, 0, len(tags)) + for len(tags) != 0 { + out = append(out, Language(strings.Join(tags, "-"))) + tags = tags[:len(tags)-1] + } + return out +} + +// IsDerivedFrom returns `true` if `l` has +// the `root` as primary language. +func (l Language) IsDerivedFrom(root Language) bool { return l.Primary() == root } + +// IsUndetermined returns `true` if its primary language is "und". +// It is a shortcut for IsDerivedFrom("und"). +func (l Language) IsUndetermined() bool { return l.IsDerivedFrom("und") } + +// SplitExtensionTags splits the language at the extension and private-use subtags, which are +// marked by a "--" pattern. +// It returns the language before the first pattern, and, if any, the private-use subtag. +// +// (l, "") is returned if the language has no extension or private-use tag. +func (l Language) SplitExtensionTags() (prefix, private Language) { + if len(l) >= 2 && l[0] == 'x' && l[1] == '-' { // x-<....> 'fully' private + return "", l + } + + firstExtension := -1 + for i := 0; i+3 < len(l); i++ { + if l[i] == '-' && l[i+2] == '-' { + if firstExtension == -1 { // mark the end of the prefix + firstExtension = i + } + + if l[i+1] == 'x' { // private-use tag + return l[:firstExtension], l[i+1:] + } + // else keep looking for private sub tags + } + } + + if firstExtension == -1 { + return l, "" + } + return l[:firstExtension], "" +} + +// LanguageComparison is a three state enum resulting from comparing two languages +type LanguageComparison uint8 + +const ( + LanguagesDiffer LanguageComparison = iota // the two languages are totally differents + LanguagesExactMatch // the two languages are exactly the same + LanguagePrimaryMatch // the two languages have the same primary language, but differs. +) + +// Compare compares `other` and `l`. +// Undetermined languages are only compared using the remaining tags, +// meaning that "und-fr" and "und-be" are compared as LanguagesDiffer, not +// LanguagePrimaryMatch. +func (l Language) Compare(other Language) LanguageComparison { + if l == other { + return LanguagesExactMatch + } + + primary1, primary2 := l.Primary(), other.Primary() + if primary1 != primary2 { + return LanguagesDiffer + } + + // check for the undetermined special case + if primary1 == "und" { + return LanguagesDiffer + } + return LanguagePrimaryMatch +} + +func languageFromLocale(locale string) Language { + if i := strings.IndexByte(locale, '.'); i >= 0 { + locale = locale[:i] + } + return NewLanguage(locale) +} + +// DefaultLanguage returns the language found in environment variables LC_ALL, LC_CTYPE or +// LANG (in that order), or the zero value if not found. +func DefaultLanguage() Language { + p, ok := os.LookupEnv("LC_ALL") + if ok { + return languageFromLocale(p) + } + + p, ok = os.LookupEnv("LC_CTYPE") + if ok { + return languageFromLocale(p) + } + + p, ok = os.LookupEnv("LANG") + if ok { + return languageFromLocale(p) + } + + return "" +} diff --git a/vendor/github.com/go-text/typesetting/language/scripts.go b/vendor/github.com/go-text/typesetting/language/scripts.go new file mode 100644 index 0000000..63c4408 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/language/scripts.go @@ -0,0 +1,50 @@ +package language + +import ( + "encoding/binary" + "fmt" +) + +// Script identifies different writing systems. +// It is represented as the binary encoding of a script tag of 4 (case sensitive) letters, +// as specified by ISO 15924. +// Note that the default value is usually the Unknown script, not the 0 value (which is invalid) +type Script uint32 + +// ParseScript converts a 4 bytes string into its binary encoding, +// enforcing the conventional capitalized case. +// If [script] is longer, only its 4 first bytes are used. +func ParseScript(script string) (Script, error) { + if len(script) < 4 { + return 0, fmt.Errorf("invalid script string: %s", script) + } + s := binary.BigEndian.Uint32([]byte(script)) + // ensure capitalized case : make first letter upper, others lower + const mask uint32 = 0x20000000 + return Script(s & ^mask | 0x00202020), nil +} + +// LookupScript looks up the script for a particular character (as defined by +// Unicode Standard Annex #24), and returns Unknown if not found. +func LookupScript(r rune) Script { + // binary search + for i, j := 0, len(ScriptRanges); i < j; { + h := i + (j-i)/2 + entry := ScriptRanges[h] + if r < entry.Start { + j = h + } else if entry.End < r { + i = h + 1 + } else { + return entry.Script + } + } + return Unknown +} + +// String returns the ISO 4 lower letters code of the script +func (s Script) String() string { + var buf [4]byte + binary.BigEndian.PutUint32(buf[:], uint32(s)) + return string(buf[:]) +} diff --git a/vendor/github.com/go-text/typesetting/language/scripts_table.go b/vendor/github.com/go-text/typesetting/language/scripts_table.go new file mode 100644 index 0000000..44b551e --- /dev/null +++ b/vendor/github.com/go-text/typesetting/language/scripts_table.go @@ -0,0 +1,1352 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package language + +// Code generated by typesettings-utils/generators/unicodedata/cmd/main.go DO NOT EDIT. + +const ( + Adlam = Script(0x41646c6d) // Adlm + Afaka = Script(0x4166616b) // Afak + Ahom = Script(0x41686f6d) // Ahom + Anatolian_Hieroglyphs = Script(0x486c7577) // Hluw + Arabic = Script(0x41726162) // Arab + Armenian = Script(0x41726d6e) // Armn + Avestan = Script(0x41767374) // Avst + Balinese = Script(0x42616c69) // Bali + Bamum = Script(0x42616d75) // Bamu + Bassa_Vah = Script(0x42617373) // Bass + Batak = Script(0x4261746b) // Batk + Bengali = Script(0x42656e67) // Beng + Bhaiksuki = Script(0x42686b73) // Bhks + Blissymbols = Script(0x426c6973) // Blis + Book_Pahlavi = Script(0x50686c76) // Phlv + Bopomofo = Script(0x426f706f) // Bopo + Brahmi = Script(0x42726168) // Brah + Braille = Script(0x42726169) // Brai + Buginese = Script(0x42756769) // Bugi + Buhid = Script(0x42756864) // Buhd + Canadian_Aboriginal = Script(0x43616e73) // Cans + Carian = Script(0x43617269) // Cari + Caucasian_Albanian = Script(0x41676862) // Aghb + Chakma = Script(0x43616b6d) // Cakm + Cham = Script(0x4368616d) // Cham + Cherokee = Script(0x43686572) // Cher + Chorasmian = Script(0x43687273) // Chrs + Cirth = Script(0x43697274) // Cirt + Code_for_unwritten_documents = Script(0x5a787878) // Zxxx + Common = Script(0x5a797979) // Zyyy + Coptic = Script(0x436f7074) // Copt + Cuneiform = Script(0x58737578) // Xsux + Cypriot = Script(0x43707274) // Cprt + Cypro_Minoan = Script(0x43706d6e) // Cpmn + Cyrillic = Script(0x4379726c) // Cyrl + Deseret = Script(0x44737274) // Dsrt + Devanagari = Script(0x44657661) // Deva + Dives_Akuru = Script(0x4469616b) // Diak + Dogra = Script(0x446f6772) // Dogr + Duployan = Script(0x4475706c) // Dupl + Egyptian_Hieroglyphs = Script(0x45677970) // Egyp + Egyptian_demotic = Script(0x45677964) // Egyd + Egyptian_hieratic = Script(0x45677968) // Egyh + Elbasan = Script(0x456c6261) // Elba + Elymaic = Script(0x456c796d) // Elym + Ethiopic = Script(0x45746869) // Ethi + Georgian = Script(0x47656f72) // Geor + Glagolitic = Script(0x476c6167) // Glag + Gothic = Script(0x476f7468) // Goth + Grantha = Script(0x4772616e) // Gran + Greek = Script(0x4772656b) // Grek + Gujarati = Script(0x47756a72) // Gujr + Gunjala_Gondi = Script(0x476f6e67) // Gong + Gurmukhi = Script(0x47757275) // Guru + Han = Script(0x48616e69) // Hani + Hangul = Script(0x48616e67) // Hang + Hanifi_Rohingya = Script(0x526f6867) // Rohg + Hanunoo = Script(0x48616e6f) // Hano + Hatran = Script(0x48617472) // Hatr + Hebrew = Script(0x48656272) // Hebr + Hiragana = Script(0x48697261) // Hira + Imperial_Aramaic = Script(0x41726d69) // Armi + Inherited = Script(0x5a696e68) // Zinh + Inscriptional_Pahlavi = Script(0x50686c69) // Phli + Inscriptional_Parthian = Script(0x50727469) // Prti + Javanese = Script(0x4a617661) // Java + Jurchen = Script(0x4a757263) // Jurc + Kaithi = Script(0x4b746869) // Kthi + Kannada = Script(0x4b6e6461) // Knda + Katakana = Script(0x4b616e61) // Kana + Katakana_Or_Hiragana = Script(0x48726b74) // Hrkt + Kawi = Script(0x4b617769) // Kawi + Kayah_Li = Script(0x4b616c69) // Kali + Kharoshthi = Script(0x4b686172) // Khar + Khitan_Small_Script = Script(0x4b697473) // Kits + Khitan_large_script = Script(0x4b69746c) // Kitl + Khmer = Script(0x4b686d72) // Khmr + Khojki = Script(0x4b686f6a) // Khoj + Khudawadi = Script(0x53696e64) // Sind + Kpelle = Script(0x4b70656c) // Kpel + Lao = Script(0x4c616f6f) // Laoo + Latin = Script(0x4c61746e) // Latn + Leke = Script(0x4c656b65) // Leke + Lepcha = Script(0x4c657063) // Lepc + Limbu = Script(0x4c696d62) // Limb + Linear_A = Script(0x4c696e61) // Lina + Linear_B = Script(0x4c696e62) // Linb + Lisu = Script(0x4c697375) // Lisu + Loma = Script(0x4c6f6d61) // Loma + Lycian = Script(0x4c796369) // Lyci + Lydian = Script(0x4c796469) // Lydi + Mahajani = Script(0x4d61686a) // Mahj + Makasar = Script(0x4d616b61) // Maka + Malayalam = Script(0x4d6c796d) // Mlym + Mandaic = Script(0x4d616e64) // Mand + Manichaean = Script(0x4d616e69) // Mani + Marchen = Script(0x4d617263) // Marc + Masaram_Gondi = Script(0x476f6e6d) // Gonm + Mathematical_notation = Script(0x5a6d7468) // Zmth + Mayan_hieroglyphs = Script(0x4d617961) // Maya + Medefaidrin = Script(0x4d656466) // Medf + Meetei_Mayek = Script(0x4d746569) // Mtei + Mende_Kikakui = Script(0x4d656e64) // Mend + Meroitic_Cursive = Script(0x4d657263) // Merc + Meroitic_Hieroglyphs = Script(0x4d65726f) // Mero + Miao = Script(0x506c7264) // Plrd + Modi = Script(0x4d6f6469) // Modi + Mongolian = Script(0x4d6f6e67) // Mong + Mro = Script(0x4d726f6f) // Mroo + Multani = Script(0x4d756c74) // Mult + Myanmar = Script(0x4d796d72) // Mymr + Nabataean = Script(0x4e626174) // Nbat + Nag_Mundari = Script(0x4e61676d) // Nagm + Nandinagari = Script(0x4e616e64) // Nand + New_Tai_Lue = Script(0x54616c75) // Talu + Newa = Script(0x4e657761) // Newa + Nko = Script(0x4e6b6f6f) // Nkoo + Nushu = Script(0x4e736875) // Nshu + Nyiakeng_Puachue_Hmong = Script(0x486d6e70) // Hmnp + Ogham = Script(0x4f67616d) // Ogam + Ol_Chiki = Script(0x4f6c636b) // Olck + Old_Hungarian = Script(0x48756e67) // Hung + Old_Italic = Script(0x4974616c) // Ital + Old_North_Arabian = Script(0x4e617262) // Narb + Old_Permic = Script(0x5065726d) // Perm + Old_Persian = Script(0x5870656f) // Xpeo + Old_Sogdian = Script(0x536f676f) // Sogo + Old_South_Arabian = Script(0x53617262) // Sarb + Old_Turkic = Script(0x4f726b68) // Orkh + Old_Uyghur = Script(0x4f756772) // Ougr + Oriya = Script(0x4f727961) // Orya + Osage = Script(0x4f736765) // Osge + Osmanya = Script(0x4f736d61) // Osma + Pahawh_Hmong = Script(0x486d6e67) // Hmng + Palmyrene = Script(0x50616c6d) // Palm + Pau_Cin_Hau = Script(0x50617563) // Pauc + Phags_Pa = Script(0x50686167) // Phag + Phoenician = Script(0x50686e78) // Phnx + Psalter_Pahlavi = Script(0x50686c70) // Phlp + Ranjana = Script(0x52616e6a) // Ranj + Rejang = Script(0x526a6e67) // Rjng + Rongorongo = Script(0x526f726f) // Roro + Runic = Script(0x52756e72) // Runr + Samaritan = Script(0x53616d72) // Samr + Sarati = Script(0x53617261) // Sara + Saurashtra = Script(0x53617572) // Saur + Sharada = Script(0x53687264) // Shrd + Shavian = Script(0x53686177) // Shaw + Shuishu = Script(0x53687569) // Shui + Siddham = Script(0x53696464) // Sidd + SignWriting = Script(0x53676e77) // Sgnw + Sinhala = Script(0x53696e68) // Sinh + Sogdian = Script(0x536f6764) // Sogd + Sora_Sompeng = Script(0x536f7261) // Sora + Soyombo = Script(0x536f796f) // Soyo + Sundanese = Script(0x53756e64) // Sund + Sunuwar = Script(0x53756e75) // Sunu + Syloti_Nagri = Script(0x53796c6f) // Sylo + Symbols = Script(0x5a73796d) // Zsym + Syriac = Script(0x53797263) // Syrc + Tagalog = Script(0x54676c67) // Tglg + Tagbanwa = Script(0x54616762) // Tagb + Tai_Le = Script(0x54616c65) // Tale + Tai_Tham = Script(0x4c616e61) // Lana + Tai_Viet = Script(0x54617674) // Tavt + Takri = Script(0x54616b72) // Takr + Tamil = Script(0x54616d6c) // Taml + Tangsa = Script(0x546e7361) // Tnsa + Tangut = Script(0x54616e67) // Tang + Telugu = Script(0x54656c75) // Telu + Tengwar = Script(0x54656e67) // Teng + Thaana = Script(0x54686161) // Thaa + Thai = Script(0x54686169) // Thai + Tibetan = Script(0x54696274) // Tibt + Tifinagh = Script(0x54666e67) // Tfng + Tirhuta = Script(0x54697268) // Tirh + Toto = Script(0x546f746f) // Toto + Ugaritic = Script(0x55676172) // Ugar + Unknown = Script(0x5a7a7a7a) // Zzzz + Vai = Script(0x56616969) // Vaii + Visible_Speech = Script(0x56697370) // Visp + Vithkuqi = Script(0x56697468) // Vith + Wancho = Script(0x5763686f) // Wcho + Warang_Citi = Script(0x57617261) // Wara + Woleai = Script(0x576f6c65) // Wole + Yezidi = Script(0x59657a69) // Yezi + Yi = Script(0x59696969) // Yiii + Zanabazar_Square = Script(0x5a616e62) // Zanb +) + +// scriptToTag is only used in tests and will be +// removed by the linker +var scriptToTag = map[string]Script{ + "Adlam": 0x41646c6d, + "Afaka": 0x4166616b, + "Ahom": 0x41686f6d, + "Anatolian_Hieroglyphs": 0x486c7577, + "Arabic": 0x41726162, + "Armenian": 0x41726d6e, + "Avestan": 0x41767374, + "Balinese": 0x42616c69, + "Bamum": 0x42616d75, + "Bassa_Vah": 0x42617373, + "Batak": 0x4261746b, + "Bengali": 0x42656e67, + "Bhaiksuki": 0x42686b73, + "Blissymbols": 0x426c6973, + "Book_Pahlavi": 0x50686c76, + "Bopomofo": 0x426f706f, + "Brahmi": 0x42726168, + "Braille": 0x42726169, + "Buginese": 0x42756769, + "Buhid": 0x42756864, + "Canadian_Aboriginal": 0x43616e73, + "Carian": 0x43617269, + "Caucasian_Albanian": 0x41676862, + "Chakma": 0x43616b6d, + "Cham": 0x4368616d, + "Cherokee": 0x43686572, + "Chorasmian": 0x43687273, + "Cirth": 0x43697274, + "Code_for_unwritten_documents": 0x5a787878, + "Common": 0x5a797979, + "Coptic": 0x436f7074, + "Cuneiform": 0x58737578, + "Cypriot": 0x43707274, + "Cypro_Minoan": 0x43706d6e, + "Cyrillic": 0x4379726c, + "Deseret": 0x44737274, + "Devanagari": 0x44657661, + "Dives_Akuru": 0x4469616b, + "Dogra": 0x446f6772, + "Duployan": 0x4475706c, + "Egyptian_Hieroglyphs": 0x45677970, + "Egyptian_demotic": 0x45677964, + "Egyptian_hieratic": 0x45677968, + "Elbasan": 0x456c6261, + "Elymaic": 0x456c796d, + "Ethiopic": 0x45746869, + "Georgian": 0x47656f72, + "Glagolitic": 0x476c6167, + "Gothic": 0x476f7468, + "Grantha": 0x4772616e, + "Greek": 0x4772656b, + "Gujarati": 0x47756a72, + "Gunjala_Gondi": 0x476f6e67, + "Gurmukhi": 0x47757275, + "Han": 0x48616e69, + "Hangul": 0x48616e67, + "Hanifi_Rohingya": 0x526f6867, + "Hanunoo": 0x48616e6f, + "Hatran": 0x48617472, + "Hebrew": 0x48656272, + "Hiragana": 0x48697261, + "Imperial_Aramaic": 0x41726d69, + "Inherited": 0x5a696e68, + "Inscriptional_Pahlavi": 0x50686c69, + "Inscriptional_Parthian": 0x50727469, + "Javanese": 0x4a617661, + "Jurchen": 0x4a757263, + "Kaithi": 0x4b746869, + "Kannada": 0x4b6e6461, + "Katakana": 0x4b616e61, + "Katakana_Or_Hiragana": 0x48726b74, + "Kawi": 0x4b617769, + "Kayah_Li": 0x4b616c69, + "Kharoshthi": 0x4b686172, + "Khitan_Small_Script": 0x4b697473, + "Khitan_large_script": 0x4b69746c, + "Khmer": 0x4b686d72, + "Khojki": 0x4b686f6a, + "Khudawadi": 0x53696e64, + "Kpelle": 0x4b70656c, + "Lao": 0x4c616f6f, + "Latin": 0x4c61746e, + "Leke": 0x4c656b65, + "Lepcha": 0x4c657063, + "Limbu": 0x4c696d62, + "Linear_A": 0x4c696e61, + "Linear_B": 0x4c696e62, + "Lisu": 0x4c697375, + "Loma": 0x4c6f6d61, + "Lycian": 0x4c796369, + "Lydian": 0x4c796469, + "Mahajani": 0x4d61686a, + "Makasar": 0x4d616b61, + "Malayalam": 0x4d6c796d, + "Mandaic": 0x4d616e64, + "Manichaean": 0x4d616e69, + "Marchen": 0x4d617263, + "Masaram_Gondi": 0x476f6e6d, + "Mathematical_notation": 0x5a6d7468, + "Mayan_hieroglyphs": 0x4d617961, + "Medefaidrin": 0x4d656466, + "Meetei_Mayek": 0x4d746569, + "Mende_Kikakui": 0x4d656e64, + "Meroitic_Cursive": 0x4d657263, + "Meroitic_Hieroglyphs": 0x4d65726f, + "Miao": 0x506c7264, + "Modi": 0x4d6f6469, + "Mongolian": 0x4d6f6e67, + "Mro": 0x4d726f6f, + "Multani": 0x4d756c74, + "Myanmar": 0x4d796d72, + "Nabataean": 0x4e626174, + "Nag_Mundari": 0x4e61676d, + "Nandinagari": 0x4e616e64, + "New_Tai_Lue": 0x54616c75, + "Newa": 0x4e657761, + "Nko": 0x4e6b6f6f, + "Nushu": 0x4e736875, + "Nyiakeng_Puachue_Hmong": 0x486d6e70, + "Ogham": 0x4f67616d, + "Ol_Chiki": 0x4f6c636b, + "Old_Hungarian": 0x48756e67, + "Old_Italic": 0x4974616c, + "Old_North_Arabian": 0x4e617262, + "Old_Permic": 0x5065726d, + "Old_Persian": 0x5870656f, + "Old_Sogdian": 0x536f676f, + "Old_South_Arabian": 0x53617262, + "Old_Turkic": 0x4f726b68, + "Old_Uyghur": 0x4f756772, + "Oriya": 0x4f727961, + "Osage": 0x4f736765, + "Osmanya": 0x4f736d61, + "Pahawh_Hmong": 0x486d6e67, + "Palmyrene": 0x50616c6d, + "Pau_Cin_Hau": 0x50617563, + "Phags_Pa": 0x50686167, + "Phoenician": 0x50686e78, + "Psalter_Pahlavi": 0x50686c70, + "Ranjana": 0x52616e6a, + "Rejang": 0x526a6e67, + "Rongorongo": 0x526f726f, + "Runic": 0x52756e72, + "Samaritan": 0x53616d72, + "Sarati": 0x53617261, + "Saurashtra": 0x53617572, + "Sharada": 0x53687264, + "Shavian": 0x53686177, + "Shuishu": 0x53687569, + "Siddham": 0x53696464, + "SignWriting": 0x53676e77, + "Sinhala": 0x53696e68, + "Sogdian": 0x536f6764, + "Sora_Sompeng": 0x536f7261, + "Soyombo": 0x536f796f, + "Sundanese": 0x53756e64, + "Sunuwar": 0x53756e75, + "Syloti_Nagri": 0x53796c6f, + "Symbols": 0x5a73796d, + "Syriac": 0x53797263, + "Tagalog": 0x54676c67, + "Tagbanwa": 0x54616762, + "Tai_Le": 0x54616c65, + "Tai_Tham": 0x4c616e61, + "Tai_Viet": 0x54617674, + "Takri": 0x54616b72, + "Tamil": 0x54616d6c, + "Tangsa": 0x546e7361, + "Tangut": 0x54616e67, + "Telugu": 0x54656c75, + "Tengwar": 0x54656e67, + "Thaana": 0x54686161, + "Thai": 0x54686169, + "Tibetan": 0x54696274, + "Tifinagh": 0x54666e67, + "Tirhuta": 0x54697268, + "Toto": 0x546f746f, + "Ugaritic": 0x55676172, + "Unknown": 0x5a7a7a7a, + "Vai": 0x56616969, + "Visible_Speech": 0x56697370, + "Vithkuqi": 0x56697468, + "Wancho": 0x5763686f, + "Warang_Citi": 0x57617261, + "Woleai": 0x576f6c65, + "Yezidi": 0x59657a69, + "Yi": 0x59696969, + "Zanabazar_Square": 0x5a616e62, +} + +// ScriptRange is an inclusive range of runes +// with constant script. +type ScriptRange struct { + Start, End rune + Script Script +} + +// ScriptRanges is a sorted list of script ranges. +var ScriptRanges = [...]ScriptRange{ + {0x0, 0x40, 0x5a797979}, + {0x41, 0x5a, 0x4c61746e}, + {0x5b, 0x60, 0x5a797979}, + {0x61, 0x7a, 0x4c61746e}, + {0x7b, 0xa9, 0x5a797979}, + {0xaa, 0xaa, 0x4c61746e}, + {0xab, 0xb9, 0x5a797979}, + {0xba, 0xba, 0x4c61746e}, + {0xbb, 0xbf, 0x5a797979}, + {0xc0, 0xd6, 0x4c61746e}, + {0xd7, 0xd7, 0x5a797979}, + {0xd8, 0xf6, 0x4c61746e}, + {0xf7, 0xf7, 0x5a797979}, + {0xf8, 0x2b8, 0x4c61746e}, + {0x2b9, 0x2df, 0x5a797979}, + {0x2e0, 0x2e4, 0x4c61746e}, + {0x2e5, 0x2e9, 0x5a797979}, + {0x2ea, 0x2eb, 0x426f706f}, + {0x2ec, 0x2ff, 0x5a797979}, + {0x300, 0x36f, 0x5a696e68}, + {0x370, 0x373, 0x4772656b}, + {0x374, 0x374, 0x5a797979}, + {0x375, 0x377, 0x4772656b}, + {0x37a, 0x37d, 0x4772656b}, + {0x37e, 0x37e, 0x5a797979}, + {0x37f, 0x37f, 0x4772656b}, + {0x384, 0x384, 0x4772656b}, + {0x385, 0x385, 0x5a797979}, + {0x386, 0x386, 0x4772656b}, + {0x387, 0x387, 0x5a797979}, + {0x388, 0x38a, 0x4772656b}, + {0x38c, 0x38c, 0x4772656b}, + {0x38e, 0x3a1, 0x4772656b}, + {0x3a3, 0x3e1, 0x4772656b}, + {0x3e2, 0x3ef, 0x436f7074}, + {0x3f0, 0x3ff, 0x4772656b}, + {0x400, 0x484, 0x4379726c}, + {0x485, 0x486, 0x5a696e68}, + {0x487, 0x52f, 0x4379726c}, + {0x531, 0x556, 0x41726d6e}, + {0x559, 0x58a, 0x41726d6e}, + {0x58d, 0x58f, 0x41726d6e}, + {0x591, 0x5c7, 0x48656272}, + {0x5d0, 0x5ea, 0x48656272}, + {0x5ef, 0x5f4, 0x48656272}, + {0x600, 0x604, 0x41726162}, + {0x605, 0x605, 0x5a797979}, + {0x606, 0x60b, 0x41726162}, + {0x60c, 0x60c, 0x5a797979}, + {0x60d, 0x61a, 0x41726162}, + {0x61b, 0x61b, 0x5a797979}, + {0x61c, 0x61e, 0x41726162}, + {0x61f, 0x61f, 0x5a797979}, + {0x620, 0x63f, 0x41726162}, + {0x640, 0x640, 0x5a797979}, + {0x641, 0x64a, 0x41726162}, + {0x64b, 0x655, 0x5a696e68}, + {0x656, 0x66f, 0x41726162}, + {0x670, 0x670, 0x5a696e68}, + {0x671, 0x6dc, 0x41726162}, + {0x6dd, 0x6dd, 0x5a797979}, + {0x6de, 0x6ff, 0x41726162}, + {0x700, 0x70d, 0x53797263}, + {0x70f, 0x74a, 0x53797263}, + {0x74d, 0x74f, 0x53797263}, + {0x750, 0x77f, 0x41726162}, + {0x780, 0x7b1, 0x54686161}, + {0x7c0, 0x7fa, 0x4e6b6f6f}, + {0x7fd, 0x7ff, 0x4e6b6f6f}, + {0x800, 0x82d, 0x53616d72}, + {0x830, 0x83e, 0x53616d72}, + {0x840, 0x85b, 0x4d616e64}, + {0x85e, 0x85e, 0x4d616e64}, + {0x860, 0x86a, 0x53797263}, + {0x870, 0x88e, 0x41726162}, + {0x890, 0x891, 0x41726162}, + {0x898, 0x8e1, 0x41726162}, + {0x8e2, 0x8e2, 0x5a797979}, + {0x8e3, 0x8ff, 0x41726162}, + {0x900, 0x950, 0x44657661}, + {0x951, 0x954, 0x5a696e68}, + {0x955, 0x963, 0x44657661}, + {0x964, 0x965, 0x5a797979}, + {0x966, 0x97f, 0x44657661}, + {0x980, 0x983, 0x42656e67}, + {0x985, 0x98c, 0x42656e67}, + {0x98f, 0x990, 0x42656e67}, + {0x993, 0x9a8, 0x42656e67}, + {0x9aa, 0x9b0, 0x42656e67}, + {0x9b2, 0x9b2, 0x42656e67}, + {0x9b6, 0x9b9, 0x42656e67}, + {0x9bc, 0x9c4, 0x42656e67}, + {0x9c7, 0x9c8, 0x42656e67}, + {0x9cb, 0x9ce, 0x42656e67}, + {0x9d7, 0x9d7, 0x42656e67}, + {0x9dc, 0x9dd, 0x42656e67}, + {0x9df, 0x9e3, 0x42656e67}, + {0x9e6, 0x9fe, 0x42656e67}, + {0xa01, 0xa03, 0x47757275}, + {0xa05, 0xa0a, 0x47757275}, + {0xa0f, 0xa10, 0x47757275}, + {0xa13, 0xa28, 0x47757275}, + {0xa2a, 0xa30, 0x47757275}, + {0xa32, 0xa33, 0x47757275}, + {0xa35, 0xa36, 0x47757275}, + {0xa38, 0xa39, 0x47757275}, + {0xa3c, 0xa3c, 0x47757275}, + {0xa3e, 0xa42, 0x47757275}, + {0xa47, 0xa48, 0x47757275}, + {0xa4b, 0xa4d, 0x47757275}, + {0xa51, 0xa51, 0x47757275}, + {0xa59, 0xa5c, 0x47757275}, + {0xa5e, 0xa5e, 0x47757275}, + {0xa66, 0xa76, 0x47757275}, + {0xa81, 0xa83, 0x47756a72}, + {0xa85, 0xa8d, 0x47756a72}, + {0xa8f, 0xa91, 0x47756a72}, + {0xa93, 0xaa8, 0x47756a72}, + {0xaaa, 0xab0, 0x47756a72}, + {0xab2, 0xab3, 0x47756a72}, + {0xab5, 0xab9, 0x47756a72}, + {0xabc, 0xac5, 0x47756a72}, + {0xac7, 0xac9, 0x47756a72}, + {0xacb, 0xacd, 0x47756a72}, + {0xad0, 0xad0, 0x47756a72}, + {0xae0, 0xae3, 0x47756a72}, + {0xae6, 0xaf1, 0x47756a72}, + {0xaf9, 0xaff, 0x47756a72}, + {0xb01, 0xb03, 0x4f727961}, + {0xb05, 0xb0c, 0x4f727961}, + {0xb0f, 0xb10, 0x4f727961}, + {0xb13, 0xb28, 0x4f727961}, + {0xb2a, 0xb30, 0x4f727961}, + {0xb32, 0xb33, 0x4f727961}, + {0xb35, 0xb39, 0x4f727961}, + {0xb3c, 0xb44, 0x4f727961}, + {0xb47, 0xb48, 0x4f727961}, + {0xb4b, 0xb4d, 0x4f727961}, + {0xb55, 0xb57, 0x4f727961}, + {0xb5c, 0xb5d, 0x4f727961}, + {0xb5f, 0xb63, 0x4f727961}, + {0xb66, 0xb77, 0x4f727961}, + {0xb82, 0xb83, 0x54616d6c}, + {0xb85, 0xb8a, 0x54616d6c}, + {0xb8e, 0xb90, 0x54616d6c}, + {0xb92, 0xb95, 0x54616d6c}, + {0xb99, 0xb9a, 0x54616d6c}, + {0xb9c, 0xb9c, 0x54616d6c}, + {0xb9e, 0xb9f, 0x54616d6c}, + {0xba3, 0xba4, 0x54616d6c}, + {0xba8, 0xbaa, 0x54616d6c}, + {0xbae, 0xbb9, 0x54616d6c}, + {0xbbe, 0xbc2, 0x54616d6c}, + {0xbc6, 0xbc8, 0x54616d6c}, + {0xbca, 0xbcd, 0x54616d6c}, + {0xbd0, 0xbd0, 0x54616d6c}, + {0xbd7, 0xbd7, 0x54616d6c}, + {0xbe6, 0xbfa, 0x54616d6c}, + {0xc00, 0xc0c, 0x54656c75}, + {0xc0e, 0xc10, 0x54656c75}, + {0xc12, 0xc28, 0x54656c75}, + {0xc2a, 0xc39, 0x54656c75}, + {0xc3c, 0xc44, 0x54656c75}, + {0xc46, 0xc48, 0x54656c75}, + {0xc4a, 0xc4d, 0x54656c75}, + {0xc55, 0xc56, 0x54656c75}, + {0xc58, 0xc5a, 0x54656c75}, + {0xc5d, 0xc5d, 0x54656c75}, + {0xc60, 0xc63, 0x54656c75}, + {0xc66, 0xc6f, 0x54656c75}, + {0xc77, 0xc7f, 0x54656c75}, + {0xc80, 0xc8c, 0x4b6e6461}, + {0xc8e, 0xc90, 0x4b6e6461}, + {0xc92, 0xca8, 0x4b6e6461}, + {0xcaa, 0xcb3, 0x4b6e6461}, + {0xcb5, 0xcb9, 0x4b6e6461}, + {0xcbc, 0xcc4, 0x4b6e6461}, + {0xcc6, 0xcc8, 0x4b6e6461}, + {0xcca, 0xccd, 0x4b6e6461}, + {0xcd5, 0xcd6, 0x4b6e6461}, + {0xcdd, 0xcde, 0x4b6e6461}, + {0xce0, 0xce3, 0x4b6e6461}, + {0xce6, 0xcef, 0x4b6e6461}, + {0xcf1, 0xcf3, 0x4b6e6461}, + {0xd00, 0xd0c, 0x4d6c796d}, + {0xd0e, 0xd10, 0x4d6c796d}, + {0xd12, 0xd44, 0x4d6c796d}, + {0xd46, 0xd48, 0x4d6c796d}, + {0xd4a, 0xd4f, 0x4d6c796d}, + {0xd54, 0xd63, 0x4d6c796d}, + {0xd66, 0xd7f, 0x4d6c796d}, + {0xd81, 0xd83, 0x53696e68}, + {0xd85, 0xd96, 0x53696e68}, + {0xd9a, 0xdb1, 0x53696e68}, + {0xdb3, 0xdbb, 0x53696e68}, + {0xdbd, 0xdbd, 0x53696e68}, + {0xdc0, 0xdc6, 0x53696e68}, + {0xdca, 0xdca, 0x53696e68}, + {0xdcf, 0xdd4, 0x53696e68}, + {0xdd6, 0xdd6, 0x53696e68}, + {0xdd8, 0xddf, 0x53696e68}, + {0xde6, 0xdef, 0x53696e68}, + {0xdf2, 0xdf4, 0x53696e68}, + {0xe01, 0xe3a, 0x54686169}, + {0xe3f, 0xe3f, 0x5a797979}, + {0xe40, 0xe5b, 0x54686169}, + {0xe81, 0xe82, 0x4c616f6f}, + {0xe84, 0xe84, 0x4c616f6f}, + {0xe86, 0xe8a, 0x4c616f6f}, + {0xe8c, 0xea3, 0x4c616f6f}, + {0xea5, 0xea5, 0x4c616f6f}, + {0xea7, 0xebd, 0x4c616f6f}, + {0xec0, 0xec4, 0x4c616f6f}, + {0xec6, 0xec6, 0x4c616f6f}, + {0xec8, 0xece, 0x4c616f6f}, + {0xed0, 0xed9, 0x4c616f6f}, + {0xedc, 0xedf, 0x4c616f6f}, + {0xf00, 0xf47, 0x54696274}, + {0xf49, 0xf6c, 0x54696274}, + {0xf71, 0xf97, 0x54696274}, + {0xf99, 0xfbc, 0x54696274}, + {0xfbe, 0xfcc, 0x54696274}, + {0xfce, 0xfd4, 0x54696274}, + {0xfd5, 0xfd8, 0x5a797979}, + {0xfd9, 0xfda, 0x54696274}, + {0x1000, 0x109f, 0x4d796d72}, + {0x10a0, 0x10c5, 0x47656f72}, + {0x10c7, 0x10c7, 0x47656f72}, + {0x10cd, 0x10cd, 0x47656f72}, + {0x10d0, 0x10fa, 0x47656f72}, + {0x10fb, 0x10fb, 0x5a797979}, + {0x10fc, 0x10ff, 0x47656f72}, + {0x1100, 0x11ff, 0x48616e67}, + {0x1200, 0x1248, 0x45746869}, + {0x124a, 0x124d, 0x45746869}, + {0x1250, 0x1256, 0x45746869}, + {0x1258, 0x1258, 0x45746869}, + {0x125a, 0x125d, 0x45746869}, + {0x1260, 0x1288, 0x45746869}, + {0x128a, 0x128d, 0x45746869}, + {0x1290, 0x12b0, 0x45746869}, + {0x12b2, 0x12b5, 0x45746869}, + {0x12b8, 0x12be, 0x45746869}, + {0x12c0, 0x12c0, 0x45746869}, + {0x12c2, 0x12c5, 0x45746869}, + {0x12c8, 0x12d6, 0x45746869}, + {0x12d8, 0x1310, 0x45746869}, + {0x1312, 0x1315, 0x45746869}, + {0x1318, 0x135a, 0x45746869}, + {0x135d, 0x137c, 0x45746869}, + {0x1380, 0x1399, 0x45746869}, + {0x13a0, 0x13f5, 0x43686572}, + {0x13f8, 0x13fd, 0x43686572}, + {0x1400, 0x167f, 0x43616e73}, + {0x1680, 0x169c, 0x4f67616d}, + {0x16a0, 0x16ea, 0x52756e72}, + {0x16eb, 0x16ed, 0x5a797979}, + {0x16ee, 0x16f8, 0x52756e72}, + {0x1700, 0x1715, 0x54676c67}, + {0x171f, 0x171f, 0x54676c67}, + {0x1720, 0x1734, 0x48616e6f}, + {0x1735, 0x1736, 0x5a797979}, + {0x1740, 0x1753, 0x42756864}, + {0x1760, 0x176c, 0x54616762}, + {0x176e, 0x1770, 0x54616762}, + {0x1772, 0x1773, 0x54616762}, + {0x1780, 0x17dd, 0x4b686d72}, + {0x17e0, 0x17e9, 0x4b686d72}, + {0x17f0, 0x17f9, 0x4b686d72}, + {0x1800, 0x1801, 0x4d6f6e67}, + {0x1802, 0x1803, 0x5a797979}, + {0x1804, 0x1804, 0x4d6f6e67}, + {0x1805, 0x1805, 0x5a797979}, + {0x1806, 0x1819, 0x4d6f6e67}, + {0x1820, 0x1878, 0x4d6f6e67}, + {0x1880, 0x18aa, 0x4d6f6e67}, + {0x18b0, 0x18f5, 0x43616e73}, + {0x1900, 0x191e, 0x4c696d62}, + {0x1920, 0x192b, 0x4c696d62}, + {0x1930, 0x193b, 0x4c696d62}, + {0x1940, 0x1940, 0x4c696d62}, + {0x1944, 0x194f, 0x4c696d62}, + {0x1950, 0x196d, 0x54616c65}, + {0x1970, 0x1974, 0x54616c65}, + {0x1980, 0x19ab, 0x54616c75}, + {0x19b0, 0x19c9, 0x54616c75}, + {0x19d0, 0x19da, 0x54616c75}, + {0x19de, 0x19df, 0x54616c75}, + {0x19e0, 0x19ff, 0x4b686d72}, + {0x1a00, 0x1a1b, 0x42756769}, + {0x1a1e, 0x1a1f, 0x42756769}, + {0x1a20, 0x1a5e, 0x4c616e61}, + {0x1a60, 0x1a7c, 0x4c616e61}, + {0x1a7f, 0x1a89, 0x4c616e61}, + {0x1a90, 0x1a99, 0x4c616e61}, + {0x1aa0, 0x1aad, 0x4c616e61}, + {0x1ab0, 0x1ace, 0x5a696e68}, + {0x1b00, 0x1b4c, 0x42616c69}, + {0x1b50, 0x1b7e, 0x42616c69}, + {0x1b80, 0x1bbf, 0x53756e64}, + {0x1bc0, 0x1bf3, 0x4261746b}, + {0x1bfc, 0x1bff, 0x4261746b}, + {0x1c00, 0x1c37, 0x4c657063}, + {0x1c3b, 0x1c49, 0x4c657063}, + {0x1c4d, 0x1c4f, 0x4c657063}, + {0x1c50, 0x1c7f, 0x4f6c636b}, + {0x1c80, 0x1c88, 0x4379726c}, + {0x1c90, 0x1cba, 0x47656f72}, + {0x1cbd, 0x1cbf, 0x47656f72}, + {0x1cc0, 0x1cc7, 0x53756e64}, + {0x1cd0, 0x1cd2, 0x5a696e68}, + {0x1cd3, 0x1cd3, 0x5a797979}, + {0x1cd4, 0x1ce0, 0x5a696e68}, + {0x1ce1, 0x1ce1, 0x5a797979}, + {0x1ce2, 0x1ce8, 0x5a696e68}, + {0x1ce9, 0x1cec, 0x5a797979}, + {0x1ced, 0x1ced, 0x5a696e68}, + {0x1cee, 0x1cf3, 0x5a797979}, + {0x1cf4, 0x1cf4, 0x5a696e68}, + {0x1cf5, 0x1cf7, 0x5a797979}, + {0x1cf8, 0x1cf9, 0x5a696e68}, + {0x1cfa, 0x1cfa, 0x5a797979}, + {0x1d00, 0x1d25, 0x4c61746e}, + {0x1d26, 0x1d2a, 0x4772656b}, + {0x1d2b, 0x1d2b, 0x4379726c}, + {0x1d2c, 0x1d5c, 0x4c61746e}, + {0x1d5d, 0x1d61, 0x4772656b}, + {0x1d62, 0x1d65, 0x4c61746e}, + {0x1d66, 0x1d6a, 0x4772656b}, + {0x1d6b, 0x1d77, 0x4c61746e}, + {0x1d78, 0x1d78, 0x4379726c}, + {0x1d79, 0x1dbe, 0x4c61746e}, + {0x1dbf, 0x1dbf, 0x4772656b}, + {0x1dc0, 0x1dff, 0x5a696e68}, + {0x1e00, 0x1eff, 0x4c61746e}, + {0x1f00, 0x1f15, 0x4772656b}, + {0x1f18, 0x1f1d, 0x4772656b}, + {0x1f20, 0x1f45, 0x4772656b}, + {0x1f48, 0x1f4d, 0x4772656b}, + {0x1f50, 0x1f57, 0x4772656b}, + {0x1f59, 0x1f59, 0x4772656b}, + {0x1f5b, 0x1f5b, 0x4772656b}, + {0x1f5d, 0x1f5d, 0x4772656b}, + {0x1f5f, 0x1f7d, 0x4772656b}, + {0x1f80, 0x1fb4, 0x4772656b}, + {0x1fb6, 0x1fc4, 0x4772656b}, + {0x1fc6, 0x1fd3, 0x4772656b}, + {0x1fd6, 0x1fdb, 0x4772656b}, + {0x1fdd, 0x1fef, 0x4772656b}, + {0x1ff2, 0x1ff4, 0x4772656b}, + {0x1ff6, 0x1ffe, 0x4772656b}, + {0x2000, 0x200b, 0x5a797979}, + {0x200c, 0x200d, 0x5a696e68}, + {0x200e, 0x2064, 0x5a797979}, + {0x2066, 0x2070, 0x5a797979}, + {0x2071, 0x2071, 0x4c61746e}, + {0x2074, 0x207e, 0x5a797979}, + {0x207f, 0x207f, 0x4c61746e}, + {0x2080, 0x208e, 0x5a797979}, + {0x2090, 0x209c, 0x4c61746e}, + {0x20a0, 0x20c0, 0x5a797979}, + {0x20d0, 0x20f0, 0x5a696e68}, + {0x2100, 0x2125, 0x5a797979}, + {0x2126, 0x2126, 0x4772656b}, + {0x2127, 0x2129, 0x5a797979}, + {0x212a, 0x212b, 0x4c61746e}, + {0x212c, 0x2131, 0x5a797979}, + {0x2132, 0x2132, 0x4c61746e}, + {0x2133, 0x214d, 0x5a797979}, + {0x214e, 0x214e, 0x4c61746e}, + {0x214f, 0x215f, 0x5a797979}, + {0x2160, 0x2188, 0x4c61746e}, + {0x2189, 0x218b, 0x5a797979}, + {0x2190, 0x2426, 0x5a797979}, + {0x2440, 0x244a, 0x5a797979}, + {0x2460, 0x27ff, 0x5a797979}, + {0x2800, 0x28ff, 0x42726169}, + {0x2900, 0x2b73, 0x5a797979}, + {0x2b76, 0x2b95, 0x5a797979}, + {0x2b97, 0x2bff, 0x5a797979}, + {0x2c00, 0x2c5f, 0x476c6167}, + {0x2c60, 0x2c7f, 0x4c61746e}, + {0x2c80, 0x2cf3, 0x436f7074}, + {0x2cf9, 0x2cff, 0x436f7074}, + {0x2d00, 0x2d25, 0x47656f72}, + {0x2d27, 0x2d27, 0x47656f72}, + {0x2d2d, 0x2d2d, 0x47656f72}, + {0x2d30, 0x2d67, 0x54666e67}, + {0x2d6f, 0x2d70, 0x54666e67}, + {0x2d7f, 0x2d7f, 0x54666e67}, + {0x2d80, 0x2d96, 0x45746869}, + {0x2da0, 0x2da6, 0x45746869}, + {0x2da8, 0x2dae, 0x45746869}, + {0x2db0, 0x2db6, 0x45746869}, + {0x2db8, 0x2dbe, 0x45746869}, + {0x2dc0, 0x2dc6, 0x45746869}, + {0x2dc8, 0x2dce, 0x45746869}, + {0x2dd0, 0x2dd6, 0x45746869}, + {0x2dd8, 0x2dde, 0x45746869}, + {0x2de0, 0x2dff, 0x4379726c}, + {0x2e00, 0x2e5d, 0x5a797979}, + {0x2e80, 0x2e99, 0x48616e69}, + {0x2e9b, 0x2ef3, 0x48616e69}, + {0x2f00, 0x2fd5, 0x48616e69}, + {0x2ff0, 0x2ffb, 0x5a797979}, + {0x3000, 0x3004, 0x5a797979}, + {0x3005, 0x3005, 0x48616e69}, + {0x3006, 0x3006, 0x5a797979}, + {0x3007, 0x3007, 0x48616e69}, + {0x3008, 0x3020, 0x5a797979}, + {0x3021, 0x3029, 0x48616e69}, + {0x302a, 0x302d, 0x5a696e68}, + {0x302e, 0x302f, 0x48616e67}, + {0x3030, 0x3037, 0x5a797979}, + {0x3038, 0x303b, 0x48616e69}, + {0x303c, 0x303f, 0x5a797979}, + {0x3041, 0x3096, 0x48697261}, + {0x3099, 0x309a, 0x5a696e68}, + {0x309b, 0x309c, 0x5a797979}, + {0x309d, 0x309f, 0x48697261}, + {0x30a0, 0x30a0, 0x5a797979}, + {0x30a1, 0x30fa, 0x4b616e61}, + {0x30fb, 0x30fc, 0x5a797979}, + {0x30fd, 0x30ff, 0x4b616e61}, + {0x3105, 0x312f, 0x426f706f}, + {0x3131, 0x318e, 0x48616e67}, + {0x3190, 0x319f, 0x5a797979}, + {0x31a0, 0x31bf, 0x426f706f}, + {0x31c0, 0x31e3, 0x5a797979}, + {0x31f0, 0x31ff, 0x4b616e61}, + {0x3200, 0x321e, 0x48616e67}, + {0x3220, 0x325f, 0x5a797979}, + {0x3260, 0x327e, 0x48616e67}, + {0x327f, 0x32cf, 0x5a797979}, + {0x32d0, 0x32fe, 0x4b616e61}, + {0x32ff, 0x32ff, 0x5a797979}, + {0x3300, 0x3357, 0x4b616e61}, + {0x3358, 0x33ff, 0x5a797979}, + {0x3400, 0x4dbf, 0x48616e69}, + {0x4dc0, 0x4dff, 0x5a797979}, + {0x4e00, 0x9fff, 0x48616e69}, + {0xa000, 0xa48c, 0x59696969}, + {0xa490, 0xa4c6, 0x59696969}, + {0xa4d0, 0xa4ff, 0x4c697375}, + {0xa500, 0xa62b, 0x56616969}, + {0xa640, 0xa69f, 0x4379726c}, + {0xa6a0, 0xa6f7, 0x42616d75}, + {0xa700, 0xa721, 0x5a797979}, + {0xa722, 0xa787, 0x4c61746e}, + {0xa788, 0xa78a, 0x5a797979}, + {0xa78b, 0xa7ca, 0x4c61746e}, + {0xa7d0, 0xa7d1, 0x4c61746e}, + {0xa7d3, 0xa7d3, 0x4c61746e}, + {0xa7d5, 0xa7d9, 0x4c61746e}, + {0xa7f2, 0xa7ff, 0x4c61746e}, + {0xa800, 0xa82c, 0x53796c6f}, + {0xa830, 0xa839, 0x5a797979}, + {0xa840, 0xa877, 0x50686167}, + {0xa880, 0xa8c5, 0x53617572}, + {0xa8ce, 0xa8d9, 0x53617572}, + {0xa8e0, 0xa8ff, 0x44657661}, + {0xa900, 0xa92d, 0x4b616c69}, + {0xa92e, 0xa92e, 0x5a797979}, + {0xa92f, 0xa92f, 0x4b616c69}, + {0xa930, 0xa953, 0x526a6e67}, + {0xa95f, 0xa95f, 0x526a6e67}, + {0xa960, 0xa97c, 0x48616e67}, + {0xa980, 0xa9cd, 0x4a617661}, + {0xa9cf, 0xa9cf, 0x5a797979}, + {0xa9d0, 0xa9d9, 0x4a617661}, + {0xa9de, 0xa9df, 0x4a617661}, + {0xa9e0, 0xa9fe, 0x4d796d72}, + {0xaa00, 0xaa36, 0x4368616d}, + {0xaa40, 0xaa4d, 0x4368616d}, + {0xaa50, 0xaa59, 0x4368616d}, + {0xaa5c, 0xaa5f, 0x4368616d}, + {0xaa60, 0xaa7f, 0x4d796d72}, + {0xaa80, 0xaac2, 0x54617674}, + {0xaadb, 0xaadf, 0x54617674}, + {0xaae0, 0xaaf6, 0x4d746569}, + {0xab01, 0xab06, 0x45746869}, + {0xab09, 0xab0e, 0x45746869}, + {0xab11, 0xab16, 0x45746869}, + {0xab20, 0xab26, 0x45746869}, + {0xab28, 0xab2e, 0x45746869}, + {0xab30, 0xab5a, 0x4c61746e}, + {0xab5b, 0xab5b, 0x5a797979}, + {0xab5c, 0xab64, 0x4c61746e}, + {0xab65, 0xab65, 0x4772656b}, + {0xab66, 0xab69, 0x4c61746e}, + {0xab6a, 0xab6b, 0x5a797979}, + {0xab70, 0xabbf, 0x43686572}, + {0xabc0, 0xabed, 0x4d746569}, + {0xabf0, 0xabf9, 0x4d746569}, + {0xac00, 0xd7a3, 0x48616e67}, + {0xd7b0, 0xd7c6, 0x48616e67}, + {0xd7cb, 0xd7fb, 0x48616e67}, + {0xf900, 0xfa6d, 0x48616e69}, + {0xfa70, 0xfad9, 0x48616e69}, + {0xfb00, 0xfb06, 0x4c61746e}, + {0xfb13, 0xfb17, 0x41726d6e}, + {0xfb1d, 0xfb36, 0x48656272}, + {0xfb38, 0xfb3c, 0x48656272}, + {0xfb3e, 0xfb3e, 0x48656272}, + {0xfb40, 0xfb41, 0x48656272}, + {0xfb43, 0xfb44, 0x48656272}, + {0xfb46, 0xfb4f, 0x48656272}, + {0xfb50, 0xfbc2, 0x41726162}, + {0xfbd3, 0xfd3d, 0x41726162}, + {0xfd3e, 0xfd3f, 0x5a797979}, + {0xfd40, 0xfd8f, 0x41726162}, + {0xfd92, 0xfdc7, 0x41726162}, + {0xfdcf, 0xfdcf, 0x41726162}, + {0xfdf0, 0xfdff, 0x41726162}, + {0xfe00, 0xfe0f, 0x5a696e68}, + {0xfe10, 0xfe19, 0x5a797979}, + {0xfe20, 0xfe2d, 0x5a696e68}, + {0xfe2e, 0xfe2f, 0x4379726c}, + {0xfe30, 0xfe52, 0x5a797979}, + {0xfe54, 0xfe66, 0x5a797979}, + {0xfe68, 0xfe6b, 0x5a797979}, + {0xfe70, 0xfe74, 0x41726162}, + {0xfe76, 0xfefc, 0x41726162}, + {0xfeff, 0xfeff, 0x5a797979}, + {0xff01, 0xff20, 0x5a797979}, + {0xff21, 0xff3a, 0x4c61746e}, + {0xff3b, 0xff40, 0x5a797979}, + {0xff41, 0xff5a, 0x4c61746e}, + {0xff5b, 0xff65, 0x5a797979}, + {0xff66, 0xff6f, 0x4b616e61}, + {0xff70, 0xff70, 0x5a797979}, + {0xff71, 0xff9d, 0x4b616e61}, + {0xff9e, 0xff9f, 0x5a797979}, + {0xffa0, 0xffbe, 0x48616e67}, + {0xffc2, 0xffc7, 0x48616e67}, + {0xffca, 0xffcf, 0x48616e67}, + {0xffd2, 0xffd7, 0x48616e67}, + {0xffda, 0xffdc, 0x48616e67}, + {0xffe0, 0xffe6, 0x5a797979}, + {0xffe8, 0xffee, 0x5a797979}, + {0xfff9, 0xfffd, 0x5a797979}, + {0x10000, 0x1000b, 0x4c696e62}, + {0x1000d, 0x10026, 0x4c696e62}, + {0x10028, 0x1003a, 0x4c696e62}, + {0x1003c, 0x1003d, 0x4c696e62}, + {0x1003f, 0x1004d, 0x4c696e62}, + {0x10050, 0x1005d, 0x4c696e62}, + {0x10080, 0x100fa, 0x4c696e62}, + {0x10100, 0x10102, 0x5a797979}, + {0x10107, 0x10133, 0x5a797979}, + {0x10137, 0x1013f, 0x5a797979}, + {0x10140, 0x1018e, 0x4772656b}, + {0x10190, 0x1019c, 0x5a797979}, + {0x101a0, 0x101a0, 0x4772656b}, + {0x101d0, 0x101fc, 0x5a797979}, + {0x101fd, 0x101fd, 0x5a696e68}, + {0x10280, 0x1029c, 0x4c796369}, + {0x102a0, 0x102d0, 0x43617269}, + {0x102e0, 0x102e0, 0x5a696e68}, + {0x102e1, 0x102fb, 0x5a797979}, + {0x10300, 0x10323, 0x4974616c}, + {0x1032d, 0x1032f, 0x4974616c}, + {0x10330, 0x1034a, 0x476f7468}, + {0x10350, 0x1037a, 0x5065726d}, + {0x10380, 0x1039d, 0x55676172}, + {0x1039f, 0x1039f, 0x55676172}, + {0x103a0, 0x103c3, 0x5870656f}, + {0x103c8, 0x103d5, 0x5870656f}, + {0x10400, 0x1044f, 0x44737274}, + {0x10450, 0x1047f, 0x53686177}, + {0x10480, 0x1049d, 0x4f736d61}, + {0x104a0, 0x104a9, 0x4f736d61}, + {0x104b0, 0x104d3, 0x4f736765}, + {0x104d8, 0x104fb, 0x4f736765}, + {0x10500, 0x10527, 0x456c6261}, + {0x10530, 0x10563, 0x41676862}, + {0x1056f, 0x1056f, 0x41676862}, + {0x10570, 0x1057a, 0x56697468}, + {0x1057c, 0x1058a, 0x56697468}, + {0x1058c, 0x10592, 0x56697468}, + {0x10594, 0x10595, 0x56697468}, + {0x10597, 0x105a1, 0x56697468}, + {0x105a3, 0x105b1, 0x56697468}, + {0x105b3, 0x105b9, 0x56697468}, + {0x105bb, 0x105bc, 0x56697468}, + {0x10600, 0x10736, 0x4c696e61}, + {0x10740, 0x10755, 0x4c696e61}, + {0x10760, 0x10767, 0x4c696e61}, + {0x10780, 0x10785, 0x4c61746e}, + {0x10787, 0x107b0, 0x4c61746e}, + {0x107b2, 0x107ba, 0x4c61746e}, + {0x10800, 0x10805, 0x43707274}, + {0x10808, 0x10808, 0x43707274}, + {0x1080a, 0x10835, 0x43707274}, + {0x10837, 0x10838, 0x43707274}, + {0x1083c, 0x1083c, 0x43707274}, + {0x1083f, 0x1083f, 0x43707274}, + {0x10840, 0x10855, 0x41726d69}, + {0x10857, 0x1085f, 0x41726d69}, + {0x10860, 0x1087f, 0x50616c6d}, + {0x10880, 0x1089e, 0x4e626174}, + {0x108a7, 0x108af, 0x4e626174}, + {0x108e0, 0x108f2, 0x48617472}, + {0x108f4, 0x108f5, 0x48617472}, + {0x108fb, 0x108ff, 0x48617472}, + {0x10900, 0x1091b, 0x50686e78}, + {0x1091f, 0x1091f, 0x50686e78}, + {0x10920, 0x10939, 0x4c796469}, + {0x1093f, 0x1093f, 0x4c796469}, + {0x10980, 0x1099f, 0x4d65726f}, + {0x109a0, 0x109b7, 0x4d657263}, + {0x109bc, 0x109cf, 0x4d657263}, + {0x109d2, 0x109ff, 0x4d657263}, + {0x10a00, 0x10a03, 0x4b686172}, + {0x10a05, 0x10a06, 0x4b686172}, + {0x10a0c, 0x10a13, 0x4b686172}, + {0x10a15, 0x10a17, 0x4b686172}, + {0x10a19, 0x10a35, 0x4b686172}, + {0x10a38, 0x10a3a, 0x4b686172}, + {0x10a3f, 0x10a48, 0x4b686172}, + {0x10a50, 0x10a58, 0x4b686172}, + {0x10a60, 0x10a7f, 0x53617262}, + {0x10a80, 0x10a9f, 0x4e617262}, + {0x10ac0, 0x10ae6, 0x4d616e69}, + {0x10aeb, 0x10af6, 0x4d616e69}, + {0x10b00, 0x10b35, 0x41767374}, + {0x10b39, 0x10b3f, 0x41767374}, + {0x10b40, 0x10b55, 0x50727469}, + {0x10b58, 0x10b5f, 0x50727469}, + {0x10b60, 0x10b72, 0x50686c69}, + {0x10b78, 0x10b7f, 0x50686c69}, + {0x10b80, 0x10b91, 0x50686c70}, + {0x10b99, 0x10b9c, 0x50686c70}, + {0x10ba9, 0x10baf, 0x50686c70}, + {0x10c00, 0x10c48, 0x4f726b68}, + {0x10c80, 0x10cb2, 0x48756e67}, + {0x10cc0, 0x10cf2, 0x48756e67}, + {0x10cfa, 0x10cff, 0x48756e67}, + {0x10d00, 0x10d27, 0x526f6867}, + {0x10d30, 0x10d39, 0x526f6867}, + {0x10e60, 0x10e7e, 0x41726162}, + {0x10e80, 0x10ea9, 0x59657a69}, + {0x10eab, 0x10ead, 0x59657a69}, + {0x10eb0, 0x10eb1, 0x59657a69}, + {0x10efd, 0x10eff, 0x41726162}, + {0x10f00, 0x10f27, 0x536f676f}, + {0x10f30, 0x10f59, 0x536f6764}, + {0x10f70, 0x10f89, 0x4f756772}, + {0x10fb0, 0x10fcb, 0x43687273}, + {0x10fe0, 0x10ff6, 0x456c796d}, + {0x11000, 0x1104d, 0x42726168}, + {0x11052, 0x11075, 0x42726168}, + {0x1107f, 0x1107f, 0x42726168}, + {0x11080, 0x110c2, 0x4b746869}, + {0x110cd, 0x110cd, 0x4b746869}, + {0x110d0, 0x110e8, 0x536f7261}, + {0x110f0, 0x110f9, 0x536f7261}, + {0x11100, 0x11134, 0x43616b6d}, + {0x11136, 0x11147, 0x43616b6d}, + {0x11150, 0x11176, 0x4d61686a}, + {0x11180, 0x111df, 0x53687264}, + {0x111e1, 0x111f4, 0x53696e68}, + {0x11200, 0x11211, 0x4b686f6a}, + {0x11213, 0x11241, 0x4b686f6a}, + {0x11280, 0x11286, 0x4d756c74}, + {0x11288, 0x11288, 0x4d756c74}, + {0x1128a, 0x1128d, 0x4d756c74}, + {0x1128f, 0x1129d, 0x4d756c74}, + {0x1129f, 0x112a9, 0x4d756c74}, + {0x112b0, 0x112ea, 0x53696e64}, + {0x112f0, 0x112f9, 0x53696e64}, + {0x11300, 0x11303, 0x4772616e}, + {0x11305, 0x1130c, 0x4772616e}, + {0x1130f, 0x11310, 0x4772616e}, + {0x11313, 0x11328, 0x4772616e}, + {0x1132a, 0x11330, 0x4772616e}, + {0x11332, 0x11333, 0x4772616e}, + {0x11335, 0x11339, 0x4772616e}, + {0x1133b, 0x1133b, 0x5a696e68}, + {0x1133c, 0x11344, 0x4772616e}, + {0x11347, 0x11348, 0x4772616e}, + {0x1134b, 0x1134d, 0x4772616e}, + {0x11350, 0x11350, 0x4772616e}, + {0x11357, 0x11357, 0x4772616e}, + {0x1135d, 0x11363, 0x4772616e}, + {0x11366, 0x1136c, 0x4772616e}, + {0x11370, 0x11374, 0x4772616e}, + {0x11400, 0x1145b, 0x4e657761}, + {0x1145d, 0x11461, 0x4e657761}, + {0x11480, 0x114c7, 0x54697268}, + {0x114d0, 0x114d9, 0x54697268}, + {0x11580, 0x115b5, 0x53696464}, + {0x115b8, 0x115dd, 0x53696464}, + {0x11600, 0x11644, 0x4d6f6469}, + {0x11650, 0x11659, 0x4d6f6469}, + {0x11660, 0x1166c, 0x4d6f6e67}, + {0x11680, 0x116b9, 0x54616b72}, + {0x116c0, 0x116c9, 0x54616b72}, + {0x11700, 0x1171a, 0x41686f6d}, + {0x1171d, 0x1172b, 0x41686f6d}, + {0x11730, 0x11746, 0x41686f6d}, + {0x11800, 0x1183b, 0x446f6772}, + {0x118a0, 0x118f2, 0x57617261}, + {0x118ff, 0x118ff, 0x57617261}, + {0x11900, 0x11906, 0x4469616b}, + {0x11909, 0x11909, 0x4469616b}, + {0x1190c, 0x11913, 0x4469616b}, + {0x11915, 0x11916, 0x4469616b}, + {0x11918, 0x11935, 0x4469616b}, + {0x11937, 0x11938, 0x4469616b}, + {0x1193b, 0x11946, 0x4469616b}, + {0x11950, 0x11959, 0x4469616b}, + {0x119a0, 0x119a7, 0x4e616e64}, + {0x119aa, 0x119d7, 0x4e616e64}, + {0x119da, 0x119e4, 0x4e616e64}, + {0x11a00, 0x11a47, 0x5a616e62}, + {0x11a50, 0x11aa2, 0x536f796f}, + {0x11ab0, 0x11abf, 0x43616e73}, + {0x11ac0, 0x11af8, 0x50617563}, + {0x11b00, 0x11b09, 0x44657661}, + {0x11c00, 0x11c08, 0x42686b73}, + {0x11c0a, 0x11c36, 0x42686b73}, + {0x11c38, 0x11c45, 0x42686b73}, + {0x11c50, 0x11c6c, 0x42686b73}, + {0x11c70, 0x11c8f, 0x4d617263}, + {0x11c92, 0x11ca7, 0x4d617263}, + {0x11ca9, 0x11cb6, 0x4d617263}, + {0x11d00, 0x11d06, 0x476f6e6d}, + {0x11d08, 0x11d09, 0x476f6e6d}, + {0x11d0b, 0x11d36, 0x476f6e6d}, + {0x11d3a, 0x11d3a, 0x476f6e6d}, + {0x11d3c, 0x11d3d, 0x476f6e6d}, + {0x11d3f, 0x11d47, 0x476f6e6d}, + {0x11d50, 0x11d59, 0x476f6e6d}, + {0x11d60, 0x11d65, 0x476f6e67}, + {0x11d67, 0x11d68, 0x476f6e67}, + {0x11d6a, 0x11d8e, 0x476f6e67}, + {0x11d90, 0x11d91, 0x476f6e67}, + {0x11d93, 0x11d98, 0x476f6e67}, + {0x11da0, 0x11da9, 0x476f6e67}, + {0x11ee0, 0x11ef8, 0x4d616b61}, + {0x11f00, 0x11f10, 0x4b617769}, + {0x11f12, 0x11f3a, 0x4b617769}, + {0x11f3e, 0x11f59, 0x4b617769}, + {0x11fb0, 0x11fb0, 0x4c697375}, + {0x11fc0, 0x11ff1, 0x54616d6c}, + {0x11fff, 0x11fff, 0x54616d6c}, + {0x12000, 0x12399, 0x58737578}, + {0x12400, 0x1246e, 0x58737578}, + {0x12470, 0x12474, 0x58737578}, + {0x12480, 0x12543, 0x58737578}, + {0x12f90, 0x12ff2, 0x43706d6e}, + {0x13000, 0x13455, 0x45677970}, + {0x14400, 0x14646, 0x486c7577}, + {0x16800, 0x16a38, 0x42616d75}, + {0x16a40, 0x16a5e, 0x4d726f6f}, + {0x16a60, 0x16a69, 0x4d726f6f}, + {0x16a6e, 0x16a6f, 0x4d726f6f}, + {0x16a70, 0x16abe, 0x546e7361}, + {0x16ac0, 0x16ac9, 0x546e7361}, + {0x16ad0, 0x16aed, 0x42617373}, + {0x16af0, 0x16af5, 0x42617373}, + {0x16b00, 0x16b45, 0x486d6e67}, + {0x16b50, 0x16b59, 0x486d6e67}, + {0x16b5b, 0x16b61, 0x486d6e67}, + {0x16b63, 0x16b77, 0x486d6e67}, + {0x16b7d, 0x16b8f, 0x486d6e67}, + {0x16e40, 0x16e9a, 0x4d656466}, + {0x16f00, 0x16f4a, 0x506c7264}, + {0x16f4f, 0x16f87, 0x506c7264}, + {0x16f8f, 0x16f9f, 0x506c7264}, + {0x16fe0, 0x16fe0, 0x54616e67}, + {0x16fe1, 0x16fe1, 0x4e736875}, + {0x16fe2, 0x16fe3, 0x48616e69}, + {0x16fe4, 0x16fe4, 0x4b697473}, + {0x16ff0, 0x16ff1, 0x48616e69}, + {0x17000, 0x187f7, 0x54616e67}, + {0x18800, 0x18aff, 0x54616e67}, + {0x18b00, 0x18cd5, 0x4b697473}, + {0x18d00, 0x18d08, 0x54616e67}, + {0x1aff0, 0x1aff3, 0x4b616e61}, + {0x1aff5, 0x1affb, 0x4b616e61}, + {0x1affd, 0x1affe, 0x4b616e61}, + {0x1b000, 0x1b000, 0x4b616e61}, + {0x1b001, 0x1b11f, 0x48697261}, + {0x1b120, 0x1b122, 0x4b616e61}, + {0x1b132, 0x1b132, 0x48697261}, + {0x1b150, 0x1b152, 0x48697261}, + {0x1b155, 0x1b155, 0x4b616e61}, + {0x1b164, 0x1b167, 0x4b616e61}, + {0x1b170, 0x1b2fb, 0x4e736875}, + {0x1bc00, 0x1bc6a, 0x4475706c}, + {0x1bc70, 0x1bc7c, 0x4475706c}, + {0x1bc80, 0x1bc88, 0x4475706c}, + {0x1bc90, 0x1bc99, 0x4475706c}, + {0x1bc9c, 0x1bc9f, 0x4475706c}, + {0x1bca0, 0x1bca3, 0x5a797979}, + {0x1cf00, 0x1cf2d, 0x5a696e68}, + {0x1cf30, 0x1cf46, 0x5a696e68}, + {0x1cf50, 0x1cfc3, 0x5a797979}, + {0x1d000, 0x1d0f5, 0x5a797979}, + {0x1d100, 0x1d126, 0x5a797979}, + {0x1d129, 0x1d166, 0x5a797979}, + {0x1d167, 0x1d169, 0x5a696e68}, + {0x1d16a, 0x1d17a, 0x5a797979}, + {0x1d17b, 0x1d182, 0x5a696e68}, + {0x1d183, 0x1d184, 0x5a797979}, + {0x1d185, 0x1d18b, 0x5a696e68}, + {0x1d18c, 0x1d1a9, 0x5a797979}, + {0x1d1aa, 0x1d1ad, 0x5a696e68}, + {0x1d1ae, 0x1d1ea, 0x5a797979}, + {0x1d200, 0x1d245, 0x4772656b}, + {0x1d2c0, 0x1d2d3, 0x5a797979}, + {0x1d2e0, 0x1d2f3, 0x5a797979}, + {0x1d300, 0x1d356, 0x5a797979}, + {0x1d360, 0x1d378, 0x5a797979}, + {0x1d400, 0x1d454, 0x5a797979}, + {0x1d456, 0x1d49c, 0x5a797979}, + {0x1d49e, 0x1d49f, 0x5a797979}, + {0x1d4a2, 0x1d4a2, 0x5a797979}, + {0x1d4a5, 0x1d4a6, 0x5a797979}, + {0x1d4a9, 0x1d4ac, 0x5a797979}, + {0x1d4ae, 0x1d4b9, 0x5a797979}, + {0x1d4bb, 0x1d4bb, 0x5a797979}, + {0x1d4bd, 0x1d4c3, 0x5a797979}, + {0x1d4c5, 0x1d505, 0x5a797979}, + {0x1d507, 0x1d50a, 0x5a797979}, + {0x1d50d, 0x1d514, 0x5a797979}, + {0x1d516, 0x1d51c, 0x5a797979}, + {0x1d51e, 0x1d539, 0x5a797979}, + {0x1d53b, 0x1d53e, 0x5a797979}, + {0x1d540, 0x1d544, 0x5a797979}, + {0x1d546, 0x1d546, 0x5a797979}, + {0x1d54a, 0x1d550, 0x5a797979}, + {0x1d552, 0x1d6a5, 0x5a797979}, + {0x1d6a8, 0x1d7cb, 0x5a797979}, + {0x1d7ce, 0x1d7ff, 0x5a797979}, + {0x1d800, 0x1da8b, 0x53676e77}, + {0x1da9b, 0x1da9f, 0x53676e77}, + {0x1daa1, 0x1daaf, 0x53676e77}, + {0x1df00, 0x1df1e, 0x4c61746e}, + {0x1df25, 0x1df2a, 0x4c61746e}, + {0x1e000, 0x1e006, 0x476c6167}, + {0x1e008, 0x1e018, 0x476c6167}, + {0x1e01b, 0x1e021, 0x476c6167}, + {0x1e023, 0x1e024, 0x476c6167}, + {0x1e026, 0x1e02a, 0x476c6167}, + {0x1e030, 0x1e06d, 0x4379726c}, + {0x1e08f, 0x1e08f, 0x4379726c}, + {0x1e100, 0x1e12c, 0x486d6e70}, + {0x1e130, 0x1e13d, 0x486d6e70}, + {0x1e140, 0x1e149, 0x486d6e70}, + {0x1e14e, 0x1e14f, 0x486d6e70}, + {0x1e290, 0x1e2ae, 0x546f746f}, + {0x1e2c0, 0x1e2f9, 0x5763686f}, + {0x1e2ff, 0x1e2ff, 0x5763686f}, + {0x1e4d0, 0x1e4f9, 0x4e61676d}, + {0x1e7e0, 0x1e7e6, 0x45746869}, + {0x1e7e8, 0x1e7eb, 0x45746869}, + {0x1e7ed, 0x1e7ee, 0x45746869}, + {0x1e7f0, 0x1e7fe, 0x45746869}, + {0x1e800, 0x1e8c4, 0x4d656e64}, + {0x1e8c7, 0x1e8d6, 0x4d656e64}, + {0x1e900, 0x1e94b, 0x41646c6d}, + {0x1e950, 0x1e959, 0x41646c6d}, + {0x1e95e, 0x1e95f, 0x41646c6d}, + {0x1ec71, 0x1ecb4, 0x5a797979}, + {0x1ed01, 0x1ed3d, 0x5a797979}, + {0x1ee00, 0x1ee03, 0x41726162}, + {0x1ee05, 0x1ee1f, 0x41726162}, + {0x1ee21, 0x1ee22, 0x41726162}, + {0x1ee24, 0x1ee24, 0x41726162}, + {0x1ee27, 0x1ee27, 0x41726162}, + {0x1ee29, 0x1ee32, 0x41726162}, + {0x1ee34, 0x1ee37, 0x41726162}, + {0x1ee39, 0x1ee39, 0x41726162}, + {0x1ee3b, 0x1ee3b, 0x41726162}, + {0x1ee42, 0x1ee42, 0x41726162}, + {0x1ee47, 0x1ee47, 0x41726162}, + {0x1ee49, 0x1ee49, 0x41726162}, + {0x1ee4b, 0x1ee4b, 0x41726162}, + {0x1ee4d, 0x1ee4f, 0x41726162}, + {0x1ee51, 0x1ee52, 0x41726162}, + {0x1ee54, 0x1ee54, 0x41726162}, + {0x1ee57, 0x1ee57, 0x41726162}, + {0x1ee59, 0x1ee59, 0x41726162}, + {0x1ee5b, 0x1ee5b, 0x41726162}, + {0x1ee5d, 0x1ee5d, 0x41726162}, + {0x1ee5f, 0x1ee5f, 0x41726162}, + {0x1ee61, 0x1ee62, 0x41726162}, + {0x1ee64, 0x1ee64, 0x41726162}, + {0x1ee67, 0x1ee6a, 0x41726162}, + {0x1ee6c, 0x1ee72, 0x41726162}, + {0x1ee74, 0x1ee77, 0x41726162}, + {0x1ee79, 0x1ee7c, 0x41726162}, + {0x1ee7e, 0x1ee7e, 0x41726162}, + {0x1ee80, 0x1ee89, 0x41726162}, + {0x1ee8b, 0x1ee9b, 0x41726162}, + {0x1eea1, 0x1eea3, 0x41726162}, + {0x1eea5, 0x1eea9, 0x41726162}, + {0x1eeab, 0x1eebb, 0x41726162}, + {0x1eef0, 0x1eef1, 0x41726162}, + {0x1f000, 0x1f02b, 0x5a797979}, + {0x1f030, 0x1f093, 0x5a797979}, + {0x1f0a0, 0x1f0ae, 0x5a797979}, + {0x1f0b1, 0x1f0bf, 0x5a797979}, + {0x1f0c1, 0x1f0cf, 0x5a797979}, + {0x1f0d1, 0x1f0f5, 0x5a797979}, + {0x1f100, 0x1f1ad, 0x5a797979}, + {0x1f1e6, 0x1f1ff, 0x5a797979}, + {0x1f200, 0x1f200, 0x48697261}, + {0x1f201, 0x1f202, 0x5a797979}, + {0x1f210, 0x1f23b, 0x5a797979}, + {0x1f240, 0x1f248, 0x5a797979}, + {0x1f250, 0x1f251, 0x5a797979}, + {0x1f260, 0x1f265, 0x5a797979}, + {0x1f300, 0x1f6d7, 0x5a797979}, + {0x1f6dc, 0x1f6ec, 0x5a797979}, + {0x1f6f0, 0x1f6fc, 0x5a797979}, + {0x1f700, 0x1f776, 0x5a797979}, + {0x1f77b, 0x1f7d9, 0x5a797979}, + {0x1f7e0, 0x1f7eb, 0x5a797979}, + {0x1f7f0, 0x1f7f0, 0x5a797979}, + {0x1f800, 0x1f80b, 0x5a797979}, + {0x1f810, 0x1f847, 0x5a797979}, + {0x1f850, 0x1f859, 0x5a797979}, + {0x1f860, 0x1f887, 0x5a797979}, + {0x1f890, 0x1f8ad, 0x5a797979}, + {0x1f8b0, 0x1f8b1, 0x5a797979}, + {0x1f900, 0x1fa53, 0x5a797979}, + {0x1fa60, 0x1fa6d, 0x5a797979}, + {0x1fa70, 0x1fa7c, 0x5a797979}, + {0x1fa80, 0x1fa88, 0x5a797979}, + {0x1fa90, 0x1fabd, 0x5a797979}, + {0x1fabf, 0x1fac5, 0x5a797979}, + {0x1face, 0x1fadb, 0x5a797979}, + {0x1fae0, 0x1fae8, 0x5a797979}, + {0x1faf0, 0x1faf8, 0x5a797979}, + {0x1fb00, 0x1fb92, 0x5a797979}, + {0x1fb94, 0x1fbca, 0x5a797979}, + {0x1fbf0, 0x1fbf9, 0x5a797979}, + {0x20000, 0x2a6df, 0x48616e69}, + {0x2a700, 0x2b739, 0x48616e69}, + {0x2b740, 0x2b81d, 0x48616e69}, + {0x2b820, 0x2cea1, 0x48616e69}, + {0x2ceb0, 0x2ebe0, 0x48616e69}, + {0x2f800, 0x2fa1d, 0x48616e69}, + {0x30000, 0x3134a, 0x48616e69}, + {0x31350, 0x323af, 0x48616e69}, + {0xe0001, 0xe0001, 0x5a797979}, + {0xe0020, 0xe007f, 0x5a797979}, + {0xe0100, 0xe01ef, 0x5a696e68}, +} diff --git a/vendor/github.com/go-text/typesetting/segmenter/segmenter.go b/vendor/github.com/go-text/typesetting/segmenter/segmenter.go new file mode 100644 index 0000000..28ae0ea --- /dev/null +++ b/vendor/github.com/go-text/typesetting/segmenter/segmenter.go @@ -0,0 +1,384 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +// Package segmenter implements Unicode rules used +// to segment a paragraph of text according to several criteria. +// In particular, it provides a way of delimiting line break opportunities. +// +// The API of the package follows the very nice iterator pattern proposed +// in github.com/npillmayer/uax, +// but use a somewhat simpler internal implementation, inspired by Pango. +// +// The reference documentation is at https://unicode.org/reports/tr14 +// and https://unicode.org/reports/tr29. +package segmenter + +import ( + "unicode" + + ucd "github.com/go-text/typesetting/unicodedata" +) + +// breakAttr is a flag storing the break properties between two runes of +// the input text. +type breakAttr uint8 + +const ( + lineBoundary breakAttr = 1 << iota + mandatoryLineBoundary // implies LineBoundary + + // graphemeBoundary is on if the cursor can appear in front of a character, + // i.e. if we are at a grapheme boundary. + graphemeBoundary + + // wordBoundary is on if we are at the beginning or end of a word. + // + // To actually detect words, you should also look for runes + // with the [Alphabetic] property, or with a General_Category of Number. + // + // See also https://unicode.org/reports/tr29/#Word_Boundary_Rules, + // http://unicode.org/reports/tr44/#Alphabetic and + // http://unicode.org/reports/tr44/#General_Category_Values + wordBoundary +) + +const paragraphSeparator rune = 0x2029 + +// lineBreakClass stores the Line Break Property +// See https://unicode.org/reports/tr14/#Properties +type lineBreakClass = *unicode.RangeTable + +// graphemeBreakClass stores the Unicode Grapheme Cluster Break Property +// See https://unicode.org/reports/tr29/#Grapheme_Cluster_Break_Property_Values +type graphemeBreakClass = *unicode.RangeTable + +// wordBreakClass stores the Unicode Word Break Property +// See https://unicode.org/reports/tr29/#Table_Word_Break_Property_Values +type wordBreakClass = *unicode.RangeTable + +// cursor holds the information for the current index +// processed by `computeAttributes`, that is +// the context provided by previous and next runes in the text +type cursor struct { + prev rune // the rune at index i-1 + r rune // the rune at index i + next rune // the rune at index i+1 + + // is r included in `ucd.Extended_Pictographic`, + // cached for efficiency + isExtentedPic bool + + // the following fields persists across iterations + + prevGrapheme graphemeBreakClass // the Grapheme Break property at index i-1 + grapheme graphemeBreakClass // the Grapheme Break property at index i + + // true if the `prev` rune was an odd Regional_Indicator, false if it was even or not an RI + // used for rules GB12 and GB13 + // see [updateGraphemeRIOdd] + isPrevGraphemeRIOdd bool + + prevPrevWord wordBreakClass // the Word Break property at the previous previous, non Extend rune + prevWord wordBreakClass // the Word Break property at the previous, non Extend rune + word wordBreakClass // the Word Break property at index i + prevWordNoExtend int // the index of the last rune NOT having a Extend word break property + + // true if the `prev` rune was an odd Regional_Indicator, false if it was even or not an RI + // used for rules WB15 and WB16 + // see [updateWordRIOdd] + isPrevWordRIOdd bool + + prevPrevLine lineBreakClass // the Line Break Class at index i-2 (see rules LB9 and LB10 for edge cases) + prevLine lineBreakClass // the Line Break Class at index i-1 (see rules LB9 and LB10 for edge cases) + line lineBreakClass // the Line Break Class at index i + nextLine lineBreakClass // the Line Break Class at index i+1 + + // the last rune after spaces, used in rules LB14,LB15,LB16,LB17 + // to match ... SP* ... + beforeSpaces lineBreakClass + + // true if the `prev` rune was an odd Regional_Indicator, false if it was even or not an RI + // used for rules LB30a + isPrevLinebreakRIOdd bool + + // are we in a numeric sequence, as defined in Example 7 of customisation for LB25 + numSequence numSequenceState + + // are we in an emoji sequence, as defined in rule GB11 + // see [updatePictoSequence] + pictoSequence pictoSequenceState +} + +// initialise the cursor properties +// some of them are set in [startIteration] +func newCursor(text []rune) *cursor { + cr := cursor{ + prevPrevLine: ucd.BreakXX, + prevWordNoExtend: -1, + } + + // `startIteration` set `breakCl` from `nextBreakCl` + // so we need to init this field before the first iteration + cr.nextLine = ucd.BreakXX + if len(text) != 0 { + cr.nextLine = ucd.LookupLineBreakClass(text[0]) + } + return &cr +} + +// computeBreakAttributes does the heavy lifting of text segmentation, +// by computing a break attribute for each rune. +// +// More precisely, `attributes` must be a slice of length len(text)+1, +// which will be filled at index i by the attribute describing the +// break between rune at index i-1 and index i. +// +// Unicode defines a lot of properties; for now we only handle +// grapheme, word and line breaking. +func computeBreakAttributes(text []rune, attributes []breakAttr) { + // The rules are somewhat complex, but the general logic is pretty simple: + // iterate through the input slice, fetch context information + // from previous and following runes required by the rules, + // and finaly apply them. + // Some rules require variable length lookup, which we handle by keeping + // a state in a [cursor] object. + + // initialise the cursor properties + cr := newCursor(text) + + for i := 0; i <= len(text); i++ { // note that we accept i == len(text) to fill the last attribute + cr.startIteration(text, i) + + var attr breakAttr + + // UAX#29 Grapheme and word Boundaries + + isGraphemeBoundary := cr.applyGraphemeBoundaryRules() + if isGraphemeBoundary { + attr |= graphemeBoundary + } + + isWordBoundary, removePrevNoExtend := cr.applyWordBoundaryRules(i) + if isWordBoundary { + attr |= wordBoundary + } + if removePrevNoExtend { + attributes[cr.prevWordNoExtend] &^= wordBoundary + } + + // UAX#14 Line Breaking + + bo := cr.applyLineBoundaryRules() + switch bo { + case breakEmpty: + // rule LB31 : default to allow line break + attr |= lineBoundary + case breakProhibited: + attr &^= lineBoundary + case breakAllowed: + attr |= lineBoundary + case breakMandatory: + attr |= lineBoundary + attr |= mandatoryLineBoundary + } + + cr.endIteration(i == 0) + + attributes[i] = attr + } + + // start and end of the paragraph are always + // grapheme boundaries and word boundaries + attributes[0] |= graphemeBoundary | wordBoundary // Rule GB1 and WB1 + attributes[len(text)] |= graphemeBoundary | wordBoundary // Rule GB2 and WB2 + + // never break before the first char, + // but always break after the last + attributes[0] &^= lineBoundary // Rule LB2 + attributes[len(text)] |= lineBoundary // Rule LB3 + attributes[len(text)] |= mandatoryLineBoundary // Rule LB3 +} + +// Segmenter is the entry point of the package. +// +// Usage : +// +// var seg Segmenter +// seg.Init(...) +// iter := seg.LineIterator() +// for iter.Next() { +// ... // do something with iter.Line() +// } +type Segmenter struct { + text []rune + // with length len(text) + 1 : + // the attribute at indice i is about the + // rune at i-1 and i. + // See also [ComputeBreakAttributes] + // Example : + // text : [b, u, l, l] + // attributes : [ b, b u, u l, l l, l ] + attributes []breakAttr +} + +// Init resets the segmenter storage with the given input, +// and computes the attributes required to segment the text. +func (seg *Segmenter) Init(paragraph []rune) { + seg.text = append(seg.text[:0], paragraph...) + seg.attributes = append(seg.attributes[:0], make([]breakAttr, len(paragraph)+1)...) + computeBreakAttributes(seg.text, seg.attributes) +} + +// attributeIterator is an helper type used to +// handle iterating over a slice of runeAttr +type attributeIterator struct { + src *Segmenter + pos int // the current position in the input slice + lastBreak int // the start of the current segment + flag breakAttr // break where this flag is on +} + +// next returns true if there is still a segment to process, +// and advances the iterator; or return false. +// if returning true, the segment is at [iter.lastBreak:iter.pos] +func (iter *attributeIterator) next() bool { + iter.lastBreak = iter.pos // remember the start of the next segment + iter.pos++ + for iter.pos <= len(iter.src.text) { + // can we break before i ? + if iter.src.attributes[iter.pos]&iter.flag != 0 { + return true + } + iter.pos++ + } + return false +} + +// Line is the content of a line delimited by the segmenter. +type Line struct { + // Text is a subslice of the original input slice, containing the delimited line + Text []rune + // Offset is the start of the line in the input rune slice + Offset int + // IsMandatoryBreak is true if breaking (at the end of the line) + // is mandatory + IsMandatoryBreak bool +} + +// LineIterator provides a convenient way of +// iterating over the lines delimited by a `Segmenter`. +type LineIterator struct { + attributeIterator +} + +// Next returns true if there is still a line to process, +// and advances the iterator; or return false. +func (li *LineIterator) Next() bool { return li.next() } + +// Line returns the current `Line` +func (li *LineIterator) Line() Line { + return Line{ + Offset: li.lastBreak, + Text: li.src.text[li.lastBreak:li.pos], // pos is not included since we break right before + IsMandatoryBreak: li.src.attributes[li.pos]&mandatoryLineBoundary != 0, + } +} + +// LineIterator returns an iterator on the lines +// delimited in [Init]. +func (sg *Segmenter) LineIterator() *LineIterator { + return &LineIterator{attributeIterator: attributeIterator{src: sg, flag: lineBoundary}} +} + +// Grapheme is the content of a grapheme delimited by the segmenter. +type Grapheme struct { + // Text is a subslice of the original input slice, containing the delimited grapheme + Text []rune + // Offset is the start of the grapheme in the input rune slice + Offset int +} + +// GraphemeIterator provides a convenient way of +// iterating over the graphemes delimited by a `Segmenter`. +type GraphemeIterator struct { + attributeIterator +} + +// Next returns true if there is still a grapheme to process, +// and advances the iterator; or return false. +func (gr *GraphemeIterator) Next() bool { return gr.next() } + +// Grapheme returns the current `Grapheme` +func (gr *GraphemeIterator) Grapheme() Grapheme { + return Grapheme{ + Offset: gr.lastBreak, + Text: gr.src.text[gr.lastBreak:gr.pos], + } +} + +// GraphemeIterator returns an iterator over the graphemes +// delimited in [Init]. +func (sg *Segmenter) GraphemeIterator() *GraphemeIterator { + return &GraphemeIterator{attributeIterator: attributeIterator{src: sg, flag: graphemeBoundary}} +} + +// Word is the content of a word delimited by the segmenter. +// +// More precisely, a word is formed by runes +// with the [Alphabetic] property, or with a General_Category of Number, +// delimited by the Word Boundary Unicode Property. +// +// See also https://unicode.org/reports/tr29/#Word_Boundary_Rules, +// http://unicode.org/reports/tr44/#Alphabetic and +// http://unicode.org/reports/tr44/#General_Category_Values +type Word struct { + // Text is a subslice of the original input slice, containing the delimited word + Text []rune + // Offset is the start of the word in the input rune slice + Offset int +} + +type WordIterator struct { + attributeIterator + + inWord bool // true if we have seen the start of a word +} + +// Next returns true if there is still a word to process, +// and advances the iterator; or return false. +func (gr *WordIterator) Next() bool { + hasBoundary := gr.next() + if !hasBoundary { + return false + } + + if gr.inWord { // we are have reached the END of a word + gr.inWord = false + return true + } + + // do we start a word ? if so, mark it + if gr.pos < len(gr.src.text) { + gr.inWord = unicode.Is(ucd.Word, gr.src.text[gr.pos]) + } + // in any case, advance again + return gr.Next() +} + +// Word returns the current `Word` +func (gr *WordIterator) Word() Word { + return Word{ + Offset: gr.lastBreak, + Text: gr.src.text[gr.lastBreak:gr.pos], + } +} + +// WordIterator returns an iterator over the word +// delimited in [Init]. +func (sg *Segmenter) WordIterator() *WordIterator { + // check is we start at a word + inWord := false + if len(sg.text) != 0 { + inWord = unicode.Is(ucd.Word, sg.text[0]) + } + return &WordIterator{attributeIterator: attributeIterator{src: sg, flag: wordBoundary}, inWord: inWord} +} diff --git a/vendor/github.com/go-text/typesetting/segmenter/unicode14_rules.go b/vendor/github.com/go-text/typesetting/segmenter/unicode14_rules.go new file mode 100644 index 0000000..5587e8d --- /dev/null +++ b/vendor/github.com/go-text/typesetting/segmenter/unicode14_rules.go @@ -0,0 +1,450 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package segmenter + +import ( + "unicode" + + ucd "github.com/go-text/typesetting/unicodedata" +) + +// Apply the Line Breaking Rules and returns the computed break opportunity +// See https://unicode.org/reports/tr14/#BreakingRules +func (cr *cursor) applyLineBoundaryRules() breakOpportunity { + // start by attributing the break class for the current rune + cr.ruleLB1() + + triggerNumSequence := cr.updateNumSequence() + + // add the line break rules in reverse order to override + // the lower priority rules. + breakOp := breakEmpty + + cr.ruleLB30(&breakOp) + cr.ruleLB30ab(&breakOp) + cr.ruleLB29To26(&breakOp) + cr.ruleLB25(&breakOp, triggerNumSequence) + cr.ruleLB24To22(&breakOp) + cr.ruleLB21To9(&breakOp) + cr.ruleLB8(&breakOp) + cr.ruleLB7To4(&breakOp) + + return breakOp +} + +// breakOpportunity is a convenient enum, +// mapped to the LineBreak and MandatoryBreak properties, +// avoiding too many bit operations +type breakOpportunity uint8 + +const ( + breakEmpty breakOpportunity = iota // not specified + breakProhibited // no break + breakAllowed // direct break (can always break here) + breakMandatory // break is mandatory (implies breakAllowed) +) + +func (cr *cursor) ruleLB30(breakOp *breakOpportunity) { + // (AL | HL | NU) × [OP-[\p{ea=F}\p{ea=W}\p{ea=H}]] + if (cr.prevLine == ucd.BreakAL || cr.prevLine == ucd.BreakHL || cr.prevLine == ucd.BreakNU) && + cr.line == ucd.BreakOP && !unicode.Is(ucd.LargeEastAsian, cr.r) { + *breakOp = breakProhibited + } + // [CP-[\p{ea=F}\p{ea=W}\p{ea=H}]] × (AL | HL | NU) + if cr.prevLine == ucd.BreakCP && !unicode.Is(ucd.LargeEastAsian, cr.prev) && + (cr.line == ucd.BreakAL || cr.line == ucd.BreakHL || cr.line == ucd.BreakNU) { + *breakOp = breakProhibited + } +} + +func (cr *cursor) ruleLB30ab(breakOp *breakOpportunity) { + // (RI RI)* RI × RI + if cr.isPrevLinebreakRIOdd && cr.line == ucd.BreakRI { // LB30a + *breakOp = breakProhibited + } + + // LB30b + // EB × EM + if cr.prevLine == ucd.BreakEB && cr.line == ucd.BreakEM { + *breakOp = breakProhibited + } + // [\p{Extended_Pictographic}&\p{Cn}] × EM + if unicode.Is(ucd.Extended_Pictographic, cr.prev) && ucd.LookupType(cr.prev) == nil && + cr.line == ucd.BreakEM { + *breakOp = breakProhibited + } +} + +func (cr *cursor) ruleLB29To26(breakOp *breakOpportunity) { + b0, b1 := cr.prevLine, cr.line + // LB29 : IS × (AL | HL) + if b0 == ucd.BreakIS && (b1 == ucd.BreakAL || b1 == ucd.BreakHL) { + *breakOp = breakProhibited + } + // LB28 : (AL | HL) × (AL | HL) + if (b0 == ucd.BreakAL || b0 == ucd.BreakHL) && (b1 == ucd.BreakAL || b1 == ucd.BreakHL) { + *breakOp = breakProhibited + } + // LB27 + // (JL | JV | JT | H2 | H3) × PO + if (b0 == ucd.BreakJL || b0 == ucd.BreakJV || b0 == ucd.BreakJT || b0 == ucd.BreakH2 || b0 == ucd.BreakH3) && + b1 == ucd.BreakPO { + *breakOp = breakProhibited + } + // PR × (JL | JV | JT | H2 | H3) + if b0 == ucd.BreakPR && + (b1 == ucd.BreakJL || b1 == ucd.BreakJV || b1 == ucd.BreakJT || b1 == ucd.BreakH2 || b1 == ucd.BreakH3) { + *breakOp = breakProhibited + } + // LB26 + // JL × (JL | JV | H2 | H3) + if b0 == ucd.BreakJL && + (b1 == ucd.BreakJL || b1 == ucd.BreakJV || b1 == ucd.BreakH2 || b1 == ucd.BreakH3) { + *breakOp = breakProhibited + } + // (JV | H2) × (JV | JT) + if (b0 == ucd.BreakJV || b0 == ucd.BreakH2) && (b1 == ucd.BreakJV || b1 == ucd.BreakJT) { + *breakOp = breakProhibited + } + // (JT | H3) × JT + if (b0 == ucd.BreakJT || b0 == ucd.BreakH3) && b1 == ucd.BreakJT { + *breakOp = breakProhibited + } +} + +// we follow other implementations by using the tailoring described +// in Example 7 +func (cr *cursor) ruleLB25(breakOp *breakOpportunity, triggerNumSequence bool) { + br0, br1 := cr.prevLine, cr.line + // (PR | PO) × ( OP | HY )? NU + if (br0 == ucd.BreakPR || br0 == ucd.BreakPO) && br1 == ucd.BreakNU { + *breakOp = breakProhibited + } + if (br0 == ucd.BreakPR || br0 == ucd.BreakPO) && + (br1 == ucd.BreakOP || br1 == ucd.BreakHY) && + cr.nextLine == ucd.BreakNU { + *breakOp = breakProhibited + } + // ( OP | HY ) × NU + if (br0 == ucd.BreakOP || br0 == ucd.BreakHY) && br1 == ucd.BreakNU { + *breakOp = breakProhibited + } + // NU × (NU | SY | IS) + if br0 == ucd.BreakNU && (br1 == ucd.BreakNU || br1 == ucd.BreakSY || br1 == ucd.BreakIS) { + *breakOp = breakProhibited + } + // NU (NU | SY | IS)* × (NU | SY | IS | CL | CP ) + if triggerNumSequence { + *breakOp = breakProhibited + } +} + +func (cr *cursor) ruleLB24To22(breakOp *breakOpportunity) { + br0, br1 := cr.prevLine, cr.line + // LB24 + // (PR | PO) × (AL | HL) + if (br0 == ucd.BreakPR || br0 == ucd.BreakPO) && (br1 == ucd.BreakAL || br1 == ucd.BreakHL) { + *breakOp = breakProhibited + } + // (AL | HL) × (PR | PO) + if (br0 == ucd.BreakAL || br0 == ucd.BreakHL) && (br1 == ucd.BreakPR || br1 == ucd.BreakPO) { + *breakOp = breakProhibited + } + // LB23 + // (AL | HL) × NU + if (br0 == ucd.BreakAL || br0 == ucd.BreakHL) && br1 == ucd.BreakNU { + *breakOp = breakProhibited + } + // NU × (AL | HL) + if br0 == ucd.BreakNU && (br1 == ucd.BreakAL || br1 == ucd.BreakHL) { + *breakOp = breakProhibited + } + // LB23a + // PR × (ID | EB | EM) + if br0 == ucd.BreakPR && (br1 == ucd.BreakID || br1 == ucd.BreakEB || br1 == ucd.BreakEM) { + *breakOp = breakProhibited + } + // (ID | EB | EM) × PO + if (br0 == ucd.BreakID || br0 == ucd.BreakEB || br0 == ucd.BreakEM) && br1 == ucd.BreakPO { + *breakOp = breakProhibited + } + + // LB22 : × IN + if br1 == ucd.BreakIN { + *breakOp = breakProhibited + } +} + +func (cr *cursor) ruleLB21To9(breakOp *breakOpportunity) { + br0, br1 := cr.prevLine, cr.line + // LB21 + // × BA + // × HY + // × NS + // BB × + if br1 == ucd.BreakBA || br1 == ucd.BreakHY || br1 == ucd.BreakNS || br0 == ucd.BreakBB { + *breakOp = breakProhibited + } + // LB21a : HL (HY | BA) × + if cr.prevPrevLine == ucd.BreakHL && + (br0 == ucd.BreakHY || br0 == ucd.BreakBA) { + *breakOp = breakProhibited + } + // LB21b : SY × HL + if br0 == ucd.BreakSY && br1 == ucd.BreakHL { + *breakOp = breakProhibited + } + // LB20 + // ÷ CB + // CB ÷ + if br0 == ucd.BreakCB || br1 == ucd.BreakCB { + *breakOp = breakAllowed + } + // LB19 + // × QU + // QU × + if br0 == ucd.BreakQU || br1 == ucd.BreakQU { + *breakOp = breakProhibited + } + // LB18 : SP ÷ + if br0 == ucd.BreakSP { + *breakOp = breakAllowed + } + // LB17 : B2 SP* × B2 + if cr.beforeSpaces == ucd.BreakB2 && br1 == ucd.BreakB2 { + *breakOp = breakProhibited + } + // LB16 : (CL | CP) SP* × NS + if (cr.beforeSpaces == ucd.BreakCL || cr.beforeSpaces == ucd.BreakCP) && br1 == ucd.BreakNS { + *breakOp = breakProhibited + } + // LB15 : QU SP* × OP + if cr.beforeSpaces == ucd.BreakQU && br1 == ucd.BreakOP { + *breakOp = breakProhibited + } + // LB14 : OP SP* × + if cr.beforeSpaces == ucd.BreakOP { + *breakOp = breakProhibited + } + + // rule LB13, with the tailoring described in Example 7 + // × EX + if br1 == ucd.BreakEX { + *breakOp = breakProhibited + } + // [^NU] × CL + // [^NU] × CP + // [^NU] × IS + // [^NU] × SY + if br0 != ucd.BreakNU && + (br1 == ucd.BreakCL || br1 == ucd.BreakCP || br1 == ucd.BreakIS || br1 == ucd.BreakSY) { + *breakOp = breakProhibited + } + // LB12 : GL × + if br0 == ucd.BreakGL { + *breakOp = breakProhibited + } + // LB12a : [^SP BA HY] × GL + if (br0 != ucd.BreakSP && br0 != ucd.BreakBA && br0 != ucd.BreakHY) && + br1 == ucd.BreakGL { + *breakOp = breakProhibited + } + // LB11 + // × WJ + // WJ × + if br0 == ucd.BreakWJ || br1 == ucd.BreakWJ { + *breakOp = breakProhibited + } + + // rule LB9 : "Do not break a combining character sequence" + // where X is any line break class except BK, CR, LF, NL, SP, or ZW. + // see also [endIteration] + if br1 == ucd.BreakCM || br1 == ucd.BreakZWJ { + if !(br0 == ucd.BreakBK || br0 == ucd.BreakCR || br0 == ucd.BreakLF || + br0 == ucd.BreakNL || br0 == ucd.BreakSP || br0 == ucd.BreakZW) { + *breakOp = breakProhibited + } + } +} + +func (cr *cursor) ruleLB8(breakOp *breakOpportunity) { + // rule LB8 : ZW SP* ÷ + if cr.beforeSpaces == ucd.BreakZW { + *breakOp = breakAllowed + } + // rule LB8a : ZWJ × + // there is a catch here : prevLine is not always exactly + // the class at index i-1, because of rules LB9 and LB10 + // however, rule LB8a applies before LB9 and LB10, meaning + // we need to use the real class + if unicode.Is(ucd.BreakZWJ, cr.prev) { + *breakOp = breakProhibited + } +} + +func (cr *cursor) ruleLB7To4(breakOp *breakOpportunity) { + // LB7 + // × SP + // × ZW + if cr.line == ucd.BreakSP || cr.line == ucd.BreakZW { + *breakOp = breakProhibited + } + // LB6 : × ( BK | CR | LF | NL ) + if cr.line == ucd.BreakBK || cr.line == ucd.BreakCR || cr.line == ucd.BreakLF || cr.line == ucd.BreakNL { + *breakOp = breakProhibited + } + + // LB4 and LB5 + // BK ! + // CR ! + // LF ! + // NL ! + // (CR × LF is actually handled in rule LB6) + if cr.prevLine == ucd.BreakBK || (cr.prevLine == ucd.BreakCR && cr.r != '\n') || + cr.prevLine == ucd.BreakLF || cr.prevLine == ucd.BreakNL { + *breakOp = breakMandatory + } +} + +// apply rule LB1 to resolve break classses AI, SG, XX, SA and CJ. +// We use the default values specified in https://unicode.org/reports/tr14/#BreakingRules. +func (cr *cursor) ruleLB1() { + switch cr.line { + case ucd.BreakAI, ucd.BreakSG, ucd.BreakXX: + cr.line = ucd.BreakAL + case ucd.BreakSA: + generalCategory := ucd.LookupType(cr.r) + if generalCategory == unicode.Mn || generalCategory == unicode.Mc { + cr.line = ucd.BreakCM + } else { + cr.line = ucd.BreakAL + } + case ucd.BreakCJ: + cr.line = ucd.BreakNS + } +} + +type numSequenceState uint8 + +const ( + noNumSequence numSequenceState = iota // we are not in a sequence + inNumSequence // we are in NU (NU | SY | IS)* + seenCloseNum // we are at NU (NU | SY | IS)* (CL | CP)? +) + +// update the `numSequence` state used for rule LB25 +// and returns true if we matched one +func (cr *cursor) updateNumSequence() bool { + // note that rule LB9 also apply : (CM|ZWJ) do not change + // the flag + if cr.line == ucd.BreakCM || cr.line == ucd.BreakZWJ { + return false + } + + switch cr.numSequence { + case noNumSequence: + if cr.line == ucd.BreakNU { // start a sequence + cr.numSequence = inNumSequence + } + return false + case inNumSequence: + switch cr.line { + case ucd.BreakNU, ucd.BreakSY, ucd.BreakIS: + // NU (NU | SY | IS)* × (NU | SY | IS) : the sequence continue + return true + case ucd.BreakCL, ucd.BreakCP: + // NU (NU | SY | IS)* × (CL | CP) + cr.numSequence = seenCloseNum + return true + case ucd.BreakPO, ucd.BreakPR: + // NU (NU | SY | IS)* × (PO | PR) : close the sequence + cr.numSequence = noNumSequence + return true + default: + cr.numSequence = noNumSequence + return false + } + case seenCloseNum: + cr.numSequence = noNumSequence // close the sequence anyway + if cr.line == ucd.BreakPO || cr.line == ucd.BreakPR { + // NU (NU | SY | IS)* (CL | CP) × (PO | PR) + return true + } + return false + default: + panic("exhaustive switch") + } +} + +// startIteration updates the cursor properties, setting the current +// rune to text[i]. +// Some properties depending on the context are rather +// updated in the previous `endIteration` call. +func (cr *cursor) startIteration(text []rune, i int) { + cr.prev = cr.r + if i < len(text) { + cr.r = text[i] + } else { + cr.r = paragraphSeparator + } + if i == len(text) { + cr.next = 0 + } else if i == len(text)-1 { + // we fill in the last element of `attrs` by assuming + // there's a paragraph separators off the end of text + cr.next = paragraphSeparator + } else { + cr.next = text[i+1] + } + + // query general unicode properties for the current rune + + cr.isExtentedPic = unicode.Is(ucd.Extended_Pictographic, cr.r) + + cr.prevGrapheme = cr.grapheme + cr.grapheme = ucd.LookupGraphemeBreakClass(cr.r) + + if cr.word != ucd.WordBreakExtendFormat { + cr.prevPrevWord = cr.prevWord + cr.prevWord = cr.word + cr.prevWordNoExtend = i - 1 + } + cr.word = ucd.LookupWordBreakClass(cr.r) + + // prevPrevLine and prevLine are handled in endIteration + cr.line = cr.nextLine // avoid calling LookupLineBreakClass twice + cr.nextLine = ucd.LookupLineBreakClass(cr.next) +} + +// end the current iteration, computing some of the properties +// required for the next rune and respecting rule LB9 and LB10 +func (cr *cursor) endIteration(isStart bool) { + // start by handling rule LB9 and LB10 + if cr.line == ucd.BreakCM || cr.line == ucd.BreakZWJ { + isLB10 := cr.prevLine == ucd.BreakBK || + cr.prevLine == ucd.BreakCR || + cr.prevLine == ucd.BreakLF || + cr.prevLine == ucd.BreakNL || + cr.prevLine == ucd.BreakSP || + cr.prevLine == ucd.BreakZW + if isStart || isLB10 { // Rule LB10 + cr.prevLine = ucd.BreakAL + } // else rule LB9 : ignore the rune for prevLine and prevPrevLine + + } else { // regular update + cr.prevPrevLine = cr.prevLine + cr.prevLine = cr.line + } + + // keep track of the rune before the spaces + if cr.prevLine != ucd.BreakSP { + cr.beforeSpaces = cr.prevLine + } + + // update RegionalIndicator parity used for LB30a + if cr.line == ucd.BreakRI { + cr.isPrevLinebreakRIOdd = !cr.isPrevLinebreakRIOdd + } else if !(cr.line == ucd.BreakCM || cr.line == ucd.BreakZWJ) { // beware of the rule LB9: (CM|ZWJ) ignore the update + cr.isPrevLinebreakRIOdd = false + } +} diff --git a/vendor/github.com/go-text/typesetting/segmenter/unicode29_rules.go b/vendor/github.com/go-text/typesetting/segmenter/unicode29_rules.go new file mode 100644 index 0000000..d41063e --- /dev/null +++ b/vendor/github.com/go-text/typesetting/segmenter/unicode29_rules.go @@ -0,0 +1,194 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package segmenter + +import ( + ucd "github.com/go-text/typesetting/unicodedata" +) + +// ----------------------------------------------------------------------- +// ------------------------- Grapheme boundaries ------------------------- +// ----------------------------------------------------------------------- + +// Apply the Grapheme_Cluster_Boundary_Rules and returns a true if we are +// at a grapheme break. +// See https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundary_Rules +func (cr *cursor) applyGraphemeBoundaryRules() bool { + triggerGB11 := cr.updatePictoSequence() // apply rule GB11 + triggerGB12_13 := cr.updateGraphemeRIOdd() // apply rule GB12 and GB13 + + br0, br1 := cr.prevGrapheme, cr.grapheme + if cr.r == '\n' && cr.prev == '\r' { + return false // Rule GB3 + } else if br0 == ucd.GraphemeBreakControl || br0 == ucd.GraphemeBreakCR || br0 == ucd.GraphemeBreakLF || + br1 == ucd.GraphemeBreakControl || br1 == ucd.GraphemeBreakCR || br1 == ucd.GraphemeBreakLF { + return true // Rules GB4 && GB5 + } else if br0 == ucd.GraphemeBreakL && + (br1 == ucd.GraphemeBreakL || br1 == ucd.GraphemeBreakV || br1 == ucd.GraphemeBreakLV || br1 == ucd.GraphemeBreakLVT) { // rule GB6 + return false + } else if (br0 == ucd.GraphemeBreakLV || br0 == ucd.GraphemeBreakV) && (br1 == ucd.GraphemeBreakV || br1 == ucd.GraphemeBreakT) { + return false // rule GB7 + } else if (br0 == ucd.GraphemeBreakLVT || br0 == ucd.GraphemeBreakT) && br1 == ucd.GraphemeBreakT { + return false // rule GB8 + } else if br1 == ucd.GraphemeBreakExtend || br1 == ucd.GraphemeBreakZWJ { + return false // Rule GB9 + } else if br1 == ucd.GraphemeBreakSpacingMark { + return false // Rule GB9a + } else if br0 == ucd.GraphemeBreakPrepend { + return false // Rule GB9b + } else if triggerGB11 { // Rule GB11 + return false + } else if triggerGB12_13 { + return false // Rule GB12 && GB13 + } + + return true // Rule GB999 +} + +// update `isPrevGraphemeRIOdd` used for the rules GB12 and GB13 +// and returns `true` if one of them triggered +func (cr *cursor) updateGraphemeRIOdd() (trigger bool) { + if cr.grapheme == ucd.GraphemeBreakRegional_Indicator { + trigger = cr.isPrevGraphemeRIOdd + cr.isPrevGraphemeRIOdd = !cr.isPrevGraphemeRIOdd // switch the parity + } else { + cr.isPrevGraphemeRIOdd = false + } + return trigger +} + +// see rule GB11 +type pictoSequenceState uint8 + +const ( + noPictoSequence pictoSequenceState = iota // we are not in a sequence + inPictoExtend // we are in (ExtendedPic)(Extend*) pattern + seenPictoZWJ // we have seen (ExtendedPic)(Extend*)(ZWJ) +) + +// update the `pictoSequence` state used for rule GB11 pattern : +// (ExtendedPic)(Extend*)(ZWJ)(ExtendedPic) +// and returns true if we matched one +func (cr *cursor) updatePictoSequence() bool { + switch cr.pictoSequence { + case noPictoSequence: + // we are not in a sequence yet, start it if we have an ExtendedPic + if cr.isExtentedPic { + cr.pictoSequence = inPictoExtend + } + return false + case inPictoExtend: + if cr.grapheme == ucd.GraphemeBreakExtend { + // continue the sequence with an Extend rune + } else if cr.grapheme == ucd.GraphemeBreakZWJ { + // close the variable part of the sequence with (ZWJ) + cr.pictoSequence = seenPictoZWJ + } else { + // stop the sequence + cr.pictoSequence = noPictoSequence + } + return false + case seenPictoZWJ: + // trigger GB11 if we have an ExtendedPic, + // and reset the sequence + if cr.isExtentedPic { + cr.pictoSequence = inPictoExtend + return true + } + cr.pictoSequence = noPictoSequence + return false + default: + panic("exhaustive switch") + } +} + +// ----------------------------------------------------------------------- +// ------------------------- Word boundaries ----------------------------- +// ----------------------------------------------------------------------- + +// update `isPrevWordRIOdd` used for the rules WB15 and WB16 +// and returns `true` if one of them triggered +func (cr *cursor) updateWordRIOdd() (trigger bool) { + if cr.word == ucd.WordBreakExtendFormat { + return false // skip + } + + if cr.word == ucd.WordBreakRegional_Indicator { + trigger = cr.isPrevWordRIOdd + cr.isPrevWordRIOdd = !cr.isPrevWordRIOdd // switch the parity + } else { + cr.isPrevWordRIOdd = false + } + return trigger +} + +// Apply the Word_Boundary_Rules and returns true if we are at a +// word boundary. +// removePrevNoExtend is true if the index [prevWordNoExtend] +// should be marked as NOT being a word boundary +// See https://unicode.org/reports/tr29/#Word_Boundary_Rules +func (cr *cursor) applyWordBoundaryRules(i int) (isWordBoundary, removePrevNoExtend bool) { + triggerWB15_16 := cr.updateWordRIOdd() + + prevPrev, prev, current := cr.prevPrevWord, cr.prevWord, cr.word + + // we apply Rules WB1 and WB2 at the end of the main loop + + isAfterNoExtend := cr.prevWordNoExtend == i-1 + + if cr.prev == '\u000D' && cr.r == '\u000A' { // Rule WB3 + isWordBoundary = false + } else if prev == ucd.WordBreakNewlineCRLF && isAfterNoExtend { + // The extra check for prevWordNoExtend is to correctly handle sequences like + // Newline ÷ Extend × Extend + // since we have not skipped ExtendFormat yet. + isWordBoundary = true // Rule WB3a + } else if current == ucd.WordBreakNewlineCRLF { + isWordBoundary = true // Rule WB3b + } else if cr.prev == 0x200D && cr.isExtentedPic { + isWordBoundary = false // Rule WB3c + } else if prev == ucd.WordBreakWSegSpace && + current == ucd.WordBreakWSegSpace && isAfterNoExtend { + isWordBoundary = false // Rule WB3d + } else if current == ucd.WordBreakExtendFormat { + isWordBoundary = false // Rules WB4 + } else if (prev == ucd.WordBreakALetter || prev == ucd.WordBreakHebrew_Letter || prev == ucd.WordBreakNumeric) && + (current == ucd.WordBreakALetter || current == ucd.WordBreakHebrew_Letter || current == ucd.WordBreakNumeric) { + isWordBoundary = false // Rules WB5, WB8, WB9, WB10 + } else if prev == ucd.WordBreakKatakana && current == ucd.WordBreakKatakana { + isWordBoundary = false // Rule WB13 + } else if (prev == ucd.WordBreakALetter || + prev == ucd.WordBreakHebrew_Letter || + prev == ucd.WordBreakNumeric || + prev == ucd.WordBreakKatakana || + prev == ucd.WordBreakExtendNumLet) && + current == ucd.WordBreakExtendNumLet { + isWordBoundary = false // Rule WB13a + } else if prev == ucd.WordBreakExtendNumLet && + (current == ucd.WordBreakALetter || current == ucd.WordBreakHebrew_Letter || current == ucd.WordBreakNumeric || + current == ucd.WordBreakKatakana) { + isWordBoundary = false // Rule WB13b + } else if (prevPrev == ucd.WordBreakALetter || prevPrev == ucd.WordBreakHebrew_Letter) && + (prev == ucd.WordBreakMidLetter || prev == ucd.WordBreakMidNumLet || prev == ucd.WordBreakSingle_Quote) && + (current == ucd.WordBreakALetter || current == ucd.WordBreakHebrew_Letter) { + removePrevNoExtend = true // Rule WB6 + isWordBoundary = false // Rule WB7 + } else if prev == ucd.WordBreakHebrew_Letter && current == ucd.WordBreakSingle_Quote { + isWordBoundary = false // Rule WB7a + } else if prevPrev == ucd.WordBreakHebrew_Letter && cr.prev == 0x0022 && + current == ucd.WordBreakHebrew_Letter { + removePrevNoExtend = true // Rule WB7b + isWordBoundary = false // Rule WB7c + } else if (prevPrev == ucd.WordBreakNumeric && current == ucd.WordBreakNumeric) && + (prev == ucd.WordBreakMidNum || prev == ucd.WordBreakMidNumLet || + prev == ucd.WordBreakSingle_Quote) { + isWordBoundary = false // Rule WB11 + removePrevNoExtend = true // Rule WB12 + } else if triggerWB15_16 { + isWordBoundary = false // Rule WB15 and WB16 + } else { + isWordBoundary = true // Rule WB999 + } + + return isWordBoundary, removePrevNoExtend +} diff --git a/vendor/github.com/go-text/typesetting/shaping/README.md b/vendor/github.com/go-text/typesetting/shaping/README.md new file mode 100644 index 0000000..cae6609 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/shaping/README.md @@ -0,0 +1,3 @@ +# shaping + +This text shaping library is shared by multiple Go UI toolkits including Fyne, and GIO. diff --git a/vendor/github.com/go-text/typesetting/shaping/input.go b/vendor/github.com/go-text/typesetting/shaping/input.go new file mode 100644 index 0000000..48ad944 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/shaping/input.go @@ -0,0 +1,433 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package shaping + +import ( + "unicode" + + "github.com/go-text/typesetting/di" + "github.com/go-text/typesetting/font" + ot "github.com/go-text/typesetting/font/opentype" + "github.com/go-text/typesetting/harfbuzz" + "github.com/go-text/typesetting/language" + "github.com/go-text/typesetting/unicodedata" + "golang.org/x/image/math/fixed" + "golang.org/x/text/unicode/bidi" +) + +type Input struct { + // Text is the body of text being shaped. Only the range Text[RunStart:RunEnd] is considered + // for shaping, with the rest provided as context for the shaper. This helps with, for example, + // cross-run Arabic shaping or handling combining marks at the start of a run. + Text []rune + // RunStart and RunEnd indicate the subslice of Text being shaped. + RunStart, RunEnd int + // Direction is the directionality of the text. + Direction di.Direction + // Face is the font face to render the text in. + Face *font.Face + + // FontFeatures activates or deactivates optional features + // provided by the font. + // The settings are applied to the whole [Text]. + FontFeatures []FontFeature + + // Size is the requested size of the font. + // More generally, it is a scale factor applied to the resulting metrics. + // For instance, given a device resolution (in dpi) and a point size (like 14), the `Size` to + // get result in pixels is given by : pointSize * dpi / 72 + Size fixed.Int26_6 + + // Script is an identifier for the writing system used in the text. + Script language.Script + + // Language is an identifier for the language of the text. + Language language.Language +} + +// FontFeature sets one font feature. +// +// A font feature is an optionnal behavior a font might expose, +// identified by a 4 bytes [Tag]. +// Most features are disabled by default; setting a non zero [Value] +// enables it. +// +// An exemple of font feature is the replacement of fractions (like 1/2, 3/4) +// by specialized glyphs, which would be activated by using +// +// FontFeature{Tag: ot.MustNewTag("frac"), Value: 1} +// +// See also https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist +// and https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_fonts/OpenType_fonts_guide +type FontFeature struct { + Tag ot.Tag + Value uint32 +} + +// Fontmap provides a general mechanism to select +// a face to use when shaping text. +type Fontmap interface { + // ResolveFace is called by `SplitByFace` for each input rune potentially + // triggering a face change. + // It must always return a valid (non nil ) *font.Face value. + ResolveFace(r rune) *font.Face +} + +var _ Fontmap = fixedFontmap(nil) + +type fixedFontmap []*font.Face + +// ResolveFace panics if the slice is empty +func (ff fixedFontmap) ResolveFace(r rune) *font.Face { + for _, f := range ff { + if _, has := f.NominalGlyph(r); has { + return f + } + } + return ff[0] +} + +// SplitByFontGlyphs split the runes from 'input' to several items, sharing the same +// characteristics as 'input', expected for the `Face` which is set to +// the first font among 'availableFonts' providing support for all the runes +// in the item. +// Runes supported by no fonts are mapped to the first element of 'availableFonts', which +// must not be empty. +// The 'Face' field of 'input' is ignored: only 'availableFaces' are consulted. +// Rune coverage is obtained by calling the NominalGlyph() method of each font. +// See also SplitByFace for a more general approach of font selection. +func SplitByFontGlyphs(input Input, availableFaces []*font.Face) []Input { + return SplitByFace(input, fixedFontmap(availableFaces)) +} + +// SplitByFace split the runes from 'input' to several items, sharing the same +// characteristics as 'input', expected for the `Face` which is set to +// the return value of the `Fontmap.ResolveFace` call. +// The 'Face' field of 'input' is ignored: only 'availableFaces' is used to select the face. +func SplitByFace(input Input, availableFaces Fontmap) []Input { + return splitByFace(input, availableFaces, nil) +} + +// Segmenter holds a state used to split input +// according to three caracteristics : text direction (bidi), +// script, and face. +type Segmenter struct { + // pools of inputs, used to reduce allocations, + // which are alternatively swapped between each step of the segmentation + input, output []Input + + // used to handle Common script + delimStack []delimEntry + + // buffer used for bidi segmentation + bidiParagraph bidi.Paragraph +} + +type delimEntry struct { + index int // in the [pairedDelims] list + script language.Script // resolved from the context +} + +// Split segments the given pre-configured input according to: +// - text direction +// - script +// - (vertical text only) glyph orientation +// - face, as defined by [faces] +// +// Only the input runes in the range [text.RunStart] to [text.RunEnd] will be split. +// +// As a consequence, it sets the following fields of the returned runs: +// - Text, RunStart, RunEnd +// - Direction +// - Script +// - Face +// +// [text.Direction] is used during bidi ordering, and should refer to the general +// context [text] is used in (typically the user system preference for GUI apps.) +// +// For vertical text, if its orientation is set, is copied as it is; otherwise, the +// orientation is resolved using the Unicode recommendations (see https://www.unicode.org/reports/tr50/). +// +// The returned sliced is owned by the [Segmenter] and is only valid until +// the next call to [Split]. +func (seg *Segmenter) Split(text Input, faces Fontmap) []Input { + seg.reset() + seg.splitByBidi(text) // fills output + + seg.input, seg.output = seg.output, seg.input // output is empty + seg.splitByScript() + + // if needed, resolve text orientation for vertical text + if text.Direction.IsVertical() && !text.Direction.HasVerticalOrientation() { + seg.input, seg.output = seg.output, seg.input + seg.output = seg.output[:0] + seg.splitByVertOrientation() + } + + seg.input, seg.output = seg.output, seg.input + seg.output = seg.output[:0] + seg.splitByFace(faces) + + return seg.output +} + +func (seg *Segmenter) reset() { + // zero the slices to avoid 'memory leak' on pointer slice fields + for i := range seg.input { + seg.input[i].Text = nil + seg.input[i].FontFeatures = nil + } + for i := range seg.output { + seg.output[i].Text = nil + seg.output[i].FontFeatures = nil + } + seg.input = seg.input[:0] + seg.output = seg.output[:0] + + // bidiParagraph is reset when using SetString + + seg.delimStack = seg.delimStack[:0] +} + +func (seg *Segmenter) splitByBidi(text Input) { + // split vertical text like horizontal one + if text.RunStart >= text.RunEnd { + seg.output = append(seg.output, text) + return + } + def := bidi.LeftToRight + if text.Direction.Progression() == di.TowardTopLeft { + def = bidi.RightToLeft + } + seg.bidiParagraph.SetString(string(text.Text[text.RunStart:text.RunEnd]), bidi.DefaultDirection(def)) + out, err := seg.bidiParagraph.Order() + if err != nil { + seg.output = append(seg.output, text) + return + } + + input := text // start a rune 0 of the run + for i := 0; i < out.NumRuns(); i++ { + currentInput := input + run := out.Run(i) + dir := run.Direction() + _, endRune := run.Pos() + endRune += text.RunStart // shift by the input run position + currentInput.RunEnd = endRune + 1 + + // override the direction + if dir == bidi.RightToLeft { + currentInput.Direction.SetProgression(di.TowardTopLeft) + } else { + currentInput.Direction.SetProgression(di.FromTopLeft) + } + + seg.output = append(seg.output, currentInput) + input.RunStart = currentInput.RunEnd + } +} + +// lookupDelimIndex binary searches in the list of the paired delimiters, +// and returns -1 if `ch` is not found +func lookupDelimIndex(ch rune) int { + lower := 0 + upper := len(pairedDelims) - 1 + + for lower <= upper { + mid := (lower + upper) / 2 + + if ch < pairedDelims[mid] { + upper = mid - 1 + } else if ch > pairedDelims[mid] { + lower = mid + 1 + } else { + return mid + } + } + + return -1 +} + +// See https://unicode.org/reports/tr24/#Common for reference +func (seg *Segmenter) splitByScript() { + for _, input := range seg.input { + currentInput := input + currentInput.Script = language.Common + + for i := input.RunStart; i < input.RunEnd; i++ { + r := input.Text[i] + rScript := language.LookupScript(r) + + // to properly handle Common script, + // we register paired delimiters + + delimIndex := -1 + if rScript == language.Common || rScript == language.Inherited { + delimIndex = lookupDelimIndex(r) + } + + if delimIndex >= 0 { // handle paired characters + if delimIndex%2 == 0 { + // this is an open character : push it onto the stack + seg.delimStack = append(seg.delimStack, delimEntry{delimIndex, currentInput.Script}) + } else { + // this is a close character : try to look backward in the stack + // for its counterpart + counterPartIndex := delimIndex - 1 + j := len(seg.delimStack) - 1 + for ; j >= 0; j-- { + if seg.delimStack[j].index == counterPartIndex { // found a match, use its script + rScript = seg.delimStack[j].script + break + } + } + // in any case, pop the open characters + if j == -1 { + j = 0 + } + seg.delimStack = seg.delimStack[:j] + } + } + + // check if we have a 'real' change of script, or not + if rScript == language.Common || rScript == language.Inherited || rScript == currentInput.Script { + // no change + continue + } else if currentInput.Script == language.Common { + // update the pair stack to attribute the resolved script + for i := range seg.delimStack { + seg.delimStack[i].script = rScript + } + // set the resolved script to the current run, + // but do NOT create a new run + currentInput.Script = rScript + } else { + // split to a new run + if i != input.RunStart { // push the existing one + currentInput.RunEnd = i + seg.output = append(seg.output, currentInput) + } + + currentInput.RunStart = i + currentInput.Script = rScript + } + } + // close and add the last input + currentInput.RunEnd = input.RunEnd + seg.output = append(seg.output, currentInput) + } +} + +// assume the script has been resolved +func (seg *Segmenter) splitByVertOrientation() { + for _, input := range seg.input { + vo := unicodedata.LookupVerticalOrientation(input.Script) + currentInput := input + + for i := input.RunStart; i < input.RunEnd; i++ { + r := input.Text[i] + sideways := vo.Orientation(r) + if i == input.RunStart { + // first run : update the orientation, + // but do not create a new run + currentInput.Direction.SetSideways(sideways) + continue + } + + if sideways != currentInput.Direction.IsSideways() { + // create new run : push the current one ... + currentInput.RunEnd = i + seg.output = append(seg.output, currentInput) + + // ... and update the 'new' + currentInput.RunStart = i + currentInput.Direction.SetSideways(sideways) + } + } + + // close and add the last input + currentInput.RunEnd = input.RunEnd + seg.output = append(seg.output, currentInput) + } +} + +func (seg *Segmenter) splitByFace(faces Fontmap) { + for _, input := range seg.input { + seg.output = splitByFace(input, faces, seg.output) + } +} + +func splitByFace(input Input, availableFaces Fontmap, buffer []Input) []Input { + currentInput := input + for i := input.RunStart; i < input.RunEnd; i++ { + r := input.Text[i] + // We can safely ignore characters if we have a face or if there is more text, + // but we must force the choice of a face if we still don't have one and we reach + // the final rune. Otherwise strings like all-whitespace are never assigned a face. + if ignoreFaceChange(r) && (currentInput.Face != nil || i < input.RunEnd-1) { + // add the rune to the current input + continue + } + + // select the first font supporting r + selectedFace := availableFaces.ResolveFace(r) + + // now that we have a font, apply it back, + // but do NOT create a new run + if currentInput.Face == nil { + currentInput.Face = selectedFace + } + + if currentInput.Face == selectedFace { + // add the rune to the current input + continue + } + + // new face needed + + if i != input.RunStart { + // close the current input ... + currentInput.RunEnd = i + // ... add it to the output ... + buffer = append(buffer, currentInput) + } + + // ... and create a new one + currentInput = input + currentInput.RunStart = i + currentInput.Face = selectedFace + } + + // close and add the last input + currentInput.RunEnd = input.RunEnd + buffer = append(buffer, currentInput) + return buffer +} + +// ignoreFaceChange returns `true` is the given rune should not trigger +// a change of font. +// +// We don't want space characters to affect font selection; in general, +// it's always wrong to select a font just to render a space. +// We assume that all fonts have the ASCII space, and for other space +// characters if they don't, HarfBuzz will compatibility-decompose them +// to ASCII space... +// +// We don't want to change fonts for line or paragraph separators. +// +// Finaly, we also don't change fonts for what Harfbuzz consider +// as ignorable (however, some Control Format runes like 06DD are not ignored). +// +// The rationale is taken from pango : see bugs +// https://bugzilla.gnome.org/show_bug.cgi?id=355987 +// https://bugzilla.gnome.org/show_bug.cgi?id=701652 +// https://bugzilla.gnome.org/show_bug.cgi?id=781123 +// for more details. +func ignoreFaceChange(r rune) bool { + return unicode.Is(unicode.Cc, r) || // control + unicode.Is(unicode.Cs, r) || // surrogate + unicode.Is(unicode.Zl, r) || // line separator + unicode.Is(unicode.Zp, r) || // paragraph separator + (unicode.Is(unicode.Zs, r) && r != '\u1680') || // space separator != OGHAM SPACE MARK + harfbuzz.IsDefaultIgnorable(r) +} diff --git a/vendor/github.com/go-text/typesetting/shaping/lru.go b/vendor/github.com/go-text/typesetting/shaping/lru.go new file mode 100644 index 0000000..0ac0acc --- /dev/null +++ b/vendor/github.com/go-text/typesetting/shaping/lru.go @@ -0,0 +1,69 @@ +package shaping + +import ( + "github.com/go-text/typesetting/font" + "github.com/go-text/typesetting/harfbuzz" +) + +// fontEntry holds a single key-value pair for an LRU cache. +type fontEntry struct { + next, prev *fontEntry + key *font.Font + v *harfbuzz.Font +} + +// fontLRU is a least-recently-used cache for harfbuzz fonts built from +// font.Fonts. It uses a doubly-linked list to track how recently elements have +// been used and a map to store element data for quick access. +type fontLRU struct { + // This implementation is derived from the one here under the terms of the UNLICENSE: + // + // https://git.sr.ht/~eliasnaur/gio/tree/e768fe347a732056031100f2c66987d6db258ea4/item/text/lru.go + m map[*font.Font]*fontEntry + head, tail *fontEntry + maxSize int +} + +// Get fetches the value associated with the given key, if any. +func (l *fontLRU) Get(k *font.Font) (*harfbuzz.Font, bool) { + if lt, ok := l.m[k]; ok { + l.remove(lt) + l.insert(lt) + return lt.v, true + } + return nil, false +} + +// Put inserts the given value with the given key, evicting old +// cache entries if necessary. +func (l *fontLRU) Put(k *font.Font, v *harfbuzz.Font) { + if l.m == nil { + l.m = make(map[*font.Font]*fontEntry) + l.head = new(fontEntry) + l.tail = new(fontEntry) + l.head.prev = l.tail + l.tail.next = l.head + } + val := &fontEntry{key: k, v: v} + l.m[k] = val + l.insert(val) + if len(l.m) > l.maxSize { + oldest := l.tail.next + l.remove(oldest) + delete(l.m, oldest.key) + } +} + +// remove cuts e out of the lru linked list. +func (l *fontLRU) remove(e *fontEntry) { + e.next.prev = e.prev + e.prev.next = e.next +} + +// insert adds e to the lru linked list. +func (l *fontLRU) insert(e *fontEntry) { + e.next = l.head + e.prev = l.head.prev + e.prev.next = e + e.next.prev = e +} diff --git a/vendor/github.com/go-text/typesetting/shaping/output.go b/vendor/github.com/go-text/typesetting/shaping/output.go new file mode 100644 index 0000000..a942bb3 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/shaping/output.go @@ -0,0 +1,338 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package shaping + +import ( + "github.com/go-text/typesetting/di" + "github.com/go-text/typesetting/font" + "golang.org/x/image/math/fixed" +) + +// Glyph describes the attributes of a single glyph from a single +// font face in a shaped output. +type Glyph struct { + // Width is the width of the glyph content, + // expressed as a distance from the [XBearing], + // typically positive + Width fixed.Int26_6 + // Height is the height of the glyph content, + // expressed as a distance from the [YBearing], + // typically negative + Height fixed.Int26_6 + // XBearing is the distance between the dot (with offset applied) and + // the glyph content, typically positive for horizontal text; + // often negative for vertical text. + XBearing fixed.Int26_6 + // YBearing is the distance between the dot (with offset applied) and + // the top of the glyph content, typically positive + YBearing fixed.Int26_6 + // XAdvance is the distance between the current dot (without offset applied) and the next dot. + // It is typically positive for horizontal text, and always zero for vertical text. + XAdvance fixed.Int26_6 + // YAdvance is the distance between the current dot (without offset applied) and the next dot. + // It is typically negative for vertical text, and always zero for horizontal text. + YAdvance fixed.Int26_6 + + // Offsets to be applied to the dot before actually drawing + // the glyph. + // For vertical text, YOffset is typically used to position the glyph + // below the horizontal line at the dot + XOffset, YOffset fixed.Int26_6 + + // ClusterIndex is the lowest rune index of all runes shaped into + // this glyph cluster. All glyphs sharing the same cluster value + // are part of the same cluster and will have identical RuneCount + // and GlyphCount fields. + ClusterIndex int + // RuneCount is the number of input runes shaped into this output + // glyph cluster. + RuneCount int + // GlyphCount is the number of glyphs in this output glyph cluster. + GlyphCount int + GlyphID font.GID + Mask uint32 + + // startLetterSpacing and endLetterSpacing are set when letter spacing is applied, + // measuring the whitespace added on one side (half of the user provided letter spacing) + // The line wrapper will ignore [endLetterSpacing] when deciding where to break, + // and will trim [startLetterSpacing] at the start of the lines + startLetterSpacing, endLetterSpacing fixed.Int26_6 +} + +// LeftSideBearing returns the distance from the glyph's X origin to +// its leftmost edge. This value can be negative if the glyph extends +// across the origin. +func (g Glyph) LeftSideBearing() fixed.Int26_6 { + return g.XBearing +} + +// RightSideBearing returns the distance from the glyph's right edge to +// the edge of the glyph's advance. This value can be negative if the glyph's +// right edge is after the end of its advance. +func (g Glyph) RightSideBearing() fixed.Int26_6 { + return g.XAdvance - g.Width - g.XBearing +} + +// Bounds describes the minor-axis bounds of a line of text. In a LTR or RTL +// layout, it describes the vertical axis. In a BTT or TTB layout, it describes +// the horizontal. +// +// For horizontal text: +// +// - Ascent GLYPH +// | GLYPH +// | GLYPH +// | GLYPH +// | GLYPH +// - Baseline GLYPH +// | GLYPH +// | GLYPH +// | GLYPH +// - Descent GLYPH +// | +// - Gap +// +// For vertical text: +// +// Descent ------- Baseline --------------- Ascent --- Gap +// | | | | +// GLYPH GLYPH GLYPH +// GLYPH GLYPH GLYPH GLYPH GLYPH +type Bounds struct { + // Ascent is the maximum ascent away from the baseline. This value is typically + // positive in coordiate systems that grow up. + Ascent fixed.Int26_6 + // Descent is the maximum descent away from the baseline. This value is typically + // negative in coordinate systems that grow up. + Descent fixed.Int26_6 + // Gap is the height of empty pixels between lines. This value is typically positive + // in coordinate systems that grow up. + Gap fixed.Int26_6 +} + +// LineThickness returns the thickness of a line of text described by b, +// that is its height for horizontal text, its width for vertical text. +func (b Bounds) LineThickness() fixed.Int26_6 { + return b.Ascent - b.Descent + b.Gap +} + +// Output describes the dimensions and content of shaped text. +type Output struct { + // Advance is the distance the Dot has advanced. + // It is typically positive for horizontal text, negative for vertical. + Advance fixed.Int26_6 + // Size is copied from the shaping.Input.Size that produced this Output. + Size fixed.Int26_6 + // Glyphs are the shaped output text. + Glyphs []Glyph + // LineBounds describes the font's suggested line bounding dimensions. The + // dimensions described should contain any glyphs from the given font. + LineBounds Bounds + // GlyphBounds describes a tight bounding box on the specific glyphs contained + // within this output. The dimensions may not be sufficient to contain all + // glyphs within the chosen font. + // + // Its [Gap] field is always zero. + GlyphBounds Bounds + + // Direction is the direction used to shape the text, + // as provided in the Input. + Direction di.Direction + + // Runes describes the runes this output represents from the input text. + Runes Range + + // Face is the font face that this output is rendered in. This is needed in + // the output in order to render each run in a multi-font sequence in the + // correct font. + Face *font.Face +} + +// ToFontUnit converts a metrics (typically found in [Glyph] fields) +// to unscaled font units. +func (o *Output) ToFontUnit(v fixed.Int26_6) float32 { + return float32(v) / float32(o.Size) * float32(o.Face.Upem()) +} + +// FromFontUnit converts an unscaled font value to the current [Size] +func (o *Output) FromFontUnit(v float32) fixed.Int26_6 { + return fixed.Int26_6(v * float32(o.Size) / float32(o.Face.Upem())) +} + +// RecomputeAdvance updates only the Advance field based on the current +// contents of the Glyphs field. It is faster than RecalculateAll(), +// and can be used to speed up line wrapping logic. +func (o *Output) RecomputeAdvance() { + advance := fixed.Int26_6(0) + if o.Direction.IsVertical() { + for _, g := range o.Glyphs { + advance += g.YAdvance + } + } else { // horizontal + for _, g := range o.Glyphs { + advance += g.XAdvance + } + } + o.Advance = advance +} + +// advanceSpaceAware adjust the value in [Advance] +// if a white space character ends the run. +// Any end letter spacing (on the last glyph) is also removed +// +// TODO: should we take into account multiple spaces ? +func (o *Output) advanceSpaceAware() fixed.Int26_6 { + L := len(o.Glyphs) + if L == 0 { + return o.Advance + } + + // adjust the last to account for spaces + lastG := o.Glyphs[L-1] + if o.Direction.IsVertical() { + if lastG.Height == 0 { + return o.Advance - lastG.YAdvance + } + } else { // horizontal + if lastG.Width == 0 { + return o.Advance - lastG.XAdvance + } + } + return o.Advance - lastG.endLetterSpacing +} + +// RecalculateAll updates the all other fields of the Output +// to match the current contents of the Glyphs field. +// This method will fail with UnimplementedDirectionError if the Output +// direction is unimplemented. +func (o *Output) RecalculateAll() { + var ( + advance fixed.Int26_6 + ascent fixed.Int26_6 + descent fixed.Int26_6 + ) + + if o.Direction.IsVertical() { + for i := range o.Glyphs { + g := &o.Glyphs[i] + advance += g.YAdvance + depth := g.XOffset + g.XBearing // start of the glyph + if depth < descent { + descent = depth + } + height := depth + g.Width // end of the glyph + if height > ascent { + ascent = height + } + } + } else { // horizontal + for i := range o.Glyphs { + g := &o.Glyphs[i] + advance += g.XAdvance + height := g.YBearing + g.YOffset + if height > ascent { + ascent = height + } + depth := height + g.Height + if depth < descent { + descent = depth + } + } + } + o.Advance = advance + o.GlyphBounds = Bounds{ + Ascent: ascent, + Descent: descent, + } +} + +// Assuming [Glyphs] comes from an horizontal shaping, +// applies a 90°, clockwise rotation to the whole slice of glyphs, +// to create 'sideways' vertical text. +// +// The [Direction] field is updated by switching the axis to vertical +// and the orientation to "sideways". +// +// [RecalculateAll] should be called afterwards to update [Avance] and [GlyphBounds]. +func (out *Output) sideways() { + for i, g := range out.Glyphs { + // switch height and width + out.Glyphs[i].Width = -g.Height // height is negative + out.Glyphs[i].Height = -g.Width + // compute the bearings + out.Glyphs[i].XBearing = g.YBearing + g.Height + out.Glyphs[i].YBearing = g.Width + // switch advance direction + out.Glyphs[i].XAdvance = 0 + out.Glyphs[i].YAdvance = -g.XAdvance // YAdvance is negative + // apply a rotation around the dot, and position the glyph + // below the dot + out.Glyphs[i].XOffset = g.YOffset + out.Glyphs[i].YOffset = -(g.XOffset + g.XBearing + g.Width) + } + + // adjust direction + out.Direction.SetSideways(true) +} + +// properly update [GlyphBounds] +func (out *Output) moveCrossAxis(d fixed.Int26_6) { + if out.Direction.IsVertical() { + for i := range out.Glyphs { + out.Glyphs[i].XOffset += d + } + } else { + for i := range out.Glyphs { + out.Glyphs[i].YOffset += d + } + } + out.GlyphBounds.Ascent += d + out.GlyphBounds.Descent += d +} + +// AdjustBaselines aligns runs with different baselines. +// +// For vertical text, it centralizes 'sideways' runs, so +// that text with mixed 'upright' and +// 'sideways' orientation is better aligned. +// +// This is currently a no-op for horizontal text. +// +// Note that this method only update cross-axis metrics, +// so that the advance is preserved. As such, it is valid +// to call this method after line wrapping, for instance. +func (l Line) AdjustBaselines() { + if len(l) == 0 { + return + } + firstRun := l[0] + + if firstRun.Direction.Axis() == di.Horizontal { + return + } + + // Centralize sideways runs, to better align + // with upright ones, which are usually visually centered. + // We want to shift all the runs by the same amount, to + // avoid breaking alignment of similar runs (consider "A あ is a pretty char.") + var sidewaysBounds Bounds + for _, run := range l { + if !run.Direction.IsSideways() { + continue + } + if a := run.GlyphBounds.Ascent; a > sidewaysBounds.Ascent { + sidewaysBounds.Ascent = a + } + if d := run.GlyphBounds.Descent; d < sidewaysBounds.Descent { + sidewaysBounds.Descent = d + } + } + // Place the middle of sideways run at the baseline (the zero) + middle := sidewaysBounds.Descent + sidewaysBounds.LineThickness()/2 + for i := range l { + if !l[i].Direction.IsSideways() { + continue + } + l[i].moveCrossAxis(-middle) + } +} diff --git a/vendor/github.com/go-text/typesetting/shaping/paired_delims_table.go b/vendor/github.com/go-text/typesetting/shaping/paired_delims_table.go new file mode 100644 index 0000000..273941f --- /dev/null +++ b/vendor/github.com/go-text/typesetting/shaping/paired_delims_table.go @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package shaping + +// Code generated by typesettings-utils/generators/unicodedata/cmd/main.go DO NOT EDIT. + +var pairedDelims = [...]rune{ + 0x0028, 0x0029, + 0x003c, 0x003e, + 0x005b, 0x005d, + 0x007b, 0x007d, + 0x00ab, 0x00bb, + 0x2018, 0x2019, + 0x201a, 0x201b, + 0x201c, 0x201d, + 0x201e, 0x201f, + 0x2039, 0x203a, + 0x2045, 0x2046, + 0x207d, 0x207e, + 0x208d, 0x208e, + 0x2308, 0x2309, + 0x230a, 0x230b, + 0x2329, 0x232a, + 0x2768, 0x2769, + 0x276a, 0x276b, + 0x276c, 0x276d, + 0x276e, 0x276f, + 0x2770, 0x2771, + 0x2772, 0x2773, + 0x2774, 0x2775, + 0x27c5, 0x27c6, + 0x27e6, 0x27e7, + 0x27e8, 0x27e9, + 0x27ea, 0x27eb, + 0x27ec, 0x27ed, + 0x27ee, 0x27ef, + 0x2983, 0x2984, + 0x2985, 0x2986, + 0x2987, 0x2988, + 0x2989, 0x298a, + 0x298b, 0x298c, + 0x298d, 0x298e, + 0x298f, 0x2990, + 0x2991, 0x2992, + 0x2993, 0x2994, + 0x2995, 0x2996, + 0x2997, 0x2998, + 0x29d8, 0x29d9, + 0x29da, 0x29db, + 0x29fc, 0x29fd, + 0x2e02, 0x2e03, + 0x2e04, 0x2e05, + 0x2e09, 0x2e0a, + 0x2e0c, 0x2e0d, + 0x2e1c, 0x2e1d, + 0x2e20, 0x2e21, + 0x2e22, 0x2e23, + 0x2e24, 0x2e25, + 0x2e26, 0x2e27, + 0x2e28, 0x2e29, + 0x2e42, 0x2e55, + 0x2e56, 0x2e57, + 0x2e58, 0x2e59, + 0x2e5a, 0x2e5b, + 0x2e5c, 0x3008, + 0x3009, 0x300a, + 0x300b, 0x300c, + 0x300d, 0x300e, + 0x300f, 0x3010, + 0x3011, 0x3014, + 0x3015, 0x3016, + 0x3017, 0x3018, + 0x3019, 0x301a, + 0x301b, 0x301d, + 0x301e, 0x301f, + 0xfd3e, 0xfd3f, + 0xfe17, 0xfe18, + 0xfe35, 0xfe36, + 0xfe37, 0xfe38, + 0xfe39, 0xfe3a, + 0xfe3b, 0xfe3c, + 0xfe3d, 0xfe3e, + 0xfe3f, 0xfe40, + 0xfe41, 0xfe42, + 0xfe43, 0xfe44, + 0xfe47, 0xfe48, + 0xfe59, 0xfe5a, + 0xfe5b, 0xfe5c, + 0xfe5d, 0xfe5e, + 0xff08, 0xff09, + 0xff3b, 0xff3d, + 0xff5b, 0xff5d, + 0xff5f, 0xff60, + 0xff62, 0xff63, +} diff --git a/vendor/github.com/go-text/typesetting/shaping/shaping.go b/vendor/github.com/go-text/typesetting/shaping/shaping.go new file mode 100644 index 0000000..2639502 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/shaping/shaping.go @@ -0,0 +1,205 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package shaping + +import ( + "github.com/go-text/typesetting/di" + "github.com/go-text/typesetting/harfbuzz" + "golang.org/x/image/math/fixed" +) + +// HarfbuzzShaper implements the Shaper interface using harfbuzz. +// Reusing this shaper type across multiple shaping operations is +// faster and more memory-efficient than creating a new shaper +// for each operation. +type HarfbuzzShaper struct { + buf *harfbuzz.Buffer + + fonts fontLRU + + features []harfbuzz.Feature +} + +// SetFontCacheSize adjusts the size of the font cache within the shaper. +// It is safe to adjust the size after using the shaper, though shrinking +// it may result in many evictions on the next shaping. +func (h *HarfbuzzShaper) SetFontCacheSize(size int) { + h.fonts.maxSize = size +} + +var _ Shaper = (*HarfbuzzShaper)(nil) + +// Shaper describes the signature of a font shaping operation. +type Shaper interface { + // Shape takes an Input and shapes it into the Output. + Shape(Input) Output +} + +const ( + // scaleShift is the power of 2 with which to automatically scale + // up the input coordinate space of the shaper. This factor will + // be removed prior to returning dimensions. This ensures that the + // returned glyph dimensions take advantage of all of the precision + // that a fixed.Int26_6 can provide. + scaleShift = 6 +) + +// clamp ensures val is in the inclusive range [low,high]. +func clamp(val, low, high int) int { + if val < low { + return low + } + if val > high { + return high + } + return val +} + +// Shape turns an input into an output. +func (t *HarfbuzzShaper) Shape(input Input) Output { + // Prepare to shape the text. + if t.buf == nil { + t.buf = harfbuzz.NewBuffer() + } else { + t.buf.Clear() + } + + runes, start, end := input.Text, input.RunStart, input.RunEnd + if end < start { + // Try to guess what the caller actually wanted. + end, start = start, end + } + start = clamp(start, 0, len(runes)) + end = clamp(end, 0, len(runes)) + t.buf.AddRunes(runes, start, end-start) + + // handle vertical sideways text + isSideways := false + if input.Direction.IsSideways() { + // temporarily switch to horizontal + input.Direction = input.Direction.SwitchAxis() + isSideways = true + } + + t.buf.Props.Direction = input.Direction.Harfbuzz() + t.buf.Props.Language = input.Language + t.buf.Props.Script = input.Script + + // reuse font when possible + font, ok := t.fonts.Get(input.Face.Font) + if !ok { // create a new font and cache it + font = harfbuzz.NewFont(input.Face) + t.fonts.Put(input.Face.Font, font) + } + // adjust the user provided fields + font.XScale = int32(input.Size.Ceil()) << scaleShift + font.YScale = font.XScale + + if L := len(input.FontFeatures); cap(t.features) < L { + t.features = make([]harfbuzz.Feature, L) + } else { + t.features = t.features[0:L] + } + for i, f := range input.FontFeatures { + t.features[i] = harfbuzz.Feature{ + Tag: f.Tag, + Value: f.Value, + Start: harfbuzz.FeatureGlobalStart, + End: harfbuzz.FeatureGlobalEnd, + } + } + + // Actually use harfbuzz to shape the text. + t.buf.Shape(font, t.features) + + // Convert the shaped text into an Output. + glyphs := make([]Glyph, len(t.buf.Info)) + for i := range glyphs { + g := t.buf.Info[i].Glyph + glyphs[i] = Glyph{ + ClusterIndex: t.buf.Info[i].Cluster, + GlyphID: g, + Mask: t.buf.Info[i].Mask, + } + extents, ok := font.GlyphExtents(g) + if !ok { + // Leave the glyph having zero size if it isn't in the font. There + // isn't really anything we can do to recover from such an error. + continue + } + glyphs[i].Width = fixed.I(int(extents.Width)) >> scaleShift + glyphs[i].Height = fixed.I(int(extents.Height)) >> scaleShift + glyphs[i].XBearing = fixed.I(int(extents.XBearing)) >> scaleShift + glyphs[i].YBearing = fixed.I(int(extents.YBearing)) >> scaleShift + glyphs[i].XAdvance = fixed.I(int(t.buf.Pos[i].XAdvance)) >> scaleShift + glyphs[i].YAdvance = fixed.I(int(t.buf.Pos[i].YAdvance)) >> scaleShift + glyphs[i].XOffset = fixed.I(int(t.buf.Pos[i].XOffset)) >> scaleShift + glyphs[i].YOffset = fixed.I(int(t.buf.Pos[i].YOffset)) >> scaleShift + } + countClusters(glyphs, input.RunEnd, input.Direction.Progression()) + out := Output{ + Glyphs: glyphs, + Direction: input.Direction, + Face: input.Face, + Size: input.Size, + } + out.Runes.Offset = input.RunStart + out.Runes.Count = input.RunEnd - input.RunStart + + if isSideways { + // set the Direction to the correct value. + // this is required here so that the following call to ExtentsForDirection + // returns the vertical data. + out.sideways() + } + + fontExtents := font.ExtentsForDirection(out.Direction.Harfbuzz()) + out.LineBounds = Bounds{ + Ascent: fixed.I(int(fontExtents.Ascender)) >> scaleShift, + Descent: fixed.I(int(fontExtents.Descender)) >> scaleShift, + Gap: fixed.I(int(fontExtents.LineGap)) >> scaleShift, + } + out.RecalculateAll() + return out +} + +// countClusters tallies the number of runes and glyphs in each cluster +// and updates the relevant fields on the provided glyph slice. +func countClusters(glyphs []Glyph, textLen int, dir di.Progression) { + currentCluster := -1 + runesInCluster := 0 + glyphsInCluster := 0 + previousCluster := textLen + for i := range glyphs { + g := glyphs[i].ClusterIndex + if g != currentCluster { + // If we're processing a new cluster, count the runes and glyphs + // that compose it. + runesInCluster = 0 + glyphsInCluster = 1 + currentCluster = g + nextCluster := -1 + glyphCountLoop: + for k := i + 1; k < len(glyphs); k++ { + if glyphs[k].ClusterIndex == g { + glyphsInCluster++ + } else { + nextCluster = glyphs[k].ClusterIndex + break glyphCountLoop + } + } + if nextCluster == -1 { + nextCluster = textLen + } + switch dir { + case di.FromTopLeft: + runesInCluster = nextCluster - currentCluster + case di.TowardTopLeft: + runesInCluster = previousCluster - currentCluster + } + previousCluster = g + } + glyphs[i].GlyphCount = glyphsInCluster + glyphs[i].RuneCount = runesInCluster + } +} diff --git a/vendor/github.com/go-text/typesetting/shaping/spacing.go b/vendor/github.com/go-text/typesetting/shaping/spacing.go new file mode 100644 index 0000000..cc16c34 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/shaping/spacing.go @@ -0,0 +1,127 @@ +package shaping + +import ( + "golang.org/x/image/math/fixed" +) + +// AddWordSpacing alters the run, adding [additionalSpacing] on each +// word separator. +// [text] is the input slice used to create the run. +// Note that space is always added, even on boundaries. +// +// See also the convenience function [AddSpacing] to handle a slice of runs. + +// See also https://www.w3.org/TR/css-text-3/#word-separator +func (run *Output) AddWordSpacing(text []rune, additionalSpacing fixed.Int26_6) { + isVertical := run.Direction.IsVertical() + for i, g := range run.Glyphs { + // find the corresponding runes : + // to simplify, we assume a simple one to one rune/glyph mapping + // which should be common in practice for word separators + if !(g.RuneCount == 1 && g.GlyphCount == 1) { + continue + } + r := text[g.ClusterIndex] + switch r { + case '\u0020', // space + '\u00A0', // no-break space + '\u1361', // Ethiopic word space + '\U00010100', '\U00010101', // Aegean word separators + '\U0001039F', // Ugaritic word divider + '\U0001091F': // Phoenician word separator + default: + continue + } + // we have a word separator: add space + // we do it by enlarging the separator glyph advance + // and distributing space around the glyph content + if isVertical { + run.Glyphs[i].YAdvance += additionalSpacing + run.Glyphs[i].YOffset += additionalSpacing / 2 + } else { + run.Glyphs[i].XAdvance += additionalSpacing + run.Glyphs[i].XOffset += additionalSpacing / 2 + } + } + run.RecomputeAdvance() +} + +// AddLetterSpacing alters the run, adding [additionalSpacing] between +// each Harfbuzz clusters. +// +// Space is added at the boundaries if and only if there is an adjacent run, as specified by [isStartRun] and [isEndRun]. +// +// See also the convenience function [AddSpacing] to handle a slice of runs. +// +// See also https://www.w3.org/TR/css-text-3/#letter-spacing-property +func (run *Output) AddLetterSpacing(additionalSpacing fixed.Int26_6, isStartRun, isEndRun bool) { + isVertical := run.Direction.IsVertical() + + halfSpacing := additionalSpacing / 2 + for startGIdx := 0; startGIdx < len(run.Glyphs); { + startGlyph := run.Glyphs[startGIdx] + endGIdx := startGIdx + startGlyph.GlyphCount - 1 + + // start : apply spacing at boundary only if the run is not the first + if startGIdx > 0 || !isStartRun { + if isVertical { + run.Glyphs[startGIdx].YAdvance += halfSpacing + run.Glyphs[startGIdx].YOffset += halfSpacing + } else { + run.Glyphs[startGIdx].XAdvance += halfSpacing + run.Glyphs[startGIdx].XOffset += halfSpacing + } + run.Glyphs[startGIdx].startLetterSpacing += halfSpacing + } + + // end : apply spacing at boundary only if the run is not the last + isLastCluster := startGIdx+startGlyph.GlyphCount >= len(run.Glyphs) + if !isLastCluster || !isEndRun { + if isVertical { + run.Glyphs[endGIdx].YAdvance += halfSpacing + } else { + run.Glyphs[endGIdx].XAdvance += halfSpacing + } + run.Glyphs[endGIdx].endLetterSpacing += halfSpacing + } + + // go to next cluster + startGIdx += startGlyph.GlyphCount + } + + run.RecomputeAdvance() +} + +// does not run RecomputeAdvance +func (run *Output) trimStartLetterSpacing() { + if len(run.Glyphs) == 0 { + return + } + firstG := &run.Glyphs[0] + halfSpacing := firstG.startLetterSpacing + if run.Direction.IsVertical() { + firstG.YAdvance -= halfSpacing + firstG.YOffset -= halfSpacing + } else { + firstG.XAdvance -= halfSpacing + firstG.XOffset -= halfSpacing + } + firstG.startLetterSpacing = 0 +} + +// AddSpacing adds additionnal spacing between words and letters, mutating the given [runs]. +// [text] is the input slice the [runs] refer to. +// +// See the method [Output.AddWordSpacing] and [Output.AddLetterSpacing] for details +// about what spacing actually is. +func AddSpacing(runs []Output, text []rune, wordSpacing, letterSpacing fixed.Int26_6) { + for i := range runs { + isStartRun, isEndRun := i == 0, i == len(runs)-1 + if wordSpacing != 0 { + runs[i].AddWordSpacing(text, wordSpacing) + } + if letterSpacing != 0 { + runs[i].AddLetterSpacing(letterSpacing, isStartRun, isEndRun) + } + } +} diff --git a/vendor/github.com/go-text/typesetting/shaping/wrapping.go b/vendor/github.com/go-text/typesetting/shaping/wrapping.go new file mode 100644 index 0000000..a7e1bc0 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/shaping/wrapping.go @@ -0,0 +1,1131 @@ +package shaping + +import ( + "sort" + + "github.com/go-text/typesetting/di" + "github.com/go-text/typesetting/segmenter" + "golang.org/x/image/math/fixed" +) + +// glyphIndex is the index in a Glyph slice +type glyphIndex = int + +// mapRunesToClusterIndices +// returns a slice that maps rune indicies in the text to the index of the +// first glyph in the glyph cluster containing that rune in the shaped text. +// The indicies are relative to the region of runes covered by the input run. +// To translate an absolute rune index in text into a rune index into the returned +// mapping, subtract run.Runes.Offset first. If the provided buf is large enough to +// hold the return value, it will be used instead of allocating a new slice. +func mapRunesToClusterIndices(dir di.Direction, runes Range, glyphs []Glyph, buf []glyphIndex) []glyphIndex { + if runes.Count <= 0 { + return nil + } + var mapping []glyphIndex + if cap(buf) >= runes.Count { + mapping = buf[:runes.Count] + } else { + mapping = make([]glyphIndex, runes.Count) + } + glyphCursor := 0 + rtl := dir.Progression() == di.TowardTopLeft + if rtl { + glyphCursor = len(glyphs) - 1 + } + // off tracks the offset position of the glyphs from the first rune of the + // shaped text. This must be subtracted from all cluster indicies in order to + // normalize them into the range [0,runes.Count). + off := runes.Offset + for i := 0; i < runes.Count; i++ { + for glyphCursor >= 0 && glyphCursor < len(glyphs) && + ((rtl && glyphs[glyphCursor].ClusterIndex-off <= i) || + (!rtl && glyphs[glyphCursor].ClusterIndex-off < i)) { + if rtl { + glyphCursor-- + } else { + glyphCursor++ + } + } + if rtl { + glyphCursor++ + } else if (glyphCursor >= 0 && glyphCursor < len(glyphs) && + glyphs[glyphCursor].ClusterIndex-off > i) || + (glyphCursor == len(glyphs) && len(glyphs) > 1) { + glyphCursor-- + targetClusterIndex := glyphs[glyphCursor].ClusterIndex - off + for glyphCursor-1 >= 0 && glyphs[glyphCursor-1].ClusterIndex-off == targetClusterIndex { + glyphCursor-- + } + } + if glyphCursor < 0 { + glyphCursor = 0 + } else if glyphCursor >= len(glyphs) { + glyphCursor = len(glyphs) - 1 + } + mapping[i] = glyphCursor + } + return mapping +} + +// mapRuneToClusterIndex finds the lowest-index glyph for the glyph cluster contiaining the rune +// at runeIdx in the source text. It uses a binary search of the glyphs in order to achieve this. +// It is equivalent to using mapRunesToClusterIndices on only a single rune index, and is thus +// more efficient for single lookups while being less efficient for runs which require many +// lookups anyway. +func mapRuneToClusterIndex(dir di.Direction, runes Range, glyphs []Glyph, runeIdx int) glyphIndex { + var index int + rtl := dir.Progression() == di.TowardTopLeft + if !rtl { + index = sort.Search(len(glyphs), func(index int) bool { + return glyphs[index].ClusterIndex-runes.Offset > runeIdx + }) + } else { + index = sort.Search(len(glyphs), func(index int) bool { + return glyphs[index].ClusterIndex-runes.Offset < runeIdx + }) + } + if index < 1 { + return 0 + } + cluster := glyphs[index-1].ClusterIndex + if rtl && cluster-runes.Offset > runeIdx { + return index + } + for index-1 >= 0 && glyphs[index-1].ClusterIndex == cluster { + index-- + } + return index +} + +func mapRunesToClusterIndices2(dir di.Direction, runes Range, glyphs []Glyph, buf []glyphIndex) []glyphIndex { + if runes.Count <= 0 { + return nil + } + var mapping []glyphIndex + if cap(buf) >= runes.Count { + mapping = buf[:runes.Count] + } else { + mapping = make([]glyphIndex, runes.Count) + } + + rtl := dir.Progression() == di.TowardTopLeft + if rtl { + for gIdx := len(glyphs) - 1; gIdx >= 0; gIdx-- { + cluster := glyphs[gIdx].ClusterIndex + clusterEnd := gIdx + for gIdx-1 >= 0 && glyphs[gIdx-1].ClusterIndex == cluster { + gIdx-- + clusterEnd = gIdx + } + var nextCluster int + if gIdx-1 >= 0 { + nextCluster = glyphs[gIdx-1].ClusterIndex + } else { + nextCluster = runes.Count + runes.Offset + } + runesInCluster := nextCluster - cluster + clusterOffset := cluster - runes.Offset + for i := clusterOffset; i <= runesInCluster+clusterOffset && i < len(mapping); i++ { + mapping[i] = clusterEnd + } + } + } else { + for gIdx := 0; gIdx < len(glyphs); gIdx++ { + cluster := glyphs[gIdx].ClusterIndex + clusterStart := gIdx + for gIdx+1 < len(glyphs) && glyphs[gIdx+1].ClusterIndex == cluster { + gIdx++ + } + var nextCluster int + if gIdx+1 < len(glyphs) { + nextCluster = glyphs[gIdx+1].ClusterIndex + } else { + nextCluster = runes.Count + runes.Offset + } + runesInCluster := nextCluster - cluster + clusterOffset := cluster - runes.Offset + for i := clusterOffset; i <= runesInCluster+clusterOffset && i < len(mapping); i++ { + mapping[i] = clusterStart + } + } + } + return mapping +} + +func mapRunesToClusterIndices3(dir di.Direction, runes Range, glyphs []Glyph, buf []glyphIndex) []glyphIndex { + if runes.Count <= 0 { + return nil + } + var mapping []glyphIndex + if cap(buf) >= runes.Count { + mapping = buf[:runes.Count] + } else { + mapping = make([]glyphIndex, runes.Count) + } + + rtl := dir.Progression() == di.TowardTopLeft + if rtl { + for gIdx := len(glyphs) - 1; gIdx >= 0; { + glyph := &glyphs[gIdx] + // go to the start of the cluster + gIdx -= (glyph.GlyphCount - 1) + clusterStart := glyph.ClusterIndex - runes.Offset // map back to [0;runes.Count[ + clusterEnd := glyph.RuneCount + clusterStart + for i := clusterStart; i <= clusterEnd && i < len(mapping); i++ { + mapping[i] = gIdx + } + // go to the next cluster + gIdx-- + } + } else { + for gIdx := 0; gIdx < len(glyphs); { + glyph := &glyphs[gIdx] + clusterStart := glyph.ClusterIndex - runes.Offset // map back to [0;runes.Count[ + clusterEnd := glyph.RuneCount + clusterStart + for i := clusterStart; i <= clusterEnd && i < len(mapping); i++ { + mapping[i] = gIdx + } + // go to the next cluster + gIdx += glyph.GlyphCount + } + } + return mapping +} + +// inclusiveGlyphRange returns the inclusive range of runes and glyphs matching +// the provided start and breakAfter rune positions. +// runeToGlyph must be a valid mapping from the rune representation to the +// glyph reprsentation produced by mapRunesToClusterIndices. +// numGlyphs is the number of glyphs in the output representing the runes +// under consideration. +func inclusiveGlyphRange(dir di.Direction, start, breakAfter int, runeToGlyph []int, numGlyphs int) (glyphStart, glyphEnd glyphIndex) { + rtl := dir.Progression() == di.TowardTopLeft + if rtl { + glyphStart = runeToGlyph[breakAfter] + if start-1 >= 0 { + glyphEnd = runeToGlyph[start-1] - 1 + } else { + glyphEnd = numGlyphs - 1 + } + } else { + glyphStart = runeToGlyph[start] + if breakAfter+1 < len(runeToGlyph) { + glyphEnd = runeToGlyph[breakAfter+1] - 1 + } else { + glyphEnd = numGlyphs - 1 + } + } + return +} + +// cutRun returns the sub-run of run containing glyphs corresponding to the provided +// _inclusive_ rune range. +// if [trimStart] is true, the leading letter spacing is removed +func cutRun(run Output, mapping []glyphIndex, startRune, endRune int, trimStart bool) Output { + // Convert the rune range of interest into an inclusive range within the + // current run's runes. + runeStart := startRune - run.Runes.Offset + runeEnd := endRune - run.Runes.Offset + if runeStart < 0 { + // If the start location is prior to the run of shaped text under consideration, + // just work from the beginning of this run. + runeStart = 0 + } + if runeEnd >= len(mapping) { + // If the break location is after the entire run of shaped text, + // keep through the end of the run. + runeEnd = len(mapping) - 1 + } + glyphStart, glyphEnd := inclusiveGlyphRange(run.Direction, runeStart, runeEnd, mapping, len(run.Glyphs)) + + // Construct a run out of the inclusive glyph range. + run.Glyphs = run.Glyphs[glyphStart : glyphEnd+1] + run.Runes.Count = runeEnd - runeStart + 1 + run.Runes.Offset = run.Runes.Offset + runeStart + if trimStart { + run.trimStartLetterSpacing() + } + run.RecomputeAdvance() + return run +} + +// breakOption represets a location within the rune slice at which +// it may be safe to break a line of text. +type breakOption struct { + // breakAtRune is the index at which it is safe to break. + breakAtRune int +} + +// isValid returns whether a given option violates shaping rules (like breaking +// a shaped text cluster). +func (option breakOption) isValid(runeToGlyph []int, out Output) bool { + breakAfter := option.breakAtRune - out.Runes.Offset + nextRune := breakAfter + 1 + if nextRune < len(runeToGlyph) && breakAfter >= 0 { + // Check if this break is valid. + gIdx := runeToGlyph[breakAfter] + g2Idx := runeToGlyph[nextRune] + cIdx := out.Glyphs[gIdx].ClusterIndex + c2Idx := out.Glyphs[g2Idx].ClusterIndex + if cIdx == c2Idx { + // This break is within a harfbuzz cluster, and is + // therefore invalid. + return false + } + } + return true +} + +// breaker generates line breaking candidates for a text. +type breaker struct { + wordSegmenter *segmenter.LineIterator + graphemeSegmenter *segmenter.GraphemeIterator + totalRunes int + // unusedWordBreak is a break requested from the breaker in a previous iteration + // but which was not chosen as the line ending. Subsequent invocations of + // WrapLine should start with this break. + unusedWordBreak breakOption + // previousWordBreak tracks the previous line breaking candidate, if any. It is + // used to identify the range of runes between the previous and current + // candidate. + previousWordBreak breakOption + // isUnusedWord indicates that the unusedBreak field is valid. + isUnusedWord bool + unusedGraphemeBreak breakOption + isUnusedGrapheme bool +} + +// newBreaker returns a breaker initialized to break the provided text. +func newBreaker(seg *segmenter.Segmenter, text []rune) *breaker { + seg.Init(text) + br := &breaker{ + wordSegmenter: seg.LineIterator(), + graphemeSegmenter: seg.GraphemeIterator(), + totalRunes: len(text), + } + return br +} + +// nextWordRaw returns a naive break candidate on a uax#14 boundary which may be invalid. +func (b *breaker) nextWordRaw() (option breakOption, ok bool) { + if b.wordSegmenter.Next() { + currentSegment := b.wordSegmenter.Line() + // Note : we dont use penalties for Mandatory Breaks so far, + // we could add it with currentSegment.IsMandatoryBreak + option := breakOption{ + breakAtRune: currentSegment.Offset + len(currentSegment.Text) - 1, + } + return option, true + } + // Unicode rules impose to always break at the end + return breakOption{}, false +} + +// nextGraphemeRaw returns a naive break candidate on a uax#29 boundary which may be invalid. +func (b *breaker) nextGraphemeRaw() (option breakOption, ok bool) { + if b.graphemeSegmenter.Next() { + currentSegment := b.graphemeSegmenter.Grapheme() + // Note : we dont use penalties for Mandatory Breaks so far, + // we could add it with currentSegment.IsMandatoryBreak + option := breakOption{ + breakAtRune: currentSegment.Offset + len(currentSegment.Text) - 1, + } + return option, true + } + // Unicode rules impose to always break at the end + return breakOption{}, false +} + +// nextWordBreak returns the next rune offset at which the line can be broken +// on a UAX#14 boundary if any. If it returns false, there are no more candidates. +func (l *breaker) nextWordBreak() (breakOption, bool) { + var option breakOption + if l.isUnusedWord { + option = l.unusedWordBreak + l.isUnusedWord = false + } else { + var breakOk bool + option, breakOk = l.nextWordRaw() + if !breakOk { + return option, false + } + l.previousWordBreak = l.unusedWordBreak + l.unusedWordBreak = option + } + return option, true +} + +func (l *breaker) markWordOptionUnused() { + l.isUnusedWord = true +} + +// nextGraphemeBreak returns the next grapheme cluster boundary break between +// the previous and current word boundary, if any. If it returns false, there are no +// more candidates between the previous and current word boundaries. +func (l *breaker) nextGraphemeBreak() (breakOption, bool) { + for { + var ( + option breakOption + breakOk bool + ) + if l.isUnusedGrapheme { + l.isUnusedGrapheme = false + option = l.unusedGraphemeBreak + breakOk = true + } else { + option, breakOk = l.nextGraphemeRaw() + } + if !breakOk { + return option, false + } + // We don't want to consider the previous word break position in general, as it has already + // been tried. The one exception to this is when we're iterating the very first time, in + // which case the previousWordBreak will have its zero value and we still want to consider + // breaking after the first rune if there's a grapheme cluseter boundary there. + if option.breakAtRune <= l.previousWordBreak.breakAtRune && l.previousWordBreak.breakAtRune > 0 { + continue + } + l.unusedGraphemeBreak = option + if option.breakAtRune > l.unusedWordBreak.breakAtRune { + // We've walked the grapheme iterator past the end of the line wrapping + // candidate, so mark that we may need to re-check this break option + // when evaluating the next segment. + l.isUnusedGrapheme = true + return option, false + } + return option, true + } +} + +func (l *breaker) markGraphemeOptionUnused() { + l.isUnusedGrapheme = true +} + +// Range indicates the location of a sequence of elements within a longer slice. +type Range struct { + Offset int + Count int +} + +// Line holds runs of shaped text wrapped onto a single line. All the contained +// Output should be displayed sequentially on one line. +type Line []Output + +// WrapConfig provides line-wrapper settings. +type WrapConfig struct { + // TruncateAfterLines is the number of lines of text to allow before truncating + // the text. A value of zero means no limit. + TruncateAfterLines int + // Truncator, if provided, will be inserted at the end of a truncated line. This + // feature is only active if TruncateAfterLines is nonzero. + Truncator Output + // TextContinues indicates that the paragraph wrapped by this config is not the + // final paragraph in the text. This alters text truncation when filling the + // final line permitted by TruncateAfterLines. If the text of this paragraph + // does fit entirely on TruncateAfterLines, normally the truncator symbol would + // not be inserted. However, if the overall body of text continues beyond this + // paragraph (indicated by TextContinues), the truncator should still be inserted + // to indicate that further paragraphs of text were truncated. This field has + // no effect if TruncateAfterLines is zero. + TextContinues bool + // BreakPolicy determines under what circumstances the wrapper will consider + // breaking in between UAX#14 line breaking candidates, or "within words" in + // many scripts. + BreakPolicy LineBreakPolicy +} + +// LineBreakPolicy specifies when considering a line break within a "word" or UAX#14 +// segment is allowed. +type LineBreakPolicy uint8 + +const ( + // WhenNecessary means that lines will only be broken within words when the word + // cannot fit on the next line by itself or during truncation to preserve as much + // of the final word as possible. + WhenNecessary LineBreakPolicy = iota + // Never means that words will never be broken internally, allowing them to exceed + // the specified maxWidth. + Never + // Always means that lines will always choose to break within words if it means that + // more text can fit on the line. + Always +) + +func (l LineBreakPolicy) String() string { + switch l { + case WhenNecessary: + return "WhenNecessary" + case Never: + return "Never" + case Always: + return "Always" + default: + return "unknown" + } +} + +// WithTruncator returns a copy of WrapConfig with the Truncator field set to the +// result of shaping input with shaper. +func (w WrapConfig) WithTruncator(shaper Shaper, input Input) WrapConfig { + w.Truncator = shaper.Shape(input) + return w +} + +// runMapper efficiently maps a run to glyph clusters. +type runMapper struct { + // valid indicates that the mapping field is populated. + valid bool + // runIdx is the index of the mapped run within glyphRuns. + runIdx int + // mapping holds the rune->glyph mapping for the run at index mappedRun within + // glyphRuns. + mapping []glyphIndex +} + +// mapRun updates the mapping field to be valid for the given run. It will skip the mapping +// operation if the provided runIdx is equal to the runIdx of the previous call, as the +// current mapping value is already correct. +func (r *runMapper) mapRun(runIdx int, run Output) { + if r.runIdx != runIdx || !r.valid { + r.mapping = mapRunesToClusterIndices3(run.Direction, run.Runes, run.Glyphs, r.mapping) + r.runIdx = runIdx + r.valid = true + } +} + +// RunIterator defines a type that can incrementally provide shaped text. +type RunIterator interface { + // Next returns the next run in the iterator, if any. If there is a next run, + // its index, content, and true will be returned, and the iterator will advance + // to the following element. Otherwise Next returns an undefined index, an empty + // Output, and false. + Next() (index int, run Output, isValid bool) + // Peek returns the same thing Next() would, but does not advance the iterator (so the + // next call to Next() will return the same thing). + Peek() (index int, run Output, isValid bool) + // Save marks the current iterator position such that the iterator can return to it later + // when Restore() is called. Only one position may be saved at a time, with subsequent + // calls to Save() overriding the current value. + Save() + // Restore resets the iteration state to the most recently Save()-ed position. + Restore() +} + +// shapedRunSlice is a [RunIterator] built from already-shaped text. +type shapedRunSlice struct { + runs []Output + idx int + savedIdx int +} + +var _ RunIterator = (*shapedRunSlice)(nil) + +// NewSliceIterator returns a [RunIterator] backed by an already-shaped slice of [Output]s. +func NewSliceIterator(outs []Output) RunIterator { + return &shapedRunSlice{ + runs: outs, + } +} + +// Reset configures the runSlice for reuse with the given shaped text. +func (r *shapedRunSlice) Reset(outs []Output) { + r.runs = outs + r.idx = 0 + r.savedIdx = 0 +} + +// Next implements [RunIterator.Next]. +func (r *shapedRunSlice) Next() (int, Output, bool) { + idx, run, ok := r.Peek() + if ok { + r.idx++ + } + return idx, run, ok +} + +// Peek implements [RunIterator.Peek]. +func (r *shapedRunSlice) Peek() (int, Output, bool) { + if r.idx >= len(r.runs) { + return r.idx, Output{}, false + } + next := r.runs[r.idx] + return r.idx, next, true +} + +// Save implements [RunIterator.Save]. +func (r *shapedRunSlice) Save() { + r.savedIdx = r.idx +} + +// Restore implements [RunIterator.Restore]. +func (r *shapedRunSlice) Restore() { + r.idx = r.savedIdx +} + +// wrapBuffer provides reusable buffers for line wrapping. When using a +// wrapBuffer, returned line wrapping results will use memory stored within +// the buffer. This means that the same buffer cannot be reused for another +// wrapping operation while the wrapped lines are still in use (unless they +// are deeply copied). If necessary, using multiple wrapBuffers can work +// around this restriction. +type wrapBuffer struct { + // paragraph is a buffer holding paragraph allocated (primarily) from subregions + // of the line field. + paragraph []Line + // line is a large buffer of Outputs that is used to build lines. + line []Output + // lineUsed is the index of the first unused element in line. + lineUsed int + // lineExhausted indicates whether the previous shaping used all of line. + lineExhausted bool + // alt is a smaller temporary buffer that holds candidate lines while + // they are being built. + alt []Output + // altAdvance is the sum of the advances of each run in alt. + altAdvance fixed.Int26_6 + // altSave is a slice into alt used to save and restore the state of the alt buffer. + altSave []Output + // altAdvanceSave is the altAdvance of the altSave field. + altAdvanceSave fixed.Int26_6 + // best is a slice holding the best known line. When possible, it + // is a subslice of line, but if line runs out of capacity it will + // be heap allocated. + best []Output + // bestInLine tracks whether the current best is allocated from within line. + bestInLine bool +} + +func (w *wrapBuffer) reset() { + if cap(w.paragraph) < 10 { + w.paragraph = make([]Line, 0, 10) + } + w.paragraph = w.paragraph[:0] + if cap(w.alt) < 10 { + w.alt = make([]Output, 0, 10) + } + w.alt = w.alt[:0] + w.altAdvance = 0 + w.altSave = w.alt[:0] + w.altAdvanceSave = 0 + if cap(w.line) < 100 { + w.line = make([]Output, 0, 100) + } + w.line = w.line[:0] + w.lineUsed = 0 + w.best = nil + w.bestInLine = false + if w.lineExhausted { + w.lineExhausted = false + // Trigger the go slice growth heuristic by appending an element to + // the capacity. + w.line = append(w.line[:cap(w.line)], Output{})[:0] + } +} + +// singleRunParagraph is an optimized helper for quickly constructing +// a []Line containing only a single run. +func (w *wrapBuffer) singleRunParagraph(run Output) []Line { + w.paragraph = w.paragraph[:0] + s := w.line[w.lineUsed : w.lineUsed+1] + s[0] = run + w.paragraphAppend(s) + return w.finalParagraph() +} + +func (w *wrapBuffer) paragraphAppend(line []Output) { + w.paragraph = append(w.paragraph, line) +} + +func (w *wrapBuffer) finalParagraph() []Line { + return w.paragraph +} + +func (w *wrapBuffer) startLine() { + w.alt = w.alt[:0] + w.altAdvance = 0 + w.altSave = w.alt[:0] + w.altAdvanceSave = 0 + w.best = nil + w.bestInLine = false +} + +// candidateLen returns the number of [Output]s in the current line wrapping candidate. +func (w *wrapBuffer) candidateLen() int { return len(w.alt) } + +// candidateAppend adds the given run to the current line wrapping candidate. +func (w *wrapBuffer) candidateAppend(run Output) { + w.alt = append(w.alt, run) + w.altAdvance = w.altAdvance + run.Advance +} + +// candidateSave captures the current state of the line candidate, enabling it to +// be restored by a call to candidateRestore(). Only one state can be saved at a +// time, and a subsequent call to candidateSave will override any current saved +// state. +func (w *wrapBuffer) candidateSave() { + w.altSave = w.alt + w.altAdvanceSave = w.altAdvance +} + +// candidateRestore resets the state of the line candidate to the state at the time +// of the most recent call to candidateSave(). +func (w *wrapBuffer) candidateRestore() { + w.alt = w.altSave + w.altAdvance = w.altAdvanceSave +} + +func (w *wrapBuffer) candidateAdvance() fixed.Int26_6 { + return w.altAdvance +} + +// markCandidateBest marks that the current line wrapping candidate is the best +// known line wrapping candidate with the given suffixes. Providing suffixes does +// not modify the current candidate, but does ensure that the "best" candidate ends +// with them. +func (w *wrapBuffer) markCandidateBest(suffixes ...Output) { + neededLen := len(w.alt) + len(suffixes) + if len(w.line[w.lineUsed:cap(w.line)]) < neededLen { + w.lineExhausted = true + w.best = make([]Output, neededLen) + w.bestInLine = false + } else { + w.best = w.line[w.lineUsed : w.lineUsed+neededLen] + w.bestInLine = true + } + n := copy(w.best, w.alt) + copy(w.best[n:], suffixes) +} + +// hasBest returns whether there is currently a known valid line wrapping candidate +// for the line. +func (w *wrapBuffer) hasBest() bool { + return len(w.best) > 0 +} + +// finalizeBest commits the storage for the current best line and returns it. +func (w *wrapBuffer) finalizeBest() []Output { + if w.bestInLine { + w.lineUsed += len(w.best) + } + return w.best +} + +// LineWrapper holds reusable state for a line wrapping operation. Reusing +// LineWrappers for multiple paragraphs should improve performance. +type LineWrapper struct { + // config holds the current line wrapping settings. + config WrapConfig + // truncating tracks whether the wrapper should be performing truncation. + truncating bool + // seg is an internal storage used to initiate the breaker iterator. + seg segmenter.Segmenter + + // breaker provides line-breaking candidates. + breaker *breaker + + // scratch holds wrapping algorithm storage buffers for reuse. + scratch wrapBuffer + + // mapper tracks rune->glyphCluster mappings. + mapper runMapper + // glyphRuns holds the runs of shaped text being wrapped. + glyphRuns RunIterator + // lineStartRune is the rune index of the first rune on the next line to + // be shaped. + lineStartRune int + // more indicates that the iteration API has more data to return. + more bool +} + +// Prepare initializes the LineWrapper for the given paragraph and shaped text. +// It must be called prior to invoking WrapNextLine. Prepare invalidates any +// lines previously returned by this wrapper. +func (l *LineWrapper) Prepare(config WrapConfig, paragraph []rune, runs RunIterator) { + l.config = config + l.truncating = l.config.TruncateAfterLines > 0 + l.breaker = newBreaker(&l.seg, paragraph) + l.glyphRuns = runs + l.lineStartRune = 0 + l.more = true + l.mapper.valid = false + l.scratch.reset() +} + +// WrapParagraph wraps the paragraph's shaped glyphs to a constant maxWidth. +// It is equivalent to iteratively invoking WrapLine with a constant maxWidth. +// If the config has a non-zero TruncateAfterLines, WrapParagraph will return at most +// that many lines. The truncated return value is the count of runes truncated from +// the end of the text. The returned lines are only valid until the next call to +// [*LineWrapper.WrapParagraph] or [*LineWrapper.Prepare]. +func (l *LineWrapper) WrapParagraph(config WrapConfig, maxWidth int, paragraph []rune, runs RunIterator) (_ []Line, truncated int) { + l.scratch.reset() + // Check whether we can skip line wrapping altogether for the simple single-run-that-fits case. + if !(config.TextContinues && config.TruncateAfterLines == 1) { + runs.Save() + _, firstRun, hasFirst := runs.Next() + _, _, hasSecond := runs.Peek() + if hasFirst && !hasSecond { + if firstRun.Advance.Ceil() <= maxWidth { + return l.scratch.singleRunParagraph(firstRun), 0 + } + } + runs.Restore() + } + + l.Prepare(config, paragraph, runs) + var ( + line WrappedLine + done bool + ) + for !done { + line, done = l.WrapNextLine(maxWidth) + if line.Line != nil { + l.scratch.paragraphAppend(line.Line) + } + } + return l.scratch.finalParagraph(), line.Truncated +} + +// fillUntil tries to fill the line candidate slice with runs until it reaches a run containing the +// provided break option. +func (l *LineWrapper) fillUntil(runs RunIterator, option breakOption) { + currRunIndex, run, more := runs.Peek() + for more && option.breakAtRune >= run.Runes.Count+run.Runes.Offset { + if l.lineStartRune >= run.Runes.Offset+run.Runes.Count { + // Consume the run we peeked (which we know is valid) + _, _, _ = runs.Next() + + currRunIndex, run, more = runs.Peek() + continue + } else if l.lineStartRune > run.Runes.Offset { + // If part of this run has already been used on a previous line, trim + // the runes corresponding to those glyphs off. + l.mapper.mapRun(currRunIndex, run) + isFirstInLine := l.scratch.candidateLen() == 0 + run = cutRun(run, l.mapper.mapping, l.lineStartRune, run.Runes.Count+run.Runes.Offset, isFirstInLine) + } + // While the run being processed doesn't contain the current line breaking + // candidate, just append it to the candidate line. + l.scratch.candidateAppend(run) + // Consume the run we peeked (which we know is valid) + _, _, _ = runs.Next() + + currRunIndex, run, more = runs.Peek() + } +} + +// lineConfig tracks settings for line wrapping a single line of text. +type lineConfig struct { + // truncating indicates whether this line is being truncated (if sufficiently long). + truncating bool + // maxWidth is the maximum space a line can occupy. + maxWidth int + // truncatedMaxWidth holds the maximum width of the line available for text if the truncator + // is occupying part of the line. + truncatedMaxWidth int +} + +// WrappedLine is the result of wrapping one line of text. +type WrappedLine struct { + // Line is the content of the line, as a slice of shaped runs + Line Line + // Truncated is the count of runes truncated from the end of the line, + // if this line was truncated. + Truncated int + // NextLine is the indice (in the input text slice) of the begining + // of the next line. It will equal len(text) if all the text + // fit in one line. + NextLine int +} + +func (l *LineWrapper) postProcessLine(finalLine Line, done bool) (WrappedLine, bool) { + if len(finalLine) > 0 { + finalRun := finalLine[len(finalLine)-1] + + // zero trailing whitespace advance, + // to be coherent with Output.advanceSpaceAware + if L := len(finalRun.Glyphs); L != 0 { + g := &finalRun.Glyphs[L-1] + if finalRun.Direction.IsVertical() { + if g.Height == 0 { + g.YAdvance = 0 + } + } else { // horizontal + if g.Width == 0 { + g.XAdvance = 0 + } + } + finalRun.RecomputeAdvance() + } + + // Update the start position of the next line. + l.lineStartRune = finalRun.Runes.Count + finalRun.Runes.Offset + } + + // Check whether we've exhausted the text. + done = done || l.lineStartRune >= l.breaker.totalRunes + + // Implement truncation if needed. + truncated := 0 + if l.truncating { + l.config.TruncateAfterLines-- + insertTruncator := false + if l.config.TruncateAfterLines == 0 { + done = true + truncated = l.breaker.totalRunes - l.lineStartRune + insertTruncator = truncated > 0 || l.config.TextContinues + } + if insertTruncator { + finalLine = append(finalLine, l.config.Truncator) + } + } + + // Mark the paragraph as complete if needed. + if done { + l.more = false + } + + return WrappedLine{finalLine, truncated, l.lineStartRune}, done +} + +// WrapNextLine wraps the shaped glyphs of a paragraph to a particular max width. +// It is meant to be called iteratively to wrap each line, allowing lines to +// be wrapped to different widths within the same paragraph. When done is true, +// subsequent calls to WrapNextLine (without calling Prepare) will return a nil line. +// +// The returned line is only valid until the next call to +// [*LineWrapper.Prepare] or [*LineWrapper.WrapParagraph]. +func (l *LineWrapper) WrapNextLine(maxWidth int) (out WrappedLine, done bool) { + // If we've already finished the paragraph, don't do any more work. + if !l.more { + return WrappedLine{NextLine: l.lineStartRune}, true + } + + defer func() { + out, done = l.postProcessLine(out.Line, done) + }() + + // If the iterator is empty, return early. + _, firstRun, hasFirst := l.glyphRuns.Peek() + if !hasFirst { + return WrappedLine{}, true + } + l.scratch.startLine() + truncating := l.config.TruncateAfterLines == 1 + + // If we're not truncating, the iterator contains only one run, and that run fits, take the fast path. + if !(l.config.TextContinues && truncating) && firstRun.Runes.Offset == l.lineStartRune && firstRun.Advance.Ceil() <= maxWidth { + // Save current iterator state so we can peek ahead. + l.glyphRuns.Save() + // Advance beyond firstRun, which we already know from the Peek() above. + _, _, _ = l.glyphRuns.Next() + _, _, hasSecond := l.glyphRuns.Peek() + emptyLine := len(firstRun.Glyphs) == 0 + if emptyLine || !hasSecond { + if emptyLine { + // Pass empty lines through as empty. + firstRun.Runes = Range{Count: l.breaker.totalRunes} + } + l.scratch.candidateAppend(firstRun) + l.scratch.markCandidateBest() + return WrappedLine{Line: l.scratch.finalizeBest()}, true + } + // Restore iterator state in preparation for real line wrapping algorithm. + l.glyphRuns.Restore() + } + + config := lineConfig{ + truncating: truncating, + maxWidth: maxWidth, + truncatedMaxWidth: maxWidth - l.config.Truncator.Advance.Ceil(), + } + done = l.wrapNextLine(config) + finalLine := l.scratch.finalizeBest() + return WrappedLine{Line: finalLine}, done +} + +// checkpoint captures both the current candidate line and the corresponding run iteration +// state. These can be restored together by calling restore(). +func (l *LineWrapper) checkpoint() { + l.scratch.candidateSave() + l.glyphRuns.Save() +} + +// restore resets the current candidate line and corresponding run iteration state to the +// values at the last call to checkpoint(). +func (l *LineWrapper) restore() { + l.scratch.candidateRestore() + l.glyphRuns.Restore() +} + +// wrapNextLine iteratively processes line breaking candidates, building a line within the +// wrapper's scratch [WrapBuffer]. It returns whether the paragraph is finished once it has +// successfully built a line. +func (l *LineWrapper) wrapNextLine(config lineConfig) (done bool) { + for { + l.checkpoint() + option, ok := l.breaker.nextWordBreak() + if !ok { + break + } + switch result, candidateRun := l.processBreakOption(option, config); result { + case breakInvalid: + l.restore() + continue + case fits: + l.scratch.markCandidateBest(candidateRun) + continue + case endLine: + // Found a valid line ending the text, append the candidateRun and use it. + l.scratch.markCandidateBest(candidateRun) + return true + case truncated: + // The candidateRun does not fit. + if !l.scratch.hasBest() { + l.scratch.markCandidateBest() + } + if l.config.BreakPolicy == Never { + return true + } + // Fall through to try grapheme breaking. + case newLineBeforeBreak: + l.restore() + // We found a valid line that didn't use this break, so mark that it can be + // reused on the next iteration. + l.breaker.markWordOptionUnused() + if l.config.BreakPolicy == Never || (l.config.BreakPolicy == WhenNecessary && !config.truncating) { + return false + } + // Fall through to try grapheme breaking. + case cannotFit: + if l.config.BreakPolicy == Never { + if config.truncating { + return true + } + l.scratch.markCandidateBest(candidateRun) + return false + } + // Fall through to try grapheme breaking. + } + // Ensure that the grapheme breaking has access to + // all runs we already tried in the iterator. + l.restore() + // segment using UAX#29 grapheme clustering here and try + // breaking again using only those boundaries to find a viable break in cases + // where no UAX#14 breaks were viable above. + for { + l.checkpoint() + option, ok := l.breaker.nextGraphemeBreak() + if !ok { + break + } + switch result, candidateRun := l.processBreakOption(option, config); result { + case breakInvalid: + l.restore() + continue + case fits: + // If we found at least one viable line candidate, we aren't using the word break option. + l.scratch.markCandidateBest(candidateRun) + l.breaker.markWordOptionUnused() + continue + case endLine: + l.scratch.markCandidateBest(candidateRun) + return true + case truncated: + if !l.scratch.hasBest() { + l.scratch.markCandidateBest() + } + return true + case newLineBeforeBreak: + l.restore() + // If we found at least one viable line candidate, we aren't using the word break option. + l.breaker.markWordOptionUnused() + l.breaker.markGraphemeOptionUnused() + return false + case cannotFit: + if config.truncating { + // Don't append the candidate grapheme to leave as much space as possible for the + // truncator. + return true + } + // If no graphemes fit, we should still use one so that the line contains something. Maybe + // the next grapheme will fit on the next line. + l.scratch.markCandidateBest(candidateRun) + l.breaker.markWordOptionUnused() + return false + } + } + return false + } + return true +} + +type processBreakResult uint8 + +const ( + // breakInvalid indicates that the provided break candidate is incompatible with the shaped + // text and should be skipped. + breakInvalid processBreakResult = iota + // endLine indicates that the candidate fits on the line and terminates the text. + endLine + // truncated indicates that the candidate does not fit on the line and that truncation needs to + // occur. + truncated + // newLineBeforeBreak indicates that the candidate contains a valid line, but the latest break + // option could not fit. + newLineBeforeBreak + // fits indicates that the text up to the break option fit within the line and that another break + // option can be attempted. + fits + // cannotFit indicates that this is the first break option on the line, and that even this option cannot + // fit within the space available. When cannotFit is returned, the scratch buffer's candidate will contain + // the run that cannot fit, but it will not be committed as the best option. The choice of how to handle + // this is left to higher-level logic. + cannotFit +) + +// processBreakOption evaluates whether the provided breakOption can fit onto the current line wrapping line. +func (l *LineWrapper) processBreakOption(option breakOption, config lineConfig) (processBreakResult, Output) { + // Discard break options on previous lines. + if option.breakAtRune < l.lineStartRune { + return breakInvalid, Output{} + } + + // Fill candidate line with runs until the run containing the break option. + l.fillUntil(l.glyphRuns, option) + + currRunIndex, run, _ := l.glyphRuns.Peek() + l.mapper.mapRun(currRunIndex, run) + if !option.isValid(l.mapper.mapping, run) { + // Reject invalid line break candidate and acquire a new one. + return breakInvalid, Output{} + } + isFirstInLine := l.scratch.candidateLen() == 0 + candidateRun := cutRun(run, l.mapper.mapping, l.lineStartRune, option.breakAtRune, isFirstInLine) + candidateLineWidth := (candidateRun.advanceSpaceAware() + l.scratch.candidateAdvance()).Ceil() + if candidateLineWidth > config.maxWidth { + // The run doesn't fit on the line. + if !l.scratch.hasBest() { + return cannotFit, candidateRun + } else { + return newLineBeforeBreak, candidateRun + } + } else if config.truncating && candidateLineWidth > config.truncatedMaxWidth { + // The run would not fit if truncated. + finalRunRune := candidateRun.Runes.Count + candidateRun.Runes.Offset + if finalRunRune == l.breaker.totalRunes && !l.config.TextContinues { + // The run contains the entire end of the text, so no truncation is + // necessary. + return endLine, candidateRun + } + // We must truncate the line in order to show it. + return truncated, candidateRun + } else { + // The run does fit on the line. Commit this line as the best known + // line, but keep lineCandidate unmodified so that later break + // options can be attempted to see if a more optimal solution is + // available. + return fits, candidateRun + } +} diff --git a/vendor/github.com/go-text/typesetting/unicodedata/combining_classes.go b/vendor/github.com/go-text/typesetting/unicodedata/combining_classes.go new file mode 100644 index 0000000..115c206 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/unicodedata/combining_classes.go @@ -0,0 +1,1334 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package unicodedata + +import "unicode" + +// Code generated by typesettings-utils/generators/unicodedata/cmd/main.go DO NOT EDIT. + +var combiningClasses = [256]*unicode.RangeTable{ + 0: { + R16: []unicode.Range16{ + {Lo: 0x0000, Hi: 0x02ff, Stride: 1}, + {Lo: 0x034f, Hi: 0x0370, Stride: 33}, + {Lo: 0x0371, Hi: 0x0377, Stride: 1}, + {Lo: 0x037a, Hi: 0x037f, Stride: 1}, + {Lo: 0x0384, Hi: 0x038a, Stride: 1}, + {Lo: 0x038c, Hi: 0x038e, Stride: 2}, + {Lo: 0x038f, Hi: 0x03a1, Stride: 1}, + {Lo: 0x03a3, Hi: 0x0482, Stride: 1}, + {Lo: 0x0488, Hi: 0x052f, Stride: 1}, + {Lo: 0x0531, Hi: 0x0556, Stride: 1}, + {Lo: 0x0559, Hi: 0x058a, Stride: 1}, + {Lo: 0x058d, Hi: 0x058f, Stride: 1}, + {Lo: 0x05be, Hi: 0x05c0, Stride: 2}, + {Lo: 0x05c3, Hi: 0x05c6, Stride: 3}, + {Lo: 0x05d0, Hi: 0x05ea, Stride: 1}, + {Lo: 0x05ef, Hi: 0x05f4, Stride: 1}, + {Lo: 0x0600, Hi: 0x060f, Stride: 1}, + {Lo: 0x061b, Hi: 0x064a, Stride: 1}, + {Lo: 0x0660, Hi: 0x066f, Stride: 1}, + {Lo: 0x0671, Hi: 0x06d5, Stride: 1}, + {Lo: 0x06dd, Hi: 0x06de, Stride: 1}, + {Lo: 0x06e5, Hi: 0x06e6, Stride: 1}, + {Lo: 0x06e9, Hi: 0x06ee, Stride: 5}, + {Lo: 0x06ef, Hi: 0x070d, Stride: 1}, + {Lo: 0x070f, Hi: 0x0710, Stride: 1}, + {Lo: 0x0712, Hi: 0x072f, Stride: 1}, + {Lo: 0x074d, Hi: 0x07b1, Stride: 1}, + {Lo: 0x07c0, Hi: 0x07ea, Stride: 1}, + {Lo: 0x07f4, Hi: 0x07fa, Stride: 1}, + {Lo: 0x07fe, Hi: 0x0815, Stride: 1}, + {Lo: 0x081a, Hi: 0x0824, Stride: 10}, + {Lo: 0x0828, Hi: 0x0830, Stride: 8}, + {Lo: 0x0831, Hi: 0x083e, Stride: 1}, + {Lo: 0x0840, Hi: 0x0858, Stride: 1}, + {Lo: 0x085e, Hi: 0x0860, Stride: 2}, + {Lo: 0x0861, Hi: 0x086a, Stride: 1}, + {Lo: 0x0870, Hi: 0x088e, Stride: 1}, + {Lo: 0x0890, Hi: 0x0891, Stride: 1}, + {Lo: 0x08a0, Hi: 0x08c9, Stride: 1}, + {Lo: 0x08e2, Hi: 0x0900, Stride: 30}, + {Lo: 0x0901, Hi: 0x093b, Stride: 1}, + {Lo: 0x093d, Hi: 0x094c, Stride: 1}, + {Lo: 0x094e, Hi: 0x0950, Stride: 1}, + {Lo: 0x0955, Hi: 0x0983, Stride: 1}, + {Lo: 0x0985, Hi: 0x098c, Stride: 1}, + {Lo: 0x098f, Hi: 0x0990, Stride: 1}, + {Lo: 0x0993, Hi: 0x09a8, Stride: 1}, + {Lo: 0x09aa, Hi: 0x09b0, Stride: 1}, + {Lo: 0x09b2, Hi: 0x09b6, Stride: 4}, + {Lo: 0x09b7, Hi: 0x09b9, Stride: 1}, + {Lo: 0x09bd, Hi: 0x09c4, Stride: 1}, + {Lo: 0x09c7, Hi: 0x09c8, Stride: 1}, + {Lo: 0x09cb, Hi: 0x09cc, Stride: 1}, + {Lo: 0x09ce, Hi: 0x09d7, Stride: 9}, + {Lo: 0x09dc, Hi: 0x09dd, Stride: 1}, + {Lo: 0x09df, Hi: 0x09e3, Stride: 1}, + {Lo: 0x09e6, Hi: 0x09fd, Stride: 1}, + {Lo: 0x0a01, Hi: 0x0a03, Stride: 1}, + {Lo: 0x0a05, Hi: 0x0a0a, Stride: 1}, + {Lo: 0x0a0f, Hi: 0x0a10, Stride: 1}, + {Lo: 0x0a13, Hi: 0x0a28, Stride: 1}, + {Lo: 0x0a2a, Hi: 0x0a30, Stride: 1}, + {Lo: 0x0a32, Hi: 0x0a33, Stride: 1}, + {Lo: 0x0a35, Hi: 0x0a36, Stride: 1}, + {Lo: 0x0a38, Hi: 0x0a39, Stride: 1}, + {Lo: 0x0a3e, Hi: 0x0a42, Stride: 1}, + {Lo: 0x0a47, Hi: 0x0a48, Stride: 1}, + {Lo: 0x0a4b, Hi: 0x0a4c, Stride: 1}, + {Lo: 0x0a51, Hi: 0x0a59, Stride: 8}, + {Lo: 0x0a5a, Hi: 0x0a5c, Stride: 1}, + {Lo: 0x0a5e, Hi: 0x0a66, Stride: 8}, + {Lo: 0x0a67, Hi: 0x0a76, Stride: 1}, + {Lo: 0x0a81, Hi: 0x0a83, Stride: 1}, + {Lo: 0x0a85, Hi: 0x0a8d, Stride: 1}, + {Lo: 0x0a8f, Hi: 0x0a91, Stride: 1}, + {Lo: 0x0a93, Hi: 0x0aa8, Stride: 1}, + {Lo: 0x0aaa, Hi: 0x0ab0, Stride: 1}, + {Lo: 0x0ab2, Hi: 0x0ab3, Stride: 1}, + {Lo: 0x0ab5, Hi: 0x0ab9, Stride: 1}, + {Lo: 0x0abd, Hi: 0x0ac5, Stride: 1}, + {Lo: 0x0ac7, Hi: 0x0ac9, Stride: 1}, + {Lo: 0x0acb, Hi: 0x0acc, Stride: 1}, + {Lo: 0x0ad0, Hi: 0x0ae0, Stride: 16}, + {Lo: 0x0ae1, Hi: 0x0ae3, Stride: 1}, + {Lo: 0x0ae6, Hi: 0x0af1, Stride: 1}, + {Lo: 0x0af9, Hi: 0x0aff, Stride: 1}, + {Lo: 0x0b01, Hi: 0x0b03, Stride: 1}, + {Lo: 0x0b05, Hi: 0x0b0c, Stride: 1}, + {Lo: 0x0b0f, Hi: 0x0b10, Stride: 1}, + {Lo: 0x0b13, Hi: 0x0b28, Stride: 1}, + {Lo: 0x0b2a, Hi: 0x0b30, Stride: 1}, + {Lo: 0x0b32, Hi: 0x0b33, Stride: 1}, + {Lo: 0x0b35, Hi: 0x0b39, Stride: 1}, + {Lo: 0x0b3d, Hi: 0x0b44, Stride: 1}, + {Lo: 0x0b47, Hi: 0x0b48, Stride: 1}, + {Lo: 0x0b4b, Hi: 0x0b4c, Stride: 1}, + {Lo: 0x0b55, Hi: 0x0b57, Stride: 1}, + {Lo: 0x0b5c, Hi: 0x0b5d, Stride: 1}, + {Lo: 0x0b5f, Hi: 0x0b63, Stride: 1}, + {Lo: 0x0b66, Hi: 0x0b77, Stride: 1}, + {Lo: 0x0b82, Hi: 0x0b83, Stride: 1}, + {Lo: 0x0b85, Hi: 0x0b8a, Stride: 1}, + {Lo: 0x0b8e, Hi: 0x0b90, Stride: 1}, + {Lo: 0x0b92, Hi: 0x0b95, Stride: 1}, + {Lo: 0x0b99, Hi: 0x0b9a, Stride: 1}, + {Lo: 0x0b9c, Hi: 0x0b9e, Stride: 2}, + {Lo: 0x0b9f, Hi: 0x0ba3, Stride: 4}, + {Lo: 0x0ba4, Hi: 0x0ba8, Stride: 4}, + {Lo: 0x0ba9, Hi: 0x0baa, Stride: 1}, + {Lo: 0x0bae, Hi: 0x0bb9, Stride: 1}, + {Lo: 0x0bbe, Hi: 0x0bc2, Stride: 1}, + {Lo: 0x0bc6, Hi: 0x0bc8, Stride: 1}, + {Lo: 0x0bca, Hi: 0x0bcc, Stride: 1}, + {Lo: 0x0bd0, Hi: 0x0bd7, Stride: 7}, + {Lo: 0x0be6, Hi: 0x0bfa, Stride: 1}, + {Lo: 0x0c00, Hi: 0x0c0c, Stride: 1}, + {Lo: 0x0c0e, Hi: 0x0c10, Stride: 1}, + {Lo: 0x0c12, Hi: 0x0c28, Stride: 1}, + {Lo: 0x0c2a, Hi: 0x0c39, Stride: 1}, + {Lo: 0x0c3d, Hi: 0x0c44, Stride: 1}, + {Lo: 0x0c46, Hi: 0x0c48, Stride: 1}, + {Lo: 0x0c4a, Hi: 0x0c4c, Stride: 1}, + {Lo: 0x0c58, Hi: 0x0c5a, Stride: 1}, + {Lo: 0x0c5d, Hi: 0x0c60, Stride: 3}, + {Lo: 0x0c61, Hi: 0x0c63, Stride: 1}, + {Lo: 0x0c66, Hi: 0x0c6f, Stride: 1}, + {Lo: 0x0c77, Hi: 0x0c8c, Stride: 1}, + {Lo: 0x0c8e, Hi: 0x0c90, Stride: 1}, + {Lo: 0x0c92, Hi: 0x0ca8, Stride: 1}, + {Lo: 0x0caa, Hi: 0x0cb3, Stride: 1}, + {Lo: 0x0cb5, Hi: 0x0cb9, Stride: 1}, + {Lo: 0x0cbd, Hi: 0x0cc4, Stride: 1}, + {Lo: 0x0cc6, Hi: 0x0cc8, Stride: 1}, + {Lo: 0x0cca, Hi: 0x0ccc, Stride: 1}, + {Lo: 0x0cd5, Hi: 0x0cd6, Stride: 1}, + {Lo: 0x0cdd, Hi: 0x0cde, Stride: 1}, + {Lo: 0x0ce0, Hi: 0x0ce3, Stride: 1}, + {Lo: 0x0ce6, Hi: 0x0cef, Stride: 1}, + {Lo: 0x0cf1, Hi: 0x0cf3, Stride: 1}, + {Lo: 0x0d00, Hi: 0x0d0c, Stride: 1}, + {Lo: 0x0d0e, Hi: 0x0d10, Stride: 1}, + {Lo: 0x0d12, Hi: 0x0d3a, Stride: 1}, + {Lo: 0x0d3d, Hi: 0x0d44, Stride: 1}, + {Lo: 0x0d46, Hi: 0x0d48, Stride: 1}, + {Lo: 0x0d4a, Hi: 0x0d4c, Stride: 1}, + {Lo: 0x0d4e, Hi: 0x0d4f, Stride: 1}, + {Lo: 0x0d54, Hi: 0x0d63, Stride: 1}, + {Lo: 0x0d66, Hi: 0x0d7f, Stride: 1}, + {Lo: 0x0d81, Hi: 0x0d83, Stride: 1}, + {Lo: 0x0d85, Hi: 0x0d96, Stride: 1}, + {Lo: 0x0d9a, Hi: 0x0db1, Stride: 1}, + {Lo: 0x0db3, Hi: 0x0dbb, Stride: 1}, + {Lo: 0x0dbd, Hi: 0x0dc0, Stride: 3}, + {Lo: 0x0dc1, Hi: 0x0dc6, Stride: 1}, + {Lo: 0x0dcf, Hi: 0x0dd4, Stride: 1}, + {Lo: 0x0dd6, Hi: 0x0dd8, Stride: 2}, + {Lo: 0x0dd9, Hi: 0x0ddf, Stride: 1}, + {Lo: 0x0de6, Hi: 0x0def, Stride: 1}, + {Lo: 0x0df2, Hi: 0x0df4, Stride: 1}, + {Lo: 0x0e01, Hi: 0x0e37, Stride: 1}, + {Lo: 0x0e3f, Hi: 0x0e47, Stride: 1}, + {Lo: 0x0e4c, Hi: 0x0e5b, Stride: 1}, + {Lo: 0x0e81, Hi: 0x0e82, Stride: 1}, + {Lo: 0x0e84, Hi: 0x0e86, Stride: 2}, + {Lo: 0x0e87, Hi: 0x0e8a, Stride: 1}, + {Lo: 0x0e8c, Hi: 0x0ea3, Stride: 1}, + {Lo: 0x0ea5, Hi: 0x0ea7, Stride: 2}, + {Lo: 0x0ea8, Hi: 0x0eb7, Stride: 1}, + {Lo: 0x0ebb, Hi: 0x0ebd, Stride: 1}, + {Lo: 0x0ec0, Hi: 0x0ec4, Stride: 1}, + {Lo: 0x0ec6, Hi: 0x0ecc, Stride: 6}, + {Lo: 0x0ecd, Hi: 0x0ece, Stride: 1}, + {Lo: 0x0ed0, Hi: 0x0ed9, Stride: 1}, + {Lo: 0x0edc, Hi: 0x0edf, Stride: 1}, + {Lo: 0x0f00, Hi: 0x0f17, Stride: 1}, + {Lo: 0x0f1a, Hi: 0x0f34, Stride: 1}, + {Lo: 0x0f36, Hi: 0x0f3a, Stride: 2}, + {Lo: 0x0f3b, Hi: 0x0f47, Stride: 1}, + {Lo: 0x0f49, Hi: 0x0f6c, Stride: 1}, + {Lo: 0x0f73, Hi: 0x0f75, Stride: 2}, + {Lo: 0x0f76, Hi: 0x0f79, Stride: 1}, + {Lo: 0x0f7e, Hi: 0x0f7f, Stride: 1}, + {Lo: 0x0f81, Hi: 0x0f85, Stride: 4}, + {Lo: 0x0f88, Hi: 0x0f97, Stride: 1}, + {Lo: 0x0f99, Hi: 0x0fbc, Stride: 1}, + {Lo: 0x0fbe, Hi: 0x0fc5, Stride: 1}, + {Lo: 0x0fc7, Hi: 0x0fcc, Stride: 1}, + {Lo: 0x0fce, Hi: 0x0fda, Stride: 1}, + {Lo: 0x1000, Hi: 0x1036, Stride: 1}, + {Lo: 0x1038, Hi: 0x103b, Stride: 3}, + {Lo: 0x103c, Hi: 0x108c, Stride: 1}, + {Lo: 0x108e, Hi: 0x10c5, Stride: 1}, + {Lo: 0x10c7, Hi: 0x10cd, Stride: 6}, + {Lo: 0x10d0, Hi: 0x1248, Stride: 1}, + {Lo: 0x124a, Hi: 0x124d, Stride: 1}, + {Lo: 0x1250, Hi: 0x1256, Stride: 1}, + {Lo: 0x1258, Hi: 0x125a, Stride: 2}, + {Lo: 0x125b, Hi: 0x125d, Stride: 1}, + {Lo: 0x1260, Hi: 0x1288, Stride: 1}, + {Lo: 0x128a, Hi: 0x128d, Stride: 1}, + {Lo: 0x1290, Hi: 0x12b0, Stride: 1}, + {Lo: 0x12b2, Hi: 0x12b5, Stride: 1}, + {Lo: 0x12b8, Hi: 0x12be, Stride: 1}, + {Lo: 0x12c0, Hi: 0x12c2, Stride: 2}, + {Lo: 0x12c3, Hi: 0x12c5, Stride: 1}, + {Lo: 0x12c8, Hi: 0x12d6, Stride: 1}, + {Lo: 0x12d8, Hi: 0x1310, Stride: 1}, + {Lo: 0x1312, Hi: 0x1315, Stride: 1}, + {Lo: 0x1318, Hi: 0x135a, Stride: 1}, + {Lo: 0x1360, Hi: 0x137c, Stride: 1}, + {Lo: 0x1380, Hi: 0x1399, Stride: 1}, + {Lo: 0x13a0, Hi: 0x13f5, Stride: 1}, + {Lo: 0x13f8, Hi: 0x13fd, Stride: 1}, + {Lo: 0x1400, Hi: 0x169c, Stride: 1}, + {Lo: 0x16a0, Hi: 0x16f8, Stride: 1}, + {Lo: 0x1700, Hi: 0x1713, Stride: 1}, + {Lo: 0x171f, Hi: 0x1733, Stride: 1}, + {Lo: 0x1735, Hi: 0x1736, Stride: 1}, + {Lo: 0x1740, Hi: 0x1753, Stride: 1}, + {Lo: 0x1760, Hi: 0x176c, Stride: 1}, + {Lo: 0x176e, Hi: 0x1770, Stride: 1}, + {Lo: 0x1772, Hi: 0x1773, Stride: 1}, + {Lo: 0x1780, Hi: 0x17d1, Stride: 1}, + {Lo: 0x17d3, Hi: 0x17dc, Stride: 1}, + {Lo: 0x17e0, Hi: 0x17e9, Stride: 1}, + {Lo: 0x17f0, Hi: 0x17f9, Stride: 1}, + {Lo: 0x1800, Hi: 0x1819, Stride: 1}, + {Lo: 0x1820, Hi: 0x1878, Stride: 1}, + {Lo: 0x1880, Hi: 0x18a8, Stride: 1}, + {Lo: 0x18aa, Hi: 0x18b0, Stride: 6}, + {Lo: 0x18b1, Hi: 0x18f5, Stride: 1}, + {Lo: 0x1900, Hi: 0x191e, Stride: 1}, + {Lo: 0x1920, Hi: 0x192b, Stride: 1}, + {Lo: 0x1930, Hi: 0x1938, Stride: 1}, + {Lo: 0x1940, Hi: 0x1944, Stride: 4}, + {Lo: 0x1945, Hi: 0x196d, Stride: 1}, + {Lo: 0x1970, Hi: 0x1974, Stride: 1}, + {Lo: 0x1980, Hi: 0x19ab, Stride: 1}, + {Lo: 0x19b0, Hi: 0x19c9, Stride: 1}, + {Lo: 0x19d0, Hi: 0x19da, Stride: 1}, + {Lo: 0x19de, Hi: 0x1a16, Stride: 1}, + {Lo: 0x1a19, Hi: 0x1a1b, Stride: 1}, + {Lo: 0x1a1e, Hi: 0x1a5e, Stride: 1}, + {Lo: 0x1a61, Hi: 0x1a74, Stride: 1}, + {Lo: 0x1a80, Hi: 0x1a89, Stride: 1}, + {Lo: 0x1a90, Hi: 0x1a99, Stride: 1}, + {Lo: 0x1aa0, Hi: 0x1aad, Stride: 1}, + {Lo: 0x1abe, Hi: 0x1b00, Stride: 66}, + {Lo: 0x1b01, Hi: 0x1b33, Stride: 1}, + {Lo: 0x1b35, Hi: 0x1b43, Stride: 1}, + {Lo: 0x1b45, Hi: 0x1b4c, Stride: 1}, + {Lo: 0x1b50, Hi: 0x1b6a, Stride: 1}, + {Lo: 0x1b74, Hi: 0x1b7e, Stride: 1}, + {Lo: 0x1b80, Hi: 0x1ba9, Stride: 1}, + {Lo: 0x1bac, Hi: 0x1be5, Stride: 1}, + {Lo: 0x1be7, Hi: 0x1bf1, Stride: 1}, + {Lo: 0x1bfc, Hi: 0x1c36, Stride: 1}, + {Lo: 0x1c3b, Hi: 0x1c49, Stride: 1}, + {Lo: 0x1c4d, Hi: 0x1c88, Stride: 1}, + {Lo: 0x1c90, Hi: 0x1cba, Stride: 1}, + {Lo: 0x1cbd, Hi: 0x1cc7, Stride: 1}, + {Lo: 0x1cd3, Hi: 0x1ce1, Stride: 14}, + {Lo: 0x1ce9, Hi: 0x1cec, Stride: 1}, + {Lo: 0x1cee, Hi: 0x1cf3, Stride: 1}, + {Lo: 0x1cf5, Hi: 0x1cf7, Stride: 1}, + {Lo: 0x1cfa, Hi: 0x1d00, Stride: 6}, + {Lo: 0x1d01, Hi: 0x1dbf, Stride: 1}, + {Lo: 0x1e00, Hi: 0x1f15, Stride: 1}, + {Lo: 0x1f18, Hi: 0x1f1d, Stride: 1}, + {Lo: 0x1f20, Hi: 0x1f45, Stride: 1}, + {Lo: 0x1f48, Hi: 0x1f4d, Stride: 1}, + {Lo: 0x1f50, Hi: 0x1f57, Stride: 1}, + {Lo: 0x1f59, Hi: 0x1f5f, Stride: 2}, + {Lo: 0x1f60, Hi: 0x1f7d, Stride: 1}, + {Lo: 0x1f80, Hi: 0x1fb4, Stride: 1}, + {Lo: 0x1fb6, Hi: 0x1fc4, Stride: 1}, + {Lo: 0x1fc6, Hi: 0x1fd3, Stride: 1}, + {Lo: 0x1fd6, Hi: 0x1fdb, Stride: 1}, + {Lo: 0x1fdd, Hi: 0x1fef, Stride: 1}, + {Lo: 0x1ff2, Hi: 0x1ff4, Stride: 1}, + {Lo: 0x1ff6, Hi: 0x1ffe, Stride: 1}, + {Lo: 0x2000, Hi: 0x2064, Stride: 1}, + {Lo: 0x2066, Hi: 0x2071, Stride: 1}, + {Lo: 0x2074, Hi: 0x208e, Stride: 1}, + {Lo: 0x2090, Hi: 0x209c, Stride: 1}, + {Lo: 0x20a0, Hi: 0x20c0, Stride: 1}, + {Lo: 0x20dd, Hi: 0x20e0, Stride: 1}, + {Lo: 0x20e2, Hi: 0x20e4, Stride: 1}, + {Lo: 0x2100, Hi: 0x218b, Stride: 1}, + {Lo: 0x2190, Hi: 0x2426, Stride: 1}, + {Lo: 0x2440, Hi: 0x244a, Stride: 1}, + {Lo: 0x2460, Hi: 0x2b73, Stride: 1}, + {Lo: 0x2b76, Hi: 0x2b95, Stride: 1}, + {Lo: 0x2b97, Hi: 0x2cee, Stride: 1}, + {Lo: 0x2cf2, Hi: 0x2cf3, Stride: 1}, + {Lo: 0x2cf9, Hi: 0x2d25, Stride: 1}, + {Lo: 0x2d27, Hi: 0x2d2d, Stride: 6}, + {Lo: 0x2d30, Hi: 0x2d67, Stride: 1}, + {Lo: 0x2d6f, Hi: 0x2d70, Stride: 1}, + {Lo: 0x2d80, Hi: 0x2d96, Stride: 1}, + {Lo: 0x2da0, Hi: 0x2da6, Stride: 1}, + {Lo: 0x2da8, Hi: 0x2dae, Stride: 1}, + {Lo: 0x2db0, Hi: 0x2db6, Stride: 1}, + {Lo: 0x2db8, Hi: 0x2dbe, Stride: 1}, + {Lo: 0x2dc0, Hi: 0x2dc6, Stride: 1}, + {Lo: 0x2dc8, Hi: 0x2dce, Stride: 1}, + {Lo: 0x2dd0, Hi: 0x2dd6, Stride: 1}, + {Lo: 0x2dd8, Hi: 0x2dde, Stride: 1}, + {Lo: 0x2e00, Hi: 0x2e5d, Stride: 1}, + {Lo: 0x2e80, Hi: 0x2e99, Stride: 1}, + {Lo: 0x2e9b, Hi: 0x2ef3, Stride: 1}, + {Lo: 0x2f00, Hi: 0x2fd5, Stride: 1}, + {Lo: 0x2ff0, Hi: 0x3029, Stride: 1}, + {Lo: 0x3030, Hi: 0x303f, Stride: 1}, + {Lo: 0x3041, Hi: 0x3096, Stride: 1}, + {Lo: 0x309b, Hi: 0x30ff, Stride: 1}, + {Lo: 0x3105, Hi: 0x312f, Stride: 1}, + {Lo: 0x3131, Hi: 0x318e, Stride: 1}, + {Lo: 0x3190, Hi: 0x31e3, Stride: 1}, + {Lo: 0x31ef, Hi: 0x321e, Stride: 1}, + {Lo: 0x3220, Hi: 0x3400, Stride: 1}, + {Lo: 0x4dbf, Hi: 0x4e00, Stride: 1}, + {Lo: 0x9fff, Hi: 0xa48c, Stride: 1}, + {Lo: 0xa490, Hi: 0xa4c6, Stride: 1}, + {Lo: 0xa4d0, Hi: 0xa62b, Stride: 1}, + {Lo: 0xa640, Hi: 0xa66e, Stride: 1}, + {Lo: 0xa670, Hi: 0xa673, Stride: 1}, + {Lo: 0xa67e, Hi: 0xa69d, Stride: 1}, + {Lo: 0xa6a0, Hi: 0xa6ef, Stride: 1}, + {Lo: 0xa6f2, Hi: 0xa6f7, Stride: 1}, + {Lo: 0xa700, Hi: 0xa7ca, Stride: 1}, + {Lo: 0xa7d0, Hi: 0xa7d1, Stride: 1}, + {Lo: 0xa7d3, Hi: 0xa7d5, Stride: 2}, + {Lo: 0xa7d6, Hi: 0xa7d9, Stride: 1}, + {Lo: 0xa7f2, Hi: 0xa805, Stride: 1}, + {Lo: 0xa807, Hi: 0xa82b, Stride: 1}, + {Lo: 0xa830, Hi: 0xa839, Stride: 1}, + {Lo: 0xa840, Hi: 0xa877, Stride: 1}, + {Lo: 0xa880, Hi: 0xa8c3, Stride: 1}, + {Lo: 0xa8c5, Hi: 0xa8ce, Stride: 9}, + {Lo: 0xa8cf, Hi: 0xa8d9, Stride: 1}, + {Lo: 0xa8f2, Hi: 0xa92a, Stride: 1}, + {Lo: 0xa92e, Hi: 0xa952, Stride: 1}, + {Lo: 0xa95f, Hi: 0xa97c, Stride: 1}, + {Lo: 0xa980, Hi: 0xa9b2, Stride: 1}, + {Lo: 0xa9b4, Hi: 0xa9bf, Stride: 1}, + {Lo: 0xa9c1, Hi: 0xa9cd, Stride: 1}, + {Lo: 0xa9cf, Hi: 0xa9d9, Stride: 1}, + {Lo: 0xa9de, Hi: 0xa9fe, Stride: 1}, + {Lo: 0xaa00, Hi: 0xaa36, Stride: 1}, + {Lo: 0xaa40, Hi: 0xaa4d, Stride: 1}, + {Lo: 0xaa50, Hi: 0xaa59, Stride: 1}, + {Lo: 0xaa5c, Hi: 0xaaaf, Stride: 1}, + {Lo: 0xaab1, Hi: 0xaab5, Stride: 4}, + {Lo: 0xaab6, Hi: 0xaab9, Stride: 3}, + {Lo: 0xaaba, Hi: 0xaabd, Stride: 1}, + {Lo: 0xaac0, Hi: 0xaac2, Stride: 2}, + {Lo: 0xaadb, Hi: 0xaaf5, Stride: 1}, + {Lo: 0xab01, Hi: 0xab06, Stride: 1}, + {Lo: 0xab09, Hi: 0xab0e, Stride: 1}, + {Lo: 0xab11, Hi: 0xab16, Stride: 1}, + {Lo: 0xab20, Hi: 0xab26, Stride: 1}, + {Lo: 0xab28, Hi: 0xab2e, Stride: 1}, + {Lo: 0xab30, Hi: 0xab6b, Stride: 1}, + {Lo: 0xab70, Hi: 0xabec, Stride: 1}, + {Lo: 0xabf0, Hi: 0xabf9, Stride: 1}, + {Lo: 0xac00, Hi: 0xd7a3, Stride: 11171}, + {Lo: 0xd7b0, Hi: 0xd7c6, Stride: 1}, + {Lo: 0xd7cb, Hi: 0xd7fb, Stride: 1}, + {Lo: 0xd800, Hi: 0xdb7f, Stride: 895}, + {Lo: 0xdb80, Hi: 0xdbff, Stride: 127}, + {Lo: 0xdc00, Hi: 0xdfff, Stride: 1023}, + {Lo: 0xe000, Hi: 0xf8ff, Stride: 6399}, + {Lo: 0xf900, Hi: 0xfa6d, Stride: 1}, + {Lo: 0xfa70, Hi: 0xfad9, Stride: 1}, + {Lo: 0xfb00, Hi: 0xfb06, Stride: 1}, + {Lo: 0xfb13, Hi: 0xfb17, Stride: 1}, + {Lo: 0xfb1d, Hi: 0xfb1f, Stride: 2}, + {Lo: 0xfb20, Hi: 0xfb36, Stride: 1}, + {Lo: 0xfb38, Hi: 0xfb3c, Stride: 1}, + {Lo: 0xfb3e, Hi: 0xfb40, Stride: 2}, + {Lo: 0xfb41, Hi: 0xfb43, Stride: 2}, + {Lo: 0xfb44, Hi: 0xfb46, Stride: 2}, + {Lo: 0xfb47, Hi: 0xfbc2, Stride: 1}, + {Lo: 0xfbd3, Hi: 0xfd8f, Stride: 1}, + {Lo: 0xfd92, Hi: 0xfdc7, Stride: 1}, + {Lo: 0xfdcf, Hi: 0xfdf0, Stride: 33}, + {Lo: 0xfdf1, Hi: 0xfe19, Stride: 1}, + {Lo: 0xfe30, Hi: 0xfe52, Stride: 1}, + {Lo: 0xfe54, Hi: 0xfe66, Stride: 1}, + {Lo: 0xfe68, Hi: 0xfe6b, Stride: 1}, + {Lo: 0xfe70, Hi: 0xfe74, Stride: 1}, + {Lo: 0xfe76, Hi: 0xfefc, Stride: 1}, + {Lo: 0xfeff, Hi: 0xff01, Stride: 2}, + {Lo: 0xff02, Hi: 0xffbe, Stride: 1}, + {Lo: 0xffc2, Hi: 0xffc7, Stride: 1}, + {Lo: 0xffca, Hi: 0xffcf, Stride: 1}, + {Lo: 0xffd2, Hi: 0xffd7, Stride: 1}, + {Lo: 0xffda, Hi: 0xffdc, Stride: 1}, + {Lo: 0xffe0, Hi: 0xffe6, Stride: 1}, + {Lo: 0xffe8, Hi: 0xffee, Stride: 1}, + {Lo: 0xfff9, Hi: 0xfffd, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x10000, Hi: 0x1000b, Stride: 1}, + {Lo: 0x1000d, Hi: 0x10026, Stride: 1}, + {Lo: 0x10028, Hi: 0x1003a, Stride: 1}, + {Lo: 0x1003c, Hi: 0x1003d, Stride: 1}, + {Lo: 0x1003f, Hi: 0x1004d, Stride: 1}, + {Lo: 0x10050, Hi: 0x1005d, Stride: 1}, + {Lo: 0x10080, Hi: 0x100fa, Stride: 1}, + {Lo: 0x10100, Hi: 0x10102, Stride: 1}, + {Lo: 0x10107, Hi: 0x10133, Stride: 1}, + {Lo: 0x10137, Hi: 0x1018e, Stride: 1}, + {Lo: 0x10190, Hi: 0x1019c, Stride: 1}, + {Lo: 0x101a0, Hi: 0x101d0, Stride: 48}, + {Lo: 0x101d1, Hi: 0x101fc, Stride: 1}, + {Lo: 0x10280, Hi: 0x1029c, Stride: 1}, + {Lo: 0x102a0, Hi: 0x102d0, Stride: 1}, + {Lo: 0x102e1, Hi: 0x102fb, Stride: 1}, + {Lo: 0x10300, Hi: 0x10323, Stride: 1}, + {Lo: 0x1032d, Hi: 0x1034a, Stride: 1}, + {Lo: 0x10350, Hi: 0x10375, Stride: 1}, + {Lo: 0x10380, Hi: 0x1039d, Stride: 1}, + {Lo: 0x1039f, Hi: 0x103c3, Stride: 1}, + {Lo: 0x103c8, Hi: 0x103d5, Stride: 1}, + {Lo: 0x10400, Hi: 0x1049d, Stride: 1}, + {Lo: 0x104a0, Hi: 0x104a9, Stride: 1}, + {Lo: 0x104b0, Hi: 0x104d3, Stride: 1}, + {Lo: 0x104d8, Hi: 0x104fb, Stride: 1}, + {Lo: 0x10500, Hi: 0x10527, Stride: 1}, + {Lo: 0x10530, Hi: 0x10563, Stride: 1}, + {Lo: 0x1056f, Hi: 0x1057a, Stride: 1}, + {Lo: 0x1057c, Hi: 0x1058a, Stride: 1}, + {Lo: 0x1058c, Hi: 0x10592, Stride: 1}, + {Lo: 0x10594, Hi: 0x10595, Stride: 1}, + {Lo: 0x10597, Hi: 0x105a1, Stride: 1}, + {Lo: 0x105a3, Hi: 0x105b1, Stride: 1}, + {Lo: 0x105b3, Hi: 0x105b9, Stride: 1}, + {Lo: 0x105bb, Hi: 0x105bc, Stride: 1}, + {Lo: 0x10600, Hi: 0x10736, Stride: 1}, + {Lo: 0x10740, Hi: 0x10755, Stride: 1}, + {Lo: 0x10760, Hi: 0x10767, Stride: 1}, + {Lo: 0x10780, Hi: 0x10785, Stride: 1}, + {Lo: 0x10787, Hi: 0x107b0, Stride: 1}, + {Lo: 0x107b2, Hi: 0x107ba, Stride: 1}, + {Lo: 0x10800, Hi: 0x10805, Stride: 1}, + {Lo: 0x10808, Hi: 0x1080a, Stride: 2}, + {Lo: 0x1080b, Hi: 0x10835, Stride: 1}, + {Lo: 0x10837, Hi: 0x10838, Stride: 1}, + {Lo: 0x1083c, Hi: 0x1083f, Stride: 3}, + {Lo: 0x10840, Hi: 0x10855, Stride: 1}, + {Lo: 0x10857, Hi: 0x1089e, Stride: 1}, + {Lo: 0x108a7, Hi: 0x108af, Stride: 1}, + {Lo: 0x108e0, Hi: 0x108f2, Stride: 1}, + {Lo: 0x108f4, Hi: 0x108f5, Stride: 1}, + {Lo: 0x108fb, Hi: 0x1091b, Stride: 1}, + {Lo: 0x1091f, Hi: 0x10939, Stride: 1}, + {Lo: 0x1093f, Hi: 0x10980, Stride: 65}, + {Lo: 0x10981, Hi: 0x109b7, Stride: 1}, + {Lo: 0x109bc, Hi: 0x109cf, Stride: 1}, + {Lo: 0x109d2, Hi: 0x10a03, Stride: 1}, + {Lo: 0x10a05, Hi: 0x10a06, Stride: 1}, + {Lo: 0x10a0c, Hi: 0x10a10, Stride: 2}, + {Lo: 0x10a11, Hi: 0x10a13, Stride: 1}, + {Lo: 0x10a15, Hi: 0x10a17, Stride: 1}, + {Lo: 0x10a19, Hi: 0x10a35, Stride: 1}, + {Lo: 0x10a40, Hi: 0x10a48, Stride: 1}, + {Lo: 0x10a50, Hi: 0x10a58, Stride: 1}, + {Lo: 0x10a60, Hi: 0x10a9f, Stride: 1}, + {Lo: 0x10ac0, Hi: 0x10ae4, Stride: 1}, + {Lo: 0x10aeb, Hi: 0x10af6, Stride: 1}, + {Lo: 0x10b00, Hi: 0x10b35, Stride: 1}, + {Lo: 0x10b39, Hi: 0x10b55, Stride: 1}, + {Lo: 0x10b58, Hi: 0x10b72, Stride: 1}, + {Lo: 0x10b78, Hi: 0x10b91, Stride: 1}, + {Lo: 0x10b99, Hi: 0x10b9c, Stride: 1}, + {Lo: 0x10ba9, Hi: 0x10baf, Stride: 1}, + {Lo: 0x10c00, Hi: 0x10c48, Stride: 1}, + {Lo: 0x10c80, Hi: 0x10cb2, Stride: 1}, + {Lo: 0x10cc0, Hi: 0x10cf2, Stride: 1}, + {Lo: 0x10cfa, Hi: 0x10d23, Stride: 1}, + {Lo: 0x10d30, Hi: 0x10d39, Stride: 1}, + {Lo: 0x10e60, Hi: 0x10e7e, Stride: 1}, + {Lo: 0x10e80, Hi: 0x10ea9, Stride: 1}, + {Lo: 0x10ead, Hi: 0x10eb0, Stride: 3}, + {Lo: 0x10eb1, Hi: 0x10f00, Stride: 79}, + {Lo: 0x10f01, Hi: 0x10f27, Stride: 1}, + {Lo: 0x10f30, Hi: 0x10f45, Stride: 1}, + {Lo: 0x10f51, Hi: 0x10f59, Stride: 1}, + {Lo: 0x10f70, Hi: 0x10f81, Stride: 1}, + {Lo: 0x10f86, Hi: 0x10f89, Stride: 1}, + {Lo: 0x10fb0, Hi: 0x10fcb, Stride: 1}, + {Lo: 0x10fe0, Hi: 0x10ff6, Stride: 1}, + {Lo: 0x11000, Hi: 0x11045, Stride: 1}, + {Lo: 0x11047, Hi: 0x1104d, Stride: 1}, + {Lo: 0x11052, Hi: 0x1106f, Stride: 1}, + {Lo: 0x11071, Hi: 0x11075, Stride: 1}, + {Lo: 0x11080, Hi: 0x110b8, Stride: 1}, + {Lo: 0x110bb, Hi: 0x110c2, Stride: 1}, + {Lo: 0x110cd, Hi: 0x110d0, Stride: 3}, + {Lo: 0x110d1, Hi: 0x110e8, Stride: 1}, + {Lo: 0x110f0, Hi: 0x110f9, Stride: 1}, + {Lo: 0x11103, Hi: 0x11132, Stride: 1}, + {Lo: 0x11136, Hi: 0x11147, Stride: 1}, + {Lo: 0x11150, Hi: 0x11172, Stride: 1}, + {Lo: 0x11174, Hi: 0x11176, Stride: 1}, + {Lo: 0x11180, Hi: 0x111bf, Stride: 1}, + {Lo: 0x111c1, Hi: 0x111c9, Stride: 1}, + {Lo: 0x111cb, Hi: 0x111df, Stride: 1}, + {Lo: 0x111e1, Hi: 0x111f4, Stride: 1}, + {Lo: 0x11200, Hi: 0x11211, Stride: 1}, + {Lo: 0x11213, Hi: 0x11234, Stride: 1}, + {Lo: 0x11237, Hi: 0x11241, Stride: 1}, + {Lo: 0x11280, Hi: 0x11286, Stride: 1}, + {Lo: 0x11288, Hi: 0x1128a, Stride: 2}, + {Lo: 0x1128b, Hi: 0x1128d, Stride: 1}, + {Lo: 0x1128f, Hi: 0x1129d, Stride: 1}, + {Lo: 0x1129f, Hi: 0x112a9, Stride: 1}, + {Lo: 0x112b0, Hi: 0x112e8, Stride: 1}, + {Lo: 0x112f0, Hi: 0x112f9, Stride: 1}, + {Lo: 0x11300, Hi: 0x11303, Stride: 1}, + {Lo: 0x11305, Hi: 0x1130c, Stride: 1}, + {Lo: 0x1130f, Hi: 0x11310, Stride: 1}, + {Lo: 0x11313, Hi: 0x11328, Stride: 1}, + {Lo: 0x1132a, Hi: 0x11330, Stride: 1}, + {Lo: 0x11332, Hi: 0x11333, Stride: 1}, + {Lo: 0x11335, Hi: 0x11339, Stride: 1}, + {Lo: 0x1133d, Hi: 0x11344, Stride: 1}, + {Lo: 0x11347, Hi: 0x11348, Stride: 1}, + {Lo: 0x1134b, Hi: 0x1134c, Stride: 1}, + {Lo: 0x11350, Hi: 0x11357, Stride: 7}, + {Lo: 0x1135d, Hi: 0x11363, Stride: 1}, + {Lo: 0x11400, Hi: 0x11441, Stride: 1}, + {Lo: 0x11443, Hi: 0x11445, Stride: 1}, + {Lo: 0x11447, Hi: 0x1145b, Stride: 1}, + {Lo: 0x1145d, Hi: 0x1145f, Stride: 2}, + {Lo: 0x11460, Hi: 0x11461, Stride: 1}, + {Lo: 0x11480, Hi: 0x114c1, Stride: 1}, + {Lo: 0x114c4, Hi: 0x114c7, Stride: 1}, + {Lo: 0x114d0, Hi: 0x114d9, Stride: 1}, + {Lo: 0x11580, Hi: 0x115b5, Stride: 1}, + {Lo: 0x115b8, Hi: 0x115be, Stride: 1}, + {Lo: 0x115c1, Hi: 0x115dd, Stride: 1}, + {Lo: 0x11600, Hi: 0x1163e, Stride: 1}, + {Lo: 0x11640, Hi: 0x11644, Stride: 1}, + {Lo: 0x11650, Hi: 0x11659, Stride: 1}, + {Lo: 0x11660, Hi: 0x1166c, Stride: 1}, + {Lo: 0x11680, Hi: 0x116b5, Stride: 1}, + {Lo: 0x116b8, Hi: 0x116b9, Stride: 1}, + {Lo: 0x116c0, Hi: 0x116c9, Stride: 1}, + {Lo: 0x11700, Hi: 0x1171a, Stride: 1}, + {Lo: 0x1171d, Hi: 0x1172a, Stride: 1}, + {Lo: 0x11730, Hi: 0x11746, Stride: 1}, + {Lo: 0x11800, Hi: 0x11838, Stride: 1}, + {Lo: 0x1183b, Hi: 0x118a0, Stride: 101}, + {Lo: 0x118a1, Hi: 0x118f2, Stride: 1}, + {Lo: 0x118ff, Hi: 0x11906, Stride: 1}, + {Lo: 0x11909, Hi: 0x1190c, Stride: 3}, + {Lo: 0x1190d, Hi: 0x11913, Stride: 1}, + {Lo: 0x11915, Hi: 0x11916, Stride: 1}, + {Lo: 0x11918, Hi: 0x11935, Stride: 1}, + {Lo: 0x11937, Hi: 0x11938, Stride: 1}, + {Lo: 0x1193b, Hi: 0x1193c, Stride: 1}, + {Lo: 0x1193f, Hi: 0x11942, Stride: 1}, + {Lo: 0x11944, Hi: 0x11946, Stride: 1}, + {Lo: 0x11950, Hi: 0x11959, Stride: 1}, + {Lo: 0x119a0, Hi: 0x119a7, Stride: 1}, + {Lo: 0x119aa, Hi: 0x119d7, Stride: 1}, + {Lo: 0x119da, Hi: 0x119df, Stride: 1}, + {Lo: 0x119e1, Hi: 0x119e4, Stride: 1}, + {Lo: 0x11a00, Hi: 0x11a33, Stride: 1}, + {Lo: 0x11a35, Hi: 0x11a46, Stride: 1}, + {Lo: 0x11a50, Hi: 0x11a98, Stride: 1}, + {Lo: 0x11a9a, Hi: 0x11aa2, Stride: 1}, + {Lo: 0x11ab0, Hi: 0x11af8, Stride: 1}, + {Lo: 0x11b00, Hi: 0x11b09, Stride: 1}, + {Lo: 0x11c00, Hi: 0x11c08, Stride: 1}, + {Lo: 0x11c0a, Hi: 0x11c36, Stride: 1}, + {Lo: 0x11c38, Hi: 0x11c3e, Stride: 1}, + {Lo: 0x11c40, Hi: 0x11c45, Stride: 1}, + {Lo: 0x11c50, Hi: 0x11c6c, Stride: 1}, + {Lo: 0x11c70, Hi: 0x11c8f, Stride: 1}, + {Lo: 0x11c92, Hi: 0x11ca7, Stride: 1}, + {Lo: 0x11ca9, Hi: 0x11cb6, Stride: 1}, + {Lo: 0x11d00, Hi: 0x11d06, Stride: 1}, + {Lo: 0x11d08, Hi: 0x11d09, Stride: 1}, + {Lo: 0x11d0b, Hi: 0x11d36, Stride: 1}, + {Lo: 0x11d3a, Hi: 0x11d3c, Stride: 2}, + {Lo: 0x11d3d, Hi: 0x11d3f, Stride: 2}, + {Lo: 0x11d40, Hi: 0x11d41, Stride: 1}, + {Lo: 0x11d43, Hi: 0x11d46, Stride: 3}, + {Lo: 0x11d47, Hi: 0x11d50, Stride: 9}, + {Lo: 0x11d51, Hi: 0x11d59, Stride: 1}, + {Lo: 0x11d60, Hi: 0x11d65, Stride: 1}, + {Lo: 0x11d67, Hi: 0x11d68, Stride: 1}, + {Lo: 0x11d6a, Hi: 0x11d8e, Stride: 1}, + {Lo: 0x11d90, Hi: 0x11d91, Stride: 1}, + {Lo: 0x11d93, Hi: 0x11d96, Stride: 1}, + {Lo: 0x11d98, Hi: 0x11da0, Stride: 8}, + {Lo: 0x11da1, Hi: 0x11da9, Stride: 1}, + {Lo: 0x11ee0, Hi: 0x11ef8, Stride: 1}, + {Lo: 0x11f00, Hi: 0x11f10, Stride: 1}, + {Lo: 0x11f12, Hi: 0x11f3a, Stride: 1}, + {Lo: 0x11f3e, Hi: 0x11f40, Stride: 1}, + {Lo: 0x11f43, Hi: 0x11f59, Stride: 1}, + {Lo: 0x11fb0, Hi: 0x11fc0, Stride: 16}, + {Lo: 0x11fc1, Hi: 0x11ff1, Stride: 1}, + {Lo: 0x11fff, Hi: 0x12399, Stride: 1}, + {Lo: 0x12400, Hi: 0x1246e, Stride: 1}, + {Lo: 0x12470, Hi: 0x12474, Stride: 1}, + {Lo: 0x12480, Hi: 0x12543, Stride: 1}, + {Lo: 0x12f90, Hi: 0x12ff2, Stride: 1}, + {Lo: 0x13000, Hi: 0x13455, Stride: 1}, + {Lo: 0x14400, Hi: 0x14646, Stride: 1}, + {Lo: 0x16800, Hi: 0x16a38, Stride: 1}, + {Lo: 0x16a40, Hi: 0x16a5e, Stride: 1}, + {Lo: 0x16a60, Hi: 0x16a69, Stride: 1}, + {Lo: 0x16a6e, Hi: 0x16abe, Stride: 1}, + {Lo: 0x16ac0, Hi: 0x16ac9, Stride: 1}, + {Lo: 0x16ad0, Hi: 0x16aed, Stride: 1}, + {Lo: 0x16af5, Hi: 0x16b00, Stride: 11}, + {Lo: 0x16b01, Hi: 0x16b2f, Stride: 1}, + {Lo: 0x16b37, Hi: 0x16b45, Stride: 1}, + {Lo: 0x16b50, Hi: 0x16b59, Stride: 1}, + {Lo: 0x16b5b, Hi: 0x16b61, Stride: 1}, + {Lo: 0x16b63, Hi: 0x16b77, Stride: 1}, + {Lo: 0x16b7d, Hi: 0x16b8f, Stride: 1}, + {Lo: 0x16e40, Hi: 0x16e9a, Stride: 1}, + {Lo: 0x16f00, Hi: 0x16f4a, Stride: 1}, + {Lo: 0x16f4f, Hi: 0x16f87, Stride: 1}, + {Lo: 0x16f8f, Hi: 0x16f9f, Stride: 1}, + {Lo: 0x16fe0, Hi: 0x16fe4, Stride: 1}, + {Lo: 0x17000, Hi: 0x187f7, Stride: 6135}, + {Lo: 0x18800, Hi: 0x18cd5, Stride: 1}, + {Lo: 0x18d00, Hi: 0x18d08, Stride: 8}, + {Lo: 0x1aff0, Hi: 0x1aff3, Stride: 1}, + {Lo: 0x1aff5, Hi: 0x1affb, Stride: 1}, + {Lo: 0x1affd, Hi: 0x1affe, Stride: 1}, + {Lo: 0x1b000, Hi: 0x1b122, Stride: 1}, + {Lo: 0x1b132, Hi: 0x1b150, Stride: 30}, + {Lo: 0x1b151, Hi: 0x1b152, Stride: 1}, + {Lo: 0x1b155, Hi: 0x1b164, Stride: 15}, + {Lo: 0x1b165, Hi: 0x1b167, Stride: 1}, + {Lo: 0x1b170, Hi: 0x1b2fb, Stride: 1}, + {Lo: 0x1bc00, Hi: 0x1bc6a, Stride: 1}, + {Lo: 0x1bc70, Hi: 0x1bc7c, Stride: 1}, + {Lo: 0x1bc80, Hi: 0x1bc88, Stride: 1}, + {Lo: 0x1bc90, Hi: 0x1bc99, Stride: 1}, + {Lo: 0x1bc9c, Hi: 0x1bc9d, Stride: 1}, + {Lo: 0x1bc9f, Hi: 0x1bca3, Stride: 1}, + {Lo: 0x1cf00, Hi: 0x1cf2d, Stride: 1}, + {Lo: 0x1cf30, Hi: 0x1cf46, Stride: 1}, + {Lo: 0x1cf50, Hi: 0x1cfc3, Stride: 1}, + {Lo: 0x1d000, Hi: 0x1d0f5, Stride: 1}, + {Lo: 0x1d100, Hi: 0x1d126, Stride: 1}, + {Lo: 0x1d129, Hi: 0x1d164, Stride: 1}, + {Lo: 0x1d16a, Hi: 0x1d16c, Stride: 1}, + {Lo: 0x1d173, Hi: 0x1d17a, Stride: 1}, + {Lo: 0x1d183, Hi: 0x1d184, Stride: 1}, + {Lo: 0x1d18c, Hi: 0x1d1a9, Stride: 1}, + {Lo: 0x1d1ae, Hi: 0x1d1ea, Stride: 1}, + {Lo: 0x1d200, Hi: 0x1d241, Stride: 1}, + {Lo: 0x1d245, Hi: 0x1d2c0, Stride: 123}, + {Lo: 0x1d2c1, Hi: 0x1d2d3, Stride: 1}, + {Lo: 0x1d2e0, Hi: 0x1d2f3, Stride: 1}, + {Lo: 0x1d300, Hi: 0x1d356, Stride: 1}, + {Lo: 0x1d360, Hi: 0x1d378, Stride: 1}, + {Lo: 0x1d400, Hi: 0x1d454, Stride: 1}, + {Lo: 0x1d456, Hi: 0x1d49c, Stride: 1}, + {Lo: 0x1d49e, Hi: 0x1d49f, Stride: 1}, + {Lo: 0x1d4a2, Hi: 0x1d4a5, Stride: 3}, + {Lo: 0x1d4a6, Hi: 0x1d4a9, Stride: 3}, + {Lo: 0x1d4aa, Hi: 0x1d4ac, Stride: 1}, + {Lo: 0x1d4ae, Hi: 0x1d4b9, Stride: 1}, + {Lo: 0x1d4bb, Hi: 0x1d4bd, Stride: 2}, + {Lo: 0x1d4be, Hi: 0x1d4c3, Stride: 1}, + {Lo: 0x1d4c5, Hi: 0x1d505, Stride: 1}, + {Lo: 0x1d507, Hi: 0x1d50a, Stride: 1}, + {Lo: 0x1d50d, Hi: 0x1d514, Stride: 1}, + {Lo: 0x1d516, Hi: 0x1d51c, Stride: 1}, + {Lo: 0x1d51e, Hi: 0x1d539, Stride: 1}, + {Lo: 0x1d53b, Hi: 0x1d53e, Stride: 1}, + {Lo: 0x1d540, Hi: 0x1d544, Stride: 1}, + {Lo: 0x1d546, Hi: 0x1d54a, Stride: 4}, + {Lo: 0x1d54b, Hi: 0x1d550, Stride: 1}, + {Lo: 0x1d552, Hi: 0x1d6a5, Stride: 1}, + {Lo: 0x1d6a8, Hi: 0x1d7cb, Stride: 1}, + {Lo: 0x1d7ce, Hi: 0x1da8b, Stride: 1}, + {Lo: 0x1da9b, Hi: 0x1da9f, Stride: 1}, + {Lo: 0x1daa1, Hi: 0x1daaf, Stride: 1}, + {Lo: 0x1df00, Hi: 0x1df1e, Stride: 1}, + {Lo: 0x1df25, Hi: 0x1df2a, Stride: 1}, + {Lo: 0x1e030, Hi: 0x1e06d, Stride: 1}, + {Lo: 0x1e100, Hi: 0x1e12c, Stride: 1}, + {Lo: 0x1e137, Hi: 0x1e13d, Stride: 1}, + {Lo: 0x1e140, Hi: 0x1e149, Stride: 1}, + {Lo: 0x1e14e, Hi: 0x1e14f, Stride: 1}, + {Lo: 0x1e290, Hi: 0x1e2ad, Stride: 1}, + {Lo: 0x1e2c0, Hi: 0x1e2eb, Stride: 1}, + {Lo: 0x1e2f0, Hi: 0x1e2f9, Stride: 1}, + {Lo: 0x1e2ff, Hi: 0x1e4d0, Stride: 465}, + {Lo: 0x1e4d1, Hi: 0x1e4eb, Stride: 1}, + {Lo: 0x1e4f0, Hi: 0x1e4f9, Stride: 1}, + {Lo: 0x1e7e0, Hi: 0x1e7e6, Stride: 1}, + {Lo: 0x1e7e8, Hi: 0x1e7eb, Stride: 1}, + {Lo: 0x1e7ed, Hi: 0x1e7ee, Stride: 1}, + {Lo: 0x1e7f0, Hi: 0x1e7fe, Stride: 1}, + {Lo: 0x1e800, Hi: 0x1e8c4, Stride: 1}, + {Lo: 0x1e8c7, Hi: 0x1e8cf, Stride: 1}, + {Lo: 0x1e900, Hi: 0x1e943, Stride: 1}, + {Lo: 0x1e94b, Hi: 0x1e950, Stride: 5}, + {Lo: 0x1e951, Hi: 0x1e959, Stride: 1}, + {Lo: 0x1e95e, Hi: 0x1e95f, Stride: 1}, + {Lo: 0x1ec71, Hi: 0x1ecb4, Stride: 1}, + {Lo: 0x1ed01, Hi: 0x1ed3d, Stride: 1}, + {Lo: 0x1ee00, Hi: 0x1ee03, Stride: 1}, + {Lo: 0x1ee05, Hi: 0x1ee1f, Stride: 1}, + {Lo: 0x1ee21, Hi: 0x1ee22, Stride: 1}, + {Lo: 0x1ee24, Hi: 0x1ee27, Stride: 3}, + {Lo: 0x1ee29, Hi: 0x1ee32, Stride: 1}, + {Lo: 0x1ee34, Hi: 0x1ee37, Stride: 1}, + {Lo: 0x1ee39, Hi: 0x1ee3b, Stride: 2}, + {Lo: 0x1ee42, Hi: 0x1ee47, Stride: 5}, + {Lo: 0x1ee49, Hi: 0x1ee4d, Stride: 2}, + {Lo: 0x1ee4e, Hi: 0x1ee4f, Stride: 1}, + {Lo: 0x1ee51, Hi: 0x1ee52, Stride: 1}, + {Lo: 0x1ee54, Hi: 0x1ee57, Stride: 3}, + {Lo: 0x1ee59, Hi: 0x1ee61, Stride: 2}, + {Lo: 0x1ee62, Hi: 0x1ee64, Stride: 2}, + {Lo: 0x1ee67, Hi: 0x1ee6a, Stride: 1}, + {Lo: 0x1ee6c, Hi: 0x1ee72, Stride: 1}, + {Lo: 0x1ee74, Hi: 0x1ee77, Stride: 1}, + {Lo: 0x1ee79, Hi: 0x1ee7c, Stride: 1}, + {Lo: 0x1ee7e, Hi: 0x1ee80, Stride: 2}, + {Lo: 0x1ee81, Hi: 0x1ee89, Stride: 1}, + {Lo: 0x1ee8b, Hi: 0x1ee9b, Stride: 1}, + {Lo: 0x1eea1, Hi: 0x1eea3, Stride: 1}, + {Lo: 0x1eea5, Hi: 0x1eea9, Stride: 1}, + {Lo: 0x1eeab, Hi: 0x1eebb, Stride: 1}, + {Lo: 0x1eef0, Hi: 0x1eef1, Stride: 1}, + {Lo: 0x1f000, Hi: 0x1f02b, Stride: 1}, + {Lo: 0x1f030, Hi: 0x1f093, Stride: 1}, + {Lo: 0x1f0a0, Hi: 0x1f0ae, Stride: 1}, + {Lo: 0x1f0b1, Hi: 0x1f0bf, Stride: 1}, + {Lo: 0x1f0c1, Hi: 0x1f0cf, Stride: 1}, + {Lo: 0x1f0d1, Hi: 0x1f0f5, Stride: 1}, + {Lo: 0x1f100, Hi: 0x1f1ad, Stride: 1}, + {Lo: 0x1f1e6, Hi: 0x1f202, Stride: 1}, + {Lo: 0x1f210, Hi: 0x1f23b, Stride: 1}, + {Lo: 0x1f240, Hi: 0x1f248, Stride: 1}, + {Lo: 0x1f250, Hi: 0x1f251, Stride: 1}, + {Lo: 0x1f260, Hi: 0x1f265, Stride: 1}, + {Lo: 0x1f300, Hi: 0x1f6d7, Stride: 1}, + {Lo: 0x1f6dc, Hi: 0x1f6ec, Stride: 1}, + {Lo: 0x1f6f0, Hi: 0x1f6fc, Stride: 1}, + {Lo: 0x1f700, Hi: 0x1f776, Stride: 1}, + {Lo: 0x1f77b, Hi: 0x1f7d9, Stride: 1}, + {Lo: 0x1f7e0, Hi: 0x1f7eb, Stride: 1}, + {Lo: 0x1f7f0, Hi: 0x1f800, Stride: 16}, + {Lo: 0x1f801, Hi: 0x1f80b, Stride: 1}, + {Lo: 0x1f810, Hi: 0x1f847, Stride: 1}, + {Lo: 0x1f850, Hi: 0x1f859, Stride: 1}, + {Lo: 0x1f860, Hi: 0x1f887, Stride: 1}, + {Lo: 0x1f890, Hi: 0x1f8ad, Stride: 1}, + {Lo: 0x1f8b0, Hi: 0x1f8b1, Stride: 1}, + {Lo: 0x1f900, Hi: 0x1fa53, Stride: 1}, + {Lo: 0x1fa60, Hi: 0x1fa6d, Stride: 1}, + {Lo: 0x1fa70, Hi: 0x1fa7c, Stride: 1}, + {Lo: 0x1fa80, Hi: 0x1fa88, Stride: 1}, + {Lo: 0x1fa90, Hi: 0x1fabd, Stride: 1}, + {Lo: 0x1fabf, Hi: 0x1fac5, Stride: 1}, + {Lo: 0x1face, Hi: 0x1fadb, Stride: 1}, + {Lo: 0x1fae0, Hi: 0x1fae8, Stride: 1}, + {Lo: 0x1faf0, Hi: 0x1faf8, Stride: 1}, + {Lo: 0x1fb00, Hi: 0x1fb92, Stride: 1}, + {Lo: 0x1fb94, Hi: 0x1fbca, Stride: 1}, + {Lo: 0x1fbf0, Hi: 0x1fbf9, Stride: 1}, + {Lo: 0x20000, Hi: 0x2a6df, Stride: 42719}, + {Lo: 0x2a700, Hi: 0x2b739, Stride: 4153}, + {Lo: 0x2b740, Hi: 0x2b81d, Stride: 221}, + {Lo: 0x2b820, Hi: 0x2cea1, Stride: 5761}, + {Lo: 0x2ceb0, Hi: 0x2ebe0, Stride: 7472}, + {Lo: 0x2ebf0, Hi: 0x2ee5d, Stride: 621}, + {Lo: 0x2f800, Hi: 0x2fa1d, Stride: 1}, + {Lo: 0x30000, Hi: 0x3134a, Stride: 4938}, + {Lo: 0x31350, Hi: 0x323af, Stride: 4191}, + {Lo: 0xe0001, Hi: 0xe0020, Stride: 31}, + {Lo: 0xe0021, Hi: 0xe007f, Stride: 1}, + {Lo: 0xe0100, Hi: 0xe01ef, Stride: 1}, + {Lo: 0xf0000, Hi: 0xffffd, Stride: 65533}, + {Lo: 0x100000, Hi: 0x10fffd, Stride: 65533}, + }, + }, + 1: { + R16: []unicode.Range16{ + {Lo: 0x0334, Hi: 0x0338, Stride: 1}, + {Lo: 0x1cd4, Hi: 0x1ce2, Stride: 14}, + {Lo: 0x1ce3, Hi: 0x1ce8, Stride: 1}, + {Lo: 0x20d2, Hi: 0x20d3, Stride: 1}, + {Lo: 0x20d8, Hi: 0x20da, Stride: 1}, + {Lo: 0x20e5, Hi: 0x20e6, Stride: 1}, + {Lo: 0x20ea, Hi: 0x20eb, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x10a39, Hi: 0x16af0, Stride: 24759}, + {Lo: 0x16af1, Hi: 0x16af4, Stride: 1}, + {Lo: 0x1bc9e, Hi: 0x1d167, Stride: 5321}, + {Lo: 0x1d168, Hi: 0x1d169, Stride: 1}, + }, + }, + 6: { + R32: []unicode.Range32{ + {Lo: 0x16ff0, Hi: 0x16ff1, Stride: 1}, + }, + }, + 7: { + R16: []unicode.Range16{ + {Lo: 0x093c, Hi: 0x0b3c, Stride: 128}, + {Lo: 0x0c3c, Hi: 0x0cbc, Stride: 128}, + {Lo: 0x1037, Hi: 0x1b34, Stride: 2813}, + {Lo: 0x1be6, Hi: 0x1c37, Stride: 81}, + {Lo: 0xa9b3, Hi: 0xa9b3, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x110ba, Hi: 0x11173, Stride: 185}, + {Lo: 0x111ca, Hi: 0x11236, Stride: 108}, + {Lo: 0x112e9, Hi: 0x1133b, Stride: 82}, + {Lo: 0x1133c, Hi: 0x11446, Stride: 266}, + {Lo: 0x114c3, Hi: 0x115c0, Stride: 253}, + {Lo: 0x116b7, Hi: 0x1183a, Stride: 387}, + {Lo: 0x11943, Hi: 0x11d42, Stride: 1023}, + {Lo: 0x1e94a, Hi: 0x1e94a, Stride: 1}, + }, + }, + 8: { + R16: []unicode.Range16{ + {Lo: 0x3099, Hi: 0x309a, Stride: 1}, + }, + }, + 9: { + R16: []unicode.Range16{ + {Lo: 0x094d, Hi: 0x0ccd, Stride: 128}, + {Lo: 0x0d3b, Hi: 0x0d3c, Stride: 1}, + {Lo: 0x0d4d, Hi: 0x0dca, Stride: 125}, + {Lo: 0x0e3a, Hi: 0x0eba, Stride: 128}, + {Lo: 0x0f84, Hi: 0x1039, Stride: 181}, + {Lo: 0x103a, Hi: 0x1714, Stride: 1754}, + {Lo: 0x1715, Hi: 0x1734, Stride: 31}, + {Lo: 0x17d2, Hi: 0x1a60, Stride: 654}, + {Lo: 0x1b44, Hi: 0x1baa, Stride: 102}, + {Lo: 0x1bab, Hi: 0x1bf2, Stride: 71}, + {Lo: 0x1bf3, Hi: 0x2d7f, Stride: 4492}, + {Lo: 0xa806, Hi: 0xa82c, Stride: 38}, + {Lo: 0xa8c4, Hi: 0xa953, Stride: 143}, + {Lo: 0xa9c0, Hi: 0xaaf6, Stride: 310}, + {Lo: 0xabed, Hi: 0xabed, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x10a3f, Hi: 0x11046, Stride: 1543}, + {Lo: 0x11070, Hi: 0x1107f, Stride: 15}, + {Lo: 0x110b9, Hi: 0x11133, Stride: 122}, + {Lo: 0x11134, Hi: 0x111c0, Stride: 140}, + {Lo: 0x11235, Hi: 0x112ea, Stride: 181}, + {Lo: 0x1134d, Hi: 0x11442, Stride: 245}, + {Lo: 0x114c2, Hi: 0x115bf, Stride: 253}, + {Lo: 0x1163f, Hi: 0x116b6, Stride: 119}, + {Lo: 0x1172b, Hi: 0x11839, Stride: 270}, + {Lo: 0x1193d, Hi: 0x1193e, Stride: 1}, + {Lo: 0x119e0, Hi: 0x11a34, Stride: 84}, + {Lo: 0x11a47, Hi: 0x11a99, Stride: 82}, + {Lo: 0x11c3f, Hi: 0x11d44, Stride: 261}, + {Lo: 0x11d45, Hi: 0x11d97, Stride: 82}, + {Lo: 0x11f41, Hi: 0x11f42, Stride: 1}, + }, + }, + 10: { + R16: []unicode.Range16{ + {Lo: 0x05b0, Hi: 0x05b0, Stride: 1}, + }, + }, + 11: { + R16: []unicode.Range16{ + {Lo: 0x05b1, Hi: 0x05b1, Stride: 1}, + }, + }, + 12: { + R16: []unicode.Range16{ + {Lo: 0x05b2, Hi: 0x05b2, Stride: 1}, + }, + }, + 13: { + R16: []unicode.Range16{ + {Lo: 0x05b3, Hi: 0x05b3, Stride: 1}, + }, + }, + 14: { + R16: []unicode.Range16{ + {Lo: 0x05b4, Hi: 0x05b4, Stride: 1}, + }, + }, + 15: { + R16: []unicode.Range16{ + {Lo: 0x05b5, Hi: 0x05b5, Stride: 1}, + }, + }, + 16: { + R16: []unicode.Range16{ + {Lo: 0x05b6, Hi: 0x05b6, Stride: 1}, + }, + }, + 17: { + R16: []unicode.Range16{ + {Lo: 0x05b7, Hi: 0x05b7, Stride: 1}, + }, + }, + 18: { + R16: []unicode.Range16{ + {Lo: 0x05b8, Hi: 0x05c7, Stride: 15}, + }, + }, + 19: { + R16: []unicode.Range16{ + {Lo: 0x05b9, Hi: 0x05ba, Stride: 1}, + }, + }, + 20: { + R16: []unicode.Range16{ + {Lo: 0x05bb, Hi: 0x05bb, Stride: 1}, + }, + }, + 21: { + R16: []unicode.Range16{ + {Lo: 0x05bc, Hi: 0x05bc, Stride: 1}, + }, + }, + 22: { + R16: []unicode.Range16{ + {Lo: 0x05bd, Hi: 0x05bd, Stride: 1}, + }, + }, + 23: { + R16: []unicode.Range16{ + {Lo: 0x05bf, Hi: 0x05bf, Stride: 1}, + }, + }, + 24: { + R16: []unicode.Range16{ + {Lo: 0x05c1, Hi: 0x05c1, Stride: 1}, + }, + }, + 25: { + R16: []unicode.Range16{ + {Lo: 0x05c2, Hi: 0x05c2, Stride: 1}, + }, + }, + 26: { + R16: []unicode.Range16{ + {Lo: 0xfb1e, Hi: 0xfb1e, Stride: 1}, + }, + }, + 27: { + R16: []unicode.Range16{ + {Lo: 0x064b, Hi: 0x08f0, Stride: 677}, + }, + }, + 28: { + R16: []unicode.Range16{ + {Lo: 0x064c, Hi: 0x08f1, Stride: 677}, + }, + }, + 29: { + R16: []unicode.Range16{ + {Lo: 0x064d, Hi: 0x08f2, Stride: 677}, + }, + }, + 30: { + R16: []unicode.Range16{ + {Lo: 0x0618, Hi: 0x064e, Stride: 54}, + }, + }, + 31: { + R16: []unicode.Range16{ + {Lo: 0x0619, Hi: 0x064f, Stride: 54}, + }, + }, + 32: { + R16: []unicode.Range16{ + {Lo: 0x061a, Hi: 0x0650, Stride: 54}, + }, + }, + 33: { + R16: []unicode.Range16{ + {Lo: 0x0651, Hi: 0x0651, Stride: 1}, + }, + }, + 34: { + R16: []unicode.Range16{ + {Lo: 0x0652, Hi: 0x0652, Stride: 1}, + }, + }, + 35: { + R16: []unicode.Range16{ + {Lo: 0x0670, Hi: 0x0670, Stride: 1}, + }, + }, + 36: { + R16: []unicode.Range16{ + {Lo: 0x0711, Hi: 0x0711, Stride: 1}, + }, + }, + 84: { + R16: []unicode.Range16{ + {Lo: 0x0c55, Hi: 0x0c55, Stride: 1}, + }, + }, + 91: { + R16: []unicode.Range16{ + {Lo: 0x0c56, Hi: 0x0c56, Stride: 1}, + }, + }, + 103: { + R16: []unicode.Range16{ + {Lo: 0x0e38, Hi: 0x0e39, Stride: 1}, + }, + }, + 107: { + R16: []unicode.Range16{ + {Lo: 0x0e48, Hi: 0x0e4b, Stride: 1}, + }, + }, + 118: { + R16: []unicode.Range16{ + {Lo: 0x0eb8, Hi: 0x0eb9, Stride: 1}, + }, + }, + 122: { + R16: []unicode.Range16{ + {Lo: 0x0ec8, Hi: 0x0ecb, Stride: 1}, + }, + }, + 129: { + R16: []unicode.Range16{ + {Lo: 0x0f71, Hi: 0x0f71, Stride: 1}, + }, + }, + 130: { + R16: []unicode.Range16{ + {Lo: 0x0f72, Hi: 0x0f7a, Stride: 8}, + {Lo: 0x0f7b, Hi: 0x0f7d, Stride: 1}, + {Lo: 0x0f80, Hi: 0x0f80, Stride: 1}, + }, + }, + 132: { + R16: []unicode.Range16{ + {Lo: 0x0f74, Hi: 0x0f74, Stride: 1}, + }, + }, + 202: { + R16: []unicode.Range16{ + {Lo: 0x0321, Hi: 0x0322, Stride: 1}, + {Lo: 0x0327, Hi: 0x0328, Stride: 1}, + {Lo: 0x1dd0, Hi: 0x1dd0, Stride: 1}, + }, + }, + 214: { + R16: []unicode.Range16{ + {Lo: 0x1dce, Hi: 0x1dce, Stride: 1}, + }, + }, + 216: { + R16: []unicode.Range16{ + {Lo: 0x031b, Hi: 0x0f39, Stride: 3102}, + }, + R32: []unicode.Range32{ + {Lo: 0x1d165, Hi: 0x1d166, Stride: 1}, + {Lo: 0x1d16e, Hi: 0x1d172, Stride: 1}, + }, + }, + 218: { + R16: []unicode.Range16{ + {Lo: 0x1dfa, Hi: 0x302a, Stride: 4656}, + }, + }, + 220: { + R16: []unicode.Range16{ + {Lo: 0x0316, Hi: 0x0319, Stride: 1}, + {Lo: 0x031c, Hi: 0x0320, Stride: 1}, + {Lo: 0x0323, Hi: 0x0326, Stride: 1}, + {Lo: 0x0329, Hi: 0x0333, Stride: 1}, + {Lo: 0x0339, Hi: 0x033c, Stride: 1}, + {Lo: 0x0347, Hi: 0x0349, Stride: 1}, + {Lo: 0x034d, Hi: 0x034e, Stride: 1}, + {Lo: 0x0353, Hi: 0x0356, Stride: 1}, + {Lo: 0x0359, Hi: 0x035a, Stride: 1}, + {Lo: 0x0591, Hi: 0x059b, Stride: 5}, + {Lo: 0x05a2, Hi: 0x05a7, Stride: 1}, + {Lo: 0x05aa, Hi: 0x05c5, Stride: 27}, + {Lo: 0x0655, Hi: 0x0656, Stride: 1}, + {Lo: 0x065c, Hi: 0x065f, Stride: 3}, + {Lo: 0x06e3, Hi: 0x06ea, Stride: 7}, + {Lo: 0x06ed, Hi: 0x0731, Stride: 68}, + {Lo: 0x0734, Hi: 0x0737, Stride: 3}, + {Lo: 0x0738, Hi: 0x0739, Stride: 1}, + {Lo: 0x073b, Hi: 0x073c, Stride: 1}, + {Lo: 0x073e, Hi: 0x0742, Stride: 4}, + {Lo: 0x0744, Hi: 0x0748, Stride: 2}, + {Lo: 0x07f2, Hi: 0x07fd, Stride: 11}, + {Lo: 0x0859, Hi: 0x085b, Stride: 1}, + {Lo: 0x0899, Hi: 0x089b, Stride: 1}, + {Lo: 0x08cf, Hi: 0x08d3, Stride: 1}, + {Lo: 0x08e3, Hi: 0x08e9, Stride: 3}, + {Lo: 0x08ed, Hi: 0x08ef, Stride: 1}, + {Lo: 0x08f6, Hi: 0x08f9, Stride: 3}, + {Lo: 0x08fa, Hi: 0x0952, Stride: 88}, + {Lo: 0x0f18, Hi: 0x0f19, Stride: 1}, + {Lo: 0x0f35, Hi: 0x0f37, Stride: 2}, + {Lo: 0x0fc6, Hi: 0x108d, Stride: 199}, + {Lo: 0x193b, Hi: 0x1a18, Stride: 221}, + {Lo: 0x1a7f, Hi: 0x1ab5, Stride: 54}, + {Lo: 0x1ab6, Hi: 0x1aba, Stride: 1}, + {Lo: 0x1abd, Hi: 0x1abf, Stride: 2}, + {Lo: 0x1ac0, Hi: 0x1ac3, Stride: 3}, + {Lo: 0x1ac4, Hi: 0x1aca, Stride: 6}, + {Lo: 0x1b6c, Hi: 0x1cd5, Stride: 361}, + {Lo: 0x1cd6, Hi: 0x1cd9, Stride: 1}, + {Lo: 0x1cdc, Hi: 0x1cdf, Stride: 1}, + {Lo: 0x1ced, Hi: 0x1dc2, Stride: 213}, + {Lo: 0x1dca, Hi: 0x1dcf, Stride: 5}, + {Lo: 0x1df9, Hi: 0x1dfd, Stride: 4}, + {Lo: 0x1dff, Hi: 0x20e8, Stride: 745}, + {Lo: 0x20ec, Hi: 0x20ef, Stride: 1}, + {Lo: 0xa92b, Hi: 0xa92d, Stride: 1}, + {Lo: 0xaab4, Hi: 0xfe27, Stride: 21363}, + {Lo: 0xfe28, Hi: 0xfe2d, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x101fd, Hi: 0x102e0, Stride: 227}, + {Lo: 0x10a0d, Hi: 0x10a3a, Stride: 45}, + {Lo: 0x10ae6, Hi: 0x10efd, Stride: 1047}, + {Lo: 0x10efe, Hi: 0x10eff, Stride: 1}, + {Lo: 0x10f46, Hi: 0x10f47, Stride: 1}, + {Lo: 0x10f4b, Hi: 0x10f4d, Stride: 2}, + {Lo: 0x10f4e, Hi: 0x10f50, Stride: 1}, + {Lo: 0x10f83, Hi: 0x10f85, Stride: 2}, + {Lo: 0x1d17b, Hi: 0x1d182, Stride: 1}, + {Lo: 0x1d18a, Hi: 0x1d18b, Stride: 1}, + {Lo: 0x1e4ee, Hi: 0x1e8d0, Stride: 994}, + {Lo: 0x1e8d1, Hi: 0x1e8d6, Stride: 1}, + }, + }, + 222: { + R16: []unicode.Range16{ + {Lo: 0x059a, Hi: 0x05ad, Stride: 19}, + {Lo: 0x1939, Hi: 0x302d, Stride: 5876}, + }, + }, + 224: { + R16: []unicode.Range16{ + {Lo: 0x302e, Hi: 0x302f, Stride: 1}, + }, + }, + 226: { + R32: []unicode.Range32{ + {Lo: 0x1d16d, Hi: 0x1d16d, Stride: 1}, + }, + }, + 228: { + R16: []unicode.Range16{ + {Lo: 0x05ae, Hi: 0x18a9, Stride: 4859}, + {Lo: 0x1df7, Hi: 0x1df8, Stride: 1}, + {Lo: 0x302b, Hi: 0x302b, Stride: 1}, + }, + }, + 230: { + R16: []unicode.Range16{ + {Lo: 0x0300, Hi: 0x0314, Stride: 1}, + {Lo: 0x033d, Hi: 0x0344, Stride: 1}, + {Lo: 0x0346, Hi: 0x034a, Stride: 4}, + {Lo: 0x034b, Hi: 0x034c, Stride: 1}, + {Lo: 0x0350, Hi: 0x0352, Stride: 1}, + {Lo: 0x0357, Hi: 0x035b, Stride: 4}, + {Lo: 0x0363, Hi: 0x036f, Stride: 1}, + {Lo: 0x0483, Hi: 0x0487, Stride: 1}, + {Lo: 0x0592, Hi: 0x0595, Stride: 1}, + {Lo: 0x0597, Hi: 0x0599, Stride: 1}, + {Lo: 0x059c, Hi: 0x05a1, Stride: 1}, + {Lo: 0x05a8, Hi: 0x05a9, Stride: 1}, + {Lo: 0x05ab, Hi: 0x05ac, Stride: 1}, + {Lo: 0x05af, Hi: 0x05c4, Stride: 21}, + {Lo: 0x0610, Hi: 0x0617, Stride: 1}, + {Lo: 0x0653, Hi: 0x0654, Stride: 1}, + {Lo: 0x0657, Hi: 0x065b, Stride: 1}, + {Lo: 0x065d, Hi: 0x065e, Stride: 1}, + {Lo: 0x06d6, Hi: 0x06dc, Stride: 1}, + {Lo: 0x06df, Hi: 0x06e2, Stride: 1}, + {Lo: 0x06e4, Hi: 0x06e7, Stride: 3}, + {Lo: 0x06e8, Hi: 0x06eb, Stride: 3}, + {Lo: 0x06ec, Hi: 0x0730, Stride: 68}, + {Lo: 0x0732, Hi: 0x0733, Stride: 1}, + {Lo: 0x0735, Hi: 0x0736, Stride: 1}, + {Lo: 0x073a, Hi: 0x073d, Stride: 3}, + {Lo: 0x073f, Hi: 0x0741, Stride: 1}, + {Lo: 0x0743, Hi: 0x0749, Stride: 2}, + {Lo: 0x074a, Hi: 0x07eb, Stride: 161}, + {Lo: 0x07ec, Hi: 0x07f1, Stride: 1}, + {Lo: 0x07f3, Hi: 0x0816, Stride: 35}, + {Lo: 0x0817, Hi: 0x0819, Stride: 1}, + {Lo: 0x081b, Hi: 0x0823, Stride: 1}, + {Lo: 0x0825, Hi: 0x0827, Stride: 1}, + {Lo: 0x0829, Hi: 0x082d, Stride: 1}, + {Lo: 0x0898, Hi: 0x089c, Stride: 4}, + {Lo: 0x089d, Hi: 0x089f, Stride: 1}, + {Lo: 0x08ca, Hi: 0x08ce, Stride: 1}, + {Lo: 0x08d4, Hi: 0x08e1, Stride: 1}, + {Lo: 0x08e4, Hi: 0x08e5, Stride: 1}, + {Lo: 0x08e7, Hi: 0x08e8, Stride: 1}, + {Lo: 0x08ea, Hi: 0x08ec, Stride: 1}, + {Lo: 0x08f3, Hi: 0x08f5, Stride: 1}, + {Lo: 0x08f7, Hi: 0x08f8, Stride: 1}, + {Lo: 0x08fb, Hi: 0x08ff, Stride: 1}, + {Lo: 0x0951, Hi: 0x0953, Stride: 2}, + {Lo: 0x0954, Hi: 0x09fe, Stride: 170}, + {Lo: 0x0f82, Hi: 0x0f83, Stride: 1}, + {Lo: 0x0f86, Hi: 0x0f87, Stride: 1}, + {Lo: 0x135d, Hi: 0x135f, Stride: 1}, + {Lo: 0x17dd, Hi: 0x193a, Stride: 349}, + {Lo: 0x1a17, Hi: 0x1a75, Stride: 94}, + {Lo: 0x1a76, Hi: 0x1a7c, Stride: 1}, + {Lo: 0x1ab0, Hi: 0x1ab4, Stride: 1}, + {Lo: 0x1abb, Hi: 0x1abc, Stride: 1}, + {Lo: 0x1ac1, Hi: 0x1ac2, Stride: 1}, + {Lo: 0x1ac5, Hi: 0x1ac9, Stride: 1}, + {Lo: 0x1acb, Hi: 0x1ace, Stride: 1}, + {Lo: 0x1b6b, Hi: 0x1b6d, Stride: 2}, + {Lo: 0x1b6e, Hi: 0x1b73, Stride: 1}, + {Lo: 0x1cd0, Hi: 0x1cd2, Stride: 1}, + {Lo: 0x1cda, Hi: 0x1cdb, Stride: 1}, + {Lo: 0x1ce0, Hi: 0x1cf4, Stride: 20}, + {Lo: 0x1cf8, Hi: 0x1cf9, Stride: 1}, + {Lo: 0x1dc0, Hi: 0x1dc1, Stride: 1}, + {Lo: 0x1dc3, Hi: 0x1dc9, Stride: 1}, + {Lo: 0x1dcb, Hi: 0x1dcc, Stride: 1}, + {Lo: 0x1dd1, Hi: 0x1df5, Stride: 1}, + {Lo: 0x1dfb, Hi: 0x1dfe, Stride: 3}, + {Lo: 0x20d0, Hi: 0x20d1, Stride: 1}, + {Lo: 0x20d4, Hi: 0x20d7, Stride: 1}, + {Lo: 0x20db, Hi: 0x20dc, Stride: 1}, + {Lo: 0x20e1, Hi: 0x20e7, Stride: 6}, + {Lo: 0x20e9, Hi: 0x20f0, Stride: 7}, + {Lo: 0x2cef, Hi: 0x2cf1, Stride: 1}, + {Lo: 0x2de0, Hi: 0x2dff, Stride: 1}, + {Lo: 0xa66f, Hi: 0xa674, Stride: 5}, + {Lo: 0xa675, Hi: 0xa67d, Stride: 1}, + {Lo: 0xa69e, Hi: 0xa69f, Stride: 1}, + {Lo: 0xa6f0, Hi: 0xa6f1, Stride: 1}, + {Lo: 0xa8e0, Hi: 0xa8f1, Stride: 1}, + {Lo: 0xaab0, Hi: 0xaab2, Stride: 2}, + {Lo: 0xaab3, Hi: 0xaab7, Stride: 4}, + {Lo: 0xaab8, Hi: 0xaabe, Stride: 6}, + {Lo: 0xaabf, Hi: 0xaac1, Stride: 2}, + {Lo: 0xfe20, Hi: 0xfe26, Stride: 1}, + {Lo: 0xfe2e, Hi: 0xfe2f, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x10376, Hi: 0x1037a, Stride: 1}, + {Lo: 0x10a0f, Hi: 0x10a38, Stride: 41}, + {Lo: 0x10ae5, Hi: 0x10d24, Stride: 575}, + {Lo: 0x10d25, Hi: 0x10d27, Stride: 1}, + {Lo: 0x10eab, Hi: 0x10eac, Stride: 1}, + {Lo: 0x10f48, Hi: 0x10f4a, Stride: 1}, + {Lo: 0x10f4c, Hi: 0x10f82, Stride: 54}, + {Lo: 0x10f84, Hi: 0x11100, Stride: 380}, + {Lo: 0x11101, Hi: 0x11102, Stride: 1}, + {Lo: 0x11366, Hi: 0x1136c, Stride: 1}, + {Lo: 0x11370, Hi: 0x11374, Stride: 1}, + {Lo: 0x1145e, Hi: 0x16b30, Stride: 22226}, + {Lo: 0x16b31, Hi: 0x16b36, Stride: 1}, + {Lo: 0x1d185, Hi: 0x1d189, Stride: 1}, + {Lo: 0x1d1aa, Hi: 0x1d1ad, Stride: 1}, + {Lo: 0x1d242, Hi: 0x1d244, Stride: 1}, + {Lo: 0x1e000, Hi: 0x1e006, Stride: 1}, + {Lo: 0x1e008, Hi: 0x1e018, Stride: 1}, + {Lo: 0x1e01b, Hi: 0x1e021, Stride: 1}, + {Lo: 0x1e023, Hi: 0x1e024, Stride: 1}, + {Lo: 0x1e026, Hi: 0x1e02a, Stride: 1}, + {Lo: 0x1e08f, Hi: 0x1e130, Stride: 161}, + {Lo: 0x1e131, Hi: 0x1e136, Stride: 1}, + {Lo: 0x1e2ae, Hi: 0x1e2ec, Stride: 62}, + {Lo: 0x1e2ed, Hi: 0x1e2ef, Stride: 1}, + {Lo: 0x1e4ef, Hi: 0x1e944, Stride: 1109}, + {Lo: 0x1e945, Hi: 0x1e949, Stride: 1}, + }, + }, + 232: { + R16: []unicode.Range16{ + {Lo: 0x0315, Hi: 0x031a, Stride: 5}, + {Lo: 0x0358, Hi: 0x1df6, Stride: 6814}, + {Lo: 0x302c, Hi: 0x302c, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x1e4ec, Hi: 0x1e4ed, Stride: 1}, + }, + }, + 233: { + R16: []unicode.Range16{ + {Lo: 0x035c, Hi: 0x0362, Stride: 3}, + {Lo: 0x1dfc, Hi: 0x1dfc, Stride: 1}, + }, + }, + 234: { + R16: []unicode.Range16{ + {Lo: 0x035d, Hi: 0x035e, Stride: 1}, + {Lo: 0x0360, Hi: 0x0361, Stride: 1}, + {Lo: 0x1dcd, Hi: 0x1dcd, Stride: 1}, + }, + }, + 240: { + R16: []unicode.Range16{ + {Lo: 0x0345, Hi: 0x0345, Stride: 1}, + }, + }, +} diff --git a/vendor/github.com/go-text/typesetting/unicodedata/decomposition.go b/vendor/github.com/go-text/typesetting/unicodedata/decomposition.go new file mode 100644 index 0000000..59edac8 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/unicodedata/decomposition.go @@ -0,0 +1,3099 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package unicodedata + +// Code generated by typesettings-utils/generators/unicodedata/cmd/main.go DO NOT EDIT. + +var decompose1 = map[rune]rune{ // 1035 entries + 0x0340: 0x0300, + 0x0341: 0x0301, + 0x0343: 0x0313, + 0x0374: 0x02b9, + 0x037e: 0x003b, + 0x0387: 0x00b7, + 0x1f71: 0x03ac, + 0x1f73: 0x03ad, + 0x1f75: 0x03ae, + 0x1f77: 0x03af, + 0x1f79: 0x03cc, + 0x1f7b: 0x03cd, + 0x1f7d: 0x03ce, + 0x1fbb: 0x0386, + 0x1fbe: 0x03b9, + 0x1fc9: 0x0388, + 0x1fcb: 0x0389, + 0x1fd3: 0x0390, + 0x1fdb: 0x038a, + 0x1fe3: 0x03b0, + 0x1feb: 0x038e, + 0x1fee: 0x0385, + 0x1fef: 0x0060, + 0x1ff9: 0x038c, + 0x1ffb: 0x038f, + 0x1ffd: 0x00b4, + 0x2000: 0x2002, + 0x2001: 0x2003, + 0x2126: 0x03a9, + 0x212a: 0x004b, + 0x212b: 0x00c5, + 0x2329: 0x3008, + 0x232a: 0x3009, + 0xf900: 0x8c48, + 0xf901: 0x66f4, + 0xf902: 0x8eca, + 0xf903: 0x8cc8, + 0xf904: 0x6ed1, + 0xf905: 0x4e32, + 0xf906: 0x53e5, + 0xf907: 0x9f9c, + 0xf908: 0x9f9c, + 0xf909: 0x5951, + 0xf90a: 0x91d1, + 0xf90b: 0x5587, + 0xf90c: 0x5948, + 0xf90d: 0x61f6, + 0xf90e: 0x7669, + 0xf90f: 0x7f85, + 0xf910: 0x863f, + 0xf911: 0x87ba, + 0xf912: 0x88f8, + 0xf913: 0x908f, + 0xf914: 0x6a02, + 0xf915: 0x6d1b, + 0xf916: 0x70d9, + 0xf917: 0x73de, + 0xf918: 0x843d, + 0xf919: 0x916a, + 0xf91a: 0x99f1, + 0xf91b: 0x4e82, + 0xf91c: 0x5375, + 0xf91d: 0x6b04, + 0xf91e: 0x721b, + 0xf91f: 0x862d, + 0xf920: 0x9e1e, + 0xf921: 0x5d50, + 0xf922: 0x6feb, + 0xf923: 0x85cd, + 0xf924: 0x8964, + 0xf925: 0x62c9, + 0xf926: 0x81d8, + 0xf927: 0x881f, + 0xf928: 0x5eca, + 0xf929: 0x6717, + 0xf92a: 0x6d6a, + 0xf92b: 0x72fc, + 0xf92c: 0x90ce, + 0xf92d: 0x4f86, + 0xf92e: 0x51b7, + 0xf92f: 0x52de, + 0xf930: 0x64c4, + 0xf931: 0x6ad3, + 0xf932: 0x7210, + 0xf933: 0x76e7, + 0xf934: 0x8001, + 0xf935: 0x8606, + 0xf936: 0x865c, + 0xf937: 0x8def, + 0xf938: 0x9732, + 0xf939: 0x9b6f, + 0xf93a: 0x9dfa, + 0xf93b: 0x788c, + 0xf93c: 0x797f, + 0xf93d: 0x7da0, + 0xf93e: 0x83c9, + 0xf93f: 0x9304, + 0xf940: 0x9e7f, + 0xf941: 0x8ad6, + 0xf942: 0x58df, + 0xf943: 0x5f04, + 0xf944: 0x7c60, + 0xf945: 0x807e, + 0xf946: 0x7262, + 0xf947: 0x78ca, + 0xf948: 0x8cc2, + 0xf949: 0x96f7, + 0xf94a: 0x58d8, + 0xf94b: 0x5c62, + 0xf94c: 0x6a13, + 0xf94d: 0x6dda, + 0xf94e: 0x6f0f, + 0xf94f: 0x7d2f, + 0xf950: 0x7e37, + 0xf951: 0x964b, + 0xf952: 0x52d2, + 0xf953: 0x808b, + 0xf954: 0x51dc, + 0xf955: 0x51cc, + 0xf956: 0x7a1c, + 0xf957: 0x7dbe, + 0xf958: 0x83f1, + 0xf959: 0x9675, + 0xf95a: 0x8b80, + 0xf95b: 0x62cf, + 0xf95c: 0x6a02, + 0xf95d: 0x8afe, + 0xf95e: 0x4e39, + 0xf95f: 0x5be7, + 0xf960: 0x6012, + 0xf961: 0x7387, + 0xf962: 0x7570, + 0xf963: 0x5317, + 0xf964: 0x78fb, + 0xf965: 0x4fbf, + 0xf966: 0x5fa9, + 0xf967: 0x4e0d, + 0xf968: 0x6ccc, + 0xf969: 0x6578, + 0xf96a: 0x7d22, + 0xf96b: 0x53c3, + 0xf96c: 0x585e, + 0xf96d: 0x7701, + 0xf96e: 0x8449, + 0xf96f: 0x8aaa, + 0xf970: 0x6bba, + 0xf971: 0x8fb0, + 0xf972: 0x6c88, + 0xf973: 0x62fe, + 0xf974: 0x82e5, + 0xf975: 0x63a0, + 0xf976: 0x7565, + 0xf977: 0x4eae, + 0xf978: 0x5169, + 0xf979: 0x51c9, + 0xf97a: 0x6881, + 0xf97b: 0x7ce7, + 0xf97c: 0x826f, + 0xf97d: 0x8ad2, + 0xf97e: 0x91cf, + 0xf97f: 0x52f5, + 0xf980: 0x5442, + 0xf981: 0x5973, + 0xf982: 0x5eec, + 0xf983: 0x65c5, + 0xf984: 0x6ffe, + 0xf985: 0x792a, + 0xf986: 0x95ad, + 0xf987: 0x9a6a, + 0xf988: 0x9e97, + 0xf989: 0x9ece, + 0xf98a: 0x529b, + 0xf98b: 0x66c6, + 0xf98c: 0x6b77, + 0xf98d: 0x8f62, + 0xf98e: 0x5e74, + 0xf98f: 0x6190, + 0xf990: 0x6200, + 0xf991: 0x649a, + 0xf992: 0x6f23, + 0xf993: 0x7149, + 0xf994: 0x7489, + 0xf995: 0x79ca, + 0xf996: 0x7df4, + 0xf997: 0x806f, + 0xf998: 0x8f26, + 0xf999: 0x84ee, + 0xf99a: 0x9023, + 0xf99b: 0x934a, + 0xf99c: 0x5217, + 0xf99d: 0x52a3, + 0xf99e: 0x54bd, + 0xf99f: 0x70c8, + 0xf9a0: 0x88c2, + 0xf9a1: 0x8aaa, + 0xf9a2: 0x5ec9, + 0xf9a3: 0x5ff5, + 0xf9a4: 0x637b, + 0xf9a5: 0x6bae, + 0xf9a6: 0x7c3e, + 0xf9a7: 0x7375, + 0xf9a8: 0x4ee4, + 0xf9a9: 0x56f9, + 0xf9aa: 0x5be7, + 0xf9ab: 0x5dba, + 0xf9ac: 0x601c, + 0xf9ad: 0x73b2, + 0xf9ae: 0x7469, + 0xf9af: 0x7f9a, + 0xf9b0: 0x8046, + 0xf9b1: 0x9234, + 0xf9b2: 0x96f6, + 0xf9b3: 0x9748, + 0xf9b4: 0x9818, + 0xf9b5: 0x4f8b, + 0xf9b6: 0x79ae, + 0xf9b7: 0x91b4, + 0xf9b8: 0x96b8, + 0xf9b9: 0x60e1, + 0xf9ba: 0x4e86, + 0xf9bb: 0x50da, + 0xf9bc: 0x5bee, + 0xf9bd: 0x5c3f, + 0xf9be: 0x6599, + 0xf9bf: 0x6a02, + 0xf9c0: 0x71ce, + 0xf9c1: 0x7642, + 0xf9c2: 0x84fc, + 0xf9c3: 0x907c, + 0xf9c4: 0x9f8d, + 0xf9c5: 0x6688, + 0xf9c6: 0x962e, + 0xf9c7: 0x5289, + 0xf9c8: 0x677b, + 0xf9c9: 0x67f3, + 0xf9ca: 0x6d41, + 0xf9cb: 0x6e9c, + 0xf9cc: 0x7409, + 0xf9cd: 0x7559, + 0xf9ce: 0x786b, + 0xf9cf: 0x7d10, + 0xf9d0: 0x985e, + 0xf9d1: 0x516d, + 0xf9d2: 0x622e, + 0xf9d3: 0x9678, + 0xf9d4: 0x502b, + 0xf9d5: 0x5d19, + 0xf9d6: 0x6dea, + 0xf9d7: 0x8f2a, + 0xf9d8: 0x5f8b, + 0xf9d9: 0x6144, + 0xf9da: 0x6817, + 0xf9db: 0x7387, + 0xf9dc: 0x9686, + 0xf9dd: 0x5229, + 0xf9de: 0x540f, + 0xf9df: 0x5c65, + 0xf9e0: 0x6613, + 0xf9e1: 0x674e, + 0xf9e2: 0x68a8, + 0xf9e3: 0x6ce5, + 0xf9e4: 0x7406, + 0xf9e5: 0x75e2, + 0xf9e6: 0x7f79, + 0xf9e7: 0x88cf, + 0xf9e8: 0x88e1, + 0xf9e9: 0x91cc, + 0xf9ea: 0x96e2, + 0xf9eb: 0x533f, + 0xf9ec: 0x6eba, + 0xf9ed: 0x541d, + 0xf9ee: 0x71d0, + 0xf9ef: 0x7498, + 0xf9f0: 0x85fa, + 0xf9f1: 0x96a3, + 0xf9f2: 0x9c57, + 0xf9f3: 0x9e9f, + 0xf9f4: 0x6797, + 0xf9f5: 0x6dcb, + 0xf9f6: 0x81e8, + 0xf9f7: 0x7acb, + 0xf9f8: 0x7b20, + 0xf9f9: 0x7c92, + 0xf9fa: 0x72c0, + 0xf9fb: 0x7099, + 0xf9fc: 0x8b58, + 0xf9fd: 0x4ec0, + 0xf9fe: 0x8336, + 0xf9ff: 0x523a, + 0xfa00: 0x5207, + 0xfa01: 0x5ea6, + 0xfa02: 0x62d3, + 0xfa03: 0x7cd6, + 0xfa04: 0x5b85, + 0xfa05: 0x6d1e, + 0xfa06: 0x66b4, + 0xfa07: 0x8f3b, + 0xfa08: 0x884c, + 0xfa09: 0x964d, + 0xfa0a: 0x898b, + 0xfa0b: 0x5ed3, + 0xfa0c: 0x5140, + 0xfa0d: 0x55c0, + 0xfa10: 0x585a, + 0xfa12: 0x6674, + 0xfa15: 0x51de, + 0xfa16: 0x732a, + 0xfa17: 0x76ca, + 0xfa18: 0x793c, + 0xfa19: 0x795e, + 0xfa1a: 0x7965, + 0xfa1b: 0x798f, + 0xfa1c: 0x9756, + 0xfa1d: 0x7cbe, + 0xfa1e: 0x7fbd, + 0xfa20: 0x8612, + 0xfa22: 0x8af8, + 0xfa25: 0x9038, + 0xfa26: 0x90fd, + 0xfa2a: 0x98ef, + 0xfa2b: 0x98fc, + 0xfa2c: 0x9928, + 0xfa2d: 0x9db4, + 0xfa2e: 0x90de, + 0xfa2f: 0x96b7, + 0xfa30: 0x4fae, + 0xfa31: 0x50e7, + 0xfa32: 0x514d, + 0xfa33: 0x52c9, + 0xfa34: 0x52e4, + 0xfa35: 0x5351, + 0xfa36: 0x559d, + 0xfa37: 0x5606, + 0xfa38: 0x5668, + 0xfa39: 0x5840, + 0xfa3a: 0x58a8, + 0xfa3b: 0x5c64, + 0xfa3c: 0x5c6e, + 0xfa3d: 0x6094, + 0xfa3e: 0x6168, + 0xfa3f: 0x618e, + 0xfa40: 0x61f2, + 0xfa41: 0x654f, + 0xfa42: 0x65e2, + 0xfa43: 0x6691, + 0xfa44: 0x6885, + 0xfa45: 0x6d77, + 0xfa46: 0x6e1a, + 0xfa47: 0x6f22, + 0xfa48: 0x716e, + 0xfa49: 0x722b, + 0xfa4a: 0x7422, + 0xfa4b: 0x7891, + 0xfa4c: 0x793e, + 0xfa4d: 0x7949, + 0xfa4e: 0x7948, + 0xfa4f: 0x7950, + 0xfa50: 0x7956, + 0xfa51: 0x795d, + 0xfa52: 0x798d, + 0xfa53: 0x798e, + 0xfa54: 0x7a40, + 0xfa55: 0x7a81, + 0xfa56: 0x7bc0, + 0xfa57: 0x7df4, + 0xfa58: 0x7e09, + 0xfa59: 0x7e41, + 0xfa5a: 0x7f72, + 0xfa5b: 0x8005, + 0xfa5c: 0x81ed, + 0xfa5d: 0x8279, + 0xfa5e: 0x8279, + 0xfa5f: 0x8457, + 0xfa60: 0x8910, + 0xfa61: 0x8996, + 0xfa62: 0x8b01, + 0xfa63: 0x8b39, + 0xfa64: 0x8cd3, + 0xfa65: 0x8d08, + 0xfa66: 0x8fb6, + 0xfa67: 0x9038, + 0xfa68: 0x96e3, + 0xfa69: 0x97ff, + 0xfa6a: 0x983b, + 0xfa6b: 0x6075, + 0xfa6c: 0x242ee, + 0xfa6d: 0x8218, + 0xfa70: 0x4e26, + 0xfa71: 0x51b5, + 0xfa72: 0x5168, + 0xfa73: 0x4f80, + 0xfa74: 0x5145, + 0xfa75: 0x5180, + 0xfa76: 0x52c7, + 0xfa77: 0x52fa, + 0xfa78: 0x559d, + 0xfa79: 0x5555, + 0xfa7a: 0x5599, + 0xfa7b: 0x55e2, + 0xfa7c: 0x585a, + 0xfa7d: 0x58b3, + 0xfa7e: 0x5944, + 0xfa7f: 0x5954, + 0xfa80: 0x5a62, + 0xfa81: 0x5b28, + 0xfa82: 0x5ed2, + 0xfa83: 0x5ed9, + 0xfa84: 0x5f69, + 0xfa85: 0x5fad, + 0xfa86: 0x60d8, + 0xfa87: 0x614e, + 0xfa88: 0x6108, + 0xfa89: 0x618e, + 0xfa8a: 0x6160, + 0xfa8b: 0x61f2, + 0xfa8c: 0x6234, + 0xfa8d: 0x63c4, + 0xfa8e: 0x641c, + 0xfa8f: 0x6452, + 0xfa90: 0x6556, + 0xfa91: 0x6674, + 0xfa92: 0x6717, + 0xfa93: 0x671b, + 0xfa94: 0x6756, + 0xfa95: 0x6b79, + 0xfa96: 0x6bba, + 0xfa97: 0x6d41, + 0xfa98: 0x6edb, + 0xfa99: 0x6ecb, + 0xfa9a: 0x6f22, + 0xfa9b: 0x701e, + 0xfa9c: 0x716e, + 0xfa9d: 0x77a7, + 0xfa9e: 0x7235, + 0xfa9f: 0x72af, + 0xfaa0: 0x732a, + 0xfaa1: 0x7471, + 0xfaa2: 0x7506, + 0xfaa3: 0x753b, + 0xfaa4: 0x761d, + 0xfaa5: 0x761f, + 0xfaa6: 0x76ca, + 0xfaa7: 0x76db, + 0xfaa8: 0x76f4, + 0xfaa9: 0x774a, + 0xfaaa: 0x7740, + 0xfaab: 0x78cc, + 0xfaac: 0x7ab1, + 0xfaad: 0x7bc0, + 0xfaae: 0x7c7b, + 0xfaaf: 0x7d5b, + 0xfab0: 0x7df4, + 0xfab1: 0x7f3e, + 0xfab2: 0x8005, + 0xfab3: 0x8352, + 0xfab4: 0x83ef, + 0xfab5: 0x8779, + 0xfab6: 0x8941, + 0xfab7: 0x8986, + 0xfab8: 0x8996, + 0xfab9: 0x8abf, + 0xfaba: 0x8af8, + 0xfabb: 0x8acb, + 0xfabc: 0x8b01, + 0xfabd: 0x8afe, + 0xfabe: 0x8aed, + 0xfabf: 0x8b39, + 0xfac0: 0x8b8a, + 0xfac1: 0x8d08, + 0xfac2: 0x8f38, + 0xfac3: 0x9072, + 0xfac4: 0x9199, + 0xfac5: 0x9276, + 0xfac6: 0x967c, + 0xfac7: 0x96e3, + 0xfac8: 0x9756, + 0xfac9: 0x97db, + 0xfaca: 0x97ff, + 0xfacb: 0x980b, + 0xfacc: 0x983b, + 0xfacd: 0x9b12, + 0xface: 0x9f9c, + 0xfacf: 0x2284a, + 0xfad0: 0x22844, + 0xfad1: 0x233d5, + 0xfad2: 0x3b9d, + 0xfad3: 0x4018, + 0xfad4: 0x4039, + 0xfad5: 0x25249, + 0xfad6: 0x25cd0, + 0xfad7: 0x27ed3, + 0xfad8: 0x9f43, + 0xfad9: 0x9f8e, + 0x2f800: 0x4e3d, + 0x2f801: 0x4e38, + 0x2f802: 0x4e41, + 0x2f803: 0x20122, + 0x2f804: 0x4f60, + 0x2f805: 0x4fae, + 0x2f806: 0x4fbb, + 0x2f807: 0x5002, + 0x2f808: 0x507a, + 0x2f809: 0x5099, + 0x2f80a: 0x50e7, + 0x2f80b: 0x50cf, + 0x2f80c: 0x349e, + 0x2f80d: 0x2063a, + 0x2f80e: 0x514d, + 0x2f80f: 0x5154, + 0x2f810: 0x5164, + 0x2f811: 0x5177, + 0x2f812: 0x2051c, + 0x2f813: 0x34b9, + 0x2f814: 0x5167, + 0x2f815: 0x518d, + 0x2f816: 0x2054b, + 0x2f817: 0x5197, + 0x2f818: 0x51a4, + 0x2f819: 0x4ecc, + 0x2f81a: 0x51ac, + 0x2f81b: 0x51b5, + 0x2f81c: 0x291df, + 0x2f81d: 0x51f5, + 0x2f81e: 0x5203, + 0x2f81f: 0x34df, + 0x2f820: 0x523b, + 0x2f821: 0x5246, + 0x2f822: 0x5272, + 0x2f823: 0x5277, + 0x2f824: 0x3515, + 0x2f825: 0x52c7, + 0x2f826: 0x52c9, + 0x2f827: 0x52e4, + 0x2f828: 0x52fa, + 0x2f829: 0x5305, + 0x2f82a: 0x5306, + 0x2f82b: 0x5317, + 0x2f82c: 0x5349, + 0x2f82d: 0x5351, + 0x2f82e: 0x535a, + 0x2f82f: 0x5373, + 0x2f830: 0x537d, + 0x2f831: 0x537f, + 0x2f832: 0x537f, + 0x2f833: 0x537f, + 0x2f834: 0x20a2c, + 0x2f835: 0x7070, + 0x2f836: 0x53ca, + 0x2f837: 0x53df, + 0x2f838: 0x20b63, + 0x2f839: 0x53eb, + 0x2f83a: 0x53f1, + 0x2f83b: 0x5406, + 0x2f83c: 0x549e, + 0x2f83d: 0x5438, + 0x2f83e: 0x5448, + 0x2f83f: 0x5468, + 0x2f840: 0x54a2, + 0x2f841: 0x54f6, + 0x2f842: 0x5510, + 0x2f843: 0x5553, + 0x2f844: 0x5563, + 0x2f845: 0x5584, + 0x2f846: 0x5584, + 0x2f847: 0x5599, + 0x2f848: 0x55ab, + 0x2f849: 0x55b3, + 0x2f84a: 0x55c2, + 0x2f84b: 0x5716, + 0x2f84c: 0x5606, + 0x2f84d: 0x5717, + 0x2f84e: 0x5651, + 0x2f84f: 0x5674, + 0x2f850: 0x5207, + 0x2f851: 0x58ee, + 0x2f852: 0x57ce, + 0x2f853: 0x57f4, + 0x2f854: 0x580d, + 0x2f855: 0x578b, + 0x2f856: 0x5832, + 0x2f857: 0x5831, + 0x2f858: 0x58ac, + 0x2f859: 0x214e4, + 0x2f85a: 0x58f2, + 0x2f85b: 0x58f7, + 0x2f85c: 0x5906, + 0x2f85d: 0x591a, + 0x2f85e: 0x5922, + 0x2f85f: 0x5962, + 0x2f860: 0x216a8, + 0x2f861: 0x216ea, + 0x2f862: 0x59ec, + 0x2f863: 0x5a1b, + 0x2f864: 0x5a27, + 0x2f865: 0x59d8, + 0x2f866: 0x5a66, + 0x2f867: 0x36ee, + 0x2f868: 0x36fc, + 0x2f869: 0x5b08, + 0x2f86a: 0x5b3e, + 0x2f86b: 0x5b3e, + 0x2f86c: 0x219c8, + 0x2f86d: 0x5bc3, + 0x2f86e: 0x5bd8, + 0x2f86f: 0x5be7, + 0x2f870: 0x5bf3, + 0x2f871: 0x21b18, + 0x2f872: 0x5bff, + 0x2f873: 0x5c06, + 0x2f874: 0x5f53, + 0x2f875: 0x5c22, + 0x2f876: 0x3781, + 0x2f877: 0x5c60, + 0x2f878: 0x5c6e, + 0x2f879: 0x5cc0, + 0x2f87a: 0x5c8d, + 0x2f87b: 0x21de4, + 0x2f87c: 0x5d43, + 0x2f87d: 0x21de6, + 0x2f87e: 0x5d6e, + 0x2f87f: 0x5d6b, + 0x2f880: 0x5d7c, + 0x2f881: 0x5de1, + 0x2f882: 0x5de2, + 0x2f883: 0x382f, + 0x2f884: 0x5dfd, + 0x2f885: 0x5e28, + 0x2f886: 0x5e3d, + 0x2f887: 0x5e69, + 0x2f888: 0x3862, + 0x2f889: 0x22183, + 0x2f88a: 0x387c, + 0x2f88b: 0x5eb0, + 0x2f88c: 0x5eb3, + 0x2f88d: 0x5eb6, + 0x2f88e: 0x5eca, + 0x2f88f: 0x2a392, + 0x2f890: 0x5efe, + 0x2f891: 0x22331, + 0x2f892: 0x22331, + 0x2f893: 0x8201, + 0x2f894: 0x5f22, + 0x2f895: 0x5f22, + 0x2f896: 0x38c7, + 0x2f897: 0x232b8, + 0x2f898: 0x261da, + 0x2f899: 0x5f62, + 0x2f89a: 0x5f6b, + 0x2f89b: 0x38e3, + 0x2f89c: 0x5f9a, + 0x2f89d: 0x5fcd, + 0x2f89e: 0x5fd7, + 0x2f89f: 0x5ff9, + 0x2f8a0: 0x6081, + 0x2f8a1: 0x393a, + 0x2f8a2: 0x391c, + 0x2f8a3: 0x6094, + 0x2f8a4: 0x226d4, + 0x2f8a5: 0x60c7, + 0x2f8a6: 0x6148, + 0x2f8a7: 0x614c, + 0x2f8a8: 0x614e, + 0x2f8a9: 0x614c, + 0x2f8aa: 0x617a, + 0x2f8ab: 0x618e, + 0x2f8ac: 0x61b2, + 0x2f8ad: 0x61a4, + 0x2f8ae: 0x61af, + 0x2f8af: 0x61de, + 0x2f8b0: 0x61f2, + 0x2f8b1: 0x61f6, + 0x2f8b2: 0x6210, + 0x2f8b3: 0x621b, + 0x2f8b4: 0x625d, + 0x2f8b5: 0x62b1, + 0x2f8b6: 0x62d4, + 0x2f8b7: 0x6350, + 0x2f8b8: 0x22b0c, + 0x2f8b9: 0x633d, + 0x2f8ba: 0x62fc, + 0x2f8bb: 0x6368, + 0x2f8bc: 0x6383, + 0x2f8bd: 0x63e4, + 0x2f8be: 0x22bf1, + 0x2f8bf: 0x6422, + 0x2f8c0: 0x63c5, + 0x2f8c1: 0x63a9, + 0x2f8c2: 0x3a2e, + 0x2f8c3: 0x6469, + 0x2f8c4: 0x647e, + 0x2f8c5: 0x649d, + 0x2f8c6: 0x6477, + 0x2f8c7: 0x3a6c, + 0x2f8c8: 0x654f, + 0x2f8c9: 0x656c, + 0x2f8ca: 0x2300a, + 0x2f8cb: 0x65e3, + 0x2f8cc: 0x66f8, + 0x2f8cd: 0x6649, + 0x2f8ce: 0x3b19, + 0x2f8cf: 0x6691, + 0x2f8d0: 0x3b08, + 0x2f8d1: 0x3ae4, + 0x2f8d2: 0x5192, + 0x2f8d3: 0x5195, + 0x2f8d4: 0x6700, + 0x2f8d5: 0x669c, + 0x2f8d6: 0x80ad, + 0x2f8d7: 0x43d9, + 0x2f8d8: 0x6717, + 0x2f8d9: 0x671b, + 0x2f8da: 0x6721, + 0x2f8db: 0x675e, + 0x2f8dc: 0x6753, + 0x2f8dd: 0x233c3, + 0x2f8de: 0x3b49, + 0x2f8df: 0x67fa, + 0x2f8e0: 0x6785, + 0x2f8e1: 0x6852, + 0x2f8e2: 0x6885, + 0x2f8e3: 0x2346d, + 0x2f8e4: 0x688e, + 0x2f8e5: 0x681f, + 0x2f8e6: 0x6914, + 0x2f8e7: 0x3b9d, + 0x2f8e8: 0x6942, + 0x2f8e9: 0x69a3, + 0x2f8ea: 0x69ea, + 0x2f8eb: 0x6aa8, + 0x2f8ec: 0x236a3, + 0x2f8ed: 0x6adb, + 0x2f8ee: 0x3c18, + 0x2f8ef: 0x6b21, + 0x2f8f0: 0x238a7, + 0x2f8f1: 0x6b54, + 0x2f8f2: 0x3c4e, + 0x2f8f3: 0x6b72, + 0x2f8f4: 0x6b9f, + 0x2f8f5: 0x6bba, + 0x2f8f6: 0x6bbb, + 0x2f8f7: 0x23a8d, + 0x2f8f8: 0x21d0b, + 0x2f8f9: 0x23afa, + 0x2f8fa: 0x6c4e, + 0x2f8fb: 0x23cbc, + 0x2f8fc: 0x6cbf, + 0x2f8fd: 0x6ccd, + 0x2f8fe: 0x6c67, + 0x2f8ff: 0x6d16, + 0x2f900: 0x6d3e, + 0x2f901: 0x6d77, + 0x2f902: 0x6d41, + 0x2f903: 0x6d69, + 0x2f904: 0x6d78, + 0x2f905: 0x6d85, + 0x2f906: 0x23d1e, + 0x2f907: 0x6d34, + 0x2f908: 0x6e2f, + 0x2f909: 0x6e6e, + 0x2f90a: 0x3d33, + 0x2f90b: 0x6ecb, + 0x2f90c: 0x6ec7, + 0x2f90d: 0x23ed1, + 0x2f90e: 0x6df9, + 0x2f90f: 0x6f6e, + 0x2f910: 0x23f5e, + 0x2f911: 0x23f8e, + 0x2f912: 0x6fc6, + 0x2f913: 0x7039, + 0x2f914: 0x701e, + 0x2f915: 0x701b, + 0x2f916: 0x3d96, + 0x2f917: 0x704a, + 0x2f918: 0x707d, + 0x2f919: 0x7077, + 0x2f91a: 0x70ad, + 0x2f91b: 0x20525, + 0x2f91c: 0x7145, + 0x2f91d: 0x24263, + 0x2f91e: 0x719c, + 0x2f91f: 0x243ab, + 0x2f920: 0x7228, + 0x2f921: 0x7235, + 0x2f922: 0x7250, + 0x2f923: 0x24608, + 0x2f924: 0x7280, + 0x2f925: 0x7295, + 0x2f926: 0x24735, + 0x2f927: 0x24814, + 0x2f928: 0x737a, + 0x2f929: 0x738b, + 0x2f92a: 0x3eac, + 0x2f92b: 0x73a5, + 0x2f92c: 0x3eb8, + 0x2f92d: 0x3eb8, + 0x2f92e: 0x7447, + 0x2f92f: 0x745c, + 0x2f930: 0x7471, + 0x2f931: 0x7485, + 0x2f932: 0x74ca, + 0x2f933: 0x3f1b, + 0x2f934: 0x7524, + 0x2f935: 0x24c36, + 0x2f936: 0x753e, + 0x2f937: 0x24c92, + 0x2f938: 0x7570, + 0x2f939: 0x2219f, + 0x2f93a: 0x7610, + 0x2f93b: 0x24fa1, + 0x2f93c: 0x24fb8, + 0x2f93d: 0x25044, + 0x2f93e: 0x3ffc, + 0x2f93f: 0x4008, + 0x2f940: 0x76f4, + 0x2f941: 0x250f3, + 0x2f942: 0x250f2, + 0x2f943: 0x25119, + 0x2f944: 0x25133, + 0x2f945: 0x771e, + 0x2f946: 0x771f, + 0x2f947: 0x771f, + 0x2f948: 0x774a, + 0x2f949: 0x4039, + 0x2f94a: 0x778b, + 0x2f94b: 0x4046, + 0x2f94c: 0x4096, + 0x2f94d: 0x2541d, + 0x2f94e: 0x784e, + 0x2f94f: 0x788c, + 0x2f950: 0x78cc, + 0x2f951: 0x40e3, + 0x2f952: 0x25626, + 0x2f953: 0x7956, + 0x2f954: 0x2569a, + 0x2f955: 0x256c5, + 0x2f956: 0x798f, + 0x2f957: 0x79eb, + 0x2f958: 0x412f, + 0x2f959: 0x7a40, + 0x2f95a: 0x7a4a, + 0x2f95b: 0x7a4f, + 0x2f95c: 0x2597c, + 0x2f95d: 0x25aa7, + 0x2f95e: 0x25aa7, + 0x2f95f: 0x7aee, + 0x2f960: 0x4202, + 0x2f961: 0x25bab, + 0x2f962: 0x7bc6, + 0x2f963: 0x7bc9, + 0x2f964: 0x4227, + 0x2f965: 0x25c80, + 0x2f966: 0x7cd2, + 0x2f967: 0x42a0, + 0x2f968: 0x7ce8, + 0x2f969: 0x7ce3, + 0x2f96a: 0x7d00, + 0x2f96b: 0x25f86, + 0x2f96c: 0x7d63, + 0x2f96d: 0x4301, + 0x2f96e: 0x7dc7, + 0x2f96f: 0x7e02, + 0x2f970: 0x7e45, + 0x2f971: 0x4334, + 0x2f972: 0x26228, + 0x2f973: 0x26247, + 0x2f974: 0x4359, + 0x2f975: 0x262d9, + 0x2f976: 0x7f7a, + 0x2f977: 0x2633e, + 0x2f978: 0x7f95, + 0x2f979: 0x7ffa, + 0x2f97a: 0x8005, + 0x2f97b: 0x264da, + 0x2f97c: 0x26523, + 0x2f97d: 0x8060, + 0x2f97e: 0x265a8, + 0x2f97f: 0x8070, + 0x2f980: 0x2335f, + 0x2f981: 0x43d5, + 0x2f982: 0x80b2, + 0x2f983: 0x8103, + 0x2f984: 0x440b, + 0x2f985: 0x813e, + 0x2f986: 0x5ab5, + 0x2f987: 0x267a7, + 0x2f988: 0x267b5, + 0x2f989: 0x23393, + 0x2f98a: 0x2339c, + 0x2f98b: 0x8201, + 0x2f98c: 0x8204, + 0x2f98d: 0x8f9e, + 0x2f98e: 0x446b, + 0x2f98f: 0x8291, + 0x2f990: 0x828b, + 0x2f991: 0x829d, + 0x2f992: 0x52b3, + 0x2f993: 0x82b1, + 0x2f994: 0x82b3, + 0x2f995: 0x82bd, + 0x2f996: 0x82e6, + 0x2f997: 0x26b3c, + 0x2f998: 0x82e5, + 0x2f999: 0x831d, + 0x2f99a: 0x8363, + 0x2f99b: 0x83ad, + 0x2f99c: 0x8323, + 0x2f99d: 0x83bd, + 0x2f99e: 0x83e7, + 0x2f99f: 0x8457, + 0x2f9a0: 0x8353, + 0x2f9a1: 0x83ca, + 0x2f9a2: 0x83cc, + 0x2f9a3: 0x83dc, + 0x2f9a4: 0x26c36, + 0x2f9a5: 0x26d6b, + 0x2f9a6: 0x26cd5, + 0x2f9a7: 0x452b, + 0x2f9a8: 0x84f1, + 0x2f9a9: 0x84f3, + 0x2f9aa: 0x8516, + 0x2f9ab: 0x273ca, + 0x2f9ac: 0x8564, + 0x2f9ad: 0x26f2c, + 0x2f9ae: 0x455d, + 0x2f9af: 0x4561, + 0x2f9b0: 0x26fb1, + 0x2f9b1: 0x270d2, + 0x2f9b2: 0x456b, + 0x2f9b3: 0x8650, + 0x2f9b4: 0x865c, + 0x2f9b5: 0x8667, + 0x2f9b6: 0x8669, + 0x2f9b7: 0x86a9, + 0x2f9b8: 0x8688, + 0x2f9b9: 0x870e, + 0x2f9ba: 0x86e2, + 0x2f9bb: 0x8779, + 0x2f9bc: 0x8728, + 0x2f9bd: 0x876b, + 0x2f9be: 0x8786, + 0x2f9bf: 0x45d7, + 0x2f9c0: 0x87e1, + 0x2f9c1: 0x8801, + 0x2f9c2: 0x45f9, + 0x2f9c3: 0x8860, + 0x2f9c4: 0x8863, + 0x2f9c5: 0x27667, + 0x2f9c6: 0x88d7, + 0x2f9c7: 0x88de, + 0x2f9c8: 0x4635, + 0x2f9c9: 0x88fa, + 0x2f9ca: 0x34bb, + 0x2f9cb: 0x278ae, + 0x2f9cc: 0x27966, + 0x2f9cd: 0x46be, + 0x2f9ce: 0x46c7, + 0x2f9cf: 0x8aa0, + 0x2f9d0: 0x8aed, + 0x2f9d1: 0x8b8a, + 0x2f9d2: 0x8c55, + 0x2f9d3: 0x27ca8, + 0x2f9d4: 0x8cab, + 0x2f9d5: 0x8cc1, + 0x2f9d6: 0x8d1b, + 0x2f9d7: 0x8d77, + 0x2f9d8: 0x27f2f, + 0x2f9d9: 0x20804, + 0x2f9da: 0x8dcb, + 0x2f9db: 0x8dbc, + 0x2f9dc: 0x8df0, + 0x2f9dd: 0x208de, + 0x2f9de: 0x8ed4, + 0x2f9df: 0x8f38, + 0x2f9e0: 0x285d2, + 0x2f9e1: 0x285ed, + 0x2f9e2: 0x9094, + 0x2f9e3: 0x90f1, + 0x2f9e4: 0x9111, + 0x2f9e5: 0x2872e, + 0x2f9e6: 0x911b, + 0x2f9e7: 0x9238, + 0x2f9e8: 0x92d7, + 0x2f9e9: 0x92d8, + 0x2f9ea: 0x927c, + 0x2f9eb: 0x93f9, + 0x2f9ec: 0x9415, + 0x2f9ed: 0x28bfa, + 0x2f9ee: 0x958b, + 0x2f9ef: 0x4995, + 0x2f9f0: 0x95b7, + 0x2f9f1: 0x28d77, + 0x2f9f2: 0x49e6, + 0x2f9f3: 0x96c3, + 0x2f9f4: 0x5db2, + 0x2f9f5: 0x9723, + 0x2f9f6: 0x29145, + 0x2f9f7: 0x2921a, + 0x2f9f8: 0x4a6e, + 0x2f9f9: 0x4a76, + 0x2f9fa: 0x97e0, + 0x2f9fb: 0x2940a, + 0x2f9fc: 0x4ab2, + 0x2f9fd: 0x29496, + 0x2f9fe: 0x980b, + 0x2f9ff: 0x980b, + 0x2fa00: 0x9829, + 0x2fa01: 0x295b6, + 0x2fa02: 0x98e2, + 0x2fa03: 0x4b33, + 0x2fa04: 0x9929, + 0x2fa05: 0x99a7, + 0x2fa06: 0x99c2, + 0x2fa07: 0x99fe, + 0x2fa08: 0x4bce, + 0x2fa09: 0x29b30, + 0x2fa0a: 0x9b12, + 0x2fa0b: 0x9c40, + 0x2fa0c: 0x9cfd, + 0x2fa0d: 0x4cce, + 0x2fa0e: 0x4ced, + 0x2fa0f: 0x9d67, + 0x2fa10: 0x2a0ce, + 0x2fa11: 0x4cf8, + 0x2fa12: 0x2a105, + 0x2fa13: 0x2a20e, + 0x2fa14: 0x2a291, + 0x2fa15: 0x9ebb, + 0x2fa16: 0x4d56, + 0x2fa17: 0x9ef9, + 0x2fa18: 0x9efe, + 0x2fa19: 0x9f05, + 0x2fa1a: 0x9f0f, + 0x2fa1b: 0x9f16, + 0x2fa1c: 0x9f3b, + 0x2fa1d: 0x2a600, +} +var decompose2 = map[rune][2]rune{ // 1026 entries + 0x00c0: {0x0041, 0x0300}, + 0x00c1: {0x0041, 0x0301}, + 0x00c2: {0x0041, 0x0302}, + 0x00c3: {0x0041, 0x0303}, + 0x00c4: {0x0041, 0x0308}, + 0x00c5: {0x0041, 0x030a}, + 0x00c7: {0x0043, 0x0327}, + 0x00c8: {0x0045, 0x0300}, + 0x00c9: {0x0045, 0x0301}, + 0x00ca: {0x0045, 0x0302}, + 0x00cb: {0x0045, 0x0308}, + 0x00cc: {0x0049, 0x0300}, + 0x00cd: {0x0049, 0x0301}, + 0x00ce: {0x0049, 0x0302}, + 0x00cf: {0x0049, 0x0308}, + 0x00d1: {0x004e, 0x0303}, + 0x00d2: {0x004f, 0x0300}, + 0x00d3: {0x004f, 0x0301}, + 0x00d4: {0x004f, 0x0302}, + 0x00d5: {0x004f, 0x0303}, + 0x00d6: {0x004f, 0x0308}, + 0x00d9: {0x0055, 0x0300}, + 0x00da: {0x0055, 0x0301}, + 0x00db: {0x0055, 0x0302}, + 0x00dc: {0x0055, 0x0308}, + 0x00dd: {0x0059, 0x0301}, + 0x00e0: {0x0061, 0x0300}, + 0x00e1: {0x0061, 0x0301}, + 0x00e2: {0x0061, 0x0302}, + 0x00e3: {0x0061, 0x0303}, + 0x00e4: {0x0061, 0x0308}, + 0x00e5: {0x0061, 0x030a}, + 0x00e7: {0x0063, 0x0327}, + 0x00e8: {0x0065, 0x0300}, + 0x00e9: {0x0065, 0x0301}, + 0x00ea: {0x0065, 0x0302}, + 0x00eb: {0x0065, 0x0308}, + 0x00ec: {0x0069, 0x0300}, + 0x00ed: {0x0069, 0x0301}, + 0x00ee: {0x0069, 0x0302}, + 0x00ef: {0x0069, 0x0308}, + 0x00f1: {0x006e, 0x0303}, + 0x00f2: {0x006f, 0x0300}, + 0x00f3: {0x006f, 0x0301}, + 0x00f4: {0x006f, 0x0302}, + 0x00f5: {0x006f, 0x0303}, + 0x00f6: {0x006f, 0x0308}, + 0x00f9: {0x0075, 0x0300}, + 0x00fa: {0x0075, 0x0301}, + 0x00fb: {0x0075, 0x0302}, + 0x00fc: {0x0075, 0x0308}, + 0x00fd: {0x0079, 0x0301}, + 0x00ff: {0x0079, 0x0308}, + 0x0100: {0x0041, 0x0304}, + 0x0101: {0x0061, 0x0304}, + 0x0102: {0x0041, 0x0306}, + 0x0103: {0x0061, 0x0306}, + 0x0104: {0x0041, 0x0328}, + 0x0105: {0x0061, 0x0328}, + 0x0106: {0x0043, 0x0301}, + 0x0107: {0x0063, 0x0301}, + 0x0108: {0x0043, 0x0302}, + 0x0109: {0x0063, 0x0302}, + 0x010a: {0x0043, 0x0307}, + 0x010b: {0x0063, 0x0307}, + 0x010c: {0x0043, 0x030c}, + 0x010d: {0x0063, 0x030c}, + 0x010e: {0x0044, 0x030c}, + 0x010f: {0x0064, 0x030c}, + 0x0112: {0x0045, 0x0304}, + 0x0113: {0x0065, 0x0304}, + 0x0114: {0x0045, 0x0306}, + 0x0115: {0x0065, 0x0306}, + 0x0116: {0x0045, 0x0307}, + 0x0117: {0x0065, 0x0307}, + 0x0118: {0x0045, 0x0328}, + 0x0119: {0x0065, 0x0328}, + 0x011a: {0x0045, 0x030c}, + 0x011b: {0x0065, 0x030c}, + 0x011c: {0x0047, 0x0302}, + 0x011d: {0x0067, 0x0302}, + 0x011e: {0x0047, 0x0306}, + 0x011f: {0x0067, 0x0306}, + 0x0120: {0x0047, 0x0307}, + 0x0121: {0x0067, 0x0307}, + 0x0122: {0x0047, 0x0327}, + 0x0123: {0x0067, 0x0327}, + 0x0124: {0x0048, 0x0302}, + 0x0125: {0x0068, 0x0302}, + 0x0128: {0x0049, 0x0303}, + 0x0129: {0x0069, 0x0303}, + 0x012a: {0x0049, 0x0304}, + 0x012b: {0x0069, 0x0304}, + 0x012c: {0x0049, 0x0306}, + 0x012d: {0x0069, 0x0306}, + 0x012e: {0x0049, 0x0328}, + 0x012f: {0x0069, 0x0328}, + 0x0130: {0x0049, 0x0307}, + 0x0134: {0x004a, 0x0302}, + 0x0135: {0x006a, 0x0302}, + 0x0136: {0x004b, 0x0327}, + 0x0137: {0x006b, 0x0327}, + 0x0139: {0x004c, 0x0301}, + 0x013a: {0x006c, 0x0301}, + 0x013b: {0x004c, 0x0327}, + 0x013c: {0x006c, 0x0327}, + 0x013d: {0x004c, 0x030c}, + 0x013e: {0x006c, 0x030c}, + 0x0143: {0x004e, 0x0301}, + 0x0144: {0x006e, 0x0301}, + 0x0145: {0x004e, 0x0327}, + 0x0146: {0x006e, 0x0327}, + 0x0147: {0x004e, 0x030c}, + 0x0148: {0x006e, 0x030c}, + 0x014c: {0x004f, 0x0304}, + 0x014d: {0x006f, 0x0304}, + 0x014e: {0x004f, 0x0306}, + 0x014f: {0x006f, 0x0306}, + 0x0150: {0x004f, 0x030b}, + 0x0151: {0x006f, 0x030b}, + 0x0154: {0x0052, 0x0301}, + 0x0155: {0x0072, 0x0301}, + 0x0156: {0x0052, 0x0327}, + 0x0157: {0x0072, 0x0327}, + 0x0158: {0x0052, 0x030c}, + 0x0159: {0x0072, 0x030c}, + 0x015a: {0x0053, 0x0301}, + 0x015b: {0x0073, 0x0301}, + 0x015c: {0x0053, 0x0302}, + 0x015d: {0x0073, 0x0302}, + 0x015e: {0x0053, 0x0327}, + 0x015f: {0x0073, 0x0327}, + 0x0160: {0x0053, 0x030c}, + 0x0161: {0x0073, 0x030c}, + 0x0162: {0x0054, 0x0327}, + 0x0163: {0x0074, 0x0327}, + 0x0164: {0x0054, 0x030c}, + 0x0165: {0x0074, 0x030c}, + 0x0168: {0x0055, 0x0303}, + 0x0169: {0x0075, 0x0303}, + 0x016a: {0x0055, 0x0304}, + 0x016b: {0x0075, 0x0304}, + 0x016c: {0x0055, 0x0306}, + 0x016d: {0x0075, 0x0306}, + 0x016e: {0x0055, 0x030a}, + 0x016f: {0x0075, 0x030a}, + 0x0170: {0x0055, 0x030b}, + 0x0171: {0x0075, 0x030b}, + 0x0172: {0x0055, 0x0328}, + 0x0173: {0x0075, 0x0328}, + 0x0174: {0x0057, 0x0302}, + 0x0175: {0x0077, 0x0302}, + 0x0176: {0x0059, 0x0302}, + 0x0177: {0x0079, 0x0302}, + 0x0178: {0x0059, 0x0308}, + 0x0179: {0x005a, 0x0301}, + 0x017a: {0x007a, 0x0301}, + 0x017b: {0x005a, 0x0307}, + 0x017c: {0x007a, 0x0307}, + 0x017d: {0x005a, 0x030c}, + 0x017e: {0x007a, 0x030c}, + 0x01a0: {0x004f, 0x031b}, + 0x01a1: {0x006f, 0x031b}, + 0x01af: {0x0055, 0x031b}, + 0x01b0: {0x0075, 0x031b}, + 0x01cd: {0x0041, 0x030c}, + 0x01ce: {0x0061, 0x030c}, + 0x01cf: {0x0049, 0x030c}, + 0x01d0: {0x0069, 0x030c}, + 0x01d1: {0x004f, 0x030c}, + 0x01d2: {0x006f, 0x030c}, + 0x01d3: {0x0055, 0x030c}, + 0x01d4: {0x0075, 0x030c}, + 0x01d5: {0x00dc, 0x0304}, + 0x01d6: {0x00fc, 0x0304}, + 0x01d7: {0x00dc, 0x0301}, + 0x01d8: {0x00fc, 0x0301}, + 0x01d9: {0x00dc, 0x030c}, + 0x01da: {0x00fc, 0x030c}, + 0x01db: {0x00dc, 0x0300}, + 0x01dc: {0x00fc, 0x0300}, + 0x01de: {0x00c4, 0x0304}, + 0x01df: {0x00e4, 0x0304}, + 0x01e0: {0x0226, 0x0304}, + 0x01e1: {0x0227, 0x0304}, + 0x01e2: {0x00c6, 0x0304}, + 0x01e3: {0x00e6, 0x0304}, + 0x01e6: {0x0047, 0x030c}, + 0x01e7: {0x0067, 0x030c}, + 0x01e8: {0x004b, 0x030c}, + 0x01e9: {0x006b, 0x030c}, + 0x01ea: {0x004f, 0x0328}, + 0x01eb: {0x006f, 0x0328}, + 0x01ec: {0x01ea, 0x0304}, + 0x01ed: {0x01eb, 0x0304}, + 0x01ee: {0x01b7, 0x030c}, + 0x01ef: {0x0292, 0x030c}, + 0x01f0: {0x006a, 0x030c}, + 0x01f4: {0x0047, 0x0301}, + 0x01f5: {0x0067, 0x0301}, + 0x01f8: {0x004e, 0x0300}, + 0x01f9: {0x006e, 0x0300}, + 0x01fa: {0x00c5, 0x0301}, + 0x01fb: {0x00e5, 0x0301}, + 0x01fc: {0x00c6, 0x0301}, + 0x01fd: {0x00e6, 0x0301}, + 0x01fe: {0x00d8, 0x0301}, + 0x01ff: {0x00f8, 0x0301}, + 0x0200: {0x0041, 0x030f}, + 0x0201: {0x0061, 0x030f}, + 0x0202: {0x0041, 0x0311}, + 0x0203: {0x0061, 0x0311}, + 0x0204: {0x0045, 0x030f}, + 0x0205: {0x0065, 0x030f}, + 0x0206: {0x0045, 0x0311}, + 0x0207: {0x0065, 0x0311}, + 0x0208: {0x0049, 0x030f}, + 0x0209: {0x0069, 0x030f}, + 0x020a: {0x0049, 0x0311}, + 0x020b: {0x0069, 0x0311}, + 0x020c: {0x004f, 0x030f}, + 0x020d: {0x006f, 0x030f}, + 0x020e: {0x004f, 0x0311}, + 0x020f: {0x006f, 0x0311}, + 0x0210: {0x0052, 0x030f}, + 0x0211: {0x0072, 0x030f}, + 0x0212: {0x0052, 0x0311}, + 0x0213: {0x0072, 0x0311}, + 0x0214: {0x0055, 0x030f}, + 0x0215: {0x0075, 0x030f}, + 0x0216: {0x0055, 0x0311}, + 0x0217: {0x0075, 0x0311}, + 0x0218: {0x0053, 0x0326}, + 0x0219: {0x0073, 0x0326}, + 0x021a: {0x0054, 0x0326}, + 0x021b: {0x0074, 0x0326}, + 0x021e: {0x0048, 0x030c}, + 0x021f: {0x0068, 0x030c}, + 0x0226: {0x0041, 0x0307}, + 0x0227: {0x0061, 0x0307}, + 0x0228: {0x0045, 0x0327}, + 0x0229: {0x0065, 0x0327}, + 0x022a: {0x00d6, 0x0304}, + 0x022b: {0x00f6, 0x0304}, + 0x022c: {0x00d5, 0x0304}, + 0x022d: {0x00f5, 0x0304}, + 0x022e: {0x004f, 0x0307}, + 0x022f: {0x006f, 0x0307}, + 0x0230: {0x022e, 0x0304}, + 0x0231: {0x022f, 0x0304}, + 0x0232: {0x0059, 0x0304}, + 0x0233: {0x0079, 0x0304}, + 0x0344: {0x0308, 0x0301}, + 0x0385: {0x00a8, 0x0301}, + 0x0386: {0x0391, 0x0301}, + 0x0388: {0x0395, 0x0301}, + 0x0389: {0x0397, 0x0301}, + 0x038a: {0x0399, 0x0301}, + 0x038c: {0x039f, 0x0301}, + 0x038e: {0x03a5, 0x0301}, + 0x038f: {0x03a9, 0x0301}, + 0x0390: {0x03ca, 0x0301}, + 0x03aa: {0x0399, 0x0308}, + 0x03ab: {0x03a5, 0x0308}, + 0x03ac: {0x03b1, 0x0301}, + 0x03ad: {0x03b5, 0x0301}, + 0x03ae: {0x03b7, 0x0301}, + 0x03af: {0x03b9, 0x0301}, + 0x03b0: {0x03cb, 0x0301}, + 0x03ca: {0x03b9, 0x0308}, + 0x03cb: {0x03c5, 0x0308}, + 0x03cc: {0x03bf, 0x0301}, + 0x03cd: {0x03c5, 0x0301}, + 0x03ce: {0x03c9, 0x0301}, + 0x03d3: {0x03d2, 0x0301}, + 0x03d4: {0x03d2, 0x0308}, + 0x0400: {0x0415, 0x0300}, + 0x0401: {0x0415, 0x0308}, + 0x0403: {0x0413, 0x0301}, + 0x0407: {0x0406, 0x0308}, + 0x040c: {0x041a, 0x0301}, + 0x040d: {0x0418, 0x0300}, + 0x040e: {0x0423, 0x0306}, + 0x0419: {0x0418, 0x0306}, + 0x0439: {0x0438, 0x0306}, + 0x0450: {0x0435, 0x0300}, + 0x0451: {0x0435, 0x0308}, + 0x0453: {0x0433, 0x0301}, + 0x0457: {0x0456, 0x0308}, + 0x045c: {0x043a, 0x0301}, + 0x045d: {0x0438, 0x0300}, + 0x045e: {0x0443, 0x0306}, + 0x0476: {0x0474, 0x030f}, + 0x0477: {0x0475, 0x030f}, + 0x04c1: {0x0416, 0x0306}, + 0x04c2: {0x0436, 0x0306}, + 0x04d0: {0x0410, 0x0306}, + 0x04d1: {0x0430, 0x0306}, + 0x04d2: {0x0410, 0x0308}, + 0x04d3: {0x0430, 0x0308}, + 0x04d6: {0x0415, 0x0306}, + 0x04d7: {0x0435, 0x0306}, + 0x04da: {0x04d8, 0x0308}, + 0x04db: {0x04d9, 0x0308}, + 0x04dc: {0x0416, 0x0308}, + 0x04dd: {0x0436, 0x0308}, + 0x04de: {0x0417, 0x0308}, + 0x04df: {0x0437, 0x0308}, + 0x04e2: {0x0418, 0x0304}, + 0x04e3: {0x0438, 0x0304}, + 0x04e4: {0x0418, 0x0308}, + 0x04e5: {0x0438, 0x0308}, + 0x04e6: {0x041e, 0x0308}, + 0x04e7: {0x043e, 0x0308}, + 0x04ea: {0x04e8, 0x0308}, + 0x04eb: {0x04e9, 0x0308}, + 0x04ec: {0x042d, 0x0308}, + 0x04ed: {0x044d, 0x0308}, + 0x04ee: {0x0423, 0x0304}, + 0x04ef: {0x0443, 0x0304}, + 0x04f0: {0x0423, 0x0308}, + 0x04f1: {0x0443, 0x0308}, + 0x04f2: {0x0423, 0x030b}, + 0x04f3: {0x0443, 0x030b}, + 0x04f4: {0x0427, 0x0308}, + 0x04f5: {0x0447, 0x0308}, + 0x04f8: {0x042b, 0x0308}, + 0x04f9: {0x044b, 0x0308}, + 0x0622: {0x0627, 0x0653}, + 0x0623: {0x0627, 0x0654}, + 0x0624: {0x0648, 0x0654}, + 0x0625: {0x0627, 0x0655}, + 0x0626: {0x064a, 0x0654}, + 0x06c0: {0x06d5, 0x0654}, + 0x06c2: {0x06c1, 0x0654}, + 0x06d3: {0x06d2, 0x0654}, + 0x0929: {0x0928, 0x093c}, + 0x0931: {0x0930, 0x093c}, + 0x0934: {0x0933, 0x093c}, + 0x0958: {0x0915, 0x093c}, + 0x0959: {0x0916, 0x093c}, + 0x095a: {0x0917, 0x093c}, + 0x095b: {0x091c, 0x093c}, + 0x095c: {0x0921, 0x093c}, + 0x095d: {0x0922, 0x093c}, + 0x095e: {0x092b, 0x093c}, + 0x095f: {0x092f, 0x093c}, + 0x09cb: {0x09c7, 0x09be}, + 0x09cc: {0x09c7, 0x09d7}, + 0x09dc: {0x09a1, 0x09bc}, + 0x09dd: {0x09a2, 0x09bc}, + 0x09df: {0x09af, 0x09bc}, + 0x0a33: {0x0a32, 0x0a3c}, + 0x0a36: {0x0a38, 0x0a3c}, + 0x0a59: {0x0a16, 0x0a3c}, + 0x0a5a: {0x0a17, 0x0a3c}, + 0x0a5b: {0x0a1c, 0x0a3c}, + 0x0a5e: {0x0a2b, 0x0a3c}, + 0x0b48: {0x0b47, 0x0b56}, + 0x0b4b: {0x0b47, 0x0b3e}, + 0x0b4c: {0x0b47, 0x0b57}, + 0x0b5c: {0x0b21, 0x0b3c}, + 0x0b5d: {0x0b22, 0x0b3c}, + 0x0b94: {0x0b92, 0x0bd7}, + 0x0bca: {0x0bc6, 0x0bbe}, + 0x0bcb: {0x0bc7, 0x0bbe}, + 0x0bcc: {0x0bc6, 0x0bd7}, + 0x0c48: {0x0c46, 0x0c56}, + 0x0cc0: {0x0cbf, 0x0cd5}, + 0x0cc7: {0x0cc6, 0x0cd5}, + 0x0cc8: {0x0cc6, 0x0cd6}, + 0x0cca: {0x0cc6, 0x0cc2}, + 0x0ccb: {0x0cca, 0x0cd5}, + 0x0d4a: {0x0d46, 0x0d3e}, + 0x0d4b: {0x0d47, 0x0d3e}, + 0x0d4c: {0x0d46, 0x0d57}, + 0x0dda: {0x0dd9, 0x0dca}, + 0x0ddc: {0x0dd9, 0x0dcf}, + 0x0ddd: {0x0ddc, 0x0dca}, + 0x0dde: {0x0dd9, 0x0ddf}, + 0x0f43: {0x0f42, 0x0fb7}, + 0x0f4d: {0x0f4c, 0x0fb7}, + 0x0f52: {0x0f51, 0x0fb7}, + 0x0f57: {0x0f56, 0x0fb7}, + 0x0f5c: {0x0f5b, 0x0fb7}, + 0x0f69: {0x0f40, 0x0fb5}, + 0x0f73: {0x0f71, 0x0f72}, + 0x0f75: {0x0f71, 0x0f74}, + 0x0f76: {0x0fb2, 0x0f80}, + 0x0f78: {0x0fb3, 0x0f80}, + 0x0f81: {0x0f71, 0x0f80}, + 0x0f93: {0x0f92, 0x0fb7}, + 0x0f9d: {0x0f9c, 0x0fb7}, + 0x0fa2: {0x0fa1, 0x0fb7}, + 0x0fa7: {0x0fa6, 0x0fb7}, + 0x0fac: {0x0fab, 0x0fb7}, + 0x0fb9: {0x0f90, 0x0fb5}, + 0x1026: {0x1025, 0x102e}, + 0x1b06: {0x1b05, 0x1b35}, + 0x1b08: {0x1b07, 0x1b35}, + 0x1b0a: {0x1b09, 0x1b35}, + 0x1b0c: {0x1b0b, 0x1b35}, + 0x1b0e: {0x1b0d, 0x1b35}, + 0x1b12: {0x1b11, 0x1b35}, + 0x1b3b: {0x1b3a, 0x1b35}, + 0x1b3d: {0x1b3c, 0x1b35}, + 0x1b40: {0x1b3e, 0x1b35}, + 0x1b41: {0x1b3f, 0x1b35}, + 0x1b43: {0x1b42, 0x1b35}, + 0x1e00: {0x0041, 0x0325}, + 0x1e01: {0x0061, 0x0325}, + 0x1e02: {0x0042, 0x0307}, + 0x1e03: {0x0062, 0x0307}, + 0x1e04: {0x0042, 0x0323}, + 0x1e05: {0x0062, 0x0323}, + 0x1e06: {0x0042, 0x0331}, + 0x1e07: {0x0062, 0x0331}, + 0x1e08: {0x00c7, 0x0301}, + 0x1e09: {0x00e7, 0x0301}, + 0x1e0a: {0x0044, 0x0307}, + 0x1e0b: {0x0064, 0x0307}, + 0x1e0c: {0x0044, 0x0323}, + 0x1e0d: {0x0064, 0x0323}, + 0x1e0e: {0x0044, 0x0331}, + 0x1e0f: {0x0064, 0x0331}, + 0x1e10: {0x0044, 0x0327}, + 0x1e11: {0x0064, 0x0327}, + 0x1e12: {0x0044, 0x032d}, + 0x1e13: {0x0064, 0x032d}, + 0x1e14: {0x0112, 0x0300}, + 0x1e15: {0x0113, 0x0300}, + 0x1e16: {0x0112, 0x0301}, + 0x1e17: {0x0113, 0x0301}, + 0x1e18: {0x0045, 0x032d}, + 0x1e19: {0x0065, 0x032d}, + 0x1e1a: {0x0045, 0x0330}, + 0x1e1b: {0x0065, 0x0330}, + 0x1e1c: {0x0228, 0x0306}, + 0x1e1d: {0x0229, 0x0306}, + 0x1e1e: {0x0046, 0x0307}, + 0x1e1f: {0x0066, 0x0307}, + 0x1e20: {0x0047, 0x0304}, + 0x1e21: {0x0067, 0x0304}, + 0x1e22: {0x0048, 0x0307}, + 0x1e23: {0x0068, 0x0307}, + 0x1e24: {0x0048, 0x0323}, + 0x1e25: {0x0068, 0x0323}, + 0x1e26: {0x0048, 0x0308}, + 0x1e27: {0x0068, 0x0308}, + 0x1e28: {0x0048, 0x0327}, + 0x1e29: {0x0068, 0x0327}, + 0x1e2a: {0x0048, 0x032e}, + 0x1e2b: {0x0068, 0x032e}, + 0x1e2c: {0x0049, 0x0330}, + 0x1e2d: {0x0069, 0x0330}, + 0x1e2e: {0x00cf, 0x0301}, + 0x1e2f: {0x00ef, 0x0301}, + 0x1e30: {0x004b, 0x0301}, + 0x1e31: {0x006b, 0x0301}, + 0x1e32: {0x004b, 0x0323}, + 0x1e33: {0x006b, 0x0323}, + 0x1e34: {0x004b, 0x0331}, + 0x1e35: {0x006b, 0x0331}, + 0x1e36: {0x004c, 0x0323}, + 0x1e37: {0x006c, 0x0323}, + 0x1e38: {0x1e36, 0x0304}, + 0x1e39: {0x1e37, 0x0304}, + 0x1e3a: {0x004c, 0x0331}, + 0x1e3b: {0x006c, 0x0331}, + 0x1e3c: {0x004c, 0x032d}, + 0x1e3d: {0x006c, 0x032d}, + 0x1e3e: {0x004d, 0x0301}, + 0x1e3f: {0x006d, 0x0301}, + 0x1e40: {0x004d, 0x0307}, + 0x1e41: {0x006d, 0x0307}, + 0x1e42: {0x004d, 0x0323}, + 0x1e43: {0x006d, 0x0323}, + 0x1e44: {0x004e, 0x0307}, + 0x1e45: {0x006e, 0x0307}, + 0x1e46: {0x004e, 0x0323}, + 0x1e47: {0x006e, 0x0323}, + 0x1e48: {0x004e, 0x0331}, + 0x1e49: {0x006e, 0x0331}, + 0x1e4a: {0x004e, 0x032d}, + 0x1e4b: {0x006e, 0x032d}, + 0x1e4c: {0x00d5, 0x0301}, + 0x1e4d: {0x00f5, 0x0301}, + 0x1e4e: {0x00d5, 0x0308}, + 0x1e4f: {0x00f5, 0x0308}, + 0x1e50: {0x014c, 0x0300}, + 0x1e51: {0x014d, 0x0300}, + 0x1e52: {0x014c, 0x0301}, + 0x1e53: {0x014d, 0x0301}, + 0x1e54: {0x0050, 0x0301}, + 0x1e55: {0x0070, 0x0301}, + 0x1e56: {0x0050, 0x0307}, + 0x1e57: {0x0070, 0x0307}, + 0x1e58: {0x0052, 0x0307}, + 0x1e59: {0x0072, 0x0307}, + 0x1e5a: {0x0052, 0x0323}, + 0x1e5b: {0x0072, 0x0323}, + 0x1e5c: {0x1e5a, 0x0304}, + 0x1e5d: {0x1e5b, 0x0304}, + 0x1e5e: {0x0052, 0x0331}, + 0x1e5f: {0x0072, 0x0331}, + 0x1e60: {0x0053, 0x0307}, + 0x1e61: {0x0073, 0x0307}, + 0x1e62: {0x0053, 0x0323}, + 0x1e63: {0x0073, 0x0323}, + 0x1e64: {0x015a, 0x0307}, + 0x1e65: {0x015b, 0x0307}, + 0x1e66: {0x0160, 0x0307}, + 0x1e67: {0x0161, 0x0307}, + 0x1e68: {0x1e62, 0x0307}, + 0x1e69: {0x1e63, 0x0307}, + 0x1e6a: {0x0054, 0x0307}, + 0x1e6b: {0x0074, 0x0307}, + 0x1e6c: {0x0054, 0x0323}, + 0x1e6d: {0x0074, 0x0323}, + 0x1e6e: {0x0054, 0x0331}, + 0x1e6f: {0x0074, 0x0331}, + 0x1e70: {0x0054, 0x032d}, + 0x1e71: {0x0074, 0x032d}, + 0x1e72: {0x0055, 0x0324}, + 0x1e73: {0x0075, 0x0324}, + 0x1e74: {0x0055, 0x0330}, + 0x1e75: {0x0075, 0x0330}, + 0x1e76: {0x0055, 0x032d}, + 0x1e77: {0x0075, 0x032d}, + 0x1e78: {0x0168, 0x0301}, + 0x1e79: {0x0169, 0x0301}, + 0x1e7a: {0x016a, 0x0308}, + 0x1e7b: {0x016b, 0x0308}, + 0x1e7c: {0x0056, 0x0303}, + 0x1e7d: {0x0076, 0x0303}, + 0x1e7e: {0x0056, 0x0323}, + 0x1e7f: {0x0076, 0x0323}, + 0x1e80: {0x0057, 0x0300}, + 0x1e81: {0x0077, 0x0300}, + 0x1e82: {0x0057, 0x0301}, + 0x1e83: {0x0077, 0x0301}, + 0x1e84: {0x0057, 0x0308}, + 0x1e85: {0x0077, 0x0308}, + 0x1e86: {0x0057, 0x0307}, + 0x1e87: {0x0077, 0x0307}, + 0x1e88: {0x0057, 0x0323}, + 0x1e89: {0x0077, 0x0323}, + 0x1e8a: {0x0058, 0x0307}, + 0x1e8b: {0x0078, 0x0307}, + 0x1e8c: {0x0058, 0x0308}, + 0x1e8d: {0x0078, 0x0308}, + 0x1e8e: {0x0059, 0x0307}, + 0x1e8f: {0x0079, 0x0307}, + 0x1e90: {0x005a, 0x0302}, + 0x1e91: {0x007a, 0x0302}, + 0x1e92: {0x005a, 0x0323}, + 0x1e93: {0x007a, 0x0323}, + 0x1e94: {0x005a, 0x0331}, + 0x1e95: {0x007a, 0x0331}, + 0x1e96: {0x0068, 0x0331}, + 0x1e97: {0x0074, 0x0308}, + 0x1e98: {0x0077, 0x030a}, + 0x1e99: {0x0079, 0x030a}, + 0x1e9b: {0x017f, 0x0307}, + 0x1ea0: {0x0041, 0x0323}, + 0x1ea1: {0x0061, 0x0323}, + 0x1ea2: {0x0041, 0x0309}, + 0x1ea3: {0x0061, 0x0309}, + 0x1ea4: {0x00c2, 0x0301}, + 0x1ea5: {0x00e2, 0x0301}, + 0x1ea6: {0x00c2, 0x0300}, + 0x1ea7: {0x00e2, 0x0300}, + 0x1ea8: {0x00c2, 0x0309}, + 0x1ea9: {0x00e2, 0x0309}, + 0x1eaa: {0x00c2, 0x0303}, + 0x1eab: {0x00e2, 0x0303}, + 0x1eac: {0x1ea0, 0x0302}, + 0x1ead: {0x1ea1, 0x0302}, + 0x1eae: {0x0102, 0x0301}, + 0x1eaf: {0x0103, 0x0301}, + 0x1eb0: {0x0102, 0x0300}, + 0x1eb1: {0x0103, 0x0300}, + 0x1eb2: {0x0102, 0x0309}, + 0x1eb3: {0x0103, 0x0309}, + 0x1eb4: {0x0102, 0x0303}, + 0x1eb5: {0x0103, 0x0303}, + 0x1eb6: {0x1ea0, 0x0306}, + 0x1eb7: {0x1ea1, 0x0306}, + 0x1eb8: {0x0045, 0x0323}, + 0x1eb9: {0x0065, 0x0323}, + 0x1eba: {0x0045, 0x0309}, + 0x1ebb: {0x0065, 0x0309}, + 0x1ebc: {0x0045, 0x0303}, + 0x1ebd: {0x0065, 0x0303}, + 0x1ebe: {0x00ca, 0x0301}, + 0x1ebf: {0x00ea, 0x0301}, + 0x1ec0: {0x00ca, 0x0300}, + 0x1ec1: {0x00ea, 0x0300}, + 0x1ec2: {0x00ca, 0x0309}, + 0x1ec3: {0x00ea, 0x0309}, + 0x1ec4: {0x00ca, 0x0303}, + 0x1ec5: {0x00ea, 0x0303}, + 0x1ec6: {0x1eb8, 0x0302}, + 0x1ec7: {0x1eb9, 0x0302}, + 0x1ec8: {0x0049, 0x0309}, + 0x1ec9: {0x0069, 0x0309}, + 0x1eca: {0x0049, 0x0323}, + 0x1ecb: {0x0069, 0x0323}, + 0x1ecc: {0x004f, 0x0323}, + 0x1ecd: {0x006f, 0x0323}, + 0x1ece: {0x004f, 0x0309}, + 0x1ecf: {0x006f, 0x0309}, + 0x1ed0: {0x00d4, 0x0301}, + 0x1ed1: {0x00f4, 0x0301}, + 0x1ed2: {0x00d4, 0x0300}, + 0x1ed3: {0x00f4, 0x0300}, + 0x1ed4: {0x00d4, 0x0309}, + 0x1ed5: {0x00f4, 0x0309}, + 0x1ed6: {0x00d4, 0x0303}, + 0x1ed7: {0x00f4, 0x0303}, + 0x1ed8: {0x1ecc, 0x0302}, + 0x1ed9: {0x1ecd, 0x0302}, + 0x1eda: {0x01a0, 0x0301}, + 0x1edb: {0x01a1, 0x0301}, + 0x1edc: {0x01a0, 0x0300}, + 0x1edd: {0x01a1, 0x0300}, + 0x1ede: {0x01a0, 0x0309}, + 0x1edf: {0x01a1, 0x0309}, + 0x1ee0: {0x01a0, 0x0303}, + 0x1ee1: {0x01a1, 0x0303}, + 0x1ee2: {0x01a0, 0x0323}, + 0x1ee3: {0x01a1, 0x0323}, + 0x1ee4: {0x0055, 0x0323}, + 0x1ee5: {0x0075, 0x0323}, + 0x1ee6: {0x0055, 0x0309}, + 0x1ee7: {0x0075, 0x0309}, + 0x1ee8: {0x01af, 0x0301}, + 0x1ee9: {0x01b0, 0x0301}, + 0x1eea: {0x01af, 0x0300}, + 0x1eeb: {0x01b0, 0x0300}, + 0x1eec: {0x01af, 0x0309}, + 0x1eed: {0x01b0, 0x0309}, + 0x1eee: {0x01af, 0x0303}, + 0x1eef: {0x01b0, 0x0303}, + 0x1ef0: {0x01af, 0x0323}, + 0x1ef1: {0x01b0, 0x0323}, + 0x1ef2: {0x0059, 0x0300}, + 0x1ef3: {0x0079, 0x0300}, + 0x1ef4: {0x0059, 0x0323}, + 0x1ef5: {0x0079, 0x0323}, + 0x1ef6: {0x0059, 0x0309}, + 0x1ef7: {0x0079, 0x0309}, + 0x1ef8: {0x0059, 0x0303}, + 0x1ef9: {0x0079, 0x0303}, + 0x1f00: {0x03b1, 0x0313}, + 0x1f01: {0x03b1, 0x0314}, + 0x1f02: {0x1f00, 0x0300}, + 0x1f03: {0x1f01, 0x0300}, + 0x1f04: {0x1f00, 0x0301}, + 0x1f05: {0x1f01, 0x0301}, + 0x1f06: {0x1f00, 0x0342}, + 0x1f07: {0x1f01, 0x0342}, + 0x1f08: {0x0391, 0x0313}, + 0x1f09: {0x0391, 0x0314}, + 0x1f0a: {0x1f08, 0x0300}, + 0x1f0b: {0x1f09, 0x0300}, + 0x1f0c: {0x1f08, 0x0301}, + 0x1f0d: {0x1f09, 0x0301}, + 0x1f0e: {0x1f08, 0x0342}, + 0x1f0f: {0x1f09, 0x0342}, + 0x1f10: {0x03b5, 0x0313}, + 0x1f11: {0x03b5, 0x0314}, + 0x1f12: {0x1f10, 0x0300}, + 0x1f13: {0x1f11, 0x0300}, + 0x1f14: {0x1f10, 0x0301}, + 0x1f15: {0x1f11, 0x0301}, + 0x1f18: {0x0395, 0x0313}, + 0x1f19: {0x0395, 0x0314}, + 0x1f1a: {0x1f18, 0x0300}, + 0x1f1b: {0x1f19, 0x0300}, + 0x1f1c: {0x1f18, 0x0301}, + 0x1f1d: {0x1f19, 0x0301}, + 0x1f20: {0x03b7, 0x0313}, + 0x1f21: {0x03b7, 0x0314}, + 0x1f22: {0x1f20, 0x0300}, + 0x1f23: {0x1f21, 0x0300}, + 0x1f24: {0x1f20, 0x0301}, + 0x1f25: {0x1f21, 0x0301}, + 0x1f26: {0x1f20, 0x0342}, + 0x1f27: {0x1f21, 0x0342}, + 0x1f28: {0x0397, 0x0313}, + 0x1f29: {0x0397, 0x0314}, + 0x1f2a: {0x1f28, 0x0300}, + 0x1f2b: {0x1f29, 0x0300}, + 0x1f2c: {0x1f28, 0x0301}, + 0x1f2d: {0x1f29, 0x0301}, + 0x1f2e: {0x1f28, 0x0342}, + 0x1f2f: {0x1f29, 0x0342}, + 0x1f30: {0x03b9, 0x0313}, + 0x1f31: {0x03b9, 0x0314}, + 0x1f32: {0x1f30, 0x0300}, + 0x1f33: {0x1f31, 0x0300}, + 0x1f34: {0x1f30, 0x0301}, + 0x1f35: {0x1f31, 0x0301}, + 0x1f36: {0x1f30, 0x0342}, + 0x1f37: {0x1f31, 0x0342}, + 0x1f38: {0x0399, 0x0313}, + 0x1f39: {0x0399, 0x0314}, + 0x1f3a: {0x1f38, 0x0300}, + 0x1f3b: {0x1f39, 0x0300}, + 0x1f3c: {0x1f38, 0x0301}, + 0x1f3d: {0x1f39, 0x0301}, + 0x1f3e: {0x1f38, 0x0342}, + 0x1f3f: {0x1f39, 0x0342}, + 0x1f40: {0x03bf, 0x0313}, + 0x1f41: {0x03bf, 0x0314}, + 0x1f42: {0x1f40, 0x0300}, + 0x1f43: {0x1f41, 0x0300}, + 0x1f44: {0x1f40, 0x0301}, + 0x1f45: {0x1f41, 0x0301}, + 0x1f48: {0x039f, 0x0313}, + 0x1f49: {0x039f, 0x0314}, + 0x1f4a: {0x1f48, 0x0300}, + 0x1f4b: {0x1f49, 0x0300}, + 0x1f4c: {0x1f48, 0x0301}, + 0x1f4d: {0x1f49, 0x0301}, + 0x1f50: {0x03c5, 0x0313}, + 0x1f51: {0x03c5, 0x0314}, + 0x1f52: {0x1f50, 0x0300}, + 0x1f53: {0x1f51, 0x0300}, + 0x1f54: {0x1f50, 0x0301}, + 0x1f55: {0x1f51, 0x0301}, + 0x1f56: {0x1f50, 0x0342}, + 0x1f57: {0x1f51, 0x0342}, + 0x1f59: {0x03a5, 0x0314}, + 0x1f5b: {0x1f59, 0x0300}, + 0x1f5d: {0x1f59, 0x0301}, + 0x1f5f: {0x1f59, 0x0342}, + 0x1f60: {0x03c9, 0x0313}, + 0x1f61: {0x03c9, 0x0314}, + 0x1f62: {0x1f60, 0x0300}, + 0x1f63: {0x1f61, 0x0300}, + 0x1f64: {0x1f60, 0x0301}, + 0x1f65: {0x1f61, 0x0301}, + 0x1f66: {0x1f60, 0x0342}, + 0x1f67: {0x1f61, 0x0342}, + 0x1f68: {0x03a9, 0x0313}, + 0x1f69: {0x03a9, 0x0314}, + 0x1f6a: {0x1f68, 0x0300}, + 0x1f6b: {0x1f69, 0x0300}, + 0x1f6c: {0x1f68, 0x0301}, + 0x1f6d: {0x1f69, 0x0301}, + 0x1f6e: {0x1f68, 0x0342}, + 0x1f6f: {0x1f69, 0x0342}, + 0x1f70: {0x03b1, 0x0300}, + 0x1f72: {0x03b5, 0x0300}, + 0x1f74: {0x03b7, 0x0300}, + 0x1f76: {0x03b9, 0x0300}, + 0x1f78: {0x03bf, 0x0300}, + 0x1f7a: {0x03c5, 0x0300}, + 0x1f7c: {0x03c9, 0x0300}, + 0x1f80: {0x1f00, 0x0345}, + 0x1f81: {0x1f01, 0x0345}, + 0x1f82: {0x1f02, 0x0345}, + 0x1f83: {0x1f03, 0x0345}, + 0x1f84: {0x1f04, 0x0345}, + 0x1f85: {0x1f05, 0x0345}, + 0x1f86: {0x1f06, 0x0345}, + 0x1f87: {0x1f07, 0x0345}, + 0x1f88: {0x1f08, 0x0345}, + 0x1f89: {0x1f09, 0x0345}, + 0x1f8a: {0x1f0a, 0x0345}, + 0x1f8b: {0x1f0b, 0x0345}, + 0x1f8c: {0x1f0c, 0x0345}, + 0x1f8d: {0x1f0d, 0x0345}, + 0x1f8e: {0x1f0e, 0x0345}, + 0x1f8f: {0x1f0f, 0x0345}, + 0x1f90: {0x1f20, 0x0345}, + 0x1f91: {0x1f21, 0x0345}, + 0x1f92: {0x1f22, 0x0345}, + 0x1f93: {0x1f23, 0x0345}, + 0x1f94: {0x1f24, 0x0345}, + 0x1f95: {0x1f25, 0x0345}, + 0x1f96: {0x1f26, 0x0345}, + 0x1f97: {0x1f27, 0x0345}, + 0x1f98: {0x1f28, 0x0345}, + 0x1f99: {0x1f29, 0x0345}, + 0x1f9a: {0x1f2a, 0x0345}, + 0x1f9b: {0x1f2b, 0x0345}, + 0x1f9c: {0x1f2c, 0x0345}, + 0x1f9d: {0x1f2d, 0x0345}, + 0x1f9e: {0x1f2e, 0x0345}, + 0x1f9f: {0x1f2f, 0x0345}, + 0x1fa0: {0x1f60, 0x0345}, + 0x1fa1: {0x1f61, 0x0345}, + 0x1fa2: {0x1f62, 0x0345}, + 0x1fa3: {0x1f63, 0x0345}, + 0x1fa4: {0x1f64, 0x0345}, + 0x1fa5: {0x1f65, 0x0345}, + 0x1fa6: {0x1f66, 0x0345}, + 0x1fa7: {0x1f67, 0x0345}, + 0x1fa8: {0x1f68, 0x0345}, + 0x1fa9: {0x1f69, 0x0345}, + 0x1faa: {0x1f6a, 0x0345}, + 0x1fab: {0x1f6b, 0x0345}, + 0x1fac: {0x1f6c, 0x0345}, + 0x1fad: {0x1f6d, 0x0345}, + 0x1fae: {0x1f6e, 0x0345}, + 0x1faf: {0x1f6f, 0x0345}, + 0x1fb0: {0x03b1, 0x0306}, + 0x1fb1: {0x03b1, 0x0304}, + 0x1fb2: {0x1f70, 0x0345}, + 0x1fb3: {0x03b1, 0x0345}, + 0x1fb4: {0x03ac, 0x0345}, + 0x1fb6: {0x03b1, 0x0342}, + 0x1fb7: {0x1fb6, 0x0345}, + 0x1fb8: {0x0391, 0x0306}, + 0x1fb9: {0x0391, 0x0304}, + 0x1fba: {0x0391, 0x0300}, + 0x1fbc: {0x0391, 0x0345}, + 0x1fc1: {0x00a8, 0x0342}, + 0x1fc2: {0x1f74, 0x0345}, + 0x1fc3: {0x03b7, 0x0345}, + 0x1fc4: {0x03ae, 0x0345}, + 0x1fc6: {0x03b7, 0x0342}, + 0x1fc7: {0x1fc6, 0x0345}, + 0x1fc8: {0x0395, 0x0300}, + 0x1fca: {0x0397, 0x0300}, + 0x1fcc: {0x0397, 0x0345}, + 0x1fcd: {0x1fbf, 0x0300}, + 0x1fce: {0x1fbf, 0x0301}, + 0x1fcf: {0x1fbf, 0x0342}, + 0x1fd0: {0x03b9, 0x0306}, + 0x1fd1: {0x03b9, 0x0304}, + 0x1fd2: {0x03ca, 0x0300}, + 0x1fd6: {0x03b9, 0x0342}, + 0x1fd7: {0x03ca, 0x0342}, + 0x1fd8: {0x0399, 0x0306}, + 0x1fd9: {0x0399, 0x0304}, + 0x1fda: {0x0399, 0x0300}, + 0x1fdd: {0x1ffe, 0x0300}, + 0x1fde: {0x1ffe, 0x0301}, + 0x1fdf: {0x1ffe, 0x0342}, + 0x1fe0: {0x03c5, 0x0306}, + 0x1fe1: {0x03c5, 0x0304}, + 0x1fe2: {0x03cb, 0x0300}, + 0x1fe4: {0x03c1, 0x0313}, + 0x1fe5: {0x03c1, 0x0314}, + 0x1fe6: {0x03c5, 0x0342}, + 0x1fe7: {0x03cb, 0x0342}, + 0x1fe8: {0x03a5, 0x0306}, + 0x1fe9: {0x03a5, 0x0304}, + 0x1fea: {0x03a5, 0x0300}, + 0x1fec: {0x03a1, 0x0314}, + 0x1fed: {0x00a8, 0x0300}, + 0x1ff2: {0x1f7c, 0x0345}, + 0x1ff3: {0x03c9, 0x0345}, + 0x1ff4: {0x03ce, 0x0345}, + 0x1ff6: {0x03c9, 0x0342}, + 0x1ff7: {0x1ff6, 0x0345}, + 0x1ff8: {0x039f, 0x0300}, + 0x1ffa: {0x03a9, 0x0300}, + 0x1ffc: {0x03a9, 0x0345}, + 0x219a: {0x2190, 0x0338}, + 0x219b: {0x2192, 0x0338}, + 0x21ae: {0x2194, 0x0338}, + 0x21cd: {0x21d0, 0x0338}, + 0x21ce: {0x21d4, 0x0338}, + 0x21cf: {0x21d2, 0x0338}, + 0x2204: {0x2203, 0x0338}, + 0x2209: {0x2208, 0x0338}, + 0x220c: {0x220b, 0x0338}, + 0x2224: {0x2223, 0x0338}, + 0x2226: {0x2225, 0x0338}, + 0x2241: {0x223c, 0x0338}, + 0x2244: {0x2243, 0x0338}, + 0x2247: {0x2245, 0x0338}, + 0x2249: {0x2248, 0x0338}, + 0x2260: {0x003d, 0x0338}, + 0x2262: {0x2261, 0x0338}, + 0x226d: {0x224d, 0x0338}, + 0x226e: {0x003c, 0x0338}, + 0x226f: {0x003e, 0x0338}, + 0x2270: {0x2264, 0x0338}, + 0x2271: {0x2265, 0x0338}, + 0x2274: {0x2272, 0x0338}, + 0x2275: {0x2273, 0x0338}, + 0x2278: {0x2276, 0x0338}, + 0x2279: {0x2277, 0x0338}, + 0x2280: {0x227a, 0x0338}, + 0x2281: {0x227b, 0x0338}, + 0x2284: {0x2282, 0x0338}, + 0x2285: {0x2283, 0x0338}, + 0x2288: {0x2286, 0x0338}, + 0x2289: {0x2287, 0x0338}, + 0x22ac: {0x22a2, 0x0338}, + 0x22ad: {0x22a8, 0x0338}, + 0x22ae: {0x22a9, 0x0338}, + 0x22af: {0x22ab, 0x0338}, + 0x22e0: {0x227c, 0x0338}, + 0x22e1: {0x227d, 0x0338}, + 0x22e2: {0x2291, 0x0338}, + 0x22e3: {0x2292, 0x0338}, + 0x22ea: {0x22b2, 0x0338}, + 0x22eb: {0x22b3, 0x0338}, + 0x22ec: {0x22b4, 0x0338}, + 0x22ed: {0x22b5, 0x0338}, + 0x2adc: {0x2add, 0x0338}, + 0x304c: {0x304b, 0x3099}, + 0x304e: {0x304d, 0x3099}, + 0x3050: {0x304f, 0x3099}, + 0x3052: {0x3051, 0x3099}, + 0x3054: {0x3053, 0x3099}, + 0x3056: {0x3055, 0x3099}, + 0x3058: {0x3057, 0x3099}, + 0x305a: {0x3059, 0x3099}, + 0x305c: {0x305b, 0x3099}, + 0x305e: {0x305d, 0x3099}, + 0x3060: {0x305f, 0x3099}, + 0x3062: {0x3061, 0x3099}, + 0x3065: {0x3064, 0x3099}, + 0x3067: {0x3066, 0x3099}, + 0x3069: {0x3068, 0x3099}, + 0x3070: {0x306f, 0x3099}, + 0x3071: {0x306f, 0x309a}, + 0x3073: {0x3072, 0x3099}, + 0x3074: {0x3072, 0x309a}, + 0x3076: {0x3075, 0x3099}, + 0x3077: {0x3075, 0x309a}, + 0x3079: {0x3078, 0x3099}, + 0x307a: {0x3078, 0x309a}, + 0x307c: {0x307b, 0x3099}, + 0x307d: {0x307b, 0x309a}, + 0x3094: {0x3046, 0x3099}, + 0x309e: {0x309d, 0x3099}, + 0x30ac: {0x30ab, 0x3099}, + 0x30ae: {0x30ad, 0x3099}, + 0x30b0: {0x30af, 0x3099}, + 0x30b2: {0x30b1, 0x3099}, + 0x30b4: {0x30b3, 0x3099}, + 0x30b6: {0x30b5, 0x3099}, + 0x30b8: {0x30b7, 0x3099}, + 0x30ba: {0x30b9, 0x3099}, + 0x30bc: {0x30bb, 0x3099}, + 0x30be: {0x30bd, 0x3099}, + 0x30c0: {0x30bf, 0x3099}, + 0x30c2: {0x30c1, 0x3099}, + 0x30c5: {0x30c4, 0x3099}, + 0x30c7: {0x30c6, 0x3099}, + 0x30c9: {0x30c8, 0x3099}, + 0x30d0: {0x30cf, 0x3099}, + 0x30d1: {0x30cf, 0x309a}, + 0x30d3: {0x30d2, 0x3099}, + 0x30d4: {0x30d2, 0x309a}, + 0x30d6: {0x30d5, 0x3099}, + 0x30d7: {0x30d5, 0x309a}, + 0x30d9: {0x30d8, 0x3099}, + 0x30da: {0x30d8, 0x309a}, + 0x30dc: {0x30db, 0x3099}, + 0x30dd: {0x30db, 0x309a}, + 0x30f4: {0x30a6, 0x3099}, + 0x30f7: {0x30ef, 0x3099}, + 0x30f8: {0x30f0, 0x3099}, + 0x30f9: {0x30f1, 0x3099}, + 0x30fa: {0x30f2, 0x3099}, + 0x30fe: {0x30fd, 0x3099}, + 0xfb1d: {0x05d9, 0x05b4}, + 0xfb1f: {0x05f2, 0x05b7}, + 0xfb2a: {0x05e9, 0x05c1}, + 0xfb2b: {0x05e9, 0x05c2}, + 0xfb2c: {0xfb49, 0x05c1}, + 0xfb2d: {0xfb49, 0x05c2}, + 0xfb2e: {0x05d0, 0x05b7}, + 0xfb2f: {0x05d0, 0x05b8}, + 0xfb30: {0x05d0, 0x05bc}, + 0xfb31: {0x05d1, 0x05bc}, + 0xfb32: {0x05d2, 0x05bc}, + 0xfb33: {0x05d3, 0x05bc}, + 0xfb34: {0x05d4, 0x05bc}, + 0xfb35: {0x05d5, 0x05bc}, + 0xfb36: {0x05d6, 0x05bc}, + 0xfb38: {0x05d8, 0x05bc}, + 0xfb39: {0x05d9, 0x05bc}, + 0xfb3a: {0x05da, 0x05bc}, + 0xfb3b: {0x05db, 0x05bc}, + 0xfb3c: {0x05dc, 0x05bc}, + 0xfb3e: {0x05de, 0x05bc}, + 0xfb40: {0x05e0, 0x05bc}, + 0xfb41: {0x05e1, 0x05bc}, + 0xfb43: {0x05e3, 0x05bc}, + 0xfb44: {0x05e4, 0x05bc}, + 0xfb46: {0x05e6, 0x05bc}, + 0xfb47: {0x05e7, 0x05bc}, + 0xfb48: {0x05e8, 0x05bc}, + 0xfb49: {0x05e9, 0x05bc}, + 0xfb4a: {0x05ea, 0x05bc}, + 0xfb4b: {0x05d5, 0x05b9}, + 0xfb4c: {0x05d1, 0x05bf}, + 0xfb4d: {0x05db, 0x05bf}, + 0xfb4e: {0x05e4, 0x05bf}, + 0x1109a: {0x11099, 0x110ba}, + 0x1109c: {0x1109b, 0x110ba}, + 0x110ab: {0x110a5, 0x110ba}, + 0x1112e: {0x11131, 0x11127}, + 0x1112f: {0x11132, 0x11127}, + 0x1134b: {0x11347, 0x1133e}, + 0x1134c: {0x11347, 0x11357}, + 0x114bb: {0x114b9, 0x114ba}, + 0x114bc: {0x114b9, 0x114b0}, + 0x114be: {0x114b9, 0x114bd}, + 0x115ba: {0x115b8, 0x115af}, + 0x115bb: {0x115b9, 0x115af}, + 0x11938: {0x11935, 0x11930}, + 0x1d15e: {0x1d157, 0x1d165}, + 0x1d15f: {0x1d158, 0x1d165}, + 0x1d160: {0x1d15f, 0x1d16e}, + 0x1d161: {0x1d15f, 0x1d16f}, + 0x1d162: {0x1d15f, 0x1d170}, + 0x1d163: {0x1d15f, 0x1d171}, + 0x1d164: {0x1d15f, 0x1d172}, + 0x1d1bb: {0x1d1b9, 0x1d165}, + 0x1d1bc: {0x1d1ba, 0x1d165}, + 0x1d1bd: {0x1d1bb, 0x1d16e}, + 0x1d1be: {0x1d1bc, 0x1d16e}, + 0x1d1bf: {0x1d1bb, 0x1d16f}, + 0x1d1c0: {0x1d1bc, 0x1d16f}, +} +var compose = map[[2]rune]rune{ // 1026 entries + {0x003c, 0x0338}: 0x226e, + {0x003d, 0x0338}: 0x2260, + {0x003e, 0x0338}: 0x226f, + {0x0041, 0x0300}: 0x00c0, + {0x0041, 0x0301}: 0x00c1, + {0x0041, 0x0302}: 0x00c2, + {0x0041, 0x0303}: 0x00c3, + {0x0041, 0x0304}: 0x0100, + {0x0041, 0x0306}: 0x0102, + {0x0041, 0x0307}: 0x0226, + {0x0041, 0x0308}: 0x00c4, + {0x0041, 0x0309}: 0x1ea2, + {0x0041, 0x030a}: 0x00c5, + {0x0041, 0x030c}: 0x01cd, + {0x0041, 0x030f}: 0x0200, + {0x0041, 0x0311}: 0x0202, + {0x0041, 0x0323}: 0x1ea0, + {0x0041, 0x0325}: 0x1e00, + {0x0041, 0x0328}: 0x0104, + {0x0042, 0x0307}: 0x1e02, + {0x0042, 0x0323}: 0x1e04, + {0x0042, 0x0331}: 0x1e06, + {0x0043, 0x0301}: 0x0106, + {0x0043, 0x0302}: 0x0108, + {0x0043, 0x0307}: 0x010a, + {0x0043, 0x030c}: 0x010c, + {0x0043, 0x0327}: 0x00c7, + {0x0044, 0x0307}: 0x1e0a, + {0x0044, 0x030c}: 0x010e, + {0x0044, 0x0323}: 0x1e0c, + {0x0044, 0x0327}: 0x1e10, + {0x0044, 0x032d}: 0x1e12, + {0x0044, 0x0331}: 0x1e0e, + {0x0045, 0x0300}: 0x00c8, + {0x0045, 0x0301}: 0x00c9, + {0x0045, 0x0302}: 0x00ca, + {0x0045, 0x0303}: 0x1ebc, + {0x0045, 0x0304}: 0x0112, + {0x0045, 0x0306}: 0x0114, + {0x0045, 0x0307}: 0x0116, + {0x0045, 0x0308}: 0x00cb, + {0x0045, 0x0309}: 0x1eba, + {0x0045, 0x030c}: 0x011a, + {0x0045, 0x030f}: 0x0204, + {0x0045, 0x0311}: 0x0206, + {0x0045, 0x0323}: 0x1eb8, + {0x0045, 0x0327}: 0x0228, + {0x0045, 0x0328}: 0x0118, + {0x0045, 0x032d}: 0x1e18, + {0x0045, 0x0330}: 0x1e1a, + {0x0046, 0x0307}: 0x1e1e, + {0x0047, 0x0301}: 0x01f4, + {0x0047, 0x0302}: 0x011c, + {0x0047, 0x0304}: 0x1e20, + {0x0047, 0x0306}: 0x011e, + {0x0047, 0x0307}: 0x0120, + {0x0047, 0x030c}: 0x01e6, + {0x0047, 0x0327}: 0x0122, + {0x0048, 0x0302}: 0x0124, + {0x0048, 0x0307}: 0x1e22, + {0x0048, 0x0308}: 0x1e26, + {0x0048, 0x030c}: 0x021e, + {0x0048, 0x0323}: 0x1e24, + {0x0048, 0x0327}: 0x1e28, + {0x0048, 0x032e}: 0x1e2a, + {0x0049, 0x0300}: 0x00cc, + {0x0049, 0x0301}: 0x00cd, + {0x0049, 0x0302}: 0x00ce, + {0x0049, 0x0303}: 0x0128, + {0x0049, 0x0304}: 0x012a, + {0x0049, 0x0306}: 0x012c, + {0x0049, 0x0307}: 0x0130, + {0x0049, 0x0308}: 0x00cf, + {0x0049, 0x0309}: 0x1ec8, + {0x0049, 0x030c}: 0x01cf, + {0x0049, 0x030f}: 0x0208, + {0x0049, 0x0311}: 0x020a, + {0x0049, 0x0323}: 0x1eca, + {0x0049, 0x0328}: 0x012e, + {0x0049, 0x0330}: 0x1e2c, + {0x004a, 0x0302}: 0x0134, + {0x004b, 0x0301}: 0x1e30, + {0x004b, 0x030c}: 0x01e8, + {0x004b, 0x0323}: 0x1e32, + {0x004b, 0x0327}: 0x0136, + {0x004b, 0x0331}: 0x1e34, + {0x004c, 0x0301}: 0x0139, + {0x004c, 0x030c}: 0x013d, + {0x004c, 0x0323}: 0x1e36, + {0x004c, 0x0327}: 0x013b, + {0x004c, 0x032d}: 0x1e3c, + {0x004c, 0x0331}: 0x1e3a, + {0x004d, 0x0301}: 0x1e3e, + {0x004d, 0x0307}: 0x1e40, + {0x004d, 0x0323}: 0x1e42, + {0x004e, 0x0300}: 0x01f8, + {0x004e, 0x0301}: 0x0143, + {0x004e, 0x0303}: 0x00d1, + {0x004e, 0x0307}: 0x1e44, + {0x004e, 0x030c}: 0x0147, + {0x004e, 0x0323}: 0x1e46, + {0x004e, 0x0327}: 0x0145, + {0x004e, 0x032d}: 0x1e4a, + {0x004e, 0x0331}: 0x1e48, + {0x004f, 0x0300}: 0x00d2, + {0x004f, 0x0301}: 0x00d3, + {0x004f, 0x0302}: 0x00d4, + {0x004f, 0x0303}: 0x00d5, + {0x004f, 0x0304}: 0x014c, + {0x004f, 0x0306}: 0x014e, + {0x004f, 0x0307}: 0x022e, + {0x004f, 0x0308}: 0x00d6, + {0x004f, 0x0309}: 0x1ece, + {0x004f, 0x030b}: 0x0150, + {0x004f, 0x030c}: 0x01d1, + {0x004f, 0x030f}: 0x020c, + {0x004f, 0x0311}: 0x020e, + {0x004f, 0x031b}: 0x01a0, + {0x004f, 0x0323}: 0x1ecc, + {0x004f, 0x0328}: 0x01ea, + {0x0050, 0x0301}: 0x1e54, + {0x0050, 0x0307}: 0x1e56, + {0x0052, 0x0301}: 0x0154, + {0x0052, 0x0307}: 0x1e58, + {0x0052, 0x030c}: 0x0158, + {0x0052, 0x030f}: 0x0210, + {0x0052, 0x0311}: 0x0212, + {0x0052, 0x0323}: 0x1e5a, + {0x0052, 0x0327}: 0x0156, + {0x0052, 0x0331}: 0x1e5e, + {0x0053, 0x0301}: 0x015a, + {0x0053, 0x0302}: 0x015c, + {0x0053, 0x0307}: 0x1e60, + {0x0053, 0x030c}: 0x0160, + {0x0053, 0x0323}: 0x1e62, + {0x0053, 0x0326}: 0x0218, + {0x0053, 0x0327}: 0x015e, + {0x0054, 0x0307}: 0x1e6a, + {0x0054, 0x030c}: 0x0164, + {0x0054, 0x0323}: 0x1e6c, + {0x0054, 0x0326}: 0x021a, + {0x0054, 0x0327}: 0x0162, + {0x0054, 0x032d}: 0x1e70, + {0x0054, 0x0331}: 0x1e6e, + {0x0055, 0x0300}: 0x00d9, + {0x0055, 0x0301}: 0x00da, + {0x0055, 0x0302}: 0x00db, + {0x0055, 0x0303}: 0x0168, + {0x0055, 0x0304}: 0x016a, + {0x0055, 0x0306}: 0x016c, + {0x0055, 0x0308}: 0x00dc, + {0x0055, 0x0309}: 0x1ee6, + {0x0055, 0x030a}: 0x016e, + {0x0055, 0x030b}: 0x0170, + {0x0055, 0x030c}: 0x01d3, + {0x0055, 0x030f}: 0x0214, + {0x0055, 0x0311}: 0x0216, + {0x0055, 0x031b}: 0x01af, + {0x0055, 0x0323}: 0x1ee4, + {0x0055, 0x0324}: 0x1e72, + {0x0055, 0x0328}: 0x0172, + {0x0055, 0x032d}: 0x1e76, + {0x0055, 0x0330}: 0x1e74, + {0x0056, 0x0303}: 0x1e7c, + {0x0056, 0x0323}: 0x1e7e, + {0x0057, 0x0300}: 0x1e80, + {0x0057, 0x0301}: 0x1e82, + {0x0057, 0x0302}: 0x0174, + {0x0057, 0x0307}: 0x1e86, + {0x0057, 0x0308}: 0x1e84, + {0x0057, 0x0323}: 0x1e88, + {0x0058, 0x0307}: 0x1e8a, + {0x0058, 0x0308}: 0x1e8c, + {0x0059, 0x0300}: 0x1ef2, + {0x0059, 0x0301}: 0x00dd, + {0x0059, 0x0302}: 0x0176, + {0x0059, 0x0303}: 0x1ef8, + {0x0059, 0x0304}: 0x0232, + {0x0059, 0x0307}: 0x1e8e, + {0x0059, 0x0308}: 0x0178, + {0x0059, 0x0309}: 0x1ef6, + {0x0059, 0x0323}: 0x1ef4, + {0x005a, 0x0301}: 0x0179, + {0x005a, 0x0302}: 0x1e90, + {0x005a, 0x0307}: 0x017b, + {0x005a, 0x030c}: 0x017d, + {0x005a, 0x0323}: 0x1e92, + {0x005a, 0x0331}: 0x1e94, + {0x0061, 0x0300}: 0x00e0, + {0x0061, 0x0301}: 0x00e1, + {0x0061, 0x0302}: 0x00e2, + {0x0061, 0x0303}: 0x00e3, + {0x0061, 0x0304}: 0x0101, + {0x0061, 0x0306}: 0x0103, + {0x0061, 0x0307}: 0x0227, + {0x0061, 0x0308}: 0x00e4, + {0x0061, 0x0309}: 0x1ea3, + {0x0061, 0x030a}: 0x00e5, + {0x0061, 0x030c}: 0x01ce, + {0x0061, 0x030f}: 0x0201, + {0x0061, 0x0311}: 0x0203, + {0x0061, 0x0323}: 0x1ea1, + {0x0061, 0x0325}: 0x1e01, + {0x0061, 0x0328}: 0x0105, + {0x0062, 0x0307}: 0x1e03, + {0x0062, 0x0323}: 0x1e05, + {0x0062, 0x0331}: 0x1e07, + {0x0063, 0x0301}: 0x0107, + {0x0063, 0x0302}: 0x0109, + {0x0063, 0x0307}: 0x010b, + {0x0063, 0x030c}: 0x010d, + {0x0063, 0x0327}: 0x00e7, + {0x0064, 0x0307}: 0x1e0b, + {0x0064, 0x030c}: 0x010f, + {0x0064, 0x0323}: 0x1e0d, + {0x0064, 0x0327}: 0x1e11, + {0x0064, 0x032d}: 0x1e13, + {0x0064, 0x0331}: 0x1e0f, + {0x0065, 0x0300}: 0x00e8, + {0x0065, 0x0301}: 0x00e9, + {0x0065, 0x0302}: 0x00ea, + {0x0065, 0x0303}: 0x1ebd, + {0x0065, 0x0304}: 0x0113, + {0x0065, 0x0306}: 0x0115, + {0x0065, 0x0307}: 0x0117, + {0x0065, 0x0308}: 0x00eb, + {0x0065, 0x0309}: 0x1ebb, + {0x0065, 0x030c}: 0x011b, + {0x0065, 0x030f}: 0x0205, + {0x0065, 0x0311}: 0x0207, + {0x0065, 0x0323}: 0x1eb9, + {0x0065, 0x0327}: 0x0229, + {0x0065, 0x0328}: 0x0119, + {0x0065, 0x032d}: 0x1e19, + {0x0065, 0x0330}: 0x1e1b, + {0x0066, 0x0307}: 0x1e1f, + {0x0067, 0x0301}: 0x01f5, + {0x0067, 0x0302}: 0x011d, + {0x0067, 0x0304}: 0x1e21, + {0x0067, 0x0306}: 0x011f, + {0x0067, 0x0307}: 0x0121, + {0x0067, 0x030c}: 0x01e7, + {0x0067, 0x0327}: 0x0123, + {0x0068, 0x0302}: 0x0125, + {0x0068, 0x0307}: 0x1e23, + {0x0068, 0x0308}: 0x1e27, + {0x0068, 0x030c}: 0x021f, + {0x0068, 0x0323}: 0x1e25, + {0x0068, 0x0327}: 0x1e29, + {0x0068, 0x032e}: 0x1e2b, + {0x0068, 0x0331}: 0x1e96, + {0x0069, 0x0300}: 0x00ec, + {0x0069, 0x0301}: 0x00ed, + {0x0069, 0x0302}: 0x00ee, + {0x0069, 0x0303}: 0x0129, + {0x0069, 0x0304}: 0x012b, + {0x0069, 0x0306}: 0x012d, + {0x0069, 0x0308}: 0x00ef, + {0x0069, 0x0309}: 0x1ec9, + {0x0069, 0x030c}: 0x01d0, + {0x0069, 0x030f}: 0x0209, + {0x0069, 0x0311}: 0x020b, + {0x0069, 0x0323}: 0x1ecb, + {0x0069, 0x0328}: 0x012f, + {0x0069, 0x0330}: 0x1e2d, + {0x006a, 0x0302}: 0x0135, + {0x006a, 0x030c}: 0x01f0, + {0x006b, 0x0301}: 0x1e31, + {0x006b, 0x030c}: 0x01e9, + {0x006b, 0x0323}: 0x1e33, + {0x006b, 0x0327}: 0x0137, + {0x006b, 0x0331}: 0x1e35, + {0x006c, 0x0301}: 0x013a, + {0x006c, 0x030c}: 0x013e, + {0x006c, 0x0323}: 0x1e37, + {0x006c, 0x0327}: 0x013c, + {0x006c, 0x032d}: 0x1e3d, + {0x006c, 0x0331}: 0x1e3b, + {0x006d, 0x0301}: 0x1e3f, + {0x006d, 0x0307}: 0x1e41, + {0x006d, 0x0323}: 0x1e43, + {0x006e, 0x0300}: 0x01f9, + {0x006e, 0x0301}: 0x0144, + {0x006e, 0x0303}: 0x00f1, + {0x006e, 0x0307}: 0x1e45, + {0x006e, 0x030c}: 0x0148, + {0x006e, 0x0323}: 0x1e47, + {0x006e, 0x0327}: 0x0146, + {0x006e, 0x032d}: 0x1e4b, + {0x006e, 0x0331}: 0x1e49, + {0x006f, 0x0300}: 0x00f2, + {0x006f, 0x0301}: 0x00f3, + {0x006f, 0x0302}: 0x00f4, + {0x006f, 0x0303}: 0x00f5, + {0x006f, 0x0304}: 0x014d, + {0x006f, 0x0306}: 0x014f, + {0x006f, 0x0307}: 0x022f, + {0x006f, 0x0308}: 0x00f6, + {0x006f, 0x0309}: 0x1ecf, + {0x006f, 0x030b}: 0x0151, + {0x006f, 0x030c}: 0x01d2, + {0x006f, 0x030f}: 0x020d, + {0x006f, 0x0311}: 0x020f, + {0x006f, 0x031b}: 0x01a1, + {0x006f, 0x0323}: 0x1ecd, + {0x006f, 0x0328}: 0x01eb, + {0x0070, 0x0301}: 0x1e55, + {0x0070, 0x0307}: 0x1e57, + {0x0072, 0x0301}: 0x0155, + {0x0072, 0x0307}: 0x1e59, + {0x0072, 0x030c}: 0x0159, + {0x0072, 0x030f}: 0x0211, + {0x0072, 0x0311}: 0x0213, + {0x0072, 0x0323}: 0x1e5b, + {0x0072, 0x0327}: 0x0157, + {0x0072, 0x0331}: 0x1e5f, + {0x0073, 0x0301}: 0x015b, + {0x0073, 0x0302}: 0x015d, + {0x0073, 0x0307}: 0x1e61, + {0x0073, 0x030c}: 0x0161, + {0x0073, 0x0323}: 0x1e63, + {0x0073, 0x0326}: 0x0219, + {0x0073, 0x0327}: 0x015f, + {0x0074, 0x0307}: 0x1e6b, + {0x0074, 0x0308}: 0x1e97, + {0x0074, 0x030c}: 0x0165, + {0x0074, 0x0323}: 0x1e6d, + {0x0074, 0x0326}: 0x021b, + {0x0074, 0x0327}: 0x0163, + {0x0074, 0x032d}: 0x1e71, + {0x0074, 0x0331}: 0x1e6f, + {0x0075, 0x0300}: 0x00f9, + {0x0075, 0x0301}: 0x00fa, + {0x0075, 0x0302}: 0x00fb, + {0x0075, 0x0303}: 0x0169, + {0x0075, 0x0304}: 0x016b, + {0x0075, 0x0306}: 0x016d, + {0x0075, 0x0308}: 0x00fc, + {0x0075, 0x0309}: 0x1ee7, + {0x0075, 0x030a}: 0x016f, + {0x0075, 0x030b}: 0x0171, + {0x0075, 0x030c}: 0x01d4, + {0x0075, 0x030f}: 0x0215, + {0x0075, 0x0311}: 0x0217, + {0x0075, 0x031b}: 0x01b0, + {0x0075, 0x0323}: 0x1ee5, + {0x0075, 0x0324}: 0x1e73, + {0x0075, 0x0328}: 0x0173, + {0x0075, 0x032d}: 0x1e77, + {0x0075, 0x0330}: 0x1e75, + {0x0076, 0x0303}: 0x1e7d, + {0x0076, 0x0323}: 0x1e7f, + {0x0077, 0x0300}: 0x1e81, + {0x0077, 0x0301}: 0x1e83, + {0x0077, 0x0302}: 0x0175, + {0x0077, 0x0307}: 0x1e87, + {0x0077, 0x0308}: 0x1e85, + {0x0077, 0x030a}: 0x1e98, + {0x0077, 0x0323}: 0x1e89, + {0x0078, 0x0307}: 0x1e8b, + {0x0078, 0x0308}: 0x1e8d, + {0x0079, 0x0300}: 0x1ef3, + {0x0079, 0x0301}: 0x00fd, + {0x0079, 0x0302}: 0x0177, + {0x0079, 0x0303}: 0x1ef9, + {0x0079, 0x0304}: 0x0233, + {0x0079, 0x0307}: 0x1e8f, + {0x0079, 0x0308}: 0x00ff, + {0x0079, 0x0309}: 0x1ef7, + {0x0079, 0x030a}: 0x1e99, + {0x0079, 0x0323}: 0x1ef5, + {0x007a, 0x0301}: 0x017a, + {0x007a, 0x0302}: 0x1e91, + {0x007a, 0x0307}: 0x017c, + {0x007a, 0x030c}: 0x017e, + {0x007a, 0x0323}: 0x1e93, + {0x007a, 0x0331}: 0x1e95, + {0x00a8, 0x0300}: 0x1fed, + {0x00a8, 0x0301}: 0x0385, + {0x00a8, 0x0342}: 0x1fc1, + {0x00c2, 0x0300}: 0x1ea6, + {0x00c2, 0x0301}: 0x1ea4, + {0x00c2, 0x0303}: 0x1eaa, + {0x00c2, 0x0309}: 0x1ea8, + {0x00c4, 0x0304}: 0x01de, + {0x00c5, 0x0301}: 0x01fa, + {0x00c6, 0x0301}: 0x01fc, + {0x00c6, 0x0304}: 0x01e2, + {0x00c7, 0x0301}: 0x1e08, + {0x00ca, 0x0300}: 0x1ec0, + {0x00ca, 0x0301}: 0x1ebe, + {0x00ca, 0x0303}: 0x1ec4, + {0x00ca, 0x0309}: 0x1ec2, + {0x00cf, 0x0301}: 0x1e2e, + {0x00d4, 0x0300}: 0x1ed2, + {0x00d4, 0x0301}: 0x1ed0, + {0x00d4, 0x0303}: 0x1ed6, + {0x00d4, 0x0309}: 0x1ed4, + {0x00d5, 0x0301}: 0x1e4c, + {0x00d5, 0x0304}: 0x022c, + {0x00d5, 0x0308}: 0x1e4e, + {0x00d6, 0x0304}: 0x022a, + {0x00d8, 0x0301}: 0x01fe, + {0x00dc, 0x0300}: 0x01db, + {0x00dc, 0x0301}: 0x01d7, + {0x00dc, 0x0304}: 0x01d5, + {0x00dc, 0x030c}: 0x01d9, + {0x00e2, 0x0300}: 0x1ea7, + {0x00e2, 0x0301}: 0x1ea5, + {0x00e2, 0x0303}: 0x1eab, + {0x00e2, 0x0309}: 0x1ea9, + {0x00e4, 0x0304}: 0x01df, + {0x00e5, 0x0301}: 0x01fb, + {0x00e6, 0x0301}: 0x01fd, + {0x00e6, 0x0304}: 0x01e3, + {0x00e7, 0x0301}: 0x1e09, + {0x00ea, 0x0300}: 0x1ec1, + {0x00ea, 0x0301}: 0x1ebf, + {0x00ea, 0x0303}: 0x1ec5, + {0x00ea, 0x0309}: 0x1ec3, + {0x00ef, 0x0301}: 0x1e2f, + {0x00f4, 0x0300}: 0x1ed3, + {0x00f4, 0x0301}: 0x1ed1, + {0x00f4, 0x0303}: 0x1ed7, + {0x00f4, 0x0309}: 0x1ed5, + {0x00f5, 0x0301}: 0x1e4d, + {0x00f5, 0x0304}: 0x022d, + {0x00f5, 0x0308}: 0x1e4f, + {0x00f6, 0x0304}: 0x022b, + {0x00f8, 0x0301}: 0x01ff, + {0x00fc, 0x0300}: 0x01dc, + {0x00fc, 0x0301}: 0x01d8, + {0x00fc, 0x0304}: 0x01d6, + {0x00fc, 0x030c}: 0x01da, + {0x0102, 0x0300}: 0x1eb0, + {0x0102, 0x0301}: 0x1eae, + {0x0102, 0x0303}: 0x1eb4, + {0x0102, 0x0309}: 0x1eb2, + {0x0103, 0x0300}: 0x1eb1, + {0x0103, 0x0301}: 0x1eaf, + {0x0103, 0x0303}: 0x1eb5, + {0x0103, 0x0309}: 0x1eb3, + {0x0112, 0x0300}: 0x1e14, + {0x0112, 0x0301}: 0x1e16, + {0x0113, 0x0300}: 0x1e15, + {0x0113, 0x0301}: 0x1e17, + {0x014c, 0x0300}: 0x1e50, + {0x014c, 0x0301}: 0x1e52, + {0x014d, 0x0300}: 0x1e51, + {0x014d, 0x0301}: 0x1e53, + {0x015a, 0x0307}: 0x1e64, + {0x015b, 0x0307}: 0x1e65, + {0x0160, 0x0307}: 0x1e66, + {0x0161, 0x0307}: 0x1e67, + {0x0168, 0x0301}: 0x1e78, + {0x0169, 0x0301}: 0x1e79, + {0x016a, 0x0308}: 0x1e7a, + {0x016b, 0x0308}: 0x1e7b, + {0x017f, 0x0307}: 0x1e9b, + {0x01a0, 0x0300}: 0x1edc, + {0x01a0, 0x0301}: 0x1eda, + {0x01a0, 0x0303}: 0x1ee0, + {0x01a0, 0x0309}: 0x1ede, + {0x01a0, 0x0323}: 0x1ee2, + {0x01a1, 0x0300}: 0x1edd, + {0x01a1, 0x0301}: 0x1edb, + {0x01a1, 0x0303}: 0x1ee1, + {0x01a1, 0x0309}: 0x1edf, + {0x01a1, 0x0323}: 0x1ee3, + {0x01af, 0x0300}: 0x1eea, + {0x01af, 0x0301}: 0x1ee8, + {0x01af, 0x0303}: 0x1eee, + {0x01af, 0x0309}: 0x1eec, + {0x01af, 0x0323}: 0x1ef0, + {0x01b0, 0x0300}: 0x1eeb, + {0x01b0, 0x0301}: 0x1ee9, + {0x01b0, 0x0303}: 0x1eef, + {0x01b0, 0x0309}: 0x1eed, + {0x01b0, 0x0323}: 0x1ef1, + {0x01b7, 0x030c}: 0x01ee, + {0x01ea, 0x0304}: 0x01ec, + {0x01eb, 0x0304}: 0x01ed, + {0x0226, 0x0304}: 0x01e0, + {0x0227, 0x0304}: 0x01e1, + {0x0228, 0x0306}: 0x1e1c, + {0x0229, 0x0306}: 0x1e1d, + {0x022e, 0x0304}: 0x0230, + {0x022f, 0x0304}: 0x0231, + {0x0292, 0x030c}: 0x01ef, + {0x0308, 0x0301}: 0x0000, + {0x0391, 0x0300}: 0x1fba, + {0x0391, 0x0301}: 0x0386, + {0x0391, 0x0304}: 0x1fb9, + {0x0391, 0x0306}: 0x1fb8, + {0x0391, 0x0313}: 0x1f08, + {0x0391, 0x0314}: 0x1f09, + {0x0391, 0x0345}: 0x1fbc, + {0x0395, 0x0300}: 0x1fc8, + {0x0395, 0x0301}: 0x0388, + {0x0395, 0x0313}: 0x1f18, + {0x0395, 0x0314}: 0x1f19, + {0x0397, 0x0300}: 0x1fca, + {0x0397, 0x0301}: 0x0389, + {0x0397, 0x0313}: 0x1f28, + {0x0397, 0x0314}: 0x1f29, + {0x0397, 0x0345}: 0x1fcc, + {0x0399, 0x0300}: 0x1fda, + {0x0399, 0x0301}: 0x038a, + {0x0399, 0x0304}: 0x1fd9, + {0x0399, 0x0306}: 0x1fd8, + {0x0399, 0x0308}: 0x03aa, + {0x0399, 0x0313}: 0x1f38, + {0x0399, 0x0314}: 0x1f39, + {0x039f, 0x0300}: 0x1ff8, + {0x039f, 0x0301}: 0x038c, + {0x039f, 0x0313}: 0x1f48, + {0x039f, 0x0314}: 0x1f49, + {0x03a1, 0x0314}: 0x1fec, + {0x03a5, 0x0300}: 0x1fea, + {0x03a5, 0x0301}: 0x038e, + {0x03a5, 0x0304}: 0x1fe9, + {0x03a5, 0x0306}: 0x1fe8, + {0x03a5, 0x0308}: 0x03ab, + {0x03a5, 0x0314}: 0x1f59, + {0x03a9, 0x0300}: 0x1ffa, + {0x03a9, 0x0301}: 0x038f, + {0x03a9, 0x0313}: 0x1f68, + {0x03a9, 0x0314}: 0x1f69, + {0x03a9, 0x0345}: 0x1ffc, + {0x03ac, 0x0345}: 0x1fb4, + {0x03ae, 0x0345}: 0x1fc4, + {0x03b1, 0x0300}: 0x1f70, + {0x03b1, 0x0301}: 0x03ac, + {0x03b1, 0x0304}: 0x1fb1, + {0x03b1, 0x0306}: 0x1fb0, + {0x03b1, 0x0313}: 0x1f00, + {0x03b1, 0x0314}: 0x1f01, + {0x03b1, 0x0342}: 0x1fb6, + {0x03b1, 0x0345}: 0x1fb3, + {0x03b5, 0x0300}: 0x1f72, + {0x03b5, 0x0301}: 0x03ad, + {0x03b5, 0x0313}: 0x1f10, + {0x03b5, 0x0314}: 0x1f11, + {0x03b7, 0x0300}: 0x1f74, + {0x03b7, 0x0301}: 0x03ae, + {0x03b7, 0x0313}: 0x1f20, + {0x03b7, 0x0314}: 0x1f21, + {0x03b7, 0x0342}: 0x1fc6, + {0x03b7, 0x0345}: 0x1fc3, + {0x03b9, 0x0300}: 0x1f76, + {0x03b9, 0x0301}: 0x03af, + {0x03b9, 0x0304}: 0x1fd1, + {0x03b9, 0x0306}: 0x1fd0, + {0x03b9, 0x0308}: 0x03ca, + {0x03b9, 0x0313}: 0x1f30, + {0x03b9, 0x0314}: 0x1f31, + {0x03b9, 0x0342}: 0x1fd6, + {0x03bf, 0x0300}: 0x1f78, + {0x03bf, 0x0301}: 0x03cc, + {0x03bf, 0x0313}: 0x1f40, + {0x03bf, 0x0314}: 0x1f41, + {0x03c1, 0x0313}: 0x1fe4, + {0x03c1, 0x0314}: 0x1fe5, + {0x03c5, 0x0300}: 0x1f7a, + {0x03c5, 0x0301}: 0x03cd, + {0x03c5, 0x0304}: 0x1fe1, + {0x03c5, 0x0306}: 0x1fe0, + {0x03c5, 0x0308}: 0x03cb, + {0x03c5, 0x0313}: 0x1f50, + {0x03c5, 0x0314}: 0x1f51, + {0x03c5, 0x0342}: 0x1fe6, + {0x03c9, 0x0300}: 0x1f7c, + {0x03c9, 0x0301}: 0x03ce, + {0x03c9, 0x0313}: 0x1f60, + {0x03c9, 0x0314}: 0x1f61, + {0x03c9, 0x0342}: 0x1ff6, + {0x03c9, 0x0345}: 0x1ff3, + {0x03ca, 0x0300}: 0x1fd2, + {0x03ca, 0x0301}: 0x0390, + {0x03ca, 0x0342}: 0x1fd7, + {0x03cb, 0x0300}: 0x1fe2, + {0x03cb, 0x0301}: 0x03b0, + {0x03cb, 0x0342}: 0x1fe7, + {0x03ce, 0x0345}: 0x1ff4, + {0x03d2, 0x0301}: 0x03d3, + {0x03d2, 0x0308}: 0x03d4, + {0x0406, 0x0308}: 0x0407, + {0x0410, 0x0306}: 0x04d0, + {0x0410, 0x0308}: 0x04d2, + {0x0413, 0x0301}: 0x0403, + {0x0415, 0x0300}: 0x0400, + {0x0415, 0x0306}: 0x04d6, + {0x0415, 0x0308}: 0x0401, + {0x0416, 0x0306}: 0x04c1, + {0x0416, 0x0308}: 0x04dc, + {0x0417, 0x0308}: 0x04de, + {0x0418, 0x0300}: 0x040d, + {0x0418, 0x0304}: 0x04e2, + {0x0418, 0x0306}: 0x0419, + {0x0418, 0x0308}: 0x04e4, + {0x041a, 0x0301}: 0x040c, + {0x041e, 0x0308}: 0x04e6, + {0x0423, 0x0304}: 0x04ee, + {0x0423, 0x0306}: 0x040e, + {0x0423, 0x0308}: 0x04f0, + {0x0423, 0x030b}: 0x04f2, + {0x0427, 0x0308}: 0x04f4, + {0x042b, 0x0308}: 0x04f8, + {0x042d, 0x0308}: 0x04ec, + {0x0430, 0x0306}: 0x04d1, + {0x0430, 0x0308}: 0x04d3, + {0x0433, 0x0301}: 0x0453, + {0x0435, 0x0300}: 0x0450, + {0x0435, 0x0306}: 0x04d7, + {0x0435, 0x0308}: 0x0451, + {0x0436, 0x0306}: 0x04c2, + {0x0436, 0x0308}: 0x04dd, + {0x0437, 0x0308}: 0x04df, + {0x0438, 0x0300}: 0x045d, + {0x0438, 0x0304}: 0x04e3, + {0x0438, 0x0306}: 0x0439, + {0x0438, 0x0308}: 0x04e5, + {0x043a, 0x0301}: 0x045c, + {0x043e, 0x0308}: 0x04e7, + {0x0443, 0x0304}: 0x04ef, + {0x0443, 0x0306}: 0x045e, + {0x0443, 0x0308}: 0x04f1, + {0x0443, 0x030b}: 0x04f3, + {0x0447, 0x0308}: 0x04f5, + {0x044b, 0x0308}: 0x04f9, + {0x044d, 0x0308}: 0x04ed, + {0x0456, 0x0308}: 0x0457, + {0x0474, 0x030f}: 0x0476, + {0x0475, 0x030f}: 0x0477, + {0x04d8, 0x0308}: 0x04da, + {0x04d9, 0x0308}: 0x04db, + {0x04e8, 0x0308}: 0x04ea, + {0x04e9, 0x0308}: 0x04eb, + {0x05d0, 0x05b7}: 0x0000, + {0x05d0, 0x05b8}: 0x0000, + {0x05d0, 0x05bc}: 0x0000, + {0x05d1, 0x05bc}: 0x0000, + {0x05d1, 0x05bf}: 0x0000, + {0x05d2, 0x05bc}: 0x0000, + {0x05d3, 0x05bc}: 0x0000, + {0x05d4, 0x05bc}: 0x0000, + {0x05d5, 0x05b9}: 0x0000, + {0x05d5, 0x05bc}: 0x0000, + {0x05d6, 0x05bc}: 0x0000, + {0x05d8, 0x05bc}: 0x0000, + {0x05d9, 0x05b4}: 0x0000, + {0x05d9, 0x05bc}: 0x0000, + {0x05da, 0x05bc}: 0x0000, + {0x05db, 0x05bc}: 0x0000, + {0x05db, 0x05bf}: 0x0000, + {0x05dc, 0x05bc}: 0x0000, + {0x05de, 0x05bc}: 0x0000, + {0x05e0, 0x05bc}: 0x0000, + {0x05e1, 0x05bc}: 0x0000, + {0x05e3, 0x05bc}: 0x0000, + {0x05e4, 0x05bc}: 0x0000, + {0x05e4, 0x05bf}: 0x0000, + {0x05e6, 0x05bc}: 0x0000, + {0x05e7, 0x05bc}: 0x0000, + {0x05e8, 0x05bc}: 0x0000, + {0x05e9, 0x05bc}: 0x0000, + {0x05e9, 0x05c1}: 0x0000, + {0x05e9, 0x05c2}: 0x0000, + {0x05ea, 0x05bc}: 0x0000, + {0x05f2, 0x05b7}: 0x0000, + {0x0627, 0x0653}: 0x0622, + {0x0627, 0x0654}: 0x0623, + {0x0627, 0x0655}: 0x0625, + {0x0648, 0x0654}: 0x0624, + {0x064a, 0x0654}: 0x0626, + {0x06c1, 0x0654}: 0x06c2, + {0x06d2, 0x0654}: 0x06d3, + {0x06d5, 0x0654}: 0x06c0, + {0x0915, 0x093c}: 0x0000, + {0x0916, 0x093c}: 0x0000, + {0x0917, 0x093c}: 0x0000, + {0x091c, 0x093c}: 0x0000, + {0x0921, 0x093c}: 0x0000, + {0x0922, 0x093c}: 0x0000, + {0x0928, 0x093c}: 0x0929, + {0x092b, 0x093c}: 0x0000, + {0x092f, 0x093c}: 0x0000, + {0x0930, 0x093c}: 0x0931, + {0x0933, 0x093c}: 0x0934, + {0x09a1, 0x09bc}: 0x0000, + {0x09a2, 0x09bc}: 0x0000, + {0x09af, 0x09bc}: 0x0000, + {0x09c7, 0x09be}: 0x09cb, + {0x09c7, 0x09d7}: 0x09cc, + {0x0a16, 0x0a3c}: 0x0000, + {0x0a17, 0x0a3c}: 0x0000, + {0x0a1c, 0x0a3c}: 0x0000, + {0x0a2b, 0x0a3c}: 0x0000, + {0x0a32, 0x0a3c}: 0x0000, + {0x0a38, 0x0a3c}: 0x0000, + {0x0b21, 0x0b3c}: 0x0000, + {0x0b22, 0x0b3c}: 0x0000, + {0x0b47, 0x0b3e}: 0x0b4b, + {0x0b47, 0x0b56}: 0x0b48, + {0x0b47, 0x0b57}: 0x0b4c, + {0x0b92, 0x0bd7}: 0x0b94, + {0x0bc6, 0x0bbe}: 0x0bca, + {0x0bc6, 0x0bd7}: 0x0bcc, + {0x0bc7, 0x0bbe}: 0x0bcb, + {0x0c46, 0x0c56}: 0x0c48, + {0x0cbf, 0x0cd5}: 0x0cc0, + {0x0cc6, 0x0cc2}: 0x0cca, + {0x0cc6, 0x0cd5}: 0x0cc7, + {0x0cc6, 0x0cd6}: 0x0cc8, + {0x0cca, 0x0cd5}: 0x0ccb, + {0x0d46, 0x0d3e}: 0x0d4a, + {0x0d46, 0x0d57}: 0x0d4c, + {0x0d47, 0x0d3e}: 0x0d4b, + {0x0dd9, 0x0dca}: 0x0dda, + {0x0dd9, 0x0dcf}: 0x0ddc, + {0x0dd9, 0x0ddf}: 0x0dde, + {0x0ddc, 0x0dca}: 0x0ddd, + {0x0f40, 0x0fb5}: 0x0000, + {0x0f42, 0x0fb7}: 0x0000, + {0x0f4c, 0x0fb7}: 0x0000, + {0x0f51, 0x0fb7}: 0x0000, + {0x0f56, 0x0fb7}: 0x0000, + {0x0f5b, 0x0fb7}: 0x0000, + {0x0f71, 0x0f72}: 0x0000, + {0x0f71, 0x0f74}: 0x0000, + {0x0f71, 0x0f80}: 0x0000, + {0x0f90, 0x0fb5}: 0x0000, + {0x0f92, 0x0fb7}: 0x0000, + {0x0f9c, 0x0fb7}: 0x0000, + {0x0fa1, 0x0fb7}: 0x0000, + {0x0fa6, 0x0fb7}: 0x0000, + {0x0fab, 0x0fb7}: 0x0000, + {0x0fb2, 0x0f80}: 0x0000, + {0x0fb3, 0x0f80}: 0x0000, + {0x1025, 0x102e}: 0x1026, + {0x1b05, 0x1b35}: 0x1b06, + {0x1b07, 0x1b35}: 0x1b08, + {0x1b09, 0x1b35}: 0x1b0a, + {0x1b0b, 0x1b35}: 0x1b0c, + {0x1b0d, 0x1b35}: 0x1b0e, + {0x1b11, 0x1b35}: 0x1b12, + {0x1b3a, 0x1b35}: 0x1b3b, + {0x1b3c, 0x1b35}: 0x1b3d, + {0x1b3e, 0x1b35}: 0x1b40, + {0x1b3f, 0x1b35}: 0x1b41, + {0x1b42, 0x1b35}: 0x1b43, + {0x1e36, 0x0304}: 0x1e38, + {0x1e37, 0x0304}: 0x1e39, + {0x1e5a, 0x0304}: 0x1e5c, + {0x1e5b, 0x0304}: 0x1e5d, + {0x1e62, 0x0307}: 0x1e68, + {0x1e63, 0x0307}: 0x1e69, + {0x1ea0, 0x0302}: 0x1eac, + {0x1ea0, 0x0306}: 0x1eb6, + {0x1ea1, 0x0302}: 0x1ead, + {0x1ea1, 0x0306}: 0x1eb7, + {0x1eb8, 0x0302}: 0x1ec6, + {0x1eb9, 0x0302}: 0x1ec7, + {0x1ecc, 0x0302}: 0x1ed8, + {0x1ecd, 0x0302}: 0x1ed9, + {0x1f00, 0x0300}: 0x1f02, + {0x1f00, 0x0301}: 0x1f04, + {0x1f00, 0x0342}: 0x1f06, + {0x1f00, 0x0345}: 0x1f80, + {0x1f01, 0x0300}: 0x1f03, + {0x1f01, 0x0301}: 0x1f05, + {0x1f01, 0x0342}: 0x1f07, + {0x1f01, 0x0345}: 0x1f81, + {0x1f02, 0x0345}: 0x1f82, + {0x1f03, 0x0345}: 0x1f83, + {0x1f04, 0x0345}: 0x1f84, + {0x1f05, 0x0345}: 0x1f85, + {0x1f06, 0x0345}: 0x1f86, + {0x1f07, 0x0345}: 0x1f87, + {0x1f08, 0x0300}: 0x1f0a, + {0x1f08, 0x0301}: 0x1f0c, + {0x1f08, 0x0342}: 0x1f0e, + {0x1f08, 0x0345}: 0x1f88, + {0x1f09, 0x0300}: 0x1f0b, + {0x1f09, 0x0301}: 0x1f0d, + {0x1f09, 0x0342}: 0x1f0f, + {0x1f09, 0x0345}: 0x1f89, + {0x1f0a, 0x0345}: 0x1f8a, + {0x1f0b, 0x0345}: 0x1f8b, + {0x1f0c, 0x0345}: 0x1f8c, + {0x1f0d, 0x0345}: 0x1f8d, + {0x1f0e, 0x0345}: 0x1f8e, + {0x1f0f, 0x0345}: 0x1f8f, + {0x1f10, 0x0300}: 0x1f12, + {0x1f10, 0x0301}: 0x1f14, + {0x1f11, 0x0300}: 0x1f13, + {0x1f11, 0x0301}: 0x1f15, + {0x1f18, 0x0300}: 0x1f1a, + {0x1f18, 0x0301}: 0x1f1c, + {0x1f19, 0x0300}: 0x1f1b, + {0x1f19, 0x0301}: 0x1f1d, + {0x1f20, 0x0300}: 0x1f22, + {0x1f20, 0x0301}: 0x1f24, + {0x1f20, 0x0342}: 0x1f26, + {0x1f20, 0x0345}: 0x1f90, + {0x1f21, 0x0300}: 0x1f23, + {0x1f21, 0x0301}: 0x1f25, + {0x1f21, 0x0342}: 0x1f27, + {0x1f21, 0x0345}: 0x1f91, + {0x1f22, 0x0345}: 0x1f92, + {0x1f23, 0x0345}: 0x1f93, + {0x1f24, 0x0345}: 0x1f94, + {0x1f25, 0x0345}: 0x1f95, + {0x1f26, 0x0345}: 0x1f96, + {0x1f27, 0x0345}: 0x1f97, + {0x1f28, 0x0300}: 0x1f2a, + {0x1f28, 0x0301}: 0x1f2c, + {0x1f28, 0x0342}: 0x1f2e, + {0x1f28, 0x0345}: 0x1f98, + {0x1f29, 0x0300}: 0x1f2b, + {0x1f29, 0x0301}: 0x1f2d, + {0x1f29, 0x0342}: 0x1f2f, + {0x1f29, 0x0345}: 0x1f99, + {0x1f2a, 0x0345}: 0x1f9a, + {0x1f2b, 0x0345}: 0x1f9b, + {0x1f2c, 0x0345}: 0x1f9c, + {0x1f2d, 0x0345}: 0x1f9d, + {0x1f2e, 0x0345}: 0x1f9e, + {0x1f2f, 0x0345}: 0x1f9f, + {0x1f30, 0x0300}: 0x1f32, + {0x1f30, 0x0301}: 0x1f34, + {0x1f30, 0x0342}: 0x1f36, + {0x1f31, 0x0300}: 0x1f33, + {0x1f31, 0x0301}: 0x1f35, + {0x1f31, 0x0342}: 0x1f37, + {0x1f38, 0x0300}: 0x1f3a, + {0x1f38, 0x0301}: 0x1f3c, + {0x1f38, 0x0342}: 0x1f3e, + {0x1f39, 0x0300}: 0x1f3b, + {0x1f39, 0x0301}: 0x1f3d, + {0x1f39, 0x0342}: 0x1f3f, + {0x1f40, 0x0300}: 0x1f42, + {0x1f40, 0x0301}: 0x1f44, + {0x1f41, 0x0300}: 0x1f43, + {0x1f41, 0x0301}: 0x1f45, + {0x1f48, 0x0300}: 0x1f4a, + {0x1f48, 0x0301}: 0x1f4c, + {0x1f49, 0x0300}: 0x1f4b, + {0x1f49, 0x0301}: 0x1f4d, + {0x1f50, 0x0300}: 0x1f52, + {0x1f50, 0x0301}: 0x1f54, + {0x1f50, 0x0342}: 0x1f56, + {0x1f51, 0x0300}: 0x1f53, + {0x1f51, 0x0301}: 0x1f55, + {0x1f51, 0x0342}: 0x1f57, + {0x1f59, 0x0300}: 0x1f5b, + {0x1f59, 0x0301}: 0x1f5d, + {0x1f59, 0x0342}: 0x1f5f, + {0x1f60, 0x0300}: 0x1f62, + {0x1f60, 0x0301}: 0x1f64, + {0x1f60, 0x0342}: 0x1f66, + {0x1f60, 0x0345}: 0x1fa0, + {0x1f61, 0x0300}: 0x1f63, + {0x1f61, 0x0301}: 0x1f65, + {0x1f61, 0x0342}: 0x1f67, + {0x1f61, 0x0345}: 0x1fa1, + {0x1f62, 0x0345}: 0x1fa2, + {0x1f63, 0x0345}: 0x1fa3, + {0x1f64, 0x0345}: 0x1fa4, + {0x1f65, 0x0345}: 0x1fa5, + {0x1f66, 0x0345}: 0x1fa6, + {0x1f67, 0x0345}: 0x1fa7, + {0x1f68, 0x0300}: 0x1f6a, + {0x1f68, 0x0301}: 0x1f6c, + {0x1f68, 0x0342}: 0x1f6e, + {0x1f68, 0x0345}: 0x1fa8, + {0x1f69, 0x0300}: 0x1f6b, + {0x1f69, 0x0301}: 0x1f6d, + {0x1f69, 0x0342}: 0x1f6f, + {0x1f69, 0x0345}: 0x1fa9, + {0x1f6a, 0x0345}: 0x1faa, + {0x1f6b, 0x0345}: 0x1fab, + {0x1f6c, 0x0345}: 0x1fac, + {0x1f6d, 0x0345}: 0x1fad, + {0x1f6e, 0x0345}: 0x1fae, + {0x1f6f, 0x0345}: 0x1faf, + {0x1f70, 0x0345}: 0x1fb2, + {0x1f74, 0x0345}: 0x1fc2, + {0x1f7c, 0x0345}: 0x1ff2, + {0x1fb6, 0x0345}: 0x1fb7, + {0x1fbf, 0x0300}: 0x1fcd, + {0x1fbf, 0x0301}: 0x1fce, + {0x1fbf, 0x0342}: 0x1fcf, + {0x1fc6, 0x0345}: 0x1fc7, + {0x1ff6, 0x0345}: 0x1ff7, + {0x1ffe, 0x0300}: 0x1fdd, + {0x1ffe, 0x0301}: 0x1fde, + {0x1ffe, 0x0342}: 0x1fdf, + {0x2190, 0x0338}: 0x219a, + {0x2192, 0x0338}: 0x219b, + {0x2194, 0x0338}: 0x21ae, + {0x21d0, 0x0338}: 0x21cd, + {0x21d2, 0x0338}: 0x21cf, + {0x21d4, 0x0338}: 0x21ce, + {0x2203, 0x0338}: 0x2204, + {0x2208, 0x0338}: 0x2209, + {0x220b, 0x0338}: 0x220c, + {0x2223, 0x0338}: 0x2224, + {0x2225, 0x0338}: 0x2226, + {0x223c, 0x0338}: 0x2241, + {0x2243, 0x0338}: 0x2244, + {0x2245, 0x0338}: 0x2247, + {0x2248, 0x0338}: 0x2249, + {0x224d, 0x0338}: 0x226d, + {0x2261, 0x0338}: 0x2262, + {0x2264, 0x0338}: 0x2270, + {0x2265, 0x0338}: 0x2271, + {0x2272, 0x0338}: 0x2274, + {0x2273, 0x0338}: 0x2275, + {0x2276, 0x0338}: 0x2278, + {0x2277, 0x0338}: 0x2279, + {0x227a, 0x0338}: 0x2280, + {0x227b, 0x0338}: 0x2281, + {0x227c, 0x0338}: 0x22e0, + {0x227d, 0x0338}: 0x22e1, + {0x2282, 0x0338}: 0x2284, + {0x2283, 0x0338}: 0x2285, + {0x2286, 0x0338}: 0x2288, + {0x2287, 0x0338}: 0x2289, + {0x2291, 0x0338}: 0x22e2, + {0x2292, 0x0338}: 0x22e3, + {0x22a2, 0x0338}: 0x22ac, + {0x22a8, 0x0338}: 0x22ad, + {0x22a9, 0x0338}: 0x22ae, + {0x22ab, 0x0338}: 0x22af, + {0x22b2, 0x0338}: 0x22ea, + {0x22b3, 0x0338}: 0x22eb, + {0x22b4, 0x0338}: 0x22ec, + {0x22b5, 0x0338}: 0x22ed, + {0x2add, 0x0338}: 0x0000, + {0x3046, 0x3099}: 0x3094, + {0x304b, 0x3099}: 0x304c, + {0x304d, 0x3099}: 0x304e, + {0x304f, 0x3099}: 0x3050, + {0x3051, 0x3099}: 0x3052, + {0x3053, 0x3099}: 0x3054, + {0x3055, 0x3099}: 0x3056, + {0x3057, 0x3099}: 0x3058, + {0x3059, 0x3099}: 0x305a, + {0x305b, 0x3099}: 0x305c, + {0x305d, 0x3099}: 0x305e, + {0x305f, 0x3099}: 0x3060, + {0x3061, 0x3099}: 0x3062, + {0x3064, 0x3099}: 0x3065, + {0x3066, 0x3099}: 0x3067, + {0x3068, 0x3099}: 0x3069, + {0x306f, 0x3099}: 0x3070, + {0x306f, 0x309a}: 0x3071, + {0x3072, 0x3099}: 0x3073, + {0x3072, 0x309a}: 0x3074, + {0x3075, 0x3099}: 0x3076, + {0x3075, 0x309a}: 0x3077, + {0x3078, 0x3099}: 0x3079, + {0x3078, 0x309a}: 0x307a, + {0x307b, 0x3099}: 0x307c, + {0x307b, 0x309a}: 0x307d, + {0x309d, 0x3099}: 0x309e, + {0x30a6, 0x3099}: 0x30f4, + {0x30ab, 0x3099}: 0x30ac, + {0x30ad, 0x3099}: 0x30ae, + {0x30af, 0x3099}: 0x30b0, + {0x30b1, 0x3099}: 0x30b2, + {0x30b3, 0x3099}: 0x30b4, + {0x30b5, 0x3099}: 0x30b6, + {0x30b7, 0x3099}: 0x30b8, + {0x30b9, 0x3099}: 0x30ba, + {0x30bb, 0x3099}: 0x30bc, + {0x30bd, 0x3099}: 0x30be, + {0x30bf, 0x3099}: 0x30c0, + {0x30c1, 0x3099}: 0x30c2, + {0x30c4, 0x3099}: 0x30c5, + {0x30c6, 0x3099}: 0x30c7, + {0x30c8, 0x3099}: 0x30c9, + {0x30cf, 0x3099}: 0x30d0, + {0x30cf, 0x309a}: 0x30d1, + {0x30d2, 0x3099}: 0x30d3, + {0x30d2, 0x309a}: 0x30d4, + {0x30d5, 0x3099}: 0x30d6, + {0x30d5, 0x309a}: 0x30d7, + {0x30d8, 0x3099}: 0x30d9, + {0x30d8, 0x309a}: 0x30da, + {0x30db, 0x3099}: 0x30dc, + {0x30db, 0x309a}: 0x30dd, + {0x30ef, 0x3099}: 0x30f7, + {0x30f0, 0x3099}: 0x30f8, + {0x30f1, 0x3099}: 0x30f9, + {0x30f2, 0x3099}: 0x30fa, + {0x30fd, 0x3099}: 0x30fe, + {0xfb49, 0x05c1}: 0x0000, + {0xfb49, 0x05c2}: 0x0000, + {0x11099, 0x110ba}: 0x1109a, + {0x1109b, 0x110ba}: 0x1109c, + {0x110a5, 0x110ba}: 0x110ab, + {0x11131, 0x11127}: 0x1112e, + {0x11132, 0x11127}: 0x1112f, + {0x11347, 0x1133e}: 0x1134b, + {0x11347, 0x11357}: 0x1134c, + {0x114b9, 0x114b0}: 0x114bc, + {0x114b9, 0x114ba}: 0x114bb, + {0x114b9, 0x114bd}: 0x114be, + {0x115b8, 0x115af}: 0x115ba, + {0x115b9, 0x115af}: 0x115bb, + {0x11935, 0x11930}: 0x11938, + {0x1d157, 0x1d165}: 0x0000, + {0x1d158, 0x1d165}: 0x0000, + {0x1d15f, 0x1d16e}: 0x0000, + {0x1d15f, 0x1d16f}: 0x0000, + {0x1d15f, 0x1d170}: 0x0000, + {0x1d15f, 0x1d171}: 0x0000, + {0x1d15f, 0x1d172}: 0x0000, + {0x1d1b9, 0x1d165}: 0x0000, + {0x1d1ba, 0x1d165}: 0x0000, + {0x1d1bb, 0x1d16e}: 0x0000, + {0x1d1bb, 0x1d16f}: 0x0000, + {0x1d1bc, 0x1d16e}: 0x0000, + {0x1d1bc, 0x1d16f}: 0x0000, +} diff --git a/vendor/github.com/go-text/typesetting/unicodedata/east_asian_width.go b/vendor/github.com/go-text/typesetting/unicodedata/east_asian_width.go new file mode 100644 index 0000000..a4843f5 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/unicodedata/east_asian_width.go @@ -0,0 +1,131 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package unicodedata + +import "unicode" + +// Code generated by typesettings-utils/generators/unicodedata/cmd/main.go DO NOT EDIT. + +// LargeEastAsian matches runes with East_Asian_Width property of +// F, W or H, and is used for UAX14, rule LB30. +var LargeEastAsian = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x1100, Hi: 0x115f, Stride: 1}, + {Lo: 0x20a9, Hi: 0x231a, Stride: 625}, + {Lo: 0x231b, Hi: 0x2329, Stride: 14}, + {Lo: 0x232a, Hi: 0x23e9, Stride: 191}, + {Lo: 0x23ea, Hi: 0x23ec, Stride: 1}, + {Lo: 0x23f0, Hi: 0x23f3, Stride: 3}, + {Lo: 0x25fd, Hi: 0x25fe, Stride: 1}, + {Lo: 0x2614, Hi: 0x2615, Stride: 1}, + {Lo: 0x2648, Hi: 0x2653, Stride: 1}, + {Lo: 0x267f, Hi: 0x2693, Stride: 20}, + {Lo: 0x26a1, Hi: 0x26aa, Stride: 9}, + {Lo: 0x26ab, Hi: 0x26bd, Stride: 18}, + {Lo: 0x26be, Hi: 0x26c4, Stride: 6}, + {Lo: 0x26c5, Hi: 0x26ce, Stride: 9}, + {Lo: 0x26d4, Hi: 0x26ea, Stride: 22}, + {Lo: 0x26f2, Hi: 0x26f3, Stride: 1}, + {Lo: 0x26f5, Hi: 0x26fa, Stride: 5}, + {Lo: 0x26fd, Hi: 0x2705, Stride: 8}, + {Lo: 0x270a, Hi: 0x270b, Stride: 1}, + {Lo: 0x2728, Hi: 0x274c, Stride: 36}, + {Lo: 0x274e, Hi: 0x2753, Stride: 5}, + {Lo: 0x2754, Hi: 0x2755, Stride: 1}, + {Lo: 0x2757, Hi: 0x2795, Stride: 62}, + {Lo: 0x2796, Hi: 0x2797, Stride: 1}, + {Lo: 0x27b0, Hi: 0x27bf, Stride: 15}, + {Lo: 0x2b1b, Hi: 0x2b1c, Stride: 1}, + {Lo: 0x2b50, Hi: 0x2b55, Stride: 5}, + {Lo: 0x2e80, Hi: 0x2e99, Stride: 1}, + {Lo: 0x2e9b, Hi: 0x2ef3, Stride: 1}, + {Lo: 0x2f00, Hi: 0x2fd5, Stride: 1}, + {Lo: 0x2ff0, Hi: 0x303e, Stride: 1}, + {Lo: 0x3041, Hi: 0x3096, Stride: 1}, + {Lo: 0x3099, Hi: 0x30ff, Stride: 1}, + {Lo: 0x3105, Hi: 0x312f, Stride: 1}, + {Lo: 0x3131, Hi: 0x318e, Stride: 1}, + {Lo: 0x3190, Hi: 0x31e3, Stride: 1}, + {Lo: 0x31ef, Hi: 0x321e, Stride: 1}, + {Lo: 0x3220, Hi: 0x3247, Stride: 1}, + {Lo: 0x3250, Hi: 0x4dbf, Stride: 1}, + {Lo: 0x4e00, Hi: 0xa48c, Stride: 1}, + {Lo: 0xa490, Hi: 0xa4c6, Stride: 1}, + {Lo: 0xa960, Hi: 0xa97c, Stride: 1}, + {Lo: 0xac00, Hi: 0xd7a3, Stride: 1}, + {Lo: 0xf900, Hi: 0xfaff, Stride: 1}, + {Lo: 0xfe10, Hi: 0xfe19, Stride: 1}, + {Lo: 0xfe30, Hi: 0xfe52, Stride: 1}, + {Lo: 0xfe54, Hi: 0xfe66, Stride: 1}, + {Lo: 0xfe68, Hi: 0xfe6b, Stride: 1}, + {Lo: 0xff01, Hi: 0xffbe, Stride: 1}, + {Lo: 0xffc2, Hi: 0xffc7, Stride: 1}, + {Lo: 0xffca, Hi: 0xffcf, Stride: 1}, + {Lo: 0xffd2, Hi: 0xffd7, Stride: 1}, + {Lo: 0xffda, Hi: 0xffdc, Stride: 1}, + {Lo: 0xffe0, Hi: 0xffe6, Stride: 1}, + {Lo: 0xffe8, Hi: 0xffee, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x16fe0, Hi: 0x16fe4, Stride: 1}, + {Lo: 0x16ff0, Hi: 0x16ff1, Stride: 1}, + {Lo: 0x17000, Hi: 0x187f7, Stride: 1}, + {Lo: 0x18800, Hi: 0x18cd5, Stride: 1}, + {Lo: 0x18d00, Hi: 0x18d08, Stride: 1}, + {Lo: 0x1aff0, Hi: 0x1aff3, Stride: 1}, + {Lo: 0x1aff5, Hi: 0x1affb, Stride: 1}, + {Lo: 0x1affd, Hi: 0x1affe, Stride: 1}, + {Lo: 0x1b000, Hi: 0x1b122, Stride: 1}, + {Lo: 0x1b132, Hi: 0x1b150, Stride: 30}, + {Lo: 0x1b151, Hi: 0x1b152, Stride: 1}, + {Lo: 0x1b155, Hi: 0x1b164, Stride: 15}, + {Lo: 0x1b165, Hi: 0x1b167, Stride: 1}, + {Lo: 0x1b170, Hi: 0x1b2fb, Stride: 1}, + {Lo: 0x1f004, Hi: 0x1f0cf, Stride: 203}, + {Lo: 0x1f18e, Hi: 0x1f191, Stride: 3}, + {Lo: 0x1f192, Hi: 0x1f19a, Stride: 1}, + {Lo: 0x1f200, Hi: 0x1f202, Stride: 1}, + {Lo: 0x1f210, Hi: 0x1f23b, Stride: 1}, + {Lo: 0x1f240, Hi: 0x1f248, Stride: 1}, + {Lo: 0x1f250, Hi: 0x1f251, Stride: 1}, + {Lo: 0x1f260, Hi: 0x1f265, Stride: 1}, + {Lo: 0x1f300, Hi: 0x1f320, Stride: 1}, + {Lo: 0x1f32d, Hi: 0x1f335, Stride: 1}, + {Lo: 0x1f337, Hi: 0x1f37c, Stride: 1}, + {Lo: 0x1f37e, Hi: 0x1f393, Stride: 1}, + {Lo: 0x1f3a0, Hi: 0x1f3ca, Stride: 1}, + {Lo: 0x1f3cf, Hi: 0x1f3d3, Stride: 1}, + {Lo: 0x1f3e0, Hi: 0x1f3f0, Stride: 1}, + {Lo: 0x1f3f4, Hi: 0x1f3f8, Stride: 4}, + {Lo: 0x1f3f9, Hi: 0x1f43e, Stride: 1}, + {Lo: 0x1f440, Hi: 0x1f442, Stride: 2}, + {Lo: 0x1f443, Hi: 0x1f4fc, Stride: 1}, + {Lo: 0x1f4ff, Hi: 0x1f53d, Stride: 1}, + {Lo: 0x1f54b, Hi: 0x1f54e, Stride: 1}, + {Lo: 0x1f550, Hi: 0x1f567, Stride: 1}, + {Lo: 0x1f57a, Hi: 0x1f595, Stride: 27}, + {Lo: 0x1f596, Hi: 0x1f5a4, Stride: 14}, + {Lo: 0x1f5fb, Hi: 0x1f64f, Stride: 1}, + {Lo: 0x1f680, Hi: 0x1f6c5, Stride: 1}, + {Lo: 0x1f6cc, Hi: 0x1f6d0, Stride: 4}, + {Lo: 0x1f6d1, Hi: 0x1f6d2, Stride: 1}, + {Lo: 0x1f6d5, Hi: 0x1f6d7, Stride: 1}, + {Lo: 0x1f6dc, Hi: 0x1f6df, Stride: 1}, + {Lo: 0x1f6eb, Hi: 0x1f6ec, Stride: 1}, + {Lo: 0x1f6f4, Hi: 0x1f6fc, Stride: 1}, + {Lo: 0x1f7e0, Hi: 0x1f7eb, Stride: 1}, + {Lo: 0x1f7f0, Hi: 0x1f90c, Stride: 284}, + {Lo: 0x1f90d, Hi: 0x1f93a, Stride: 1}, + {Lo: 0x1f93c, Hi: 0x1f945, Stride: 1}, + {Lo: 0x1f947, Hi: 0x1f9ff, Stride: 1}, + {Lo: 0x1fa70, Hi: 0x1fa7c, Stride: 1}, + {Lo: 0x1fa80, Hi: 0x1fa88, Stride: 1}, + {Lo: 0x1fa90, Hi: 0x1fabd, Stride: 1}, + {Lo: 0x1fabf, Hi: 0x1fac5, Stride: 1}, + {Lo: 0x1face, Hi: 0x1fadb, Stride: 1}, + {Lo: 0x1fae0, Hi: 0x1fae8, Stride: 1}, + {Lo: 0x1faf0, Hi: 0x1faf8, Stride: 1}, + {Lo: 0x20000, Hi: 0x2fffd, Stride: 1}, + {Lo: 0x30000, Hi: 0x3fffd, Stride: 1}, + }, +} diff --git a/vendor/github.com/go-text/typesetting/unicodedata/emojis.go b/vendor/github.com/go-text/typesetting/unicodedata/emojis.go new file mode 100644 index 0000000..01ac795 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/unicodedata/emojis.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package unicodedata + +import "unicode" + +// Code generated by typesettings-utils/generators/unicodedata/cmd/main.go DO NOT EDIT. + +var Extended_Pictographic = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x00a9, Hi: 0x00ae, Stride: 5}, + {Lo: 0x203c, Hi: 0x2049, Stride: 13}, + {Lo: 0x2122, Hi: 0x2139, Stride: 23}, + {Lo: 0x2194, Hi: 0x2199, Stride: 1}, + {Lo: 0x21a9, Hi: 0x21aa, Stride: 1}, + {Lo: 0x231a, Hi: 0x231b, Stride: 1}, + {Lo: 0x2328, Hi: 0x2388, Stride: 96}, + {Lo: 0x23cf, Hi: 0x23e9, Stride: 26}, + {Lo: 0x23ea, Hi: 0x23f3, Stride: 1}, + {Lo: 0x23f8, Hi: 0x23fa, Stride: 1}, + {Lo: 0x24c2, Hi: 0x25aa, Stride: 232}, + {Lo: 0x25ab, Hi: 0x25b6, Stride: 11}, + {Lo: 0x25c0, Hi: 0x25fb, Stride: 59}, + {Lo: 0x25fc, Hi: 0x25fe, Stride: 1}, + {Lo: 0x2600, Hi: 0x2605, Stride: 1}, + {Lo: 0x2607, Hi: 0x2612, Stride: 1}, + {Lo: 0x2614, Hi: 0x2685, Stride: 1}, + {Lo: 0x2690, Hi: 0x2705, Stride: 1}, + {Lo: 0x2708, Hi: 0x2712, Stride: 1}, + {Lo: 0x2714, Hi: 0x2716, Stride: 2}, + {Lo: 0x271d, Hi: 0x2721, Stride: 4}, + {Lo: 0x2728, Hi: 0x2733, Stride: 11}, + {Lo: 0x2734, Hi: 0x2744, Stride: 16}, + {Lo: 0x2747, Hi: 0x274c, Stride: 5}, + {Lo: 0x274e, Hi: 0x2753, Stride: 5}, + {Lo: 0x2754, Hi: 0x2755, Stride: 1}, + {Lo: 0x2757, Hi: 0x2763, Stride: 12}, + {Lo: 0x2764, Hi: 0x2767, Stride: 1}, + {Lo: 0x2795, Hi: 0x2797, Stride: 1}, + {Lo: 0x27a1, Hi: 0x27bf, Stride: 15}, + {Lo: 0x2934, Hi: 0x2935, Stride: 1}, + {Lo: 0x2b05, Hi: 0x2b07, Stride: 1}, + {Lo: 0x2b1b, Hi: 0x2b1c, Stride: 1}, + {Lo: 0x2b50, Hi: 0x2b55, Stride: 5}, + {Lo: 0x3030, Hi: 0x303d, Stride: 13}, + {Lo: 0x3297, Hi: 0x3299, Stride: 2}, + }, + R32: []unicode.Range32{ + {Lo: 0x1f000, Hi: 0x1f0ff, Stride: 1}, + {Lo: 0x1f10d, Hi: 0x1f10f, Stride: 1}, + {Lo: 0x1f12f, Hi: 0x1f16c, Stride: 61}, + {Lo: 0x1f16d, Hi: 0x1f171, Stride: 1}, + {Lo: 0x1f17e, Hi: 0x1f17f, Stride: 1}, + {Lo: 0x1f18e, Hi: 0x1f191, Stride: 3}, + {Lo: 0x1f192, Hi: 0x1f19a, Stride: 1}, + {Lo: 0x1f1ad, Hi: 0x1f1e5, Stride: 1}, + {Lo: 0x1f201, Hi: 0x1f20f, Stride: 1}, + {Lo: 0x1f21a, Hi: 0x1f22f, Stride: 21}, + {Lo: 0x1f232, Hi: 0x1f23a, Stride: 1}, + {Lo: 0x1f23c, Hi: 0x1f23f, Stride: 1}, + {Lo: 0x1f249, Hi: 0x1f3fa, Stride: 1}, + {Lo: 0x1f400, Hi: 0x1f53d, Stride: 1}, + {Lo: 0x1f546, Hi: 0x1f64f, Stride: 1}, + {Lo: 0x1f680, Hi: 0x1f6ff, Stride: 1}, + {Lo: 0x1f774, Hi: 0x1f77f, Stride: 1}, + {Lo: 0x1f7d5, Hi: 0x1f7ff, Stride: 1}, + {Lo: 0x1f80c, Hi: 0x1f80f, Stride: 1}, + {Lo: 0x1f848, Hi: 0x1f84f, Stride: 1}, + {Lo: 0x1f85a, Hi: 0x1f85f, Stride: 1}, + {Lo: 0x1f888, Hi: 0x1f88f, Stride: 1}, + {Lo: 0x1f8ae, Hi: 0x1f8ff, Stride: 1}, + {Lo: 0x1f90c, Hi: 0x1f93a, Stride: 1}, + {Lo: 0x1f93c, Hi: 0x1f945, Stride: 1}, + {Lo: 0x1f947, Hi: 0x1faff, Stride: 1}, + {Lo: 0x1fc00, Hi: 0x1fffd, Stride: 1}, + }, + LatinOffset: 1, +} diff --git a/vendor/github.com/go-text/typesetting/unicodedata/general_category.go b/vendor/github.com/go-text/typesetting/unicodedata/general_category.go new file mode 100644 index 0000000..06cc02e --- /dev/null +++ b/vendor/github.com/go-text/typesetting/unicodedata/general_category.go @@ -0,0 +1,2207 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package unicodedata + +import "unicode" + +// Code generated by typesettings-utils/generators/unicodedata/cmd/main.go DO NOT EDIT. + +var Cc = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0000, Hi: 0x001f, Stride: 1}, + {Lo: 0x007f, Hi: 0x009f, Stride: 1}, + }, + LatinOffset: 2, +} + +var Cf = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x00ad, Hi: 0x0600, Stride: 1363}, + {Lo: 0x0601, Hi: 0x0605, Stride: 1}, + {Lo: 0x061c, Hi: 0x06dd, Stride: 193}, + {Lo: 0x070f, Hi: 0x0890, Stride: 385}, + {Lo: 0x0891, Hi: 0x08e2, Stride: 81}, + {Lo: 0x180e, Hi: 0x200b, Stride: 2045}, + {Lo: 0x200c, Hi: 0x200f, Stride: 1}, + {Lo: 0x202a, Hi: 0x202e, Stride: 1}, + {Lo: 0x2060, Hi: 0x2064, Stride: 1}, + {Lo: 0x2066, Hi: 0x206f, Stride: 1}, + {Lo: 0xfeff, Hi: 0xfff9, Stride: 250}, + {Lo: 0xfffa, Hi: 0xfffb, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x110bd, Hi: 0x110cd, Stride: 16}, + {Lo: 0x13430, Hi: 0x1343f, Stride: 1}, + {Lo: 0x1bca0, Hi: 0x1bca3, Stride: 1}, + {Lo: 0x1d173, Hi: 0x1d17a, Stride: 1}, + {Lo: 0xe0001, Hi: 0xe0020, Stride: 31}, + {Lo: 0xe0021, Hi: 0xe007f, Stride: 1}, + }, +} + +var Co = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0xe000, Hi: 0xf8ff, Stride: 6399}, + }, + R32: []unicode.Range32{ + {Lo: 0xf0000, Hi: 0xffffd, Stride: 65533}, + {Lo: 0x100000, Hi: 0x10fffd, Stride: 65533}, + }, +} + +var Cs = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0xd800, Hi: 0xdb7f, Stride: 895}, + {Lo: 0xdb80, Hi: 0xdbff, Stride: 127}, + {Lo: 0xdc00, Hi: 0xdfff, Stride: 1023}, + }, +} + +var Ll = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0061, Hi: 0x007a, Stride: 1}, + {Lo: 0x00b5, Hi: 0x00df, Stride: 42}, + {Lo: 0x00e0, Hi: 0x00f6, Stride: 1}, + {Lo: 0x00f8, Hi: 0x00ff, Stride: 1}, + {Lo: 0x0101, Hi: 0x0137, Stride: 2}, + {Lo: 0x0138, Hi: 0x0148, Stride: 2}, + {Lo: 0x0149, Hi: 0x0177, Stride: 2}, + {Lo: 0x017a, Hi: 0x017e, Stride: 2}, + {Lo: 0x017f, Hi: 0x0180, Stride: 1}, + {Lo: 0x0183, Hi: 0x0185, Stride: 2}, + {Lo: 0x0188, Hi: 0x018c, Stride: 4}, + {Lo: 0x018d, Hi: 0x0192, Stride: 5}, + {Lo: 0x0195, Hi: 0x0199, Stride: 4}, + {Lo: 0x019a, Hi: 0x019b, Stride: 1}, + {Lo: 0x019e, Hi: 0x01a1, Stride: 3}, + {Lo: 0x01a3, Hi: 0x01a5, Stride: 2}, + {Lo: 0x01a8, Hi: 0x01aa, Stride: 2}, + {Lo: 0x01ab, Hi: 0x01ad, Stride: 2}, + {Lo: 0x01b0, Hi: 0x01b4, Stride: 4}, + {Lo: 0x01b6, Hi: 0x01b9, Stride: 3}, + {Lo: 0x01ba, Hi: 0x01bd, Stride: 3}, + {Lo: 0x01be, Hi: 0x01bf, Stride: 1}, + {Lo: 0x01c6, Hi: 0x01cc, Stride: 3}, + {Lo: 0x01ce, Hi: 0x01dc, Stride: 2}, + {Lo: 0x01dd, Hi: 0x01ef, Stride: 2}, + {Lo: 0x01f0, Hi: 0x01f3, Stride: 3}, + {Lo: 0x01f5, Hi: 0x01f9, Stride: 4}, + {Lo: 0x01fb, Hi: 0x0233, Stride: 2}, + {Lo: 0x0234, Hi: 0x0239, Stride: 1}, + {Lo: 0x023c, Hi: 0x023f, Stride: 3}, + {Lo: 0x0240, Hi: 0x0242, Stride: 2}, + {Lo: 0x0247, Hi: 0x024f, Stride: 2}, + {Lo: 0x0250, Hi: 0x0293, Stride: 1}, + {Lo: 0x0295, Hi: 0x02af, Stride: 1}, + {Lo: 0x0371, Hi: 0x0373, Stride: 2}, + {Lo: 0x0377, Hi: 0x037b, Stride: 4}, + {Lo: 0x037c, Hi: 0x037d, Stride: 1}, + {Lo: 0x0390, Hi: 0x03ac, Stride: 28}, + {Lo: 0x03ad, Hi: 0x03ce, Stride: 1}, + {Lo: 0x03d0, Hi: 0x03d1, Stride: 1}, + {Lo: 0x03d5, Hi: 0x03d7, Stride: 1}, + {Lo: 0x03d9, Hi: 0x03ef, Stride: 2}, + {Lo: 0x03f0, Hi: 0x03f3, Stride: 1}, + {Lo: 0x03f5, Hi: 0x03fb, Stride: 3}, + {Lo: 0x03fc, Hi: 0x0430, Stride: 52}, + {Lo: 0x0431, Hi: 0x045f, Stride: 1}, + {Lo: 0x0461, Hi: 0x0481, Stride: 2}, + {Lo: 0x048b, Hi: 0x04bf, Stride: 2}, + {Lo: 0x04c2, Hi: 0x04ce, Stride: 2}, + {Lo: 0x04cf, Hi: 0x052f, Stride: 2}, + {Lo: 0x0560, Hi: 0x0588, Stride: 1}, + {Lo: 0x10d0, Hi: 0x10fa, Stride: 1}, + {Lo: 0x10fd, Hi: 0x10ff, Stride: 1}, + {Lo: 0x13f8, Hi: 0x13fd, Stride: 1}, + {Lo: 0x1c80, Hi: 0x1c88, Stride: 1}, + {Lo: 0x1d00, Hi: 0x1d2b, Stride: 1}, + {Lo: 0x1d6b, Hi: 0x1d77, Stride: 1}, + {Lo: 0x1d79, Hi: 0x1d9a, Stride: 1}, + {Lo: 0x1e01, Hi: 0x1e95, Stride: 2}, + {Lo: 0x1e96, Hi: 0x1e9d, Stride: 1}, + {Lo: 0x1e9f, Hi: 0x1eff, Stride: 2}, + {Lo: 0x1f00, Hi: 0x1f07, Stride: 1}, + {Lo: 0x1f10, Hi: 0x1f15, Stride: 1}, + {Lo: 0x1f20, Hi: 0x1f27, Stride: 1}, + {Lo: 0x1f30, Hi: 0x1f37, Stride: 1}, + {Lo: 0x1f40, Hi: 0x1f45, Stride: 1}, + {Lo: 0x1f50, Hi: 0x1f57, Stride: 1}, + {Lo: 0x1f60, Hi: 0x1f67, Stride: 1}, + {Lo: 0x1f70, Hi: 0x1f7d, Stride: 1}, + {Lo: 0x1f80, Hi: 0x1f87, Stride: 1}, + {Lo: 0x1f90, Hi: 0x1f97, Stride: 1}, + {Lo: 0x1fa0, Hi: 0x1fa7, Stride: 1}, + {Lo: 0x1fb0, Hi: 0x1fb4, Stride: 1}, + {Lo: 0x1fb6, Hi: 0x1fb7, Stride: 1}, + {Lo: 0x1fbe, Hi: 0x1fc2, Stride: 4}, + {Lo: 0x1fc3, Hi: 0x1fc4, Stride: 1}, + {Lo: 0x1fc6, Hi: 0x1fc7, Stride: 1}, + {Lo: 0x1fd0, Hi: 0x1fd3, Stride: 1}, + {Lo: 0x1fd6, Hi: 0x1fd7, Stride: 1}, + {Lo: 0x1fe0, Hi: 0x1fe7, Stride: 1}, + {Lo: 0x1ff2, Hi: 0x1ff4, Stride: 1}, + {Lo: 0x1ff6, Hi: 0x1ff7, Stride: 1}, + {Lo: 0x210a, Hi: 0x210e, Stride: 4}, + {Lo: 0x210f, Hi: 0x2113, Stride: 4}, + {Lo: 0x212f, Hi: 0x2139, Stride: 5}, + {Lo: 0x213c, Hi: 0x213d, Stride: 1}, + {Lo: 0x2146, Hi: 0x2149, Stride: 1}, + {Lo: 0x214e, Hi: 0x2184, Stride: 54}, + {Lo: 0x2c30, Hi: 0x2c5f, Stride: 1}, + {Lo: 0x2c61, Hi: 0x2c65, Stride: 4}, + {Lo: 0x2c66, Hi: 0x2c6c, Stride: 2}, + {Lo: 0x2c71, Hi: 0x2c73, Stride: 2}, + {Lo: 0x2c74, Hi: 0x2c76, Stride: 2}, + {Lo: 0x2c77, Hi: 0x2c7b, Stride: 1}, + {Lo: 0x2c81, Hi: 0x2ce3, Stride: 2}, + {Lo: 0x2ce4, Hi: 0x2cec, Stride: 8}, + {Lo: 0x2cee, Hi: 0x2cf3, Stride: 5}, + {Lo: 0x2d00, Hi: 0x2d25, Stride: 1}, + {Lo: 0x2d27, Hi: 0x2d2d, Stride: 6}, + {Lo: 0xa641, Hi: 0xa66d, Stride: 2}, + {Lo: 0xa681, Hi: 0xa69b, Stride: 2}, + {Lo: 0xa723, Hi: 0xa72f, Stride: 2}, + {Lo: 0xa730, Hi: 0xa731, Stride: 1}, + {Lo: 0xa733, Hi: 0xa771, Stride: 2}, + {Lo: 0xa772, Hi: 0xa778, Stride: 1}, + {Lo: 0xa77a, Hi: 0xa77c, Stride: 2}, + {Lo: 0xa77f, Hi: 0xa787, Stride: 2}, + {Lo: 0xa78c, Hi: 0xa78e, Stride: 2}, + {Lo: 0xa791, Hi: 0xa793, Stride: 2}, + {Lo: 0xa794, Hi: 0xa795, Stride: 1}, + {Lo: 0xa797, Hi: 0xa7a9, Stride: 2}, + {Lo: 0xa7af, Hi: 0xa7b5, Stride: 6}, + {Lo: 0xa7b7, Hi: 0xa7c3, Stride: 2}, + {Lo: 0xa7c8, Hi: 0xa7ca, Stride: 2}, + {Lo: 0xa7d1, Hi: 0xa7d9, Stride: 2}, + {Lo: 0xa7f6, Hi: 0xa7fa, Stride: 4}, + {Lo: 0xab30, Hi: 0xab5a, Stride: 1}, + {Lo: 0xab60, Hi: 0xab68, Stride: 1}, + {Lo: 0xab70, Hi: 0xabbf, Stride: 1}, + {Lo: 0xfb00, Hi: 0xfb06, Stride: 1}, + {Lo: 0xfb13, Hi: 0xfb17, Stride: 1}, + {Lo: 0xff41, Hi: 0xff5a, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x10428, Hi: 0x1044f, Stride: 1}, + {Lo: 0x104d8, Hi: 0x104fb, Stride: 1}, + {Lo: 0x10597, Hi: 0x105a1, Stride: 1}, + {Lo: 0x105a3, Hi: 0x105b1, Stride: 1}, + {Lo: 0x105b3, Hi: 0x105b9, Stride: 1}, + {Lo: 0x105bb, Hi: 0x105bc, Stride: 1}, + {Lo: 0x10cc0, Hi: 0x10cf2, Stride: 1}, + {Lo: 0x118c0, Hi: 0x118df, Stride: 1}, + {Lo: 0x16e60, Hi: 0x16e7f, Stride: 1}, + {Lo: 0x1d41a, Hi: 0x1d433, Stride: 1}, + {Lo: 0x1d44e, Hi: 0x1d454, Stride: 1}, + {Lo: 0x1d456, Hi: 0x1d467, Stride: 1}, + {Lo: 0x1d482, Hi: 0x1d49b, Stride: 1}, + {Lo: 0x1d4b6, Hi: 0x1d4b9, Stride: 1}, + {Lo: 0x1d4bb, Hi: 0x1d4bd, Stride: 2}, + {Lo: 0x1d4be, Hi: 0x1d4c3, Stride: 1}, + {Lo: 0x1d4c5, Hi: 0x1d4cf, Stride: 1}, + {Lo: 0x1d4ea, Hi: 0x1d503, Stride: 1}, + {Lo: 0x1d51e, Hi: 0x1d537, Stride: 1}, + {Lo: 0x1d552, Hi: 0x1d56b, Stride: 1}, + {Lo: 0x1d586, Hi: 0x1d59f, Stride: 1}, + {Lo: 0x1d5ba, Hi: 0x1d5d3, Stride: 1}, + {Lo: 0x1d5ee, Hi: 0x1d607, Stride: 1}, + {Lo: 0x1d622, Hi: 0x1d63b, Stride: 1}, + {Lo: 0x1d656, Hi: 0x1d66f, Stride: 1}, + {Lo: 0x1d68a, Hi: 0x1d6a5, Stride: 1}, + {Lo: 0x1d6c2, Hi: 0x1d6da, Stride: 1}, + {Lo: 0x1d6dc, Hi: 0x1d6e1, Stride: 1}, + {Lo: 0x1d6fc, Hi: 0x1d714, Stride: 1}, + {Lo: 0x1d716, Hi: 0x1d71b, Stride: 1}, + {Lo: 0x1d736, Hi: 0x1d74e, Stride: 1}, + {Lo: 0x1d750, Hi: 0x1d755, Stride: 1}, + {Lo: 0x1d770, Hi: 0x1d788, Stride: 1}, + {Lo: 0x1d78a, Hi: 0x1d78f, Stride: 1}, + {Lo: 0x1d7aa, Hi: 0x1d7c2, Stride: 1}, + {Lo: 0x1d7c4, Hi: 0x1d7c9, Stride: 1}, + {Lo: 0x1d7cb, Hi: 0x1df00, Stride: 1845}, + {Lo: 0x1df01, Hi: 0x1df09, Stride: 1}, + {Lo: 0x1df0b, Hi: 0x1df1e, Stride: 1}, + {Lo: 0x1df25, Hi: 0x1df2a, Stride: 1}, + {Lo: 0x1e922, Hi: 0x1e943, Stride: 1}, + }, + LatinOffset: 4, +} + +var Lm = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x02b0, Hi: 0x02c1, Stride: 1}, + {Lo: 0x02c6, Hi: 0x02d1, Stride: 1}, + {Lo: 0x02e0, Hi: 0x02e4, Stride: 1}, + {Lo: 0x02ec, Hi: 0x02ee, Stride: 2}, + {Lo: 0x0374, Hi: 0x037a, Stride: 6}, + {Lo: 0x0559, Hi: 0x0640, Stride: 231}, + {Lo: 0x06e5, Hi: 0x06e6, Stride: 1}, + {Lo: 0x07f4, Hi: 0x07f5, Stride: 1}, + {Lo: 0x07fa, Hi: 0x081a, Stride: 32}, + {Lo: 0x0824, Hi: 0x0828, Stride: 4}, + {Lo: 0x08c9, Hi: 0x0971, Stride: 168}, + {Lo: 0x0e46, Hi: 0x0ec6, Stride: 128}, + {Lo: 0x10fc, Hi: 0x17d7, Stride: 1755}, + {Lo: 0x1843, Hi: 0x1aa7, Stride: 612}, + {Lo: 0x1c78, Hi: 0x1c7d, Stride: 1}, + {Lo: 0x1d2c, Hi: 0x1d6a, Stride: 1}, + {Lo: 0x1d78, Hi: 0x1d9b, Stride: 35}, + {Lo: 0x1d9c, Hi: 0x1dbf, Stride: 1}, + {Lo: 0x2071, Hi: 0x207f, Stride: 14}, + {Lo: 0x2090, Hi: 0x209c, Stride: 1}, + {Lo: 0x2c7c, Hi: 0x2c7d, Stride: 1}, + {Lo: 0x2d6f, Hi: 0x2e2f, Stride: 192}, + {Lo: 0x3005, Hi: 0x3031, Stride: 44}, + {Lo: 0x3032, Hi: 0x3035, Stride: 1}, + {Lo: 0x303b, Hi: 0x309d, Stride: 98}, + {Lo: 0x309e, Hi: 0x30fc, Stride: 94}, + {Lo: 0x30fd, Hi: 0x30fe, Stride: 1}, + {Lo: 0xa015, Hi: 0xa4f8, Stride: 1251}, + {Lo: 0xa4f9, Hi: 0xa4fd, Stride: 1}, + {Lo: 0xa60c, Hi: 0xa67f, Stride: 115}, + {Lo: 0xa69c, Hi: 0xa69d, Stride: 1}, + {Lo: 0xa717, Hi: 0xa71f, Stride: 1}, + {Lo: 0xa770, Hi: 0xa788, Stride: 24}, + {Lo: 0xa7f2, Hi: 0xa7f4, Stride: 1}, + {Lo: 0xa7f8, Hi: 0xa7f9, Stride: 1}, + {Lo: 0xa9cf, Hi: 0xa9e6, Stride: 23}, + {Lo: 0xaa70, Hi: 0xaadd, Stride: 109}, + {Lo: 0xaaf3, Hi: 0xaaf4, Stride: 1}, + {Lo: 0xab5c, Hi: 0xab5f, Stride: 1}, + {Lo: 0xab69, Hi: 0xff70, Stride: 21511}, + {Lo: 0xff9e, Hi: 0xff9f, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x10780, Hi: 0x10785, Stride: 1}, + {Lo: 0x10787, Hi: 0x107b0, Stride: 1}, + {Lo: 0x107b2, Hi: 0x107ba, Stride: 1}, + {Lo: 0x16b40, Hi: 0x16b43, Stride: 1}, + {Lo: 0x16f93, Hi: 0x16f9f, Stride: 1}, + {Lo: 0x16fe0, Hi: 0x16fe1, Stride: 1}, + {Lo: 0x16fe3, Hi: 0x1aff0, Stride: 16397}, + {Lo: 0x1aff1, Hi: 0x1aff3, Stride: 1}, + {Lo: 0x1aff5, Hi: 0x1affb, Stride: 1}, + {Lo: 0x1affd, Hi: 0x1affe, Stride: 1}, + {Lo: 0x1e030, Hi: 0x1e06d, Stride: 1}, + {Lo: 0x1e137, Hi: 0x1e13d, Stride: 1}, + {Lo: 0x1e4eb, Hi: 0x1e94b, Stride: 1120}, + }, +} + +var Lo = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x00aa, Hi: 0x00ba, Stride: 16}, + {Lo: 0x01bb, Hi: 0x01c0, Stride: 5}, + {Lo: 0x01c1, Hi: 0x01c3, Stride: 1}, + {Lo: 0x0294, Hi: 0x05d0, Stride: 828}, + {Lo: 0x05d1, Hi: 0x05ea, Stride: 1}, + {Lo: 0x05ef, Hi: 0x05f2, Stride: 1}, + {Lo: 0x0620, Hi: 0x063f, Stride: 1}, + {Lo: 0x0641, Hi: 0x064a, Stride: 1}, + {Lo: 0x066e, Hi: 0x066f, Stride: 1}, + {Lo: 0x0671, Hi: 0x06d3, Stride: 1}, + {Lo: 0x06d5, Hi: 0x06ee, Stride: 25}, + {Lo: 0x06ef, Hi: 0x06fa, Stride: 11}, + {Lo: 0x06fb, Hi: 0x06fc, Stride: 1}, + {Lo: 0x06ff, Hi: 0x0710, Stride: 17}, + {Lo: 0x0712, Hi: 0x072f, Stride: 1}, + {Lo: 0x074d, Hi: 0x07a5, Stride: 1}, + {Lo: 0x07b1, Hi: 0x07ca, Stride: 25}, + {Lo: 0x07cb, Hi: 0x07ea, Stride: 1}, + {Lo: 0x0800, Hi: 0x0815, Stride: 1}, + {Lo: 0x0840, Hi: 0x0858, Stride: 1}, + {Lo: 0x0860, Hi: 0x086a, Stride: 1}, + {Lo: 0x0870, Hi: 0x0887, Stride: 1}, + {Lo: 0x0889, Hi: 0x088e, Stride: 1}, + {Lo: 0x08a0, Hi: 0x08c8, Stride: 1}, + {Lo: 0x0904, Hi: 0x0939, Stride: 1}, + {Lo: 0x093d, Hi: 0x0950, Stride: 19}, + {Lo: 0x0958, Hi: 0x0961, Stride: 1}, + {Lo: 0x0972, Hi: 0x0980, Stride: 1}, + {Lo: 0x0985, Hi: 0x098c, Stride: 1}, + {Lo: 0x098f, Hi: 0x0990, Stride: 1}, + {Lo: 0x0993, Hi: 0x09a8, Stride: 1}, + {Lo: 0x09aa, Hi: 0x09b0, Stride: 1}, + {Lo: 0x09b2, Hi: 0x09b6, Stride: 4}, + {Lo: 0x09b7, Hi: 0x09b9, Stride: 1}, + {Lo: 0x09bd, Hi: 0x09ce, Stride: 17}, + {Lo: 0x09dc, Hi: 0x09dd, Stride: 1}, + {Lo: 0x09df, Hi: 0x09e1, Stride: 1}, + {Lo: 0x09f0, Hi: 0x09f1, Stride: 1}, + {Lo: 0x09fc, Hi: 0x0a05, Stride: 9}, + {Lo: 0x0a06, Hi: 0x0a0a, Stride: 1}, + {Lo: 0x0a0f, Hi: 0x0a10, Stride: 1}, + {Lo: 0x0a13, Hi: 0x0a28, Stride: 1}, + {Lo: 0x0a2a, Hi: 0x0a30, Stride: 1}, + {Lo: 0x0a32, Hi: 0x0a33, Stride: 1}, + {Lo: 0x0a35, Hi: 0x0a36, Stride: 1}, + {Lo: 0x0a38, Hi: 0x0a39, Stride: 1}, + {Lo: 0x0a59, Hi: 0x0a5c, Stride: 1}, + {Lo: 0x0a5e, Hi: 0x0a72, Stride: 20}, + {Lo: 0x0a73, Hi: 0x0a74, Stride: 1}, + {Lo: 0x0a85, Hi: 0x0a8d, Stride: 1}, + {Lo: 0x0a8f, Hi: 0x0a91, Stride: 1}, + {Lo: 0x0a93, Hi: 0x0aa8, Stride: 1}, + {Lo: 0x0aaa, Hi: 0x0ab0, Stride: 1}, + {Lo: 0x0ab2, Hi: 0x0ab3, Stride: 1}, + {Lo: 0x0ab5, Hi: 0x0ab9, Stride: 1}, + {Lo: 0x0abd, Hi: 0x0ad0, Stride: 19}, + {Lo: 0x0ae0, Hi: 0x0ae1, Stride: 1}, + {Lo: 0x0af9, Hi: 0x0b05, Stride: 12}, + {Lo: 0x0b06, Hi: 0x0b0c, Stride: 1}, + {Lo: 0x0b0f, Hi: 0x0b10, Stride: 1}, + {Lo: 0x0b13, Hi: 0x0b28, Stride: 1}, + {Lo: 0x0b2a, Hi: 0x0b30, Stride: 1}, + {Lo: 0x0b32, Hi: 0x0b33, Stride: 1}, + {Lo: 0x0b35, Hi: 0x0b39, Stride: 1}, + {Lo: 0x0b3d, Hi: 0x0b5c, Stride: 31}, + {Lo: 0x0b5d, Hi: 0x0b5f, Stride: 2}, + {Lo: 0x0b60, Hi: 0x0b61, Stride: 1}, + {Lo: 0x0b71, Hi: 0x0b83, Stride: 18}, + {Lo: 0x0b85, Hi: 0x0b8a, Stride: 1}, + {Lo: 0x0b8e, Hi: 0x0b90, Stride: 1}, + {Lo: 0x0b92, Hi: 0x0b95, Stride: 1}, + {Lo: 0x0b99, Hi: 0x0b9a, Stride: 1}, + {Lo: 0x0b9c, Hi: 0x0b9e, Stride: 2}, + {Lo: 0x0b9f, Hi: 0x0ba3, Stride: 4}, + {Lo: 0x0ba4, Hi: 0x0ba8, Stride: 4}, + {Lo: 0x0ba9, Hi: 0x0baa, Stride: 1}, + {Lo: 0x0bae, Hi: 0x0bb9, Stride: 1}, + {Lo: 0x0bd0, Hi: 0x0c05, Stride: 53}, + {Lo: 0x0c06, Hi: 0x0c0c, Stride: 1}, + {Lo: 0x0c0e, Hi: 0x0c10, Stride: 1}, + {Lo: 0x0c12, Hi: 0x0c28, Stride: 1}, + {Lo: 0x0c2a, Hi: 0x0c39, Stride: 1}, + {Lo: 0x0c3d, Hi: 0x0c58, Stride: 27}, + {Lo: 0x0c59, Hi: 0x0c5a, Stride: 1}, + {Lo: 0x0c5d, Hi: 0x0c60, Stride: 3}, + {Lo: 0x0c61, Hi: 0x0c80, Stride: 31}, + {Lo: 0x0c85, Hi: 0x0c8c, Stride: 1}, + {Lo: 0x0c8e, Hi: 0x0c90, Stride: 1}, + {Lo: 0x0c92, Hi: 0x0ca8, Stride: 1}, + {Lo: 0x0caa, Hi: 0x0cb3, Stride: 1}, + {Lo: 0x0cb5, Hi: 0x0cb9, Stride: 1}, + {Lo: 0x0cbd, Hi: 0x0cdd, Stride: 32}, + {Lo: 0x0cde, Hi: 0x0ce0, Stride: 2}, + {Lo: 0x0ce1, Hi: 0x0cf1, Stride: 16}, + {Lo: 0x0cf2, Hi: 0x0d04, Stride: 18}, + {Lo: 0x0d05, Hi: 0x0d0c, Stride: 1}, + {Lo: 0x0d0e, Hi: 0x0d10, Stride: 1}, + {Lo: 0x0d12, Hi: 0x0d3a, Stride: 1}, + {Lo: 0x0d3d, Hi: 0x0d4e, Stride: 17}, + {Lo: 0x0d54, Hi: 0x0d56, Stride: 1}, + {Lo: 0x0d5f, Hi: 0x0d61, Stride: 1}, + {Lo: 0x0d7a, Hi: 0x0d7f, Stride: 1}, + {Lo: 0x0d85, Hi: 0x0d96, Stride: 1}, + {Lo: 0x0d9a, Hi: 0x0db1, Stride: 1}, + {Lo: 0x0db3, Hi: 0x0dbb, Stride: 1}, + {Lo: 0x0dbd, Hi: 0x0dc0, Stride: 3}, + {Lo: 0x0dc1, Hi: 0x0dc6, Stride: 1}, + {Lo: 0x0e01, Hi: 0x0e30, Stride: 1}, + {Lo: 0x0e32, Hi: 0x0e33, Stride: 1}, + {Lo: 0x0e40, Hi: 0x0e45, Stride: 1}, + {Lo: 0x0e81, Hi: 0x0e82, Stride: 1}, + {Lo: 0x0e84, Hi: 0x0e86, Stride: 2}, + {Lo: 0x0e87, Hi: 0x0e8a, Stride: 1}, + {Lo: 0x0e8c, Hi: 0x0ea3, Stride: 1}, + {Lo: 0x0ea5, Hi: 0x0ea7, Stride: 2}, + {Lo: 0x0ea8, Hi: 0x0eb0, Stride: 1}, + {Lo: 0x0eb2, Hi: 0x0eb3, Stride: 1}, + {Lo: 0x0ebd, Hi: 0x0ec0, Stride: 3}, + {Lo: 0x0ec1, Hi: 0x0ec4, Stride: 1}, + {Lo: 0x0edc, Hi: 0x0edf, Stride: 1}, + {Lo: 0x0f00, Hi: 0x0f40, Stride: 64}, + {Lo: 0x0f41, Hi: 0x0f47, Stride: 1}, + {Lo: 0x0f49, Hi: 0x0f6c, Stride: 1}, + {Lo: 0x0f88, Hi: 0x0f8c, Stride: 1}, + {Lo: 0x1000, Hi: 0x102a, Stride: 1}, + {Lo: 0x103f, Hi: 0x1050, Stride: 17}, + {Lo: 0x1051, Hi: 0x1055, Stride: 1}, + {Lo: 0x105a, Hi: 0x105d, Stride: 1}, + {Lo: 0x1061, Hi: 0x1065, Stride: 4}, + {Lo: 0x1066, Hi: 0x106e, Stride: 8}, + {Lo: 0x106f, Hi: 0x1070, Stride: 1}, + {Lo: 0x1075, Hi: 0x1081, Stride: 1}, + {Lo: 0x108e, Hi: 0x1100, Stride: 114}, + {Lo: 0x1101, Hi: 0x1248, Stride: 1}, + {Lo: 0x124a, Hi: 0x124d, Stride: 1}, + {Lo: 0x1250, Hi: 0x1256, Stride: 1}, + {Lo: 0x1258, Hi: 0x125a, Stride: 2}, + {Lo: 0x125b, Hi: 0x125d, Stride: 1}, + {Lo: 0x1260, Hi: 0x1288, Stride: 1}, + {Lo: 0x128a, Hi: 0x128d, Stride: 1}, + {Lo: 0x1290, Hi: 0x12b0, Stride: 1}, + {Lo: 0x12b2, Hi: 0x12b5, Stride: 1}, + {Lo: 0x12b8, Hi: 0x12be, Stride: 1}, + {Lo: 0x12c0, Hi: 0x12c2, Stride: 2}, + {Lo: 0x12c3, Hi: 0x12c5, Stride: 1}, + {Lo: 0x12c8, Hi: 0x12d6, Stride: 1}, + {Lo: 0x12d8, Hi: 0x1310, Stride: 1}, + {Lo: 0x1312, Hi: 0x1315, Stride: 1}, + {Lo: 0x1318, Hi: 0x135a, Stride: 1}, + {Lo: 0x1380, Hi: 0x138f, Stride: 1}, + {Lo: 0x1401, Hi: 0x166c, Stride: 1}, + {Lo: 0x166f, Hi: 0x167f, Stride: 1}, + {Lo: 0x1681, Hi: 0x169a, Stride: 1}, + {Lo: 0x16a0, Hi: 0x16ea, Stride: 1}, + {Lo: 0x16f1, Hi: 0x16f8, Stride: 1}, + {Lo: 0x1700, Hi: 0x1711, Stride: 1}, + {Lo: 0x171f, Hi: 0x1731, Stride: 1}, + {Lo: 0x1740, Hi: 0x1751, Stride: 1}, + {Lo: 0x1760, Hi: 0x176c, Stride: 1}, + {Lo: 0x176e, Hi: 0x1770, Stride: 1}, + {Lo: 0x1780, Hi: 0x17b3, Stride: 1}, + {Lo: 0x17dc, Hi: 0x1820, Stride: 68}, + {Lo: 0x1821, Hi: 0x1842, Stride: 1}, + {Lo: 0x1844, Hi: 0x1878, Stride: 1}, + {Lo: 0x1880, Hi: 0x1884, Stride: 1}, + {Lo: 0x1887, Hi: 0x18a8, Stride: 1}, + {Lo: 0x18aa, Hi: 0x18b0, Stride: 6}, + {Lo: 0x18b1, Hi: 0x18f5, Stride: 1}, + {Lo: 0x1900, Hi: 0x191e, Stride: 1}, + {Lo: 0x1950, Hi: 0x196d, Stride: 1}, + {Lo: 0x1970, Hi: 0x1974, Stride: 1}, + {Lo: 0x1980, Hi: 0x19ab, Stride: 1}, + {Lo: 0x19b0, Hi: 0x19c9, Stride: 1}, + {Lo: 0x1a00, Hi: 0x1a16, Stride: 1}, + {Lo: 0x1a20, Hi: 0x1a54, Stride: 1}, + {Lo: 0x1b05, Hi: 0x1b33, Stride: 1}, + {Lo: 0x1b45, Hi: 0x1b4c, Stride: 1}, + {Lo: 0x1b83, Hi: 0x1ba0, Stride: 1}, + {Lo: 0x1bae, Hi: 0x1baf, Stride: 1}, + {Lo: 0x1bba, Hi: 0x1be5, Stride: 1}, + {Lo: 0x1c00, Hi: 0x1c23, Stride: 1}, + {Lo: 0x1c4d, Hi: 0x1c4f, Stride: 1}, + {Lo: 0x1c5a, Hi: 0x1c77, Stride: 1}, + {Lo: 0x1ce9, Hi: 0x1cec, Stride: 1}, + {Lo: 0x1cee, Hi: 0x1cf3, Stride: 1}, + {Lo: 0x1cf5, Hi: 0x1cf6, Stride: 1}, + {Lo: 0x1cfa, Hi: 0x2135, Stride: 1083}, + {Lo: 0x2136, Hi: 0x2138, Stride: 1}, + {Lo: 0x2d30, Hi: 0x2d67, Stride: 1}, + {Lo: 0x2d80, Hi: 0x2d96, Stride: 1}, + {Lo: 0x2da0, Hi: 0x2da6, Stride: 1}, + {Lo: 0x2da8, Hi: 0x2dae, Stride: 1}, + {Lo: 0x2db0, Hi: 0x2db6, Stride: 1}, + {Lo: 0x2db8, Hi: 0x2dbe, Stride: 1}, + {Lo: 0x2dc0, Hi: 0x2dc6, Stride: 1}, + {Lo: 0x2dc8, Hi: 0x2dce, Stride: 1}, + {Lo: 0x2dd0, Hi: 0x2dd6, Stride: 1}, + {Lo: 0x2dd8, Hi: 0x2dde, Stride: 1}, + {Lo: 0x3006, Hi: 0x303c, Stride: 54}, + {Lo: 0x3041, Hi: 0x3096, Stride: 1}, + {Lo: 0x309f, Hi: 0x30a1, Stride: 2}, + {Lo: 0x30a2, Hi: 0x30fa, Stride: 1}, + {Lo: 0x30ff, Hi: 0x3105, Stride: 6}, + {Lo: 0x3106, Hi: 0x312f, Stride: 1}, + {Lo: 0x3131, Hi: 0x318e, Stride: 1}, + {Lo: 0x31a0, Hi: 0x31bf, Stride: 1}, + {Lo: 0x31f0, Hi: 0x31ff, Stride: 1}, + {Lo: 0x3400, Hi: 0x4dbf, Stride: 6591}, + {Lo: 0x4e00, Hi: 0x9fff, Stride: 20991}, + {Lo: 0xa000, Hi: 0xa014, Stride: 1}, + {Lo: 0xa016, Hi: 0xa48c, Stride: 1}, + {Lo: 0xa4d0, Hi: 0xa4f7, Stride: 1}, + {Lo: 0xa500, Hi: 0xa60b, Stride: 1}, + {Lo: 0xa610, Hi: 0xa61f, Stride: 1}, + {Lo: 0xa62a, Hi: 0xa62b, Stride: 1}, + {Lo: 0xa66e, Hi: 0xa6a0, Stride: 50}, + {Lo: 0xa6a1, Hi: 0xa6e5, Stride: 1}, + {Lo: 0xa78f, Hi: 0xa7f7, Stride: 104}, + {Lo: 0xa7fb, Hi: 0xa801, Stride: 1}, + {Lo: 0xa803, Hi: 0xa805, Stride: 1}, + {Lo: 0xa807, Hi: 0xa80a, Stride: 1}, + {Lo: 0xa80c, Hi: 0xa822, Stride: 1}, + {Lo: 0xa840, Hi: 0xa873, Stride: 1}, + {Lo: 0xa882, Hi: 0xa8b3, Stride: 1}, + {Lo: 0xa8f2, Hi: 0xa8f7, Stride: 1}, + {Lo: 0xa8fb, Hi: 0xa8fd, Stride: 2}, + {Lo: 0xa8fe, Hi: 0xa90a, Stride: 12}, + {Lo: 0xa90b, Hi: 0xa925, Stride: 1}, + {Lo: 0xa930, Hi: 0xa946, Stride: 1}, + {Lo: 0xa960, Hi: 0xa97c, Stride: 1}, + {Lo: 0xa984, Hi: 0xa9b2, Stride: 1}, + {Lo: 0xa9e0, Hi: 0xa9e4, Stride: 1}, + {Lo: 0xa9e7, Hi: 0xa9ef, Stride: 1}, + {Lo: 0xa9fa, Hi: 0xa9fe, Stride: 1}, + {Lo: 0xaa00, Hi: 0xaa28, Stride: 1}, + {Lo: 0xaa40, Hi: 0xaa42, Stride: 1}, + {Lo: 0xaa44, Hi: 0xaa4b, Stride: 1}, + {Lo: 0xaa60, Hi: 0xaa6f, Stride: 1}, + {Lo: 0xaa71, Hi: 0xaa76, Stride: 1}, + {Lo: 0xaa7a, Hi: 0xaa7e, Stride: 4}, + {Lo: 0xaa7f, Hi: 0xaaaf, Stride: 1}, + {Lo: 0xaab1, Hi: 0xaab5, Stride: 4}, + {Lo: 0xaab6, Hi: 0xaab9, Stride: 3}, + {Lo: 0xaaba, Hi: 0xaabd, Stride: 1}, + {Lo: 0xaac0, Hi: 0xaac2, Stride: 2}, + {Lo: 0xaadb, Hi: 0xaadc, Stride: 1}, + {Lo: 0xaae0, Hi: 0xaaea, Stride: 1}, + {Lo: 0xaaf2, Hi: 0xab01, Stride: 15}, + {Lo: 0xab02, Hi: 0xab06, Stride: 1}, + {Lo: 0xab09, Hi: 0xab0e, Stride: 1}, + {Lo: 0xab11, Hi: 0xab16, Stride: 1}, + {Lo: 0xab20, Hi: 0xab26, Stride: 1}, + {Lo: 0xab28, Hi: 0xab2e, Stride: 1}, + {Lo: 0xabc0, Hi: 0xabe2, Stride: 1}, + {Lo: 0xac00, Hi: 0xd7a3, Stride: 11171}, + {Lo: 0xd7b0, Hi: 0xd7c6, Stride: 1}, + {Lo: 0xd7cb, Hi: 0xd7fb, Stride: 1}, + {Lo: 0xf900, Hi: 0xfa6d, Stride: 1}, + {Lo: 0xfa70, Hi: 0xfad9, Stride: 1}, + {Lo: 0xfb1d, Hi: 0xfb1f, Stride: 2}, + {Lo: 0xfb20, Hi: 0xfb28, Stride: 1}, + {Lo: 0xfb2a, Hi: 0xfb36, Stride: 1}, + {Lo: 0xfb38, Hi: 0xfb3c, Stride: 1}, + {Lo: 0xfb3e, Hi: 0xfb40, Stride: 2}, + {Lo: 0xfb41, Hi: 0xfb43, Stride: 2}, + {Lo: 0xfb44, Hi: 0xfb46, Stride: 2}, + {Lo: 0xfb47, Hi: 0xfbb1, Stride: 1}, + {Lo: 0xfbd3, Hi: 0xfd3d, Stride: 1}, + {Lo: 0xfd50, Hi: 0xfd8f, Stride: 1}, + {Lo: 0xfd92, Hi: 0xfdc7, Stride: 1}, + {Lo: 0xfdf0, Hi: 0xfdfb, Stride: 1}, + {Lo: 0xfe70, Hi: 0xfe74, Stride: 1}, + {Lo: 0xfe76, Hi: 0xfefc, Stride: 1}, + {Lo: 0xff66, Hi: 0xff6f, Stride: 1}, + {Lo: 0xff71, Hi: 0xff9d, Stride: 1}, + {Lo: 0xffa0, Hi: 0xffbe, Stride: 1}, + {Lo: 0xffc2, Hi: 0xffc7, Stride: 1}, + {Lo: 0xffca, Hi: 0xffcf, Stride: 1}, + {Lo: 0xffd2, Hi: 0xffd7, Stride: 1}, + {Lo: 0xffda, Hi: 0xffdc, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x10000, Hi: 0x1000b, Stride: 1}, + {Lo: 0x1000d, Hi: 0x10026, Stride: 1}, + {Lo: 0x10028, Hi: 0x1003a, Stride: 1}, + {Lo: 0x1003c, Hi: 0x1003d, Stride: 1}, + {Lo: 0x1003f, Hi: 0x1004d, Stride: 1}, + {Lo: 0x10050, Hi: 0x1005d, Stride: 1}, + {Lo: 0x10080, Hi: 0x100fa, Stride: 1}, + {Lo: 0x10280, Hi: 0x1029c, Stride: 1}, + {Lo: 0x102a0, Hi: 0x102d0, Stride: 1}, + {Lo: 0x10300, Hi: 0x1031f, Stride: 1}, + {Lo: 0x1032d, Hi: 0x10340, Stride: 1}, + {Lo: 0x10342, Hi: 0x10349, Stride: 1}, + {Lo: 0x10350, Hi: 0x10375, Stride: 1}, + {Lo: 0x10380, Hi: 0x1039d, Stride: 1}, + {Lo: 0x103a0, Hi: 0x103c3, Stride: 1}, + {Lo: 0x103c8, Hi: 0x103cf, Stride: 1}, + {Lo: 0x10450, Hi: 0x1049d, Stride: 1}, + {Lo: 0x10500, Hi: 0x10527, Stride: 1}, + {Lo: 0x10530, Hi: 0x10563, Stride: 1}, + {Lo: 0x10600, Hi: 0x10736, Stride: 1}, + {Lo: 0x10740, Hi: 0x10755, Stride: 1}, + {Lo: 0x10760, Hi: 0x10767, Stride: 1}, + {Lo: 0x10800, Hi: 0x10805, Stride: 1}, + {Lo: 0x10808, Hi: 0x1080a, Stride: 2}, + {Lo: 0x1080b, Hi: 0x10835, Stride: 1}, + {Lo: 0x10837, Hi: 0x10838, Stride: 1}, + {Lo: 0x1083c, Hi: 0x1083f, Stride: 3}, + {Lo: 0x10840, Hi: 0x10855, Stride: 1}, + {Lo: 0x10860, Hi: 0x10876, Stride: 1}, + {Lo: 0x10880, Hi: 0x1089e, Stride: 1}, + {Lo: 0x108e0, Hi: 0x108f2, Stride: 1}, + {Lo: 0x108f4, Hi: 0x108f5, Stride: 1}, + {Lo: 0x10900, Hi: 0x10915, Stride: 1}, + {Lo: 0x10920, Hi: 0x10939, Stride: 1}, + {Lo: 0x10980, Hi: 0x109b7, Stride: 1}, + {Lo: 0x109be, Hi: 0x109bf, Stride: 1}, + {Lo: 0x10a00, Hi: 0x10a10, Stride: 16}, + {Lo: 0x10a11, Hi: 0x10a13, Stride: 1}, + {Lo: 0x10a15, Hi: 0x10a17, Stride: 1}, + {Lo: 0x10a19, Hi: 0x10a35, Stride: 1}, + {Lo: 0x10a60, Hi: 0x10a7c, Stride: 1}, + {Lo: 0x10a80, Hi: 0x10a9c, Stride: 1}, + {Lo: 0x10ac0, Hi: 0x10ac7, Stride: 1}, + {Lo: 0x10ac9, Hi: 0x10ae4, Stride: 1}, + {Lo: 0x10b00, Hi: 0x10b35, Stride: 1}, + {Lo: 0x10b40, Hi: 0x10b55, Stride: 1}, + {Lo: 0x10b60, Hi: 0x10b72, Stride: 1}, + {Lo: 0x10b80, Hi: 0x10b91, Stride: 1}, + {Lo: 0x10c00, Hi: 0x10c48, Stride: 1}, + {Lo: 0x10d00, Hi: 0x10d23, Stride: 1}, + {Lo: 0x10e80, Hi: 0x10ea9, Stride: 1}, + {Lo: 0x10eb0, Hi: 0x10eb1, Stride: 1}, + {Lo: 0x10f00, Hi: 0x10f1c, Stride: 1}, + {Lo: 0x10f27, Hi: 0x10f30, Stride: 9}, + {Lo: 0x10f31, Hi: 0x10f45, Stride: 1}, + {Lo: 0x10f70, Hi: 0x10f81, Stride: 1}, + {Lo: 0x10fb0, Hi: 0x10fc4, Stride: 1}, + {Lo: 0x10fe0, Hi: 0x10ff6, Stride: 1}, + {Lo: 0x11003, Hi: 0x11037, Stride: 1}, + {Lo: 0x11071, Hi: 0x11072, Stride: 1}, + {Lo: 0x11075, Hi: 0x11083, Stride: 14}, + {Lo: 0x11084, Hi: 0x110af, Stride: 1}, + {Lo: 0x110d0, Hi: 0x110e8, Stride: 1}, + {Lo: 0x11103, Hi: 0x11126, Stride: 1}, + {Lo: 0x11144, Hi: 0x11147, Stride: 3}, + {Lo: 0x11150, Hi: 0x11172, Stride: 1}, + {Lo: 0x11176, Hi: 0x11183, Stride: 13}, + {Lo: 0x11184, Hi: 0x111b2, Stride: 1}, + {Lo: 0x111c1, Hi: 0x111c4, Stride: 1}, + {Lo: 0x111da, Hi: 0x111dc, Stride: 2}, + {Lo: 0x11200, Hi: 0x11211, Stride: 1}, + {Lo: 0x11213, Hi: 0x1122b, Stride: 1}, + {Lo: 0x1123f, Hi: 0x11240, Stride: 1}, + {Lo: 0x11280, Hi: 0x11286, Stride: 1}, + {Lo: 0x11288, Hi: 0x1128a, Stride: 2}, + {Lo: 0x1128b, Hi: 0x1128d, Stride: 1}, + {Lo: 0x1128f, Hi: 0x1129d, Stride: 1}, + {Lo: 0x1129f, Hi: 0x112a8, Stride: 1}, + {Lo: 0x112b0, Hi: 0x112de, Stride: 1}, + {Lo: 0x11305, Hi: 0x1130c, Stride: 1}, + {Lo: 0x1130f, Hi: 0x11310, Stride: 1}, + {Lo: 0x11313, Hi: 0x11328, Stride: 1}, + {Lo: 0x1132a, Hi: 0x11330, Stride: 1}, + {Lo: 0x11332, Hi: 0x11333, Stride: 1}, + {Lo: 0x11335, Hi: 0x11339, Stride: 1}, + {Lo: 0x1133d, Hi: 0x11350, Stride: 19}, + {Lo: 0x1135d, Hi: 0x11361, Stride: 1}, + {Lo: 0x11400, Hi: 0x11434, Stride: 1}, + {Lo: 0x11447, Hi: 0x1144a, Stride: 1}, + {Lo: 0x1145f, Hi: 0x11461, Stride: 1}, + {Lo: 0x11480, Hi: 0x114af, Stride: 1}, + {Lo: 0x114c4, Hi: 0x114c5, Stride: 1}, + {Lo: 0x114c7, Hi: 0x11580, Stride: 185}, + {Lo: 0x11581, Hi: 0x115ae, Stride: 1}, + {Lo: 0x115d8, Hi: 0x115db, Stride: 1}, + {Lo: 0x11600, Hi: 0x1162f, Stride: 1}, + {Lo: 0x11644, Hi: 0x11680, Stride: 60}, + {Lo: 0x11681, Hi: 0x116aa, Stride: 1}, + {Lo: 0x116b8, Hi: 0x11700, Stride: 72}, + {Lo: 0x11701, Hi: 0x1171a, Stride: 1}, + {Lo: 0x11740, Hi: 0x11746, Stride: 1}, + {Lo: 0x11800, Hi: 0x1182b, Stride: 1}, + {Lo: 0x118ff, Hi: 0x11906, Stride: 1}, + {Lo: 0x11909, Hi: 0x1190c, Stride: 3}, + {Lo: 0x1190d, Hi: 0x11913, Stride: 1}, + {Lo: 0x11915, Hi: 0x11916, Stride: 1}, + {Lo: 0x11918, Hi: 0x1192f, Stride: 1}, + {Lo: 0x1193f, Hi: 0x11941, Stride: 2}, + {Lo: 0x119a0, Hi: 0x119a7, Stride: 1}, + {Lo: 0x119aa, Hi: 0x119d0, Stride: 1}, + {Lo: 0x119e1, Hi: 0x119e3, Stride: 2}, + {Lo: 0x11a00, Hi: 0x11a0b, Stride: 11}, + {Lo: 0x11a0c, Hi: 0x11a32, Stride: 1}, + {Lo: 0x11a3a, Hi: 0x11a50, Stride: 22}, + {Lo: 0x11a5c, Hi: 0x11a89, Stride: 1}, + {Lo: 0x11a9d, Hi: 0x11ab0, Stride: 19}, + {Lo: 0x11ab1, Hi: 0x11af8, Stride: 1}, + {Lo: 0x11c00, Hi: 0x11c08, Stride: 1}, + {Lo: 0x11c0a, Hi: 0x11c2e, Stride: 1}, + {Lo: 0x11c40, Hi: 0x11c72, Stride: 50}, + {Lo: 0x11c73, Hi: 0x11c8f, Stride: 1}, + {Lo: 0x11d00, Hi: 0x11d06, Stride: 1}, + {Lo: 0x11d08, Hi: 0x11d09, Stride: 1}, + {Lo: 0x11d0b, Hi: 0x11d30, Stride: 1}, + {Lo: 0x11d46, Hi: 0x11d60, Stride: 26}, + {Lo: 0x11d61, Hi: 0x11d65, Stride: 1}, + {Lo: 0x11d67, Hi: 0x11d68, Stride: 1}, + {Lo: 0x11d6a, Hi: 0x11d89, Stride: 1}, + {Lo: 0x11d98, Hi: 0x11ee0, Stride: 328}, + {Lo: 0x11ee1, Hi: 0x11ef2, Stride: 1}, + {Lo: 0x11f02, Hi: 0x11f04, Stride: 2}, + {Lo: 0x11f05, Hi: 0x11f10, Stride: 1}, + {Lo: 0x11f12, Hi: 0x11f33, Stride: 1}, + {Lo: 0x11fb0, Hi: 0x12000, Stride: 80}, + {Lo: 0x12001, Hi: 0x12399, Stride: 1}, + {Lo: 0x12480, Hi: 0x12543, Stride: 1}, + {Lo: 0x12f90, Hi: 0x12ff0, Stride: 1}, + {Lo: 0x13000, Hi: 0x1342f, Stride: 1}, + {Lo: 0x13441, Hi: 0x13446, Stride: 1}, + {Lo: 0x14400, Hi: 0x14646, Stride: 1}, + {Lo: 0x16800, Hi: 0x16a38, Stride: 1}, + {Lo: 0x16a40, Hi: 0x16a5e, Stride: 1}, + {Lo: 0x16a70, Hi: 0x16abe, Stride: 1}, + {Lo: 0x16ad0, Hi: 0x16aed, Stride: 1}, + {Lo: 0x16b00, Hi: 0x16b2f, Stride: 1}, + {Lo: 0x16b63, Hi: 0x16b77, Stride: 1}, + {Lo: 0x16b7d, Hi: 0x16b8f, Stride: 1}, + {Lo: 0x16f00, Hi: 0x16f4a, Stride: 1}, + {Lo: 0x16f50, Hi: 0x17000, Stride: 176}, + {Lo: 0x187f7, Hi: 0x18800, Stride: 9}, + {Lo: 0x18801, Hi: 0x18cd5, Stride: 1}, + {Lo: 0x18d00, Hi: 0x18d08, Stride: 8}, + {Lo: 0x1b000, Hi: 0x1b122, Stride: 1}, + {Lo: 0x1b132, Hi: 0x1b150, Stride: 30}, + {Lo: 0x1b151, Hi: 0x1b152, Stride: 1}, + {Lo: 0x1b155, Hi: 0x1b164, Stride: 15}, + {Lo: 0x1b165, Hi: 0x1b167, Stride: 1}, + {Lo: 0x1b170, Hi: 0x1b2fb, Stride: 1}, + {Lo: 0x1bc00, Hi: 0x1bc6a, Stride: 1}, + {Lo: 0x1bc70, Hi: 0x1bc7c, Stride: 1}, + {Lo: 0x1bc80, Hi: 0x1bc88, Stride: 1}, + {Lo: 0x1bc90, Hi: 0x1bc99, Stride: 1}, + {Lo: 0x1df0a, Hi: 0x1e100, Stride: 502}, + {Lo: 0x1e101, Hi: 0x1e12c, Stride: 1}, + {Lo: 0x1e14e, Hi: 0x1e290, Stride: 322}, + {Lo: 0x1e291, Hi: 0x1e2ad, Stride: 1}, + {Lo: 0x1e2c0, Hi: 0x1e2eb, Stride: 1}, + {Lo: 0x1e4d0, Hi: 0x1e4ea, Stride: 1}, + {Lo: 0x1e7e0, Hi: 0x1e7e6, Stride: 1}, + {Lo: 0x1e7e8, Hi: 0x1e7eb, Stride: 1}, + {Lo: 0x1e7ed, Hi: 0x1e7ee, Stride: 1}, + {Lo: 0x1e7f0, Hi: 0x1e7fe, Stride: 1}, + {Lo: 0x1e800, Hi: 0x1e8c4, Stride: 1}, + {Lo: 0x1ee00, Hi: 0x1ee03, Stride: 1}, + {Lo: 0x1ee05, Hi: 0x1ee1f, Stride: 1}, + {Lo: 0x1ee21, Hi: 0x1ee22, Stride: 1}, + {Lo: 0x1ee24, Hi: 0x1ee27, Stride: 3}, + {Lo: 0x1ee29, Hi: 0x1ee32, Stride: 1}, + {Lo: 0x1ee34, Hi: 0x1ee37, Stride: 1}, + {Lo: 0x1ee39, Hi: 0x1ee3b, Stride: 2}, + {Lo: 0x1ee42, Hi: 0x1ee47, Stride: 5}, + {Lo: 0x1ee49, Hi: 0x1ee4d, Stride: 2}, + {Lo: 0x1ee4e, Hi: 0x1ee4f, Stride: 1}, + {Lo: 0x1ee51, Hi: 0x1ee52, Stride: 1}, + {Lo: 0x1ee54, Hi: 0x1ee57, Stride: 3}, + {Lo: 0x1ee59, Hi: 0x1ee61, Stride: 2}, + {Lo: 0x1ee62, Hi: 0x1ee64, Stride: 2}, + {Lo: 0x1ee67, Hi: 0x1ee6a, Stride: 1}, + {Lo: 0x1ee6c, Hi: 0x1ee72, Stride: 1}, + {Lo: 0x1ee74, Hi: 0x1ee77, Stride: 1}, + {Lo: 0x1ee79, Hi: 0x1ee7c, Stride: 1}, + {Lo: 0x1ee7e, Hi: 0x1ee80, Stride: 2}, + {Lo: 0x1ee81, Hi: 0x1ee89, Stride: 1}, + {Lo: 0x1ee8b, Hi: 0x1ee9b, Stride: 1}, + {Lo: 0x1eea1, Hi: 0x1eea3, Stride: 1}, + {Lo: 0x1eea5, Hi: 0x1eea9, Stride: 1}, + {Lo: 0x1eeab, Hi: 0x1eebb, Stride: 1}, + {Lo: 0x20000, Hi: 0x2a6df, Stride: 42719}, + {Lo: 0x2a700, Hi: 0x2b739, Stride: 4153}, + {Lo: 0x2b740, Hi: 0x2b81d, Stride: 221}, + {Lo: 0x2b820, Hi: 0x2cea1, Stride: 5761}, + {Lo: 0x2ceb0, Hi: 0x2ebe0, Stride: 7472}, + {Lo: 0x2ebf0, Hi: 0x2ee5d, Stride: 621}, + {Lo: 0x2f800, Hi: 0x2fa1d, Stride: 1}, + {Lo: 0x30000, Hi: 0x3134a, Stride: 4938}, + {Lo: 0x31350, Hi: 0x323af, Stride: 4191}, + }, + LatinOffset: 1, +} + +var Lt = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x01c5, Hi: 0x01cb, Stride: 3}, + {Lo: 0x01f2, Hi: 0x1f88, Stride: 7574}, + {Lo: 0x1f89, Hi: 0x1f8f, Stride: 1}, + {Lo: 0x1f98, Hi: 0x1f9f, Stride: 1}, + {Lo: 0x1fa8, Hi: 0x1faf, Stride: 1}, + {Lo: 0x1fbc, Hi: 0x1fcc, Stride: 16}, + {Lo: 0x1ffc, Hi: 0x1ffc, Stride: 1}, + }, +} + +var Lu = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0041, Hi: 0x005a, Stride: 1}, + {Lo: 0x00c0, Hi: 0x00d6, Stride: 1}, + {Lo: 0x00d8, Hi: 0x00de, Stride: 1}, + {Lo: 0x0100, Hi: 0x0136, Stride: 2}, + {Lo: 0x0139, Hi: 0x0147, Stride: 2}, + {Lo: 0x014a, Hi: 0x0178, Stride: 2}, + {Lo: 0x0179, Hi: 0x017d, Stride: 2}, + {Lo: 0x0181, Hi: 0x0182, Stride: 1}, + {Lo: 0x0184, Hi: 0x0186, Stride: 2}, + {Lo: 0x0187, Hi: 0x0189, Stride: 2}, + {Lo: 0x018a, Hi: 0x018b, Stride: 1}, + {Lo: 0x018e, Hi: 0x0191, Stride: 1}, + {Lo: 0x0193, Hi: 0x0194, Stride: 1}, + {Lo: 0x0196, Hi: 0x0198, Stride: 1}, + {Lo: 0x019c, Hi: 0x019d, Stride: 1}, + {Lo: 0x019f, Hi: 0x01a0, Stride: 1}, + {Lo: 0x01a2, Hi: 0x01a6, Stride: 2}, + {Lo: 0x01a7, Hi: 0x01a9, Stride: 2}, + {Lo: 0x01ac, Hi: 0x01ae, Stride: 2}, + {Lo: 0x01af, Hi: 0x01b1, Stride: 2}, + {Lo: 0x01b2, Hi: 0x01b3, Stride: 1}, + {Lo: 0x01b5, Hi: 0x01b7, Stride: 2}, + {Lo: 0x01b8, Hi: 0x01bc, Stride: 4}, + {Lo: 0x01c4, Hi: 0x01cd, Stride: 3}, + {Lo: 0x01cf, Hi: 0x01db, Stride: 2}, + {Lo: 0x01de, Hi: 0x01ee, Stride: 2}, + {Lo: 0x01f1, Hi: 0x01f4, Stride: 3}, + {Lo: 0x01f6, Hi: 0x01f8, Stride: 1}, + {Lo: 0x01fa, Hi: 0x0232, Stride: 2}, + {Lo: 0x023a, Hi: 0x023b, Stride: 1}, + {Lo: 0x023d, Hi: 0x023e, Stride: 1}, + {Lo: 0x0241, Hi: 0x0243, Stride: 2}, + {Lo: 0x0244, Hi: 0x0246, Stride: 1}, + {Lo: 0x0248, Hi: 0x024e, Stride: 2}, + {Lo: 0x0370, Hi: 0x0372, Stride: 2}, + {Lo: 0x0376, Hi: 0x037f, Stride: 9}, + {Lo: 0x0386, Hi: 0x0388, Stride: 2}, + {Lo: 0x0389, Hi: 0x038a, Stride: 1}, + {Lo: 0x038c, Hi: 0x038e, Stride: 2}, + {Lo: 0x038f, Hi: 0x0391, Stride: 2}, + {Lo: 0x0392, Hi: 0x03a1, Stride: 1}, + {Lo: 0x03a3, Hi: 0x03ab, Stride: 1}, + {Lo: 0x03cf, Hi: 0x03d2, Stride: 3}, + {Lo: 0x03d3, Hi: 0x03d4, Stride: 1}, + {Lo: 0x03d8, Hi: 0x03ee, Stride: 2}, + {Lo: 0x03f4, Hi: 0x03f7, Stride: 3}, + {Lo: 0x03f9, Hi: 0x03fa, Stride: 1}, + {Lo: 0x03fd, Hi: 0x042f, Stride: 1}, + {Lo: 0x0460, Hi: 0x0480, Stride: 2}, + {Lo: 0x048a, Hi: 0x04c0, Stride: 2}, + {Lo: 0x04c1, Hi: 0x04cd, Stride: 2}, + {Lo: 0x04d0, Hi: 0x052e, Stride: 2}, + {Lo: 0x0531, Hi: 0x0556, Stride: 1}, + {Lo: 0x10a0, Hi: 0x10c5, Stride: 1}, + {Lo: 0x10c7, Hi: 0x10cd, Stride: 6}, + {Lo: 0x13a0, Hi: 0x13f5, Stride: 1}, + {Lo: 0x1c90, Hi: 0x1cba, Stride: 1}, + {Lo: 0x1cbd, Hi: 0x1cbf, Stride: 1}, + {Lo: 0x1e00, Hi: 0x1e94, Stride: 2}, + {Lo: 0x1e9e, Hi: 0x1efe, Stride: 2}, + {Lo: 0x1f08, Hi: 0x1f0f, Stride: 1}, + {Lo: 0x1f18, Hi: 0x1f1d, Stride: 1}, + {Lo: 0x1f28, Hi: 0x1f2f, Stride: 1}, + {Lo: 0x1f38, Hi: 0x1f3f, Stride: 1}, + {Lo: 0x1f48, Hi: 0x1f4d, Stride: 1}, + {Lo: 0x1f59, Hi: 0x1f5f, Stride: 2}, + {Lo: 0x1f68, Hi: 0x1f6f, Stride: 1}, + {Lo: 0x1fb8, Hi: 0x1fbb, Stride: 1}, + {Lo: 0x1fc8, Hi: 0x1fcb, Stride: 1}, + {Lo: 0x1fd8, Hi: 0x1fdb, Stride: 1}, + {Lo: 0x1fe8, Hi: 0x1fec, Stride: 1}, + {Lo: 0x1ff8, Hi: 0x1ffb, Stride: 1}, + {Lo: 0x2102, Hi: 0x2107, Stride: 5}, + {Lo: 0x210b, Hi: 0x210d, Stride: 1}, + {Lo: 0x2110, Hi: 0x2112, Stride: 1}, + {Lo: 0x2115, Hi: 0x2119, Stride: 4}, + {Lo: 0x211a, Hi: 0x211d, Stride: 1}, + {Lo: 0x2124, Hi: 0x212a, Stride: 2}, + {Lo: 0x212b, Hi: 0x212d, Stride: 1}, + {Lo: 0x2130, Hi: 0x2133, Stride: 1}, + {Lo: 0x213e, Hi: 0x213f, Stride: 1}, + {Lo: 0x2145, Hi: 0x2183, Stride: 62}, + {Lo: 0x2c00, Hi: 0x2c2f, Stride: 1}, + {Lo: 0x2c60, Hi: 0x2c62, Stride: 2}, + {Lo: 0x2c63, Hi: 0x2c64, Stride: 1}, + {Lo: 0x2c67, Hi: 0x2c6d, Stride: 2}, + {Lo: 0x2c6e, Hi: 0x2c70, Stride: 1}, + {Lo: 0x2c72, Hi: 0x2c75, Stride: 3}, + {Lo: 0x2c7e, Hi: 0x2c80, Stride: 1}, + {Lo: 0x2c82, Hi: 0x2ce2, Stride: 2}, + {Lo: 0x2ceb, Hi: 0x2ced, Stride: 2}, + {Lo: 0x2cf2, Hi: 0xa640, Stride: 31054}, + {Lo: 0xa642, Hi: 0xa66c, Stride: 2}, + {Lo: 0xa680, Hi: 0xa69a, Stride: 2}, + {Lo: 0xa722, Hi: 0xa72e, Stride: 2}, + {Lo: 0xa732, Hi: 0xa76e, Stride: 2}, + {Lo: 0xa779, Hi: 0xa77d, Stride: 2}, + {Lo: 0xa77e, Hi: 0xa786, Stride: 2}, + {Lo: 0xa78b, Hi: 0xa78d, Stride: 2}, + {Lo: 0xa790, Hi: 0xa792, Stride: 2}, + {Lo: 0xa796, Hi: 0xa7aa, Stride: 2}, + {Lo: 0xa7ab, Hi: 0xa7ae, Stride: 1}, + {Lo: 0xa7b0, Hi: 0xa7b4, Stride: 1}, + {Lo: 0xa7b6, Hi: 0xa7c4, Stride: 2}, + {Lo: 0xa7c5, Hi: 0xa7c7, Stride: 1}, + {Lo: 0xa7c9, Hi: 0xa7d0, Stride: 7}, + {Lo: 0xa7d6, Hi: 0xa7d8, Stride: 2}, + {Lo: 0xa7f5, Hi: 0xff21, Stride: 22316}, + {Lo: 0xff22, Hi: 0xff3a, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x10400, Hi: 0x10427, Stride: 1}, + {Lo: 0x104b0, Hi: 0x104d3, Stride: 1}, + {Lo: 0x10570, Hi: 0x1057a, Stride: 1}, + {Lo: 0x1057c, Hi: 0x1058a, Stride: 1}, + {Lo: 0x1058c, Hi: 0x10592, Stride: 1}, + {Lo: 0x10594, Hi: 0x10595, Stride: 1}, + {Lo: 0x10c80, Hi: 0x10cb2, Stride: 1}, + {Lo: 0x118a0, Hi: 0x118bf, Stride: 1}, + {Lo: 0x16e40, Hi: 0x16e5f, Stride: 1}, + {Lo: 0x1d400, Hi: 0x1d419, Stride: 1}, + {Lo: 0x1d434, Hi: 0x1d44d, Stride: 1}, + {Lo: 0x1d468, Hi: 0x1d481, Stride: 1}, + {Lo: 0x1d49c, Hi: 0x1d49e, Stride: 2}, + {Lo: 0x1d49f, Hi: 0x1d4a5, Stride: 3}, + {Lo: 0x1d4a6, Hi: 0x1d4a9, Stride: 3}, + {Lo: 0x1d4aa, Hi: 0x1d4ac, Stride: 1}, + {Lo: 0x1d4ae, Hi: 0x1d4b5, Stride: 1}, + {Lo: 0x1d4d0, Hi: 0x1d4e9, Stride: 1}, + {Lo: 0x1d504, Hi: 0x1d505, Stride: 1}, + {Lo: 0x1d507, Hi: 0x1d50a, Stride: 1}, + {Lo: 0x1d50d, Hi: 0x1d514, Stride: 1}, + {Lo: 0x1d516, Hi: 0x1d51c, Stride: 1}, + {Lo: 0x1d538, Hi: 0x1d539, Stride: 1}, + {Lo: 0x1d53b, Hi: 0x1d53e, Stride: 1}, + {Lo: 0x1d540, Hi: 0x1d544, Stride: 1}, + {Lo: 0x1d546, Hi: 0x1d54a, Stride: 4}, + {Lo: 0x1d54b, Hi: 0x1d550, Stride: 1}, + {Lo: 0x1d56c, Hi: 0x1d585, Stride: 1}, + {Lo: 0x1d5a0, Hi: 0x1d5b9, Stride: 1}, + {Lo: 0x1d5d4, Hi: 0x1d5ed, Stride: 1}, + {Lo: 0x1d608, Hi: 0x1d621, Stride: 1}, + {Lo: 0x1d63c, Hi: 0x1d655, Stride: 1}, + {Lo: 0x1d670, Hi: 0x1d689, Stride: 1}, + {Lo: 0x1d6a8, Hi: 0x1d6c0, Stride: 1}, + {Lo: 0x1d6e2, Hi: 0x1d6fa, Stride: 1}, + {Lo: 0x1d71c, Hi: 0x1d734, Stride: 1}, + {Lo: 0x1d756, Hi: 0x1d76e, Stride: 1}, + {Lo: 0x1d790, Hi: 0x1d7a8, Stride: 1}, + {Lo: 0x1d7ca, Hi: 0x1e900, Stride: 4406}, + {Lo: 0x1e901, Hi: 0x1e921, Stride: 1}, + }, + LatinOffset: 3, +} + +var Mc = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0903, Hi: 0x093b, Stride: 56}, + {Lo: 0x093e, Hi: 0x0940, Stride: 1}, + {Lo: 0x0949, Hi: 0x094c, Stride: 1}, + {Lo: 0x094e, Hi: 0x094f, Stride: 1}, + {Lo: 0x0982, Hi: 0x0983, Stride: 1}, + {Lo: 0x09be, Hi: 0x09c0, Stride: 1}, + {Lo: 0x09c7, Hi: 0x09c8, Stride: 1}, + {Lo: 0x09cb, Hi: 0x09cc, Stride: 1}, + {Lo: 0x09d7, Hi: 0x0a03, Stride: 44}, + {Lo: 0x0a3e, Hi: 0x0a40, Stride: 1}, + {Lo: 0x0a83, Hi: 0x0abe, Stride: 59}, + {Lo: 0x0abf, Hi: 0x0ac0, Stride: 1}, + {Lo: 0x0ac9, Hi: 0x0acb, Stride: 2}, + {Lo: 0x0acc, Hi: 0x0b02, Stride: 54}, + {Lo: 0x0b03, Hi: 0x0b3e, Stride: 59}, + {Lo: 0x0b40, Hi: 0x0b47, Stride: 7}, + {Lo: 0x0b48, Hi: 0x0b4b, Stride: 3}, + {Lo: 0x0b4c, Hi: 0x0b57, Stride: 11}, + {Lo: 0x0bbe, Hi: 0x0bbf, Stride: 1}, + {Lo: 0x0bc1, Hi: 0x0bc2, Stride: 1}, + {Lo: 0x0bc6, Hi: 0x0bc8, Stride: 1}, + {Lo: 0x0bca, Hi: 0x0bcc, Stride: 1}, + {Lo: 0x0bd7, Hi: 0x0c01, Stride: 42}, + {Lo: 0x0c02, Hi: 0x0c03, Stride: 1}, + {Lo: 0x0c41, Hi: 0x0c44, Stride: 1}, + {Lo: 0x0c82, Hi: 0x0c83, Stride: 1}, + {Lo: 0x0cbe, Hi: 0x0cc0, Stride: 2}, + {Lo: 0x0cc1, Hi: 0x0cc4, Stride: 1}, + {Lo: 0x0cc7, Hi: 0x0cc8, Stride: 1}, + {Lo: 0x0cca, Hi: 0x0ccb, Stride: 1}, + {Lo: 0x0cd5, Hi: 0x0cd6, Stride: 1}, + {Lo: 0x0cf3, Hi: 0x0d02, Stride: 15}, + {Lo: 0x0d03, Hi: 0x0d3e, Stride: 59}, + {Lo: 0x0d3f, Hi: 0x0d40, Stride: 1}, + {Lo: 0x0d46, Hi: 0x0d48, Stride: 1}, + {Lo: 0x0d4a, Hi: 0x0d4c, Stride: 1}, + {Lo: 0x0d57, Hi: 0x0d82, Stride: 43}, + {Lo: 0x0d83, Hi: 0x0dcf, Stride: 76}, + {Lo: 0x0dd0, Hi: 0x0dd1, Stride: 1}, + {Lo: 0x0dd8, Hi: 0x0ddf, Stride: 1}, + {Lo: 0x0df2, Hi: 0x0df3, Stride: 1}, + {Lo: 0x0f3e, Hi: 0x0f3f, Stride: 1}, + {Lo: 0x0f7f, Hi: 0x102b, Stride: 172}, + {Lo: 0x102c, Hi: 0x1031, Stride: 5}, + {Lo: 0x1038, Hi: 0x103b, Stride: 3}, + {Lo: 0x103c, Hi: 0x1056, Stride: 26}, + {Lo: 0x1057, Hi: 0x1062, Stride: 11}, + {Lo: 0x1063, Hi: 0x1064, Stride: 1}, + {Lo: 0x1067, Hi: 0x106d, Stride: 1}, + {Lo: 0x1083, Hi: 0x1084, Stride: 1}, + {Lo: 0x1087, Hi: 0x108c, Stride: 1}, + {Lo: 0x108f, Hi: 0x109a, Stride: 11}, + {Lo: 0x109b, Hi: 0x109c, Stride: 1}, + {Lo: 0x1715, Hi: 0x1734, Stride: 31}, + {Lo: 0x17b6, Hi: 0x17be, Stride: 8}, + {Lo: 0x17bf, Hi: 0x17c5, Stride: 1}, + {Lo: 0x17c7, Hi: 0x17c8, Stride: 1}, + {Lo: 0x1923, Hi: 0x1926, Stride: 1}, + {Lo: 0x1929, Hi: 0x192b, Stride: 1}, + {Lo: 0x1930, Hi: 0x1931, Stride: 1}, + {Lo: 0x1933, Hi: 0x1938, Stride: 1}, + {Lo: 0x1a19, Hi: 0x1a1a, Stride: 1}, + {Lo: 0x1a55, Hi: 0x1a57, Stride: 2}, + {Lo: 0x1a61, Hi: 0x1a63, Stride: 2}, + {Lo: 0x1a64, Hi: 0x1a6d, Stride: 9}, + {Lo: 0x1a6e, Hi: 0x1a72, Stride: 1}, + {Lo: 0x1b04, Hi: 0x1b35, Stride: 49}, + {Lo: 0x1b3b, Hi: 0x1b3d, Stride: 2}, + {Lo: 0x1b3e, Hi: 0x1b41, Stride: 1}, + {Lo: 0x1b43, Hi: 0x1b44, Stride: 1}, + {Lo: 0x1b82, Hi: 0x1ba1, Stride: 31}, + {Lo: 0x1ba6, Hi: 0x1ba7, Stride: 1}, + {Lo: 0x1baa, Hi: 0x1be7, Stride: 61}, + {Lo: 0x1bea, Hi: 0x1bec, Stride: 1}, + {Lo: 0x1bee, Hi: 0x1bf2, Stride: 4}, + {Lo: 0x1bf3, Hi: 0x1c24, Stride: 49}, + {Lo: 0x1c25, Hi: 0x1c2b, Stride: 1}, + {Lo: 0x1c34, Hi: 0x1c35, Stride: 1}, + {Lo: 0x1ce1, Hi: 0x1cf7, Stride: 22}, + {Lo: 0x302e, Hi: 0x302f, Stride: 1}, + {Lo: 0xa823, Hi: 0xa824, Stride: 1}, + {Lo: 0xa827, Hi: 0xa880, Stride: 89}, + {Lo: 0xa881, Hi: 0xa8b4, Stride: 51}, + {Lo: 0xa8b5, Hi: 0xa8c3, Stride: 1}, + {Lo: 0xa952, Hi: 0xa953, Stride: 1}, + {Lo: 0xa983, Hi: 0xa9b4, Stride: 49}, + {Lo: 0xa9b5, Hi: 0xa9ba, Stride: 5}, + {Lo: 0xa9bb, Hi: 0xa9be, Stride: 3}, + {Lo: 0xa9bf, Hi: 0xa9c0, Stride: 1}, + {Lo: 0xaa2f, Hi: 0xaa30, Stride: 1}, + {Lo: 0xaa33, Hi: 0xaa34, Stride: 1}, + {Lo: 0xaa4d, Hi: 0xaa7b, Stride: 46}, + {Lo: 0xaa7d, Hi: 0xaaeb, Stride: 110}, + {Lo: 0xaaee, Hi: 0xaaef, Stride: 1}, + {Lo: 0xaaf5, Hi: 0xabe3, Stride: 238}, + {Lo: 0xabe4, Hi: 0xabe6, Stride: 2}, + {Lo: 0xabe7, Hi: 0xabe9, Stride: 2}, + {Lo: 0xabea, Hi: 0xabec, Stride: 2}, + }, + R32: []unicode.Range32{ + {Lo: 0x11000, Hi: 0x11002, Stride: 2}, + {Lo: 0x11082, Hi: 0x110b0, Stride: 46}, + {Lo: 0x110b1, Hi: 0x110b2, Stride: 1}, + {Lo: 0x110b7, Hi: 0x110b8, Stride: 1}, + {Lo: 0x1112c, Hi: 0x11145, Stride: 25}, + {Lo: 0x11146, Hi: 0x11182, Stride: 60}, + {Lo: 0x111b3, Hi: 0x111b5, Stride: 1}, + {Lo: 0x111bf, Hi: 0x111c0, Stride: 1}, + {Lo: 0x111ce, Hi: 0x1122c, Stride: 94}, + {Lo: 0x1122d, Hi: 0x1122e, Stride: 1}, + {Lo: 0x11232, Hi: 0x11233, Stride: 1}, + {Lo: 0x11235, Hi: 0x112e0, Stride: 171}, + {Lo: 0x112e1, Hi: 0x112e2, Stride: 1}, + {Lo: 0x11302, Hi: 0x11303, Stride: 1}, + {Lo: 0x1133e, Hi: 0x1133f, Stride: 1}, + {Lo: 0x11341, Hi: 0x11344, Stride: 1}, + {Lo: 0x11347, Hi: 0x11348, Stride: 1}, + {Lo: 0x1134b, Hi: 0x1134d, Stride: 1}, + {Lo: 0x11357, Hi: 0x11362, Stride: 11}, + {Lo: 0x11363, Hi: 0x11435, Stride: 210}, + {Lo: 0x11436, Hi: 0x11437, Stride: 1}, + {Lo: 0x11440, Hi: 0x11441, Stride: 1}, + {Lo: 0x11445, Hi: 0x114b0, Stride: 107}, + {Lo: 0x114b1, Hi: 0x114b2, Stride: 1}, + {Lo: 0x114b9, Hi: 0x114bb, Stride: 2}, + {Lo: 0x114bc, Hi: 0x114be, Stride: 1}, + {Lo: 0x114c1, Hi: 0x115af, Stride: 238}, + {Lo: 0x115b0, Hi: 0x115b1, Stride: 1}, + {Lo: 0x115b8, Hi: 0x115bb, Stride: 1}, + {Lo: 0x115be, Hi: 0x11630, Stride: 114}, + {Lo: 0x11631, Hi: 0x11632, Stride: 1}, + {Lo: 0x1163b, Hi: 0x1163c, Stride: 1}, + {Lo: 0x1163e, Hi: 0x116ac, Stride: 110}, + {Lo: 0x116ae, Hi: 0x116af, Stride: 1}, + {Lo: 0x116b6, Hi: 0x11720, Stride: 106}, + {Lo: 0x11721, Hi: 0x11726, Stride: 5}, + {Lo: 0x1182c, Hi: 0x1182e, Stride: 1}, + {Lo: 0x11838, Hi: 0x11930, Stride: 248}, + {Lo: 0x11931, Hi: 0x11935, Stride: 1}, + {Lo: 0x11937, Hi: 0x11938, Stride: 1}, + {Lo: 0x1193d, Hi: 0x11940, Stride: 3}, + {Lo: 0x11942, Hi: 0x119d1, Stride: 143}, + {Lo: 0x119d2, Hi: 0x119d3, Stride: 1}, + {Lo: 0x119dc, Hi: 0x119df, Stride: 1}, + {Lo: 0x119e4, Hi: 0x11a39, Stride: 85}, + {Lo: 0x11a57, Hi: 0x11a58, Stride: 1}, + {Lo: 0x11a97, Hi: 0x11c2f, Stride: 408}, + {Lo: 0x11c3e, Hi: 0x11ca9, Stride: 107}, + {Lo: 0x11cb1, Hi: 0x11cb4, Stride: 3}, + {Lo: 0x11d8a, Hi: 0x11d8e, Stride: 1}, + {Lo: 0x11d93, Hi: 0x11d94, Stride: 1}, + {Lo: 0x11d96, Hi: 0x11ef5, Stride: 351}, + {Lo: 0x11ef6, Hi: 0x11f03, Stride: 13}, + {Lo: 0x11f34, Hi: 0x11f35, Stride: 1}, + {Lo: 0x11f3e, Hi: 0x11f3f, Stride: 1}, + {Lo: 0x11f41, Hi: 0x16f51, Stride: 20496}, + {Lo: 0x16f52, Hi: 0x16f87, Stride: 1}, + {Lo: 0x16ff0, Hi: 0x16ff1, Stride: 1}, + {Lo: 0x1d165, Hi: 0x1d166, Stride: 1}, + {Lo: 0x1d16d, Hi: 0x1d172, Stride: 1}, + }, +} + +var Me = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0488, Hi: 0x0489, Stride: 1}, + {Lo: 0x1abe, Hi: 0x20dd, Stride: 1567}, + {Lo: 0x20de, Hi: 0x20e0, Stride: 1}, + {Lo: 0x20e2, Hi: 0x20e4, Stride: 1}, + {Lo: 0xa670, Hi: 0xa672, Stride: 1}, + }, +} + +var Mn = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0300, Hi: 0x036f, Stride: 1}, + {Lo: 0x0483, Hi: 0x0487, Stride: 1}, + {Lo: 0x0591, Hi: 0x05bd, Stride: 1}, + {Lo: 0x05bf, Hi: 0x05c1, Stride: 2}, + {Lo: 0x05c2, Hi: 0x05c4, Stride: 2}, + {Lo: 0x05c5, Hi: 0x05c7, Stride: 2}, + {Lo: 0x0610, Hi: 0x061a, Stride: 1}, + {Lo: 0x064b, Hi: 0x065f, Stride: 1}, + {Lo: 0x0670, Hi: 0x06d6, Stride: 102}, + {Lo: 0x06d7, Hi: 0x06dc, Stride: 1}, + {Lo: 0x06df, Hi: 0x06e4, Stride: 1}, + {Lo: 0x06e7, Hi: 0x06e8, Stride: 1}, + {Lo: 0x06ea, Hi: 0x06ed, Stride: 1}, + {Lo: 0x0711, Hi: 0x0730, Stride: 31}, + {Lo: 0x0731, Hi: 0x074a, Stride: 1}, + {Lo: 0x07a6, Hi: 0x07b0, Stride: 1}, + {Lo: 0x07eb, Hi: 0x07f3, Stride: 1}, + {Lo: 0x07fd, Hi: 0x0816, Stride: 25}, + {Lo: 0x0817, Hi: 0x0819, Stride: 1}, + {Lo: 0x081b, Hi: 0x0823, Stride: 1}, + {Lo: 0x0825, Hi: 0x0827, Stride: 1}, + {Lo: 0x0829, Hi: 0x082d, Stride: 1}, + {Lo: 0x0859, Hi: 0x085b, Stride: 1}, + {Lo: 0x0898, Hi: 0x089f, Stride: 1}, + {Lo: 0x08ca, Hi: 0x08e1, Stride: 1}, + {Lo: 0x08e3, Hi: 0x0902, Stride: 1}, + {Lo: 0x093a, Hi: 0x093c, Stride: 2}, + {Lo: 0x0941, Hi: 0x0948, Stride: 1}, + {Lo: 0x094d, Hi: 0x0951, Stride: 4}, + {Lo: 0x0952, Hi: 0x0957, Stride: 1}, + {Lo: 0x0962, Hi: 0x0963, Stride: 1}, + {Lo: 0x0981, Hi: 0x09bc, Stride: 59}, + {Lo: 0x09c1, Hi: 0x09c4, Stride: 1}, + {Lo: 0x09cd, Hi: 0x09e2, Stride: 21}, + {Lo: 0x09e3, Hi: 0x09fe, Stride: 27}, + {Lo: 0x0a01, Hi: 0x0a02, Stride: 1}, + {Lo: 0x0a3c, Hi: 0x0a41, Stride: 5}, + {Lo: 0x0a42, Hi: 0x0a47, Stride: 5}, + {Lo: 0x0a48, Hi: 0x0a4b, Stride: 3}, + {Lo: 0x0a4c, Hi: 0x0a4d, Stride: 1}, + {Lo: 0x0a51, Hi: 0x0a70, Stride: 31}, + {Lo: 0x0a71, Hi: 0x0a75, Stride: 4}, + {Lo: 0x0a81, Hi: 0x0a82, Stride: 1}, + {Lo: 0x0abc, Hi: 0x0ac1, Stride: 5}, + {Lo: 0x0ac2, Hi: 0x0ac5, Stride: 1}, + {Lo: 0x0ac7, Hi: 0x0ac8, Stride: 1}, + {Lo: 0x0acd, Hi: 0x0ae2, Stride: 21}, + {Lo: 0x0ae3, Hi: 0x0afa, Stride: 23}, + {Lo: 0x0afb, Hi: 0x0aff, Stride: 1}, + {Lo: 0x0b01, Hi: 0x0b3c, Stride: 59}, + {Lo: 0x0b3f, Hi: 0x0b41, Stride: 2}, + {Lo: 0x0b42, Hi: 0x0b44, Stride: 1}, + {Lo: 0x0b4d, Hi: 0x0b55, Stride: 8}, + {Lo: 0x0b56, Hi: 0x0b62, Stride: 12}, + {Lo: 0x0b63, Hi: 0x0b82, Stride: 31}, + {Lo: 0x0bc0, Hi: 0x0bcd, Stride: 13}, + {Lo: 0x0c00, Hi: 0x0c04, Stride: 4}, + {Lo: 0x0c3c, Hi: 0x0c3e, Stride: 2}, + {Lo: 0x0c3f, Hi: 0x0c40, Stride: 1}, + {Lo: 0x0c46, Hi: 0x0c48, Stride: 1}, + {Lo: 0x0c4a, Hi: 0x0c4d, Stride: 1}, + {Lo: 0x0c55, Hi: 0x0c56, Stride: 1}, + {Lo: 0x0c62, Hi: 0x0c63, Stride: 1}, + {Lo: 0x0c81, Hi: 0x0cbc, Stride: 59}, + {Lo: 0x0cbf, Hi: 0x0cc6, Stride: 7}, + {Lo: 0x0ccc, Hi: 0x0ccd, Stride: 1}, + {Lo: 0x0ce2, Hi: 0x0ce3, Stride: 1}, + {Lo: 0x0d00, Hi: 0x0d01, Stride: 1}, + {Lo: 0x0d3b, Hi: 0x0d3c, Stride: 1}, + {Lo: 0x0d41, Hi: 0x0d44, Stride: 1}, + {Lo: 0x0d4d, Hi: 0x0d62, Stride: 21}, + {Lo: 0x0d63, Hi: 0x0d81, Stride: 30}, + {Lo: 0x0dca, Hi: 0x0dd2, Stride: 8}, + {Lo: 0x0dd3, Hi: 0x0dd4, Stride: 1}, + {Lo: 0x0dd6, Hi: 0x0e31, Stride: 91}, + {Lo: 0x0e34, Hi: 0x0e3a, Stride: 1}, + {Lo: 0x0e47, Hi: 0x0e4e, Stride: 1}, + {Lo: 0x0eb1, Hi: 0x0eb4, Stride: 3}, + {Lo: 0x0eb5, Hi: 0x0ebc, Stride: 1}, + {Lo: 0x0ec8, Hi: 0x0ece, Stride: 1}, + {Lo: 0x0f18, Hi: 0x0f19, Stride: 1}, + {Lo: 0x0f35, Hi: 0x0f39, Stride: 2}, + {Lo: 0x0f71, Hi: 0x0f7e, Stride: 1}, + {Lo: 0x0f80, Hi: 0x0f84, Stride: 1}, + {Lo: 0x0f86, Hi: 0x0f87, Stride: 1}, + {Lo: 0x0f8d, Hi: 0x0f97, Stride: 1}, + {Lo: 0x0f99, Hi: 0x0fbc, Stride: 1}, + {Lo: 0x0fc6, Hi: 0x102d, Stride: 103}, + {Lo: 0x102e, Hi: 0x1030, Stride: 1}, + {Lo: 0x1032, Hi: 0x1037, Stride: 1}, + {Lo: 0x1039, Hi: 0x103a, Stride: 1}, + {Lo: 0x103d, Hi: 0x103e, Stride: 1}, + {Lo: 0x1058, Hi: 0x1059, Stride: 1}, + {Lo: 0x105e, Hi: 0x1060, Stride: 1}, + {Lo: 0x1071, Hi: 0x1074, Stride: 1}, + {Lo: 0x1082, Hi: 0x1085, Stride: 3}, + {Lo: 0x1086, Hi: 0x108d, Stride: 7}, + {Lo: 0x109d, Hi: 0x135d, Stride: 704}, + {Lo: 0x135e, Hi: 0x135f, Stride: 1}, + {Lo: 0x1712, Hi: 0x1714, Stride: 1}, + {Lo: 0x1732, Hi: 0x1733, Stride: 1}, + {Lo: 0x1752, Hi: 0x1753, Stride: 1}, + {Lo: 0x1772, Hi: 0x1773, Stride: 1}, + {Lo: 0x17b4, Hi: 0x17b5, Stride: 1}, + {Lo: 0x17b7, Hi: 0x17bd, Stride: 1}, + {Lo: 0x17c6, Hi: 0x17c9, Stride: 3}, + {Lo: 0x17ca, Hi: 0x17d3, Stride: 1}, + {Lo: 0x17dd, Hi: 0x180b, Stride: 46}, + {Lo: 0x180c, Hi: 0x180d, Stride: 1}, + {Lo: 0x180f, Hi: 0x1885, Stride: 118}, + {Lo: 0x1886, Hi: 0x18a9, Stride: 35}, + {Lo: 0x1920, Hi: 0x1922, Stride: 1}, + {Lo: 0x1927, Hi: 0x1928, Stride: 1}, + {Lo: 0x1932, Hi: 0x1939, Stride: 7}, + {Lo: 0x193a, Hi: 0x193b, Stride: 1}, + {Lo: 0x1a17, Hi: 0x1a18, Stride: 1}, + {Lo: 0x1a1b, Hi: 0x1a56, Stride: 59}, + {Lo: 0x1a58, Hi: 0x1a5e, Stride: 1}, + {Lo: 0x1a60, Hi: 0x1a62, Stride: 2}, + {Lo: 0x1a65, Hi: 0x1a6c, Stride: 1}, + {Lo: 0x1a73, Hi: 0x1a7c, Stride: 1}, + {Lo: 0x1a7f, Hi: 0x1ab0, Stride: 49}, + {Lo: 0x1ab1, Hi: 0x1abd, Stride: 1}, + {Lo: 0x1abf, Hi: 0x1ace, Stride: 1}, + {Lo: 0x1b00, Hi: 0x1b03, Stride: 1}, + {Lo: 0x1b34, Hi: 0x1b36, Stride: 2}, + {Lo: 0x1b37, Hi: 0x1b3a, Stride: 1}, + {Lo: 0x1b3c, Hi: 0x1b42, Stride: 6}, + {Lo: 0x1b6b, Hi: 0x1b73, Stride: 1}, + {Lo: 0x1b80, Hi: 0x1b81, Stride: 1}, + {Lo: 0x1ba2, Hi: 0x1ba5, Stride: 1}, + {Lo: 0x1ba8, Hi: 0x1ba9, Stride: 1}, + {Lo: 0x1bab, Hi: 0x1bad, Stride: 1}, + {Lo: 0x1be6, Hi: 0x1be8, Stride: 2}, + {Lo: 0x1be9, Hi: 0x1bed, Stride: 4}, + {Lo: 0x1bef, Hi: 0x1bf1, Stride: 1}, + {Lo: 0x1c2c, Hi: 0x1c33, Stride: 1}, + {Lo: 0x1c36, Hi: 0x1c37, Stride: 1}, + {Lo: 0x1cd0, Hi: 0x1cd2, Stride: 1}, + {Lo: 0x1cd4, Hi: 0x1ce0, Stride: 1}, + {Lo: 0x1ce2, Hi: 0x1ce8, Stride: 1}, + {Lo: 0x1ced, Hi: 0x1cf4, Stride: 7}, + {Lo: 0x1cf8, Hi: 0x1cf9, Stride: 1}, + {Lo: 0x1dc0, Hi: 0x1dff, Stride: 1}, + {Lo: 0x20d0, Hi: 0x20dc, Stride: 1}, + {Lo: 0x20e1, Hi: 0x20e5, Stride: 4}, + {Lo: 0x20e6, Hi: 0x20f0, Stride: 1}, + {Lo: 0x2cef, Hi: 0x2cf1, Stride: 1}, + {Lo: 0x2d7f, Hi: 0x2de0, Stride: 97}, + {Lo: 0x2de1, Hi: 0x2dff, Stride: 1}, + {Lo: 0x302a, Hi: 0x302d, Stride: 1}, + {Lo: 0x3099, Hi: 0x309a, Stride: 1}, + {Lo: 0xa66f, Hi: 0xa674, Stride: 5}, + {Lo: 0xa675, Hi: 0xa67d, Stride: 1}, + {Lo: 0xa69e, Hi: 0xa69f, Stride: 1}, + {Lo: 0xa6f0, Hi: 0xa6f1, Stride: 1}, + {Lo: 0xa802, Hi: 0xa806, Stride: 4}, + {Lo: 0xa80b, Hi: 0xa825, Stride: 26}, + {Lo: 0xa826, Hi: 0xa82c, Stride: 6}, + {Lo: 0xa8c4, Hi: 0xa8c5, Stride: 1}, + {Lo: 0xa8e0, Hi: 0xa8f1, Stride: 1}, + {Lo: 0xa8ff, Hi: 0xa926, Stride: 39}, + {Lo: 0xa927, Hi: 0xa92d, Stride: 1}, + {Lo: 0xa947, Hi: 0xa951, Stride: 1}, + {Lo: 0xa980, Hi: 0xa982, Stride: 1}, + {Lo: 0xa9b3, Hi: 0xa9b6, Stride: 3}, + {Lo: 0xa9b7, Hi: 0xa9b9, Stride: 1}, + {Lo: 0xa9bc, Hi: 0xa9bd, Stride: 1}, + {Lo: 0xa9e5, Hi: 0xaa29, Stride: 68}, + {Lo: 0xaa2a, Hi: 0xaa2e, Stride: 1}, + {Lo: 0xaa31, Hi: 0xaa32, Stride: 1}, + {Lo: 0xaa35, Hi: 0xaa36, Stride: 1}, + {Lo: 0xaa43, Hi: 0xaa4c, Stride: 9}, + {Lo: 0xaa7c, Hi: 0xaab0, Stride: 52}, + {Lo: 0xaab2, Hi: 0xaab4, Stride: 1}, + {Lo: 0xaab7, Hi: 0xaab8, Stride: 1}, + {Lo: 0xaabe, Hi: 0xaabf, Stride: 1}, + {Lo: 0xaac1, Hi: 0xaaec, Stride: 43}, + {Lo: 0xaaed, Hi: 0xaaf6, Stride: 9}, + {Lo: 0xabe5, Hi: 0xabe8, Stride: 3}, + {Lo: 0xabed, Hi: 0xfb1e, Stride: 20273}, + {Lo: 0xfe00, Hi: 0xfe0f, Stride: 1}, + {Lo: 0xfe20, Hi: 0xfe2f, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x101fd, Hi: 0x102e0, Stride: 227}, + {Lo: 0x10376, Hi: 0x1037a, Stride: 1}, + {Lo: 0x10a01, Hi: 0x10a03, Stride: 1}, + {Lo: 0x10a05, Hi: 0x10a06, Stride: 1}, + {Lo: 0x10a0c, Hi: 0x10a0f, Stride: 1}, + {Lo: 0x10a38, Hi: 0x10a3a, Stride: 1}, + {Lo: 0x10a3f, Hi: 0x10ae5, Stride: 166}, + {Lo: 0x10ae6, Hi: 0x10d24, Stride: 574}, + {Lo: 0x10d25, Hi: 0x10d27, Stride: 1}, + {Lo: 0x10eab, Hi: 0x10eac, Stride: 1}, + {Lo: 0x10efd, Hi: 0x10eff, Stride: 1}, + {Lo: 0x10f46, Hi: 0x10f50, Stride: 1}, + {Lo: 0x10f82, Hi: 0x10f85, Stride: 1}, + {Lo: 0x11001, Hi: 0x11038, Stride: 55}, + {Lo: 0x11039, Hi: 0x11046, Stride: 1}, + {Lo: 0x11070, Hi: 0x11073, Stride: 3}, + {Lo: 0x11074, Hi: 0x1107f, Stride: 11}, + {Lo: 0x11080, Hi: 0x11081, Stride: 1}, + {Lo: 0x110b3, Hi: 0x110b6, Stride: 1}, + {Lo: 0x110b9, Hi: 0x110ba, Stride: 1}, + {Lo: 0x110c2, Hi: 0x11100, Stride: 62}, + {Lo: 0x11101, Hi: 0x11102, Stride: 1}, + {Lo: 0x11127, Hi: 0x1112b, Stride: 1}, + {Lo: 0x1112d, Hi: 0x11134, Stride: 1}, + {Lo: 0x11173, Hi: 0x11180, Stride: 13}, + {Lo: 0x11181, Hi: 0x111b6, Stride: 53}, + {Lo: 0x111b7, Hi: 0x111be, Stride: 1}, + {Lo: 0x111c9, Hi: 0x111cc, Stride: 1}, + {Lo: 0x111cf, Hi: 0x1122f, Stride: 96}, + {Lo: 0x11230, Hi: 0x11231, Stride: 1}, + {Lo: 0x11234, Hi: 0x11236, Stride: 2}, + {Lo: 0x11237, Hi: 0x1123e, Stride: 7}, + {Lo: 0x11241, Hi: 0x112df, Stride: 158}, + {Lo: 0x112e3, Hi: 0x112ea, Stride: 1}, + {Lo: 0x11300, Hi: 0x11301, Stride: 1}, + {Lo: 0x1133b, Hi: 0x1133c, Stride: 1}, + {Lo: 0x11340, Hi: 0x11366, Stride: 38}, + {Lo: 0x11367, Hi: 0x1136c, Stride: 1}, + {Lo: 0x11370, Hi: 0x11374, Stride: 1}, + {Lo: 0x11438, Hi: 0x1143f, Stride: 1}, + {Lo: 0x11442, Hi: 0x11444, Stride: 1}, + {Lo: 0x11446, Hi: 0x1145e, Stride: 24}, + {Lo: 0x114b3, Hi: 0x114b8, Stride: 1}, + {Lo: 0x114ba, Hi: 0x114bf, Stride: 5}, + {Lo: 0x114c0, Hi: 0x114c2, Stride: 2}, + {Lo: 0x114c3, Hi: 0x115b2, Stride: 239}, + {Lo: 0x115b3, Hi: 0x115b5, Stride: 1}, + {Lo: 0x115bc, Hi: 0x115bd, Stride: 1}, + {Lo: 0x115bf, Hi: 0x115c0, Stride: 1}, + {Lo: 0x115dc, Hi: 0x115dd, Stride: 1}, + {Lo: 0x11633, Hi: 0x1163a, Stride: 1}, + {Lo: 0x1163d, Hi: 0x1163f, Stride: 2}, + {Lo: 0x11640, Hi: 0x116ab, Stride: 107}, + {Lo: 0x116ad, Hi: 0x116b0, Stride: 3}, + {Lo: 0x116b1, Hi: 0x116b5, Stride: 1}, + {Lo: 0x116b7, Hi: 0x1171d, Stride: 102}, + {Lo: 0x1171e, Hi: 0x1171f, Stride: 1}, + {Lo: 0x11722, Hi: 0x11725, Stride: 1}, + {Lo: 0x11727, Hi: 0x1172b, Stride: 1}, + {Lo: 0x1182f, Hi: 0x11837, Stride: 1}, + {Lo: 0x11839, Hi: 0x1183a, Stride: 1}, + {Lo: 0x1193b, Hi: 0x1193c, Stride: 1}, + {Lo: 0x1193e, Hi: 0x11943, Stride: 5}, + {Lo: 0x119d4, Hi: 0x119d7, Stride: 1}, + {Lo: 0x119da, Hi: 0x119db, Stride: 1}, + {Lo: 0x119e0, Hi: 0x11a01, Stride: 33}, + {Lo: 0x11a02, Hi: 0x11a0a, Stride: 1}, + {Lo: 0x11a33, Hi: 0x11a38, Stride: 1}, + {Lo: 0x11a3b, Hi: 0x11a3e, Stride: 1}, + {Lo: 0x11a47, Hi: 0x11a51, Stride: 10}, + {Lo: 0x11a52, Hi: 0x11a56, Stride: 1}, + {Lo: 0x11a59, Hi: 0x11a5b, Stride: 1}, + {Lo: 0x11a8a, Hi: 0x11a96, Stride: 1}, + {Lo: 0x11a98, Hi: 0x11a99, Stride: 1}, + {Lo: 0x11c30, Hi: 0x11c36, Stride: 1}, + {Lo: 0x11c38, Hi: 0x11c3d, Stride: 1}, + {Lo: 0x11c3f, Hi: 0x11c92, Stride: 83}, + {Lo: 0x11c93, Hi: 0x11ca7, Stride: 1}, + {Lo: 0x11caa, Hi: 0x11cb0, Stride: 1}, + {Lo: 0x11cb2, Hi: 0x11cb3, Stride: 1}, + {Lo: 0x11cb5, Hi: 0x11cb6, Stride: 1}, + {Lo: 0x11d31, Hi: 0x11d36, Stride: 1}, + {Lo: 0x11d3a, Hi: 0x11d3c, Stride: 2}, + {Lo: 0x11d3d, Hi: 0x11d3f, Stride: 2}, + {Lo: 0x11d40, Hi: 0x11d45, Stride: 1}, + {Lo: 0x11d47, Hi: 0x11d90, Stride: 73}, + {Lo: 0x11d91, Hi: 0x11d95, Stride: 4}, + {Lo: 0x11d97, Hi: 0x11ef3, Stride: 348}, + {Lo: 0x11ef4, Hi: 0x11f00, Stride: 12}, + {Lo: 0x11f01, Hi: 0x11f36, Stride: 53}, + {Lo: 0x11f37, Hi: 0x11f3a, Stride: 1}, + {Lo: 0x11f40, Hi: 0x11f42, Stride: 2}, + {Lo: 0x13440, Hi: 0x13447, Stride: 7}, + {Lo: 0x13448, Hi: 0x13455, Stride: 1}, + {Lo: 0x16af0, Hi: 0x16af4, Stride: 1}, + {Lo: 0x16b30, Hi: 0x16b36, Stride: 1}, + {Lo: 0x16f4f, Hi: 0x16f8f, Stride: 64}, + {Lo: 0x16f90, Hi: 0x16f92, Stride: 1}, + {Lo: 0x16fe4, Hi: 0x1bc9d, Stride: 19641}, + {Lo: 0x1bc9e, Hi: 0x1cf00, Stride: 4706}, + {Lo: 0x1cf01, Hi: 0x1cf2d, Stride: 1}, + {Lo: 0x1cf30, Hi: 0x1cf46, Stride: 1}, + {Lo: 0x1d167, Hi: 0x1d169, Stride: 1}, + {Lo: 0x1d17b, Hi: 0x1d182, Stride: 1}, + {Lo: 0x1d185, Hi: 0x1d18b, Stride: 1}, + {Lo: 0x1d1aa, Hi: 0x1d1ad, Stride: 1}, + {Lo: 0x1d242, Hi: 0x1d244, Stride: 1}, + {Lo: 0x1da00, Hi: 0x1da36, Stride: 1}, + {Lo: 0x1da3b, Hi: 0x1da6c, Stride: 1}, + {Lo: 0x1da75, Hi: 0x1da84, Stride: 15}, + {Lo: 0x1da9b, Hi: 0x1da9f, Stride: 1}, + {Lo: 0x1daa1, Hi: 0x1daaf, Stride: 1}, + {Lo: 0x1e000, Hi: 0x1e006, Stride: 1}, + {Lo: 0x1e008, Hi: 0x1e018, Stride: 1}, + {Lo: 0x1e01b, Hi: 0x1e021, Stride: 1}, + {Lo: 0x1e023, Hi: 0x1e024, Stride: 1}, + {Lo: 0x1e026, Hi: 0x1e02a, Stride: 1}, + {Lo: 0x1e08f, Hi: 0x1e130, Stride: 161}, + {Lo: 0x1e131, Hi: 0x1e136, Stride: 1}, + {Lo: 0x1e2ae, Hi: 0x1e2ec, Stride: 62}, + {Lo: 0x1e2ed, Hi: 0x1e2ef, Stride: 1}, + {Lo: 0x1e4ec, Hi: 0x1e4ef, Stride: 1}, + {Lo: 0x1e8d0, Hi: 0x1e8d6, Stride: 1}, + {Lo: 0x1e944, Hi: 0x1e94a, Stride: 1}, + {Lo: 0xe0100, Hi: 0xe01ef, Stride: 1}, + }, +} + +var Nd = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0030, Hi: 0x0039, Stride: 1}, + {Lo: 0x0660, Hi: 0x0669, Stride: 1}, + {Lo: 0x06f0, Hi: 0x06f9, Stride: 1}, + {Lo: 0x07c0, Hi: 0x07c9, Stride: 1}, + {Lo: 0x0966, Hi: 0x096f, Stride: 1}, + {Lo: 0x09e6, Hi: 0x09ef, Stride: 1}, + {Lo: 0x0a66, Hi: 0x0a6f, Stride: 1}, + {Lo: 0x0ae6, Hi: 0x0aef, Stride: 1}, + {Lo: 0x0b66, Hi: 0x0b6f, Stride: 1}, + {Lo: 0x0be6, Hi: 0x0bef, Stride: 1}, + {Lo: 0x0c66, Hi: 0x0c6f, Stride: 1}, + {Lo: 0x0ce6, Hi: 0x0cef, Stride: 1}, + {Lo: 0x0d66, Hi: 0x0d6f, Stride: 1}, + {Lo: 0x0de6, Hi: 0x0def, Stride: 1}, + {Lo: 0x0e50, Hi: 0x0e59, Stride: 1}, + {Lo: 0x0ed0, Hi: 0x0ed9, Stride: 1}, + {Lo: 0x0f20, Hi: 0x0f29, Stride: 1}, + {Lo: 0x1040, Hi: 0x1049, Stride: 1}, + {Lo: 0x1090, Hi: 0x1099, Stride: 1}, + {Lo: 0x17e0, Hi: 0x17e9, Stride: 1}, + {Lo: 0x1810, Hi: 0x1819, Stride: 1}, + {Lo: 0x1946, Hi: 0x194f, Stride: 1}, + {Lo: 0x19d0, Hi: 0x19d9, Stride: 1}, + {Lo: 0x1a80, Hi: 0x1a89, Stride: 1}, + {Lo: 0x1a90, Hi: 0x1a99, Stride: 1}, + {Lo: 0x1b50, Hi: 0x1b59, Stride: 1}, + {Lo: 0x1bb0, Hi: 0x1bb9, Stride: 1}, + {Lo: 0x1c40, Hi: 0x1c49, Stride: 1}, + {Lo: 0x1c50, Hi: 0x1c59, Stride: 1}, + {Lo: 0xa620, Hi: 0xa629, Stride: 1}, + {Lo: 0xa8d0, Hi: 0xa8d9, Stride: 1}, + {Lo: 0xa900, Hi: 0xa909, Stride: 1}, + {Lo: 0xa9d0, Hi: 0xa9d9, Stride: 1}, + {Lo: 0xa9f0, Hi: 0xa9f9, Stride: 1}, + {Lo: 0xaa50, Hi: 0xaa59, Stride: 1}, + {Lo: 0xabf0, Hi: 0xabf9, Stride: 1}, + {Lo: 0xff10, Hi: 0xff19, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x104a0, Hi: 0x104a9, Stride: 1}, + {Lo: 0x10d30, Hi: 0x10d39, Stride: 1}, + {Lo: 0x11066, Hi: 0x1106f, Stride: 1}, + {Lo: 0x110f0, Hi: 0x110f9, Stride: 1}, + {Lo: 0x11136, Hi: 0x1113f, Stride: 1}, + {Lo: 0x111d0, Hi: 0x111d9, Stride: 1}, + {Lo: 0x112f0, Hi: 0x112f9, Stride: 1}, + {Lo: 0x11450, Hi: 0x11459, Stride: 1}, + {Lo: 0x114d0, Hi: 0x114d9, Stride: 1}, + {Lo: 0x11650, Hi: 0x11659, Stride: 1}, + {Lo: 0x116c0, Hi: 0x116c9, Stride: 1}, + {Lo: 0x11730, Hi: 0x11739, Stride: 1}, + {Lo: 0x118e0, Hi: 0x118e9, Stride: 1}, + {Lo: 0x11950, Hi: 0x11959, Stride: 1}, + {Lo: 0x11c50, Hi: 0x11c59, Stride: 1}, + {Lo: 0x11d50, Hi: 0x11d59, Stride: 1}, + {Lo: 0x11da0, Hi: 0x11da9, Stride: 1}, + {Lo: 0x11f50, Hi: 0x11f59, Stride: 1}, + {Lo: 0x16a60, Hi: 0x16a69, Stride: 1}, + {Lo: 0x16ac0, Hi: 0x16ac9, Stride: 1}, + {Lo: 0x16b50, Hi: 0x16b59, Stride: 1}, + {Lo: 0x1d7ce, Hi: 0x1d7ff, Stride: 1}, + {Lo: 0x1e140, Hi: 0x1e149, Stride: 1}, + {Lo: 0x1e2f0, Hi: 0x1e2f9, Stride: 1}, + {Lo: 0x1e4f0, Hi: 0x1e4f9, Stride: 1}, + {Lo: 0x1e950, Hi: 0x1e959, Stride: 1}, + {Lo: 0x1fbf0, Hi: 0x1fbf9, Stride: 1}, + }, + LatinOffset: 1, +} + +var Nl = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x16ee, Hi: 0x16f0, Stride: 1}, + {Lo: 0x2160, Hi: 0x2182, Stride: 1}, + {Lo: 0x2185, Hi: 0x2188, Stride: 1}, + {Lo: 0x3007, Hi: 0x3021, Stride: 26}, + {Lo: 0x3022, Hi: 0x3029, Stride: 1}, + {Lo: 0x3038, Hi: 0x303a, Stride: 1}, + {Lo: 0xa6e6, Hi: 0xa6ef, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x10140, Hi: 0x10174, Stride: 1}, + {Lo: 0x10341, Hi: 0x1034a, Stride: 9}, + {Lo: 0x103d1, Hi: 0x103d5, Stride: 1}, + {Lo: 0x12400, Hi: 0x1246e, Stride: 1}, + }, +} + +var No = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x00b2, Hi: 0x00b3, Stride: 1}, + {Lo: 0x00b9, Hi: 0x00bc, Stride: 3}, + {Lo: 0x00bd, Hi: 0x00be, Stride: 1}, + {Lo: 0x09f4, Hi: 0x09f9, Stride: 1}, + {Lo: 0x0b72, Hi: 0x0b77, Stride: 1}, + {Lo: 0x0bf0, Hi: 0x0bf2, Stride: 1}, + {Lo: 0x0c78, Hi: 0x0c7e, Stride: 1}, + {Lo: 0x0d58, Hi: 0x0d5e, Stride: 1}, + {Lo: 0x0d70, Hi: 0x0d78, Stride: 1}, + {Lo: 0x0f2a, Hi: 0x0f33, Stride: 1}, + {Lo: 0x1369, Hi: 0x137c, Stride: 1}, + {Lo: 0x17f0, Hi: 0x17f9, Stride: 1}, + {Lo: 0x19da, Hi: 0x2070, Stride: 1686}, + {Lo: 0x2074, Hi: 0x2079, Stride: 1}, + {Lo: 0x2080, Hi: 0x2089, Stride: 1}, + {Lo: 0x2150, Hi: 0x215f, Stride: 1}, + {Lo: 0x2189, Hi: 0x2460, Stride: 727}, + {Lo: 0x2461, Hi: 0x249b, Stride: 1}, + {Lo: 0x24ea, Hi: 0x24ff, Stride: 1}, + {Lo: 0x2776, Hi: 0x2793, Stride: 1}, + {Lo: 0x2cfd, Hi: 0x3192, Stride: 1173}, + {Lo: 0x3193, Hi: 0x3195, Stride: 1}, + {Lo: 0x3220, Hi: 0x3229, Stride: 1}, + {Lo: 0x3248, Hi: 0x324f, Stride: 1}, + {Lo: 0x3251, Hi: 0x325f, Stride: 1}, + {Lo: 0x3280, Hi: 0x3289, Stride: 1}, + {Lo: 0x32b1, Hi: 0x32bf, Stride: 1}, + {Lo: 0xa830, Hi: 0xa835, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x10107, Hi: 0x10133, Stride: 1}, + {Lo: 0x10175, Hi: 0x10178, Stride: 1}, + {Lo: 0x1018a, Hi: 0x1018b, Stride: 1}, + {Lo: 0x102e1, Hi: 0x102fb, Stride: 1}, + {Lo: 0x10320, Hi: 0x10323, Stride: 1}, + {Lo: 0x10858, Hi: 0x1085f, Stride: 1}, + {Lo: 0x10879, Hi: 0x1087f, Stride: 1}, + {Lo: 0x108a7, Hi: 0x108af, Stride: 1}, + {Lo: 0x108fb, Hi: 0x108ff, Stride: 1}, + {Lo: 0x10916, Hi: 0x1091b, Stride: 1}, + {Lo: 0x109bc, Hi: 0x109bd, Stride: 1}, + {Lo: 0x109c0, Hi: 0x109cf, Stride: 1}, + {Lo: 0x109d2, Hi: 0x109ff, Stride: 1}, + {Lo: 0x10a40, Hi: 0x10a48, Stride: 1}, + {Lo: 0x10a7d, Hi: 0x10a7e, Stride: 1}, + {Lo: 0x10a9d, Hi: 0x10a9f, Stride: 1}, + {Lo: 0x10aeb, Hi: 0x10aef, Stride: 1}, + {Lo: 0x10b58, Hi: 0x10b5f, Stride: 1}, + {Lo: 0x10b78, Hi: 0x10b7f, Stride: 1}, + {Lo: 0x10ba9, Hi: 0x10baf, Stride: 1}, + {Lo: 0x10cfa, Hi: 0x10cff, Stride: 1}, + {Lo: 0x10e60, Hi: 0x10e7e, Stride: 1}, + {Lo: 0x10f1d, Hi: 0x10f26, Stride: 1}, + {Lo: 0x10f51, Hi: 0x10f54, Stride: 1}, + {Lo: 0x10fc5, Hi: 0x10fcb, Stride: 1}, + {Lo: 0x11052, Hi: 0x11065, Stride: 1}, + {Lo: 0x111e1, Hi: 0x111f4, Stride: 1}, + {Lo: 0x1173a, Hi: 0x1173b, Stride: 1}, + {Lo: 0x118ea, Hi: 0x118f2, Stride: 1}, + {Lo: 0x11c5a, Hi: 0x11c6c, Stride: 1}, + {Lo: 0x11fc0, Hi: 0x11fd4, Stride: 1}, + {Lo: 0x16b5b, Hi: 0x16b61, Stride: 1}, + {Lo: 0x16e80, Hi: 0x16e96, Stride: 1}, + {Lo: 0x1d2c0, Hi: 0x1d2d3, Stride: 1}, + {Lo: 0x1d2e0, Hi: 0x1d2f3, Stride: 1}, + {Lo: 0x1d360, Hi: 0x1d378, Stride: 1}, + {Lo: 0x1e8c7, Hi: 0x1e8cf, Stride: 1}, + {Lo: 0x1ec71, Hi: 0x1ecab, Stride: 1}, + {Lo: 0x1ecad, Hi: 0x1ecaf, Stride: 1}, + {Lo: 0x1ecb1, Hi: 0x1ecb4, Stride: 1}, + {Lo: 0x1ed01, Hi: 0x1ed2d, Stride: 1}, + {Lo: 0x1ed2f, Hi: 0x1ed3d, Stride: 1}, + {Lo: 0x1f100, Hi: 0x1f10c, Stride: 1}, + }, + LatinOffset: 3, +} + +var Pc = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x005f, Hi: 0x203f, Stride: 8160}, + {Lo: 0x2040, Hi: 0x2054, Stride: 20}, + {Lo: 0xfe33, Hi: 0xfe34, Stride: 1}, + {Lo: 0xfe4d, Hi: 0xfe4f, Stride: 1}, + {Lo: 0xff3f, Hi: 0xff3f, Stride: 1}, + }, +} + +var Pd = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x002d, Hi: 0x058a, Stride: 1373}, + {Lo: 0x05be, Hi: 0x1400, Stride: 3650}, + {Lo: 0x1806, Hi: 0x2010, Stride: 2058}, + {Lo: 0x2011, Hi: 0x2015, Stride: 1}, + {Lo: 0x2e17, Hi: 0x2e1a, Stride: 3}, + {Lo: 0x2e3a, Hi: 0x2e3b, Stride: 1}, + {Lo: 0x2e40, Hi: 0x2e5d, Stride: 29}, + {Lo: 0x301c, Hi: 0x3030, Stride: 20}, + {Lo: 0x30a0, Hi: 0xfe31, Stride: 52625}, + {Lo: 0xfe32, Hi: 0xfe58, Stride: 38}, + {Lo: 0xfe63, Hi: 0xff0d, Stride: 170}, + }, + R32: []unicode.Range32{ + {Lo: 0x10ead, Hi: 0x10ead, Stride: 1}, + }, +} + +var Pe = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0029, Hi: 0x005d, Stride: 52}, + {Lo: 0x007d, Hi: 0x0f3b, Stride: 3774}, + {Lo: 0x0f3d, Hi: 0x169c, Stride: 1887}, + {Lo: 0x2046, Hi: 0x207e, Stride: 56}, + {Lo: 0x208e, Hi: 0x2309, Stride: 635}, + {Lo: 0x230b, Hi: 0x232a, Stride: 31}, + {Lo: 0x2769, Hi: 0x2775, Stride: 2}, + {Lo: 0x27c6, Hi: 0x27e7, Stride: 33}, + {Lo: 0x27e9, Hi: 0x27ef, Stride: 2}, + {Lo: 0x2984, Hi: 0x2998, Stride: 2}, + {Lo: 0x29d9, Hi: 0x29db, Stride: 2}, + {Lo: 0x29fd, Hi: 0x2e23, Stride: 1062}, + {Lo: 0x2e25, Hi: 0x2e29, Stride: 2}, + {Lo: 0x2e56, Hi: 0x2e5c, Stride: 2}, + {Lo: 0x3009, Hi: 0x3011, Stride: 2}, + {Lo: 0x3015, Hi: 0x301b, Stride: 2}, + {Lo: 0x301e, Hi: 0x301f, Stride: 1}, + {Lo: 0xfd3e, Hi: 0xfe18, Stride: 218}, + {Lo: 0xfe36, Hi: 0xfe44, Stride: 2}, + {Lo: 0xfe48, Hi: 0xfe5a, Stride: 18}, + {Lo: 0xfe5c, Hi: 0xfe5e, Stride: 2}, + {Lo: 0xff09, Hi: 0xff3d, Stride: 52}, + {Lo: 0xff5d, Hi: 0xff63, Stride: 3}, + }, + LatinOffset: 1, +} + +var Pf = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x00bb, Hi: 0x2019, Stride: 8030}, + {Lo: 0x201d, Hi: 0x203a, Stride: 29}, + {Lo: 0x2e03, Hi: 0x2e05, Stride: 2}, + {Lo: 0x2e0a, Hi: 0x2e0d, Stride: 3}, + {Lo: 0x2e1d, Hi: 0x2e21, Stride: 4}, + }, +} + +var Pi = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x00ab, Hi: 0x2018, Stride: 8045}, + {Lo: 0x201b, Hi: 0x201c, Stride: 1}, + {Lo: 0x201f, Hi: 0x2039, Stride: 26}, + {Lo: 0x2e02, Hi: 0x2e04, Stride: 2}, + {Lo: 0x2e09, Hi: 0x2e0c, Stride: 3}, + {Lo: 0x2e1c, Hi: 0x2e20, Stride: 4}, + }, +} + +var Po = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0021, Hi: 0x0023, Stride: 1}, + {Lo: 0x0025, Hi: 0x0027, Stride: 1}, + {Lo: 0x002a, Hi: 0x002e, Stride: 2}, + {Lo: 0x002f, Hi: 0x003a, Stride: 11}, + {Lo: 0x003b, Hi: 0x003f, Stride: 4}, + {Lo: 0x0040, Hi: 0x005c, Stride: 28}, + {Lo: 0x00a1, Hi: 0x00a7, Stride: 6}, + {Lo: 0x00b6, Hi: 0x00b7, Stride: 1}, + {Lo: 0x00bf, Hi: 0x037e, Stride: 703}, + {Lo: 0x0387, Hi: 0x055a, Stride: 467}, + {Lo: 0x055b, Hi: 0x055f, Stride: 1}, + {Lo: 0x0589, Hi: 0x05c0, Stride: 55}, + {Lo: 0x05c3, Hi: 0x05c6, Stride: 3}, + {Lo: 0x05f3, Hi: 0x05f4, Stride: 1}, + {Lo: 0x0609, Hi: 0x060a, Stride: 1}, + {Lo: 0x060c, Hi: 0x060d, Stride: 1}, + {Lo: 0x061b, Hi: 0x061d, Stride: 2}, + {Lo: 0x061e, Hi: 0x061f, Stride: 1}, + {Lo: 0x066a, Hi: 0x066d, Stride: 1}, + {Lo: 0x06d4, Hi: 0x0700, Stride: 44}, + {Lo: 0x0701, Hi: 0x070d, Stride: 1}, + {Lo: 0x07f7, Hi: 0x07f9, Stride: 1}, + {Lo: 0x0830, Hi: 0x083e, Stride: 1}, + {Lo: 0x085e, Hi: 0x0964, Stride: 262}, + {Lo: 0x0965, Hi: 0x0970, Stride: 11}, + {Lo: 0x09fd, Hi: 0x0a76, Stride: 121}, + {Lo: 0x0af0, Hi: 0x0c77, Stride: 391}, + {Lo: 0x0c84, Hi: 0x0df4, Stride: 368}, + {Lo: 0x0e4f, Hi: 0x0e5a, Stride: 11}, + {Lo: 0x0e5b, Hi: 0x0f04, Stride: 169}, + {Lo: 0x0f05, Hi: 0x0f12, Stride: 1}, + {Lo: 0x0f14, Hi: 0x0f85, Stride: 113}, + {Lo: 0x0fd0, Hi: 0x0fd4, Stride: 1}, + {Lo: 0x0fd9, Hi: 0x0fda, Stride: 1}, + {Lo: 0x104a, Hi: 0x104f, Stride: 1}, + {Lo: 0x10fb, Hi: 0x1360, Stride: 613}, + {Lo: 0x1361, Hi: 0x1368, Stride: 1}, + {Lo: 0x166e, Hi: 0x16eb, Stride: 125}, + {Lo: 0x16ec, Hi: 0x16ed, Stride: 1}, + {Lo: 0x1735, Hi: 0x1736, Stride: 1}, + {Lo: 0x17d4, Hi: 0x17d6, Stride: 1}, + {Lo: 0x17d8, Hi: 0x17da, Stride: 1}, + {Lo: 0x1800, Hi: 0x1805, Stride: 1}, + {Lo: 0x1807, Hi: 0x180a, Stride: 1}, + {Lo: 0x1944, Hi: 0x1945, Stride: 1}, + {Lo: 0x1a1e, Hi: 0x1a1f, Stride: 1}, + {Lo: 0x1aa0, Hi: 0x1aa6, Stride: 1}, + {Lo: 0x1aa8, Hi: 0x1aad, Stride: 1}, + {Lo: 0x1b5a, Hi: 0x1b60, Stride: 1}, + {Lo: 0x1b7d, Hi: 0x1b7e, Stride: 1}, + {Lo: 0x1bfc, Hi: 0x1bff, Stride: 1}, + {Lo: 0x1c3b, Hi: 0x1c3f, Stride: 1}, + {Lo: 0x1c7e, Hi: 0x1c7f, Stride: 1}, + {Lo: 0x1cc0, Hi: 0x1cc7, Stride: 1}, + {Lo: 0x1cd3, Hi: 0x2016, Stride: 835}, + {Lo: 0x2017, Hi: 0x2020, Stride: 9}, + {Lo: 0x2021, Hi: 0x2027, Stride: 1}, + {Lo: 0x2030, Hi: 0x2038, Stride: 1}, + {Lo: 0x203b, Hi: 0x203e, Stride: 1}, + {Lo: 0x2041, Hi: 0x2043, Stride: 1}, + {Lo: 0x2047, Hi: 0x2051, Stride: 1}, + {Lo: 0x2053, Hi: 0x2055, Stride: 2}, + {Lo: 0x2056, Hi: 0x205e, Stride: 1}, + {Lo: 0x2cf9, Hi: 0x2cfc, Stride: 1}, + {Lo: 0x2cfe, Hi: 0x2cff, Stride: 1}, + {Lo: 0x2d70, Hi: 0x2e00, Stride: 144}, + {Lo: 0x2e01, Hi: 0x2e06, Stride: 5}, + {Lo: 0x2e07, Hi: 0x2e08, Stride: 1}, + {Lo: 0x2e0b, Hi: 0x2e0e, Stride: 3}, + {Lo: 0x2e0f, Hi: 0x2e16, Stride: 1}, + {Lo: 0x2e18, Hi: 0x2e19, Stride: 1}, + {Lo: 0x2e1b, Hi: 0x2e1e, Stride: 3}, + {Lo: 0x2e1f, Hi: 0x2e2a, Stride: 11}, + {Lo: 0x2e2b, Hi: 0x2e2e, Stride: 1}, + {Lo: 0x2e30, Hi: 0x2e39, Stride: 1}, + {Lo: 0x2e3c, Hi: 0x2e3f, Stride: 1}, + {Lo: 0x2e41, Hi: 0x2e43, Stride: 2}, + {Lo: 0x2e44, Hi: 0x2e4f, Stride: 1}, + {Lo: 0x2e52, Hi: 0x2e54, Stride: 1}, + {Lo: 0x3001, Hi: 0x3003, Stride: 1}, + {Lo: 0x303d, Hi: 0x30fb, Stride: 190}, + {Lo: 0xa4fe, Hi: 0xa4ff, Stride: 1}, + {Lo: 0xa60d, Hi: 0xa60f, Stride: 1}, + {Lo: 0xa673, Hi: 0xa67e, Stride: 11}, + {Lo: 0xa6f2, Hi: 0xa6f7, Stride: 1}, + {Lo: 0xa874, Hi: 0xa877, Stride: 1}, + {Lo: 0xa8ce, Hi: 0xa8cf, Stride: 1}, + {Lo: 0xa8f8, Hi: 0xa8fa, Stride: 1}, + {Lo: 0xa8fc, Hi: 0xa92e, Stride: 50}, + {Lo: 0xa92f, Hi: 0xa95f, Stride: 48}, + {Lo: 0xa9c1, Hi: 0xa9cd, Stride: 1}, + {Lo: 0xa9de, Hi: 0xa9df, Stride: 1}, + {Lo: 0xaa5c, Hi: 0xaa5f, Stride: 1}, + {Lo: 0xaade, Hi: 0xaadf, Stride: 1}, + {Lo: 0xaaf0, Hi: 0xaaf1, Stride: 1}, + {Lo: 0xabeb, Hi: 0xfe10, Stride: 21029}, + {Lo: 0xfe11, Hi: 0xfe16, Stride: 1}, + {Lo: 0xfe19, Hi: 0xfe30, Stride: 23}, + {Lo: 0xfe45, Hi: 0xfe46, Stride: 1}, + {Lo: 0xfe49, Hi: 0xfe4c, Stride: 1}, + {Lo: 0xfe50, Hi: 0xfe52, Stride: 1}, + {Lo: 0xfe54, Hi: 0xfe57, Stride: 1}, + {Lo: 0xfe5f, Hi: 0xfe61, Stride: 1}, + {Lo: 0xfe68, Hi: 0xfe6a, Stride: 2}, + {Lo: 0xfe6b, Hi: 0xff01, Stride: 150}, + {Lo: 0xff02, Hi: 0xff03, Stride: 1}, + {Lo: 0xff05, Hi: 0xff07, Stride: 1}, + {Lo: 0xff0a, Hi: 0xff0e, Stride: 2}, + {Lo: 0xff0f, Hi: 0xff1a, Stride: 11}, + {Lo: 0xff1b, Hi: 0xff1f, Stride: 4}, + {Lo: 0xff20, Hi: 0xff3c, Stride: 28}, + {Lo: 0xff61, Hi: 0xff64, Stride: 3}, + {Lo: 0xff65, Hi: 0xff65, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x10100, Hi: 0x10102, Stride: 1}, + {Lo: 0x1039f, Hi: 0x103d0, Stride: 49}, + {Lo: 0x1056f, Hi: 0x10857, Stride: 744}, + {Lo: 0x1091f, Hi: 0x1093f, Stride: 32}, + {Lo: 0x10a50, Hi: 0x10a58, Stride: 1}, + {Lo: 0x10a7f, Hi: 0x10af0, Stride: 113}, + {Lo: 0x10af1, Hi: 0x10af6, Stride: 1}, + {Lo: 0x10b39, Hi: 0x10b3f, Stride: 1}, + {Lo: 0x10b99, Hi: 0x10b9c, Stride: 1}, + {Lo: 0x10f55, Hi: 0x10f59, Stride: 1}, + {Lo: 0x10f86, Hi: 0x10f89, Stride: 1}, + {Lo: 0x11047, Hi: 0x1104d, Stride: 1}, + {Lo: 0x110bb, Hi: 0x110bc, Stride: 1}, + {Lo: 0x110be, Hi: 0x110c1, Stride: 1}, + {Lo: 0x11140, Hi: 0x11143, Stride: 1}, + {Lo: 0x11174, Hi: 0x11175, Stride: 1}, + {Lo: 0x111c5, Hi: 0x111c8, Stride: 1}, + {Lo: 0x111cd, Hi: 0x111db, Stride: 14}, + {Lo: 0x111dd, Hi: 0x111df, Stride: 1}, + {Lo: 0x11238, Hi: 0x1123d, Stride: 1}, + {Lo: 0x112a9, Hi: 0x1144b, Stride: 418}, + {Lo: 0x1144c, Hi: 0x1144f, Stride: 1}, + {Lo: 0x1145a, Hi: 0x1145b, Stride: 1}, + {Lo: 0x1145d, Hi: 0x114c6, Stride: 105}, + {Lo: 0x115c1, Hi: 0x115d7, Stride: 1}, + {Lo: 0x11641, Hi: 0x11643, Stride: 1}, + {Lo: 0x11660, Hi: 0x1166c, Stride: 1}, + {Lo: 0x116b9, Hi: 0x1173c, Stride: 131}, + {Lo: 0x1173d, Hi: 0x1173e, Stride: 1}, + {Lo: 0x1183b, Hi: 0x11944, Stride: 265}, + {Lo: 0x11945, Hi: 0x11946, Stride: 1}, + {Lo: 0x119e2, Hi: 0x11a3f, Stride: 93}, + {Lo: 0x11a40, Hi: 0x11a46, Stride: 1}, + {Lo: 0x11a9a, Hi: 0x11a9c, Stride: 1}, + {Lo: 0x11a9e, Hi: 0x11aa2, Stride: 1}, + {Lo: 0x11b00, Hi: 0x11b09, Stride: 1}, + {Lo: 0x11c41, Hi: 0x11c45, Stride: 1}, + {Lo: 0x11c70, Hi: 0x11c71, Stride: 1}, + {Lo: 0x11ef7, Hi: 0x11ef8, Stride: 1}, + {Lo: 0x11f43, Hi: 0x11f4f, Stride: 1}, + {Lo: 0x11fff, Hi: 0x12470, Stride: 1137}, + {Lo: 0x12471, Hi: 0x12474, Stride: 1}, + {Lo: 0x12ff1, Hi: 0x12ff2, Stride: 1}, + {Lo: 0x16a6e, Hi: 0x16a6f, Stride: 1}, + {Lo: 0x16af5, Hi: 0x16b37, Stride: 66}, + {Lo: 0x16b38, Hi: 0x16b3b, Stride: 1}, + {Lo: 0x16b44, Hi: 0x16e97, Stride: 851}, + {Lo: 0x16e98, Hi: 0x16e9a, Stride: 1}, + {Lo: 0x16fe2, Hi: 0x1bc9f, Stride: 19645}, + {Lo: 0x1da87, Hi: 0x1da8b, Stride: 1}, + {Lo: 0x1e95e, Hi: 0x1e95f, Stride: 1}, + }, + LatinOffset: 8, +} + +var Ps = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0028, Hi: 0x005b, Stride: 51}, + {Lo: 0x007b, Hi: 0x0f3a, Stride: 3775}, + {Lo: 0x0f3c, Hi: 0x169b, Stride: 1887}, + {Lo: 0x201a, Hi: 0x201e, Stride: 4}, + {Lo: 0x2045, Hi: 0x207d, Stride: 56}, + {Lo: 0x208d, Hi: 0x2308, Stride: 635}, + {Lo: 0x230a, Hi: 0x2329, Stride: 31}, + {Lo: 0x2768, Hi: 0x2774, Stride: 2}, + {Lo: 0x27c5, Hi: 0x27e6, Stride: 33}, + {Lo: 0x27e8, Hi: 0x27ee, Stride: 2}, + {Lo: 0x2983, Hi: 0x2997, Stride: 2}, + {Lo: 0x29d8, Hi: 0x29da, Stride: 2}, + {Lo: 0x29fc, Hi: 0x2e22, Stride: 1062}, + {Lo: 0x2e24, Hi: 0x2e28, Stride: 2}, + {Lo: 0x2e42, Hi: 0x2e55, Stride: 19}, + {Lo: 0x2e57, Hi: 0x2e5b, Stride: 2}, + {Lo: 0x3008, Hi: 0x3010, Stride: 2}, + {Lo: 0x3014, Hi: 0x301a, Stride: 2}, + {Lo: 0x301d, Hi: 0xfd3f, Stride: 52514}, + {Lo: 0xfe17, Hi: 0xfe35, Stride: 30}, + {Lo: 0xfe37, Hi: 0xfe43, Stride: 2}, + {Lo: 0xfe47, Hi: 0xfe59, Stride: 18}, + {Lo: 0xfe5b, Hi: 0xfe5d, Stride: 2}, + {Lo: 0xff08, Hi: 0xff3b, Stride: 51}, + {Lo: 0xff5b, Hi: 0xff5f, Stride: 4}, + {Lo: 0xff62, Hi: 0xff62, Stride: 1}, + }, + LatinOffset: 1, +} + +var Sc = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0024, Hi: 0x00a2, Stride: 126}, + {Lo: 0x00a3, Hi: 0x00a5, Stride: 1}, + {Lo: 0x058f, Hi: 0x060b, Stride: 124}, + {Lo: 0x07fe, Hi: 0x07ff, Stride: 1}, + {Lo: 0x09f2, Hi: 0x09f3, Stride: 1}, + {Lo: 0x09fb, Hi: 0x0af1, Stride: 246}, + {Lo: 0x0bf9, Hi: 0x0e3f, Stride: 582}, + {Lo: 0x17db, Hi: 0x20a0, Stride: 2245}, + {Lo: 0x20a1, Hi: 0x20c0, Stride: 1}, + {Lo: 0xa838, Hi: 0xfdfc, Stride: 21956}, + {Lo: 0xfe69, Hi: 0xff04, Stride: 155}, + {Lo: 0xffe0, Hi: 0xffe1, Stride: 1}, + {Lo: 0xffe5, Hi: 0xffe6, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x11fdd, Hi: 0x11fe0, Stride: 1}, + {Lo: 0x1e2ff, Hi: 0x1ecb0, Stride: 2481}, + }, + LatinOffset: 2, +} + +var Sk = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x005e, Hi: 0x0060, Stride: 2}, + {Lo: 0x00a8, Hi: 0x00af, Stride: 7}, + {Lo: 0x00b4, Hi: 0x00b8, Stride: 4}, + {Lo: 0x02c2, Hi: 0x02c5, Stride: 1}, + {Lo: 0x02d2, Hi: 0x02df, Stride: 1}, + {Lo: 0x02e5, Hi: 0x02eb, Stride: 1}, + {Lo: 0x02ed, Hi: 0x02ef, Stride: 2}, + {Lo: 0x02f0, Hi: 0x02ff, Stride: 1}, + {Lo: 0x0375, Hi: 0x0384, Stride: 15}, + {Lo: 0x0385, Hi: 0x0888, Stride: 1283}, + {Lo: 0x1fbd, Hi: 0x1fbf, Stride: 2}, + {Lo: 0x1fc0, Hi: 0x1fc1, Stride: 1}, + {Lo: 0x1fcd, Hi: 0x1fcf, Stride: 1}, + {Lo: 0x1fdd, Hi: 0x1fdf, Stride: 1}, + {Lo: 0x1fed, Hi: 0x1fef, Stride: 1}, + {Lo: 0x1ffd, Hi: 0x1ffe, Stride: 1}, + {Lo: 0x309b, Hi: 0x309c, Stride: 1}, + {Lo: 0xa700, Hi: 0xa716, Stride: 1}, + {Lo: 0xa720, Hi: 0xa721, Stride: 1}, + {Lo: 0xa789, Hi: 0xa78a, Stride: 1}, + {Lo: 0xab5b, Hi: 0xab6a, Stride: 15}, + {Lo: 0xab6b, Hi: 0xfbb2, Stride: 20551}, + {Lo: 0xfbb3, Hi: 0xfbc2, Stride: 1}, + {Lo: 0xff3e, Hi: 0xff40, Stride: 2}, + {Lo: 0xffe3, Hi: 0xffe3, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x1f3fb, Hi: 0x1f3ff, Stride: 1}, + }, + LatinOffset: 3, +} + +var Sm = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x002b, Hi: 0x003c, Stride: 17}, + {Lo: 0x003d, Hi: 0x003e, Stride: 1}, + {Lo: 0x007c, Hi: 0x007e, Stride: 2}, + {Lo: 0x00ac, Hi: 0x00b1, Stride: 5}, + {Lo: 0x00d7, Hi: 0x00f7, Stride: 32}, + {Lo: 0x03f6, Hi: 0x0606, Stride: 528}, + {Lo: 0x0607, Hi: 0x0608, Stride: 1}, + {Lo: 0x2044, Hi: 0x2052, Stride: 14}, + {Lo: 0x207a, Hi: 0x207c, Stride: 1}, + {Lo: 0x208a, Hi: 0x208c, Stride: 1}, + {Lo: 0x2118, Hi: 0x2140, Stride: 40}, + {Lo: 0x2141, Hi: 0x2144, Stride: 1}, + {Lo: 0x214b, Hi: 0x2190, Stride: 69}, + {Lo: 0x2191, Hi: 0x2194, Stride: 1}, + {Lo: 0x219a, Hi: 0x219b, Stride: 1}, + {Lo: 0x21a0, Hi: 0x21a6, Stride: 3}, + {Lo: 0x21ae, Hi: 0x21ce, Stride: 32}, + {Lo: 0x21cf, Hi: 0x21d2, Stride: 3}, + {Lo: 0x21d4, Hi: 0x21f4, Stride: 32}, + {Lo: 0x21f5, Hi: 0x22ff, Stride: 1}, + {Lo: 0x2320, Hi: 0x2321, Stride: 1}, + {Lo: 0x237c, Hi: 0x239b, Stride: 31}, + {Lo: 0x239c, Hi: 0x23b3, Stride: 1}, + {Lo: 0x23dc, Hi: 0x23e1, Stride: 1}, + {Lo: 0x25b7, Hi: 0x25c1, Stride: 10}, + {Lo: 0x25f8, Hi: 0x25ff, Stride: 1}, + {Lo: 0x266f, Hi: 0x27c0, Stride: 337}, + {Lo: 0x27c1, Hi: 0x27c4, Stride: 1}, + {Lo: 0x27c7, Hi: 0x27e5, Stride: 1}, + {Lo: 0x27f0, Hi: 0x27ff, Stride: 1}, + {Lo: 0x2900, Hi: 0x2982, Stride: 1}, + {Lo: 0x2999, Hi: 0x29d7, Stride: 1}, + {Lo: 0x29dc, Hi: 0x29fb, Stride: 1}, + {Lo: 0x29fe, Hi: 0x2aff, Stride: 1}, + {Lo: 0x2b30, Hi: 0x2b44, Stride: 1}, + {Lo: 0x2b47, Hi: 0x2b4c, Stride: 1}, + {Lo: 0xfb29, Hi: 0xfe62, Stride: 825}, + {Lo: 0xfe64, Hi: 0xfe66, Stride: 1}, + {Lo: 0xff0b, Hi: 0xff1c, Stride: 17}, + {Lo: 0xff1d, Hi: 0xff1e, Stride: 1}, + {Lo: 0xff5c, Hi: 0xff5e, Stride: 2}, + {Lo: 0xffe2, Hi: 0xffe9, Stride: 7}, + {Lo: 0xffea, Hi: 0xffec, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x1d6c1, Hi: 0x1d6db, Stride: 26}, + {Lo: 0x1d6fb, Hi: 0x1d715, Stride: 26}, + {Lo: 0x1d735, Hi: 0x1d74f, Stride: 26}, + {Lo: 0x1d76f, Hi: 0x1d789, Stride: 26}, + {Lo: 0x1d7a9, Hi: 0x1d7c3, Stride: 26}, + {Lo: 0x1eef0, Hi: 0x1eef1, Stride: 1}, + }, + LatinOffset: 5, +} + +var So = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x00a6, Hi: 0x00a9, Stride: 3}, + {Lo: 0x00ae, Hi: 0x00b0, Stride: 2}, + {Lo: 0x0482, Hi: 0x058d, Stride: 267}, + {Lo: 0x058e, Hi: 0x060e, Stride: 128}, + {Lo: 0x060f, Hi: 0x06de, Stride: 207}, + {Lo: 0x06e9, Hi: 0x06fd, Stride: 20}, + {Lo: 0x06fe, Hi: 0x07f6, Stride: 248}, + {Lo: 0x09fa, Hi: 0x0b70, Stride: 374}, + {Lo: 0x0bf3, Hi: 0x0bf8, Stride: 1}, + {Lo: 0x0bfa, Hi: 0x0c7f, Stride: 133}, + {Lo: 0x0d4f, Hi: 0x0d79, Stride: 42}, + {Lo: 0x0f01, Hi: 0x0f03, Stride: 1}, + {Lo: 0x0f13, Hi: 0x0f15, Stride: 2}, + {Lo: 0x0f16, Hi: 0x0f17, Stride: 1}, + {Lo: 0x0f1a, Hi: 0x0f1f, Stride: 1}, + {Lo: 0x0f34, Hi: 0x0f38, Stride: 2}, + {Lo: 0x0fbe, Hi: 0x0fc5, Stride: 1}, + {Lo: 0x0fc7, Hi: 0x0fcc, Stride: 1}, + {Lo: 0x0fce, Hi: 0x0fcf, Stride: 1}, + {Lo: 0x0fd5, Hi: 0x0fd8, Stride: 1}, + {Lo: 0x109e, Hi: 0x109f, Stride: 1}, + {Lo: 0x1390, Hi: 0x1399, Stride: 1}, + {Lo: 0x166d, Hi: 0x1940, Stride: 723}, + {Lo: 0x19de, Hi: 0x19ff, Stride: 1}, + {Lo: 0x1b61, Hi: 0x1b6a, Stride: 1}, + {Lo: 0x1b74, Hi: 0x1b7c, Stride: 1}, + {Lo: 0x2100, Hi: 0x2101, Stride: 1}, + {Lo: 0x2103, Hi: 0x2106, Stride: 1}, + {Lo: 0x2108, Hi: 0x2109, Stride: 1}, + {Lo: 0x2114, Hi: 0x2116, Stride: 2}, + {Lo: 0x2117, Hi: 0x211e, Stride: 7}, + {Lo: 0x211f, Hi: 0x2123, Stride: 1}, + {Lo: 0x2125, Hi: 0x2129, Stride: 2}, + {Lo: 0x212e, Hi: 0x213a, Stride: 12}, + {Lo: 0x213b, Hi: 0x214a, Stride: 15}, + {Lo: 0x214c, Hi: 0x214d, Stride: 1}, + {Lo: 0x214f, Hi: 0x218a, Stride: 59}, + {Lo: 0x218b, Hi: 0x2195, Stride: 10}, + {Lo: 0x2196, Hi: 0x2199, Stride: 1}, + {Lo: 0x219c, Hi: 0x219f, Stride: 1}, + {Lo: 0x21a1, Hi: 0x21a2, Stride: 1}, + {Lo: 0x21a4, Hi: 0x21a5, Stride: 1}, + {Lo: 0x21a7, Hi: 0x21ad, Stride: 1}, + {Lo: 0x21af, Hi: 0x21cd, Stride: 1}, + {Lo: 0x21d0, Hi: 0x21d1, Stride: 1}, + {Lo: 0x21d3, Hi: 0x21d5, Stride: 2}, + {Lo: 0x21d6, Hi: 0x21f3, Stride: 1}, + {Lo: 0x2300, Hi: 0x2307, Stride: 1}, + {Lo: 0x230c, Hi: 0x231f, Stride: 1}, + {Lo: 0x2322, Hi: 0x2328, Stride: 1}, + {Lo: 0x232b, Hi: 0x237b, Stride: 1}, + {Lo: 0x237d, Hi: 0x239a, Stride: 1}, + {Lo: 0x23b4, Hi: 0x23db, Stride: 1}, + {Lo: 0x23e2, Hi: 0x2426, Stride: 1}, + {Lo: 0x2440, Hi: 0x244a, Stride: 1}, + {Lo: 0x249c, Hi: 0x24e9, Stride: 1}, + {Lo: 0x2500, Hi: 0x25b6, Stride: 1}, + {Lo: 0x25b8, Hi: 0x25c0, Stride: 1}, + {Lo: 0x25c2, Hi: 0x25f7, Stride: 1}, + {Lo: 0x2600, Hi: 0x266e, Stride: 1}, + {Lo: 0x2670, Hi: 0x2767, Stride: 1}, + {Lo: 0x2794, Hi: 0x27bf, Stride: 1}, + {Lo: 0x2800, Hi: 0x28ff, Stride: 1}, + {Lo: 0x2b00, Hi: 0x2b2f, Stride: 1}, + {Lo: 0x2b45, Hi: 0x2b46, Stride: 1}, + {Lo: 0x2b4d, Hi: 0x2b73, Stride: 1}, + {Lo: 0x2b76, Hi: 0x2b95, Stride: 1}, + {Lo: 0x2b97, Hi: 0x2bff, Stride: 1}, + {Lo: 0x2ce5, Hi: 0x2cea, Stride: 1}, + {Lo: 0x2e50, Hi: 0x2e51, Stride: 1}, + {Lo: 0x2e80, Hi: 0x2e99, Stride: 1}, + {Lo: 0x2e9b, Hi: 0x2ef3, Stride: 1}, + {Lo: 0x2f00, Hi: 0x2fd5, Stride: 1}, + {Lo: 0x2ff0, Hi: 0x2fff, Stride: 1}, + {Lo: 0x3004, Hi: 0x3012, Stride: 14}, + {Lo: 0x3013, Hi: 0x3020, Stride: 13}, + {Lo: 0x3036, Hi: 0x3037, Stride: 1}, + {Lo: 0x303e, Hi: 0x303f, Stride: 1}, + {Lo: 0x3190, Hi: 0x3191, Stride: 1}, + {Lo: 0x3196, Hi: 0x319f, Stride: 1}, + {Lo: 0x31c0, Hi: 0x31e3, Stride: 1}, + {Lo: 0x31ef, Hi: 0x3200, Stride: 17}, + {Lo: 0x3201, Hi: 0x321e, Stride: 1}, + {Lo: 0x322a, Hi: 0x3247, Stride: 1}, + {Lo: 0x3250, Hi: 0x3260, Stride: 16}, + {Lo: 0x3261, Hi: 0x327f, Stride: 1}, + {Lo: 0x328a, Hi: 0x32b0, Stride: 1}, + {Lo: 0x32c0, Hi: 0x33ff, Stride: 1}, + {Lo: 0x4dc0, Hi: 0x4dff, Stride: 1}, + {Lo: 0xa490, Hi: 0xa4c6, Stride: 1}, + {Lo: 0xa828, Hi: 0xa82b, Stride: 1}, + {Lo: 0xa836, Hi: 0xa837, Stride: 1}, + {Lo: 0xa839, Hi: 0xaa77, Stride: 574}, + {Lo: 0xaa78, Hi: 0xaa79, Stride: 1}, + {Lo: 0xfd40, Hi: 0xfd4f, Stride: 1}, + {Lo: 0xfdcf, Hi: 0xfdfd, Stride: 46}, + {Lo: 0xfdfe, Hi: 0xfdff, Stride: 1}, + {Lo: 0xffe4, Hi: 0xffe8, Stride: 4}, + {Lo: 0xffed, Hi: 0xffee, Stride: 1}, + {Lo: 0xfffc, Hi: 0xfffd, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x10137, Hi: 0x1013f, Stride: 1}, + {Lo: 0x10179, Hi: 0x10189, Stride: 1}, + {Lo: 0x1018c, Hi: 0x1018e, Stride: 1}, + {Lo: 0x10190, Hi: 0x1019c, Stride: 1}, + {Lo: 0x101a0, Hi: 0x101d0, Stride: 48}, + {Lo: 0x101d1, Hi: 0x101fc, Stride: 1}, + {Lo: 0x10877, Hi: 0x10878, Stride: 1}, + {Lo: 0x10ac8, Hi: 0x1173f, Stride: 3191}, + {Lo: 0x11fd5, Hi: 0x11fdc, Stride: 1}, + {Lo: 0x11fe1, Hi: 0x11ff1, Stride: 1}, + {Lo: 0x16b3c, Hi: 0x16b3f, Stride: 1}, + {Lo: 0x16b45, Hi: 0x1bc9c, Stride: 20823}, + {Lo: 0x1cf50, Hi: 0x1cfc3, Stride: 1}, + {Lo: 0x1d000, Hi: 0x1d0f5, Stride: 1}, + {Lo: 0x1d100, Hi: 0x1d126, Stride: 1}, + {Lo: 0x1d129, Hi: 0x1d164, Stride: 1}, + {Lo: 0x1d16a, Hi: 0x1d16c, Stride: 1}, + {Lo: 0x1d183, Hi: 0x1d184, Stride: 1}, + {Lo: 0x1d18c, Hi: 0x1d1a9, Stride: 1}, + {Lo: 0x1d1ae, Hi: 0x1d1ea, Stride: 1}, + {Lo: 0x1d200, Hi: 0x1d241, Stride: 1}, + {Lo: 0x1d245, Hi: 0x1d300, Stride: 187}, + {Lo: 0x1d301, Hi: 0x1d356, Stride: 1}, + {Lo: 0x1d800, Hi: 0x1d9ff, Stride: 1}, + {Lo: 0x1da37, Hi: 0x1da3a, Stride: 1}, + {Lo: 0x1da6d, Hi: 0x1da74, Stride: 1}, + {Lo: 0x1da76, Hi: 0x1da83, Stride: 1}, + {Lo: 0x1da85, Hi: 0x1da86, Stride: 1}, + {Lo: 0x1e14f, Hi: 0x1ecac, Stride: 2909}, + {Lo: 0x1ed2e, Hi: 0x1f000, Stride: 722}, + {Lo: 0x1f001, Hi: 0x1f02b, Stride: 1}, + {Lo: 0x1f030, Hi: 0x1f093, Stride: 1}, + {Lo: 0x1f0a0, Hi: 0x1f0ae, Stride: 1}, + {Lo: 0x1f0b1, Hi: 0x1f0bf, Stride: 1}, + {Lo: 0x1f0c1, Hi: 0x1f0cf, Stride: 1}, + {Lo: 0x1f0d1, Hi: 0x1f0f5, Stride: 1}, + {Lo: 0x1f10d, Hi: 0x1f1ad, Stride: 1}, + {Lo: 0x1f1e6, Hi: 0x1f202, Stride: 1}, + {Lo: 0x1f210, Hi: 0x1f23b, Stride: 1}, + {Lo: 0x1f240, Hi: 0x1f248, Stride: 1}, + {Lo: 0x1f250, Hi: 0x1f251, Stride: 1}, + {Lo: 0x1f260, Hi: 0x1f265, Stride: 1}, + {Lo: 0x1f300, Hi: 0x1f3fa, Stride: 1}, + {Lo: 0x1f400, Hi: 0x1f6d7, Stride: 1}, + {Lo: 0x1f6dc, Hi: 0x1f6ec, Stride: 1}, + {Lo: 0x1f6f0, Hi: 0x1f6fc, Stride: 1}, + {Lo: 0x1f700, Hi: 0x1f776, Stride: 1}, + {Lo: 0x1f77b, Hi: 0x1f7d9, Stride: 1}, + {Lo: 0x1f7e0, Hi: 0x1f7eb, Stride: 1}, + {Lo: 0x1f7f0, Hi: 0x1f800, Stride: 16}, + {Lo: 0x1f801, Hi: 0x1f80b, Stride: 1}, + {Lo: 0x1f810, Hi: 0x1f847, Stride: 1}, + {Lo: 0x1f850, Hi: 0x1f859, Stride: 1}, + {Lo: 0x1f860, Hi: 0x1f887, Stride: 1}, + {Lo: 0x1f890, Hi: 0x1f8ad, Stride: 1}, + {Lo: 0x1f8b0, Hi: 0x1f8b1, Stride: 1}, + {Lo: 0x1f900, Hi: 0x1fa53, Stride: 1}, + {Lo: 0x1fa60, Hi: 0x1fa6d, Stride: 1}, + {Lo: 0x1fa70, Hi: 0x1fa7c, Stride: 1}, + {Lo: 0x1fa80, Hi: 0x1fa88, Stride: 1}, + {Lo: 0x1fa90, Hi: 0x1fabd, Stride: 1}, + {Lo: 0x1fabf, Hi: 0x1fac5, Stride: 1}, + {Lo: 0x1face, Hi: 0x1fadb, Stride: 1}, + {Lo: 0x1fae0, Hi: 0x1fae8, Stride: 1}, + {Lo: 0x1faf0, Hi: 0x1faf8, Stride: 1}, + {Lo: 0x1fb00, Hi: 0x1fb92, Stride: 1}, + {Lo: 0x1fb94, Hi: 0x1fbca, Stride: 1}, + }, + LatinOffset: 2, +} + +var Zl = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x2028, Hi: 0x2028, Stride: 1}, + }, +} + +var Zp = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x2029, Hi: 0x2029, Stride: 1}, + }, +} + +var Zs = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0020, Hi: 0x00a0, Stride: 128}, + {Lo: 0x1680, Hi: 0x2000, Stride: 2432}, + {Lo: 0x2001, Hi: 0x200a, Stride: 1}, + {Lo: 0x202f, Hi: 0x205f, Stride: 48}, + {Lo: 0x3000, Hi: 0x3000, Stride: 1}, + }, + LatinOffset: 1, +} diff --git a/vendor/github.com/go-text/typesetting/unicodedata/grapheme_break.go b/vendor/github.com/go-text/typesetting/unicodedata/grapheme_break.go new file mode 100644 index 0000000..3c22ed5 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/unicodedata/grapheme_break.go @@ -0,0 +1,1334 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package unicodedata + +import "unicode" + +// Code generated by typesettings-utils/generators/unicodedata/cmd/main.go DO NOT EDIT. + +// GraphemeBreakProperty: CR +var GraphemeBreakCR = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x000d, Hi: 0x000d, Stride: 1}, + }, + LatinOffset: 1, +} + +// GraphemeBreakProperty: Control +var GraphemeBreakControl = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0000, Hi: 0x0009, Stride: 1}, + {Lo: 0x000b, Hi: 0x000c, Stride: 1}, + {Lo: 0x000e, Hi: 0x001f, Stride: 1}, + {Lo: 0x007f, Hi: 0x009f, Stride: 1}, + {Lo: 0x00ad, Hi: 0x061c, Stride: 1391}, + {Lo: 0x180e, Hi: 0x200b, Stride: 2045}, + {Lo: 0x200e, Hi: 0x200f, Stride: 1}, + {Lo: 0x2028, Hi: 0x202e, Stride: 1}, + {Lo: 0x2060, Hi: 0x206f, Stride: 1}, + {Lo: 0xfeff, Hi: 0xfff0, Stride: 241}, + {Lo: 0xfff1, Hi: 0xfffb, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x13430, Hi: 0x1343f, Stride: 1}, + {Lo: 0x1bca0, Hi: 0x1bca3, Stride: 1}, + {Lo: 0x1d173, Hi: 0x1d17a, Stride: 1}, + {Lo: 0xe0000, Hi: 0xe001f, Stride: 1}, + {Lo: 0xe0080, Hi: 0xe00ff, Stride: 1}, + {Lo: 0xe01f0, Hi: 0xe0fff, Stride: 1}, + }, + LatinOffset: 4, +} + +// GraphemeBreakProperty: Extend +var GraphemeBreakExtend = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0300, Hi: 0x036f, Stride: 1}, + {Lo: 0x0483, Hi: 0x0489, Stride: 1}, + {Lo: 0x0591, Hi: 0x05bd, Stride: 1}, + {Lo: 0x05bf, Hi: 0x05c1, Stride: 2}, + {Lo: 0x05c2, Hi: 0x05c4, Stride: 2}, + {Lo: 0x05c5, Hi: 0x05c7, Stride: 2}, + {Lo: 0x0610, Hi: 0x061a, Stride: 1}, + {Lo: 0x064b, Hi: 0x065f, Stride: 1}, + {Lo: 0x0670, Hi: 0x06d6, Stride: 102}, + {Lo: 0x06d7, Hi: 0x06dc, Stride: 1}, + {Lo: 0x06df, Hi: 0x06e4, Stride: 1}, + {Lo: 0x06e7, Hi: 0x06e8, Stride: 1}, + {Lo: 0x06ea, Hi: 0x06ed, Stride: 1}, + {Lo: 0x0711, Hi: 0x0730, Stride: 31}, + {Lo: 0x0731, Hi: 0x074a, Stride: 1}, + {Lo: 0x07a6, Hi: 0x07b0, Stride: 1}, + {Lo: 0x07eb, Hi: 0x07f3, Stride: 1}, + {Lo: 0x07fd, Hi: 0x0816, Stride: 25}, + {Lo: 0x0817, Hi: 0x0819, Stride: 1}, + {Lo: 0x081b, Hi: 0x0823, Stride: 1}, + {Lo: 0x0825, Hi: 0x0827, Stride: 1}, + {Lo: 0x0829, Hi: 0x082d, Stride: 1}, + {Lo: 0x0859, Hi: 0x085b, Stride: 1}, + {Lo: 0x0898, Hi: 0x089f, Stride: 1}, + {Lo: 0x08ca, Hi: 0x08e1, Stride: 1}, + {Lo: 0x08e3, Hi: 0x0902, Stride: 1}, + {Lo: 0x093a, Hi: 0x093c, Stride: 2}, + {Lo: 0x0941, Hi: 0x0948, Stride: 1}, + {Lo: 0x094d, Hi: 0x0951, Stride: 4}, + {Lo: 0x0952, Hi: 0x0957, Stride: 1}, + {Lo: 0x0962, Hi: 0x0963, Stride: 1}, + {Lo: 0x0981, Hi: 0x09bc, Stride: 59}, + {Lo: 0x09be, Hi: 0x09c1, Stride: 3}, + {Lo: 0x09c2, Hi: 0x09c4, Stride: 1}, + {Lo: 0x09cd, Hi: 0x09d7, Stride: 10}, + {Lo: 0x09e2, Hi: 0x09e3, Stride: 1}, + {Lo: 0x09fe, Hi: 0x0a01, Stride: 3}, + {Lo: 0x0a02, Hi: 0x0a3c, Stride: 58}, + {Lo: 0x0a41, Hi: 0x0a42, Stride: 1}, + {Lo: 0x0a47, Hi: 0x0a48, Stride: 1}, + {Lo: 0x0a4b, Hi: 0x0a4d, Stride: 1}, + {Lo: 0x0a51, Hi: 0x0a70, Stride: 31}, + {Lo: 0x0a71, Hi: 0x0a75, Stride: 4}, + {Lo: 0x0a81, Hi: 0x0a82, Stride: 1}, + {Lo: 0x0abc, Hi: 0x0ac1, Stride: 5}, + {Lo: 0x0ac2, Hi: 0x0ac5, Stride: 1}, + {Lo: 0x0ac7, Hi: 0x0ac8, Stride: 1}, + {Lo: 0x0acd, Hi: 0x0ae2, Stride: 21}, + {Lo: 0x0ae3, Hi: 0x0afa, Stride: 23}, + {Lo: 0x0afb, Hi: 0x0aff, Stride: 1}, + {Lo: 0x0b01, Hi: 0x0b3c, Stride: 59}, + {Lo: 0x0b3e, Hi: 0x0b3f, Stride: 1}, + {Lo: 0x0b41, Hi: 0x0b44, Stride: 1}, + {Lo: 0x0b4d, Hi: 0x0b55, Stride: 8}, + {Lo: 0x0b56, Hi: 0x0b57, Stride: 1}, + {Lo: 0x0b62, Hi: 0x0b63, Stride: 1}, + {Lo: 0x0b82, Hi: 0x0bbe, Stride: 60}, + {Lo: 0x0bc0, Hi: 0x0bcd, Stride: 13}, + {Lo: 0x0bd7, Hi: 0x0c00, Stride: 41}, + {Lo: 0x0c04, Hi: 0x0c3c, Stride: 56}, + {Lo: 0x0c3e, Hi: 0x0c40, Stride: 1}, + {Lo: 0x0c46, Hi: 0x0c48, Stride: 1}, + {Lo: 0x0c4a, Hi: 0x0c4d, Stride: 1}, + {Lo: 0x0c55, Hi: 0x0c56, Stride: 1}, + {Lo: 0x0c62, Hi: 0x0c63, Stride: 1}, + {Lo: 0x0c81, Hi: 0x0cbc, Stride: 59}, + {Lo: 0x0cbf, Hi: 0x0cc2, Stride: 3}, + {Lo: 0x0cc6, Hi: 0x0ccc, Stride: 6}, + {Lo: 0x0ccd, Hi: 0x0cd5, Stride: 8}, + {Lo: 0x0cd6, Hi: 0x0ce2, Stride: 12}, + {Lo: 0x0ce3, Hi: 0x0d00, Stride: 29}, + {Lo: 0x0d01, Hi: 0x0d3b, Stride: 58}, + {Lo: 0x0d3c, Hi: 0x0d3e, Stride: 2}, + {Lo: 0x0d41, Hi: 0x0d44, Stride: 1}, + {Lo: 0x0d4d, Hi: 0x0d57, Stride: 10}, + {Lo: 0x0d62, Hi: 0x0d63, Stride: 1}, + {Lo: 0x0d81, Hi: 0x0dca, Stride: 73}, + {Lo: 0x0dcf, Hi: 0x0dd2, Stride: 3}, + {Lo: 0x0dd3, Hi: 0x0dd4, Stride: 1}, + {Lo: 0x0dd6, Hi: 0x0ddf, Stride: 9}, + {Lo: 0x0e31, Hi: 0x0e34, Stride: 3}, + {Lo: 0x0e35, Hi: 0x0e3a, Stride: 1}, + {Lo: 0x0e47, Hi: 0x0e4e, Stride: 1}, + {Lo: 0x0eb1, Hi: 0x0eb4, Stride: 3}, + {Lo: 0x0eb5, Hi: 0x0ebc, Stride: 1}, + {Lo: 0x0ec8, Hi: 0x0ece, Stride: 1}, + {Lo: 0x0f18, Hi: 0x0f19, Stride: 1}, + {Lo: 0x0f35, Hi: 0x0f39, Stride: 2}, + {Lo: 0x0f71, Hi: 0x0f7e, Stride: 1}, + {Lo: 0x0f80, Hi: 0x0f84, Stride: 1}, + {Lo: 0x0f86, Hi: 0x0f87, Stride: 1}, + {Lo: 0x0f8d, Hi: 0x0f97, Stride: 1}, + {Lo: 0x0f99, Hi: 0x0fbc, Stride: 1}, + {Lo: 0x0fc6, Hi: 0x102d, Stride: 103}, + {Lo: 0x102e, Hi: 0x1030, Stride: 1}, + {Lo: 0x1032, Hi: 0x1037, Stride: 1}, + {Lo: 0x1039, Hi: 0x103a, Stride: 1}, + {Lo: 0x103d, Hi: 0x103e, Stride: 1}, + {Lo: 0x1058, Hi: 0x1059, Stride: 1}, + {Lo: 0x105e, Hi: 0x1060, Stride: 1}, + {Lo: 0x1071, Hi: 0x1074, Stride: 1}, + {Lo: 0x1082, Hi: 0x1085, Stride: 3}, + {Lo: 0x1086, Hi: 0x108d, Stride: 7}, + {Lo: 0x109d, Hi: 0x135d, Stride: 704}, + {Lo: 0x135e, Hi: 0x135f, Stride: 1}, + {Lo: 0x1712, Hi: 0x1714, Stride: 1}, + {Lo: 0x1732, Hi: 0x1733, Stride: 1}, + {Lo: 0x1752, Hi: 0x1753, Stride: 1}, + {Lo: 0x1772, Hi: 0x1773, Stride: 1}, + {Lo: 0x17b4, Hi: 0x17b5, Stride: 1}, + {Lo: 0x17b7, Hi: 0x17bd, Stride: 1}, + {Lo: 0x17c6, Hi: 0x17c9, Stride: 3}, + {Lo: 0x17ca, Hi: 0x17d3, Stride: 1}, + {Lo: 0x17dd, Hi: 0x180b, Stride: 46}, + {Lo: 0x180c, Hi: 0x180d, Stride: 1}, + {Lo: 0x180f, Hi: 0x1885, Stride: 118}, + {Lo: 0x1886, Hi: 0x18a9, Stride: 35}, + {Lo: 0x1920, Hi: 0x1922, Stride: 1}, + {Lo: 0x1927, Hi: 0x1928, Stride: 1}, + {Lo: 0x1932, Hi: 0x1939, Stride: 7}, + {Lo: 0x193a, Hi: 0x193b, Stride: 1}, + {Lo: 0x1a17, Hi: 0x1a18, Stride: 1}, + {Lo: 0x1a1b, Hi: 0x1a56, Stride: 59}, + {Lo: 0x1a58, Hi: 0x1a5e, Stride: 1}, + {Lo: 0x1a60, Hi: 0x1a62, Stride: 2}, + {Lo: 0x1a65, Hi: 0x1a6c, Stride: 1}, + {Lo: 0x1a73, Hi: 0x1a7c, Stride: 1}, + {Lo: 0x1a7f, Hi: 0x1ab0, Stride: 49}, + {Lo: 0x1ab1, Hi: 0x1ace, Stride: 1}, + {Lo: 0x1b00, Hi: 0x1b03, Stride: 1}, + {Lo: 0x1b34, Hi: 0x1b3a, Stride: 1}, + {Lo: 0x1b3c, Hi: 0x1b42, Stride: 6}, + {Lo: 0x1b6b, Hi: 0x1b73, Stride: 1}, + {Lo: 0x1b80, Hi: 0x1b81, Stride: 1}, + {Lo: 0x1ba2, Hi: 0x1ba5, Stride: 1}, + {Lo: 0x1ba8, Hi: 0x1ba9, Stride: 1}, + {Lo: 0x1bab, Hi: 0x1bad, Stride: 1}, + {Lo: 0x1be6, Hi: 0x1be8, Stride: 2}, + {Lo: 0x1be9, Hi: 0x1bed, Stride: 4}, + {Lo: 0x1bef, Hi: 0x1bf1, Stride: 1}, + {Lo: 0x1c2c, Hi: 0x1c33, Stride: 1}, + {Lo: 0x1c36, Hi: 0x1c37, Stride: 1}, + {Lo: 0x1cd0, Hi: 0x1cd2, Stride: 1}, + {Lo: 0x1cd4, Hi: 0x1ce0, Stride: 1}, + {Lo: 0x1ce2, Hi: 0x1ce8, Stride: 1}, + {Lo: 0x1ced, Hi: 0x1cf4, Stride: 7}, + {Lo: 0x1cf8, Hi: 0x1cf9, Stride: 1}, + {Lo: 0x1dc0, Hi: 0x1dff, Stride: 1}, + {Lo: 0x200c, Hi: 0x20d0, Stride: 196}, + {Lo: 0x20d1, Hi: 0x20f0, Stride: 1}, + {Lo: 0x2cef, Hi: 0x2cf1, Stride: 1}, + {Lo: 0x2d7f, Hi: 0x2de0, Stride: 97}, + {Lo: 0x2de1, Hi: 0x2dff, Stride: 1}, + {Lo: 0x302a, Hi: 0x302f, Stride: 1}, + {Lo: 0x3099, Hi: 0x309a, Stride: 1}, + {Lo: 0xa66f, Hi: 0xa672, Stride: 1}, + {Lo: 0xa674, Hi: 0xa67d, Stride: 1}, + {Lo: 0xa69e, Hi: 0xa69f, Stride: 1}, + {Lo: 0xa6f0, Hi: 0xa6f1, Stride: 1}, + {Lo: 0xa802, Hi: 0xa806, Stride: 4}, + {Lo: 0xa80b, Hi: 0xa825, Stride: 26}, + {Lo: 0xa826, Hi: 0xa82c, Stride: 6}, + {Lo: 0xa8c4, Hi: 0xa8c5, Stride: 1}, + {Lo: 0xa8e0, Hi: 0xa8f1, Stride: 1}, + {Lo: 0xa8ff, Hi: 0xa926, Stride: 39}, + {Lo: 0xa927, Hi: 0xa92d, Stride: 1}, + {Lo: 0xa947, Hi: 0xa951, Stride: 1}, + {Lo: 0xa980, Hi: 0xa982, Stride: 1}, + {Lo: 0xa9b3, Hi: 0xa9b6, Stride: 3}, + {Lo: 0xa9b7, Hi: 0xa9b9, Stride: 1}, + {Lo: 0xa9bc, Hi: 0xa9bd, Stride: 1}, + {Lo: 0xa9e5, Hi: 0xaa29, Stride: 68}, + {Lo: 0xaa2a, Hi: 0xaa2e, Stride: 1}, + {Lo: 0xaa31, Hi: 0xaa32, Stride: 1}, + {Lo: 0xaa35, Hi: 0xaa36, Stride: 1}, + {Lo: 0xaa43, Hi: 0xaa4c, Stride: 9}, + {Lo: 0xaa7c, Hi: 0xaab0, Stride: 52}, + {Lo: 0xaab2, Hi: 0xaab4, Stride: 1}, + {Lo: 0xaab7, Hi: 0xaab8, Stride: 1}, + {Lo: 0xaabe, Hi: 0xaabf, Stride: 1}, + {Lo: 0xaac1, Hi: 0xaaec, Stride: 43}, + {Lo: 0xaaed, Hi: 0xaaf6, Stride: 9}, + {Lo: 0xabe5, Hi: 0xabe8, Stride: 3}, + {Lo: 0xabed, Hi: 0xfb1e, Stride: 20273}, + {Lo: 0xfe00, Hi: 0xfe0f, Stride: 1}, + {Lo: 0xfe20, Hi: 0xfe2f, Stride: 1}, + {Lo: 0xff9e, Hi: 0xff9f, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x101fd, Hi: 0x102e0, Stride: 227}, + {Lo: 0x10376, Hi: 0x1037a, Stride: 1}, + {Lo: 0x10a01, Hi: 0x10a03, Stride: 1}, + {Lo: 0x10a05, Hi: 0x10a06, Stride: 1}, + {Lo: 0x10a0c, Hi: 0x10a0f, Stride: 1}, + {Lo: 0x10a38, Hi: 0x10a3a, Stride: 1}, + {Lo: 0x10a3f, Hi: 0x10ae5, Stride: 166}, + {Lo: 0x10ae6, Hi: 0x10d24, Stride: 574}, + {Lo: 0x10d25, Hi: 0x10d27, Stride: 1}, + {Lo: 0x10eab, Hi: 0x10eac, Stride: 1}, + {Lo: 0x10efd, Hi: 0x10eff, Stride: 1}, + {Lo: 0x10f46, Hi: 0x10f50, Stride: 1}, + {Lo: 0x10f82, Hi: 0x10f85, Stride: 1}, + {Lo: 0x11001, Hi: 0x11038, Stride: 55}, + {Lo: 0x11039, Hi: 0x11046, Stride: 1}, + {Lo: 0x11070, Hi: 0x11073, Stride: 3}, + {Lo: 0x11074, Hi: 0x1107f, Stride: 11}, + {Lo: 0x11080, Hi: 0x11081, Stride: 1}, + {Lo: 0x110b3, Hi: 0x110b6, Stride: 1}, + {Lo: 0x110b9, Hi: 0x110ba, Stride: 1}, + {Lo: 0x110c2, Hi: 0x11100, Stride: 62}, + {Lo: 0x11101, Hi: 0x11102, Stride: 1}, + {Lo: 0x11127, Hi: 0x1112b, Stride: 1}, + {Lo: 0x1112d, Hi: 0x11134, Stride: 1}, + {Lo: 0x11173, Hi: 0x11180, Stride: 13}, + {Lo: 0x11181, Hi: 0x111b6, Stride: 53}, + {Lo: 0x111b7, Hi: 0x111be, Stride: 1}, + {Lo: 0x111c9, Hi: 0x111cc, Stride: 1}, + {Lo: 0x111cf, Hi: 0x1122f, Stride: 96}, + {Lo: 0x11230, Hi: 0x11231, Stride: 1}, + {Lo: 0x11234, Hi: 0x11236, Stride: 2}, + {Lo: 0x11237, Hi: 0x1123e, Stride: 7}, + {Lo: 0x11241, Hi: 0x112df, Stride: 158}, + {Lo: 0x112e3, Hi: 0x112ea, Stride: 1}, + {Lo: 0x11300, Hi: 0x11301, Stride: 1}, + {Lo: 0x1133b, Hi: 0x1133c, Stride: 1}, + {Lo: 0x1133e, Hi: 0x11340, Stride: 2}, + {Lo: 0x11357, Hi: 0x11366, Stride: 15}, + {Lo: 0x11367, Hi: 0x1136c, Stride: 1}, + {Lo: 0x11370, Hi: 0x11374, Stride: 1}, + {Lo: 0x11438, Hi: 0x1143f, Stride: 1}, + {Lo: 0x11442, Hi: 0x11444, Stride: 1}, + {Lo: 0x11446, Hi: 0x1145e, Stride: 24}, + {Lo: 0x114b0, Hi: 0x114b3, Stride: 3}, + {Lo: 0x114b4, Hi: 0x114b8, Stride: 1}, + {Lo: 0x114ba, Hi: 0x114bd, Stride: 3}, + {Lo: 0x114bf, Hi: 0x114c0, Stride: 1}, + {Lo: 0x114c2, Hi: 0x114c3, Stride: 1}, + {Lo: 0x115af, Hi: 0x115b2, Stride: 3}, + {Lo: 0x115b3, Hi: 0x115b5, Stride: 1}, + {Lo: 0x115bc, Hi: 0x115bd, Stride: 1}, + {Lo: 0x115bf, Hi: 0x115c0, Stride: 1}, + {Lo: 0x115dc, Hi: 0x115dd, Stride: 1}, + {Lo: 0x11633, Hi: 0x1163a, Stride: 1}, + {Lo: 0x1163d, Hi: 0x1163f, Stride: 2}, + {Lo: 0x11640, Hi: 0x116ab, Stride: 107}, + {Lo: 0x116ad, Hi: 0x116b0, Stride: 3}, + {Lo: 0x116b1, Hi: 0x116b5, Stride: 1}, + {Lo: 0x116b7, Hi: 0x1171d, Stride: 102}, + {Lo: 0x1171e, Hi: 0x1171f, Stride: 1}, + {Lo: 0x11722, Hi: 0x11725, Stride: 1}, + {Lo: 0x11727, Hi: 0x1172b, Stride: 1}, + {Lo: 0x1182f, Hi: 0x11837, Stride: 1}, + {Lo: 0x11839, Hi: 0x1183a, Stride: 1}, + {Lo: 0x11930, Hi: 0x1193b, Stride: 11}, + {Lo: 0x1193c, Hi: 0x1193e, Stride: 2}, + {Lo: 0x11943, Hi: 0x119d4, Stride: 145}, + {Lo: 0x119d5, Hi: 0x119d7, Stride: 1}, + {Lo: 0x119da, Hi: 0x119db, Stride: 1}, + {Lo: 0x119e0, Hi: 0x11a01, Stride: 33}, + {Lo: 0x11a02, Hi: 0x11a0a, Stride: 1}, + {Lo: 0x11a33, Hi: 0x11a38, Stride: 1}, + {Lo: 0x11a3b, Hi: 0x11a3e, Stride: 1}, + {Lo: 0x11a47, Hi: 0x11a51, Stride: 10}, + {Lo: 0x11a52, Hi: 0x11a56, Stride: 1}, + {Lo: 0x11a59, Hi: 0x11a5b, Stride: 1}, + {Lo: 0x11a8a, Hi: 0x11a96, Stride: 1}, + {Lo: 0x11a98, Hi: 0x11a99, Stride: 1}, + {Lo: 0x11c30, Hi: 0x11c36, Stride: 1}, + {Lo: 0x11c38, Hi: 0x11c3d, Stride: 1}, + {Lo: 0x11c3f, Hi: 0x11c92, Stride: 83}, + {Lo: 0x11c93, Hi: 0x11ca7, Stride: 1}, + {Lo: 0x11caa, Hi: 0x11cb0, Stride: 1}, + {Lo: 0x11cb2, Hi: 0x11cb3, Stride: 1}, + {Lo: 0x11cb5, Hi: 0x11cb6, Stride: 1}, + {Lo: 0x11d31, Hi: 0x11d36, Stride: 1}, + {Lo: 0x11d3a, Hi: 0x11d3c, Stride: 2}, + {Lo: 0x11d3d, Hi: 0x11d3f, Stride: 2}, + {Lo: 0x11d40, Hi: 0x11d45, Stride: 1}, + {Lo: 0x11d47, Hi: 0x11d90, Stride: 73}, + {Lo: 0x11d91, Hi: 0x11d95, Stride: 4}, + {Lo: 0x11d97, Hi: 0x11ef3, Stride: 348}, + {Lo: 0x11ef4, Hi: 0x11f00, Stride: 12}, + {Lo: 0x11f01, Hi: 0x11f36, Stride: 53}, + {Lo: 0x11f37, Hi: 0x11f3a, Stride: 1}, + {Lo: 0x11f40, Hi: 0x11f42, Stride: 2}, + {Lo: 0x13440, Hi: 0x13447, Stride: 7}, + {Lo: 0x13448, Hi: 0x13455, Stride: 1}, + {Lo: 0x16af0, Hi: 0x16af4, Stride: 1}, + {Lo: 0x16b30, Hi: 0x16b36, Stride: 1}, + {Lo: 0x16f4f, Hi: 0x16f8f, Stride: 64}, + {Lo: 0x16f90, Hi: 0x16f92, Stride: 1}, + {Lo: 0x16fe4, Hi: 0x1bc9d, Stride: 19641}, + {Lo: 0x1bc9e, Hi: 0x1cf00, Stride: 4706}, + {Lo: 0x1cf01, Hi: 0x1cf2d, Stride: 1}, + {Lo: 0x1cf30, Hi: 0x1cf46, Stride: 1}, + {Lo: 0x1d165, Hi: 0x1d167, Stride: 2}, + {Lo: 0x1d168, Hi: 0x1d169, Stride: 1}, + {Lo: 0x1d16e, Hi: 0x1d172, Stride: 1}, + {Lo: 0x1d17b, Hi: 0x1d182, Stride: 1}, + {Lo: 0x1d185, Hi: 0x1d18b, Stride: 1}, + {Lo: 0x1d1aa, Hi: 0x1d1ad, Stride: 1}, + {Lo: 0x1d242, Hi: 0x1d244, Stride: 1}, + {Lo: 0x1da00, Hi: 0x1da36, Stride: 1}, + {Lo: 0x1da3b, Hi: 0x1da6c, Stride: 1}, + {Lo: 0x1da75, Hi: 0x1da84, Stride: 15}, + {Lo: 0x1da9b, Hi: 0x1da9f, Stride: 1}, + {Lo: 0x1daa1, Hi: 0x1daaf, Stride: 1}, + {Lo: 0x1e000, Hi: 0x1e006, Stride: 1}, + {Lo: 0x1e008, Hi: 0x1e018, Stride: 1}, + {Lo: 0x1e01b, Hi: 0x1e021, Stride: 1}, + {Lo: 0x1e023, Hi: 0x1e024, Stride: 1}, + {Lo: 0x1e026, Hi: 0x1e02a, Stride: 1}, + {Lo: 0x1e08f, Hi: 0x1e130, Stride: 161}, + {Lo: 0x1e131, Hi: 0x1e136, Stride: 1}, + {Lo: 0x1e2ae, Hi: 0x1e2ec, Stride: 62}, + {Lo: 0x1e2ed, Hi: 0x1e2ef, Stride: 1}, + {Lo: 0x1e4ec, Hi: 0x1e4ef, Stride: 1}, + {Lo: 0x1e8d0, Hi: 0x1e8d6, Stride: 1}, + {Lo: 0x1e944, Hi: 0x1e94a, Stride: 1}, + {Lo: 0x1f3fb, Hi: 0x1f3ff, Stride: 1}, + {Lo: 0xe0020, Hi: 0xe007f, Stride: 1}, + {Lo: 0xe0100, Hi: 0xe01ef, Stride: 1}, + }, +} + +// GraphemeBreakProperty: L +var GraphemeBreakL = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x1100, Hi: 0x115f, Stride: 1}, + {Lo: 0xa960, Hi: 0xa97c, Stride: 1}, + }, +} + +// GraphemeBreakProperty: LF +var GraphemeBreakLF = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x000a, Hi: 0x000a, Stride: 1}, + }, + LatinOffset: 1, +} + +// GraphemeBreakProperty: LV +var GraphemeBreakLV = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0xac00, Hi: 0xd788, Stride: 28}, + }, +} + +// GraphemeBreakProperty: LVT +var GraphemeBreakLVT = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0xac01, Hi: 0xac1b, Stride: 1}, + {Lo: 0xac1d, Hi: 0xac37, Stride: 1}, + {Lo: 0xac39, Hi: 0xac53, Stride: 1}, + {Lo: 0xac55, Hi: 0xac6f, Stride: 1}, + {Lo: 0xac71, Hi: 0xac8b, Stride: 1}, + {Lo: 0xac8d, Hi: 0xaca7, Stride: 1}, + {Lo: 0xaca9, Hi: 0xacc3, Stride: 1}, + {Lo: 0xacc5, Hi: 0xacdf, Stride: 1}, + {Lo: 0xace1, Hi: 0xacfb, Stride: 1}, + {Lo: 0xacfd, Hi: 0xad17, Stride: 1}, + {Lo: 0xad19, Hi: 0xad33, Stride: 1}, + {Lo: 0xad35, Hi: 0xad4f, Stride: 1}, + {Lo: 0xad51, Hi: 0xad6b, Stride: 1}, + {Lo: 0xad6d, Hi: 0xad87, Stride: 1}, + {Lo: 0xad89, Hi: 0xada3, Stride: 1}, + {Lo: 0xada5, Hi: 0xadbf, Stride: 1}, + {Lo: 0xadc1, Hi: 0xaddb, Stride: 1}, + {Lo: 0xaddd, Hi: 0xadf7, Stride: 1}, + {Lo: 0xadf9, Hi: 0xae13, Stride: 1}, + {Lo: 0xae15, Hi: 0xae2f, Stride: 1}, + {Lo: 0xae31, Hi: 0xae4b, Stride: 1}, + {Lo: 0xae4d, Hi: 0xae67, Stride: 1}, + {Lo: 0xae69, Hi: 0xae83, Stride: 1}, + {Lo: 0xae85, Hi: 0xae9f, Stride: 1}, + {Lo: 0xaea1, Hi: 0xaebb, Stride: 1}, + {Lo: 0xaebd, Hi: 0xaed7, Stride: 1}, + {Lo: 0xaed9, Hi: 0xaef3, Stride: 1}, + {Lo: 0xaef5, Hi: 0xaf0f, Stride: 1}, + {Lo: 0xaf11, Hi: 0xaf2b, Stride: 1}, + {Lo: 0xaf2d, Hi: 0xaf47, Stride: 1}, + {Lo: 0xaf49, Hi: 0xaf63, Stride: 1}, + {Lo: 0xaf65, Hi: 0xaf7f, Stride: 1}, + {Lo: 0xaf81, Hi: 0xaf9b, Stride: 1}, + {Lo: 0xaf9d, Hi: 0xafb7, Stride: 1}, + {Lo: 0xafb9, Hi: 0xafd3, Stride: 1}, + {Lo: 0xafd5, Hi: 0xafef, Stride: 1}, + {Lo: 0xaff1, Hi: 0xb00b, Stride: 1}, + {Lo: 0xb00d, Hi: 0xb027, Stride: 1}, + {Lo: 0xb029, Hi: 0xb043, Stride: 1}, + {Lo: 0xb045, Hi: 0xb05f, Stride: 1}, + {Lo: 0xb061, Hi: 0xb07b, Stride: 1}, + {Lo: 0xb07d, Hi: 0xb097, Stride: 1}, + {Lo: 0xb099, Hi: 0xb0b3, Stride: 1}, + {Lo: 0xb0b5, Hi: 0xb0cf, Stride: 1}, + {Lo: 0xb0d1, Hi: 0xb0eb, Stride: 1}, + {Lo: 0xb0ed, Hi: 0xb107, Stride: 1}, + {Lo: 0xb109, Hi: 0xb123, Stride: 1}, + {Lo: 0xb125, Hi: 0xb13f, Stride: 1}, + {Lo: 0xb141, Hi: 0xb15b, Stride: 1}, + {Lo: 0xb15d, Hi: 0xb177, Stride: 1}, + {Lo: 0xb179, Hi: 0xb193, Stride: 1}, + {Lo: 0xb195, Hi: 0xb1af, Stride: 1}, + {Lo: 0xb1b1, Hi: 0xb1cb, Stride: 1}, + {Lo: 0xb1cd, Hi: 0xb1e7, Stride: 1}, + {Lo: 0xb1e9, Hi: 0xb203, Stride: 1}, + {Lo: 0xb205, Hi: 0xb21f, Stride: 1}, + {Lo: 0xb221, Hi: 0xb23b, Stride: 1}, + {Lo: 0xb23d, Hi: 0xb257, Stride: 1}, + {Lo: 0xb259, Hi: 0xb273, Stride: 1}, + {Lo: 0xb275, Hi: 0xb28f, Stride: 1}, + {Lo: 0xb291, Hi: 0xb2ab, Stride: 1}, + {Lo: 0xb2ad, Hi: 0xb2c7, Stride: 1}, + {Lo: 0xb2c9, Hi: 0xb2e3, Stride: 1}, + {Lo: 0xb2e5, Hi: 0xb2ff, Stride: 1}, + {Lo: 0xb301, Hi: 0xb31b, Stride: 1}, + {Lo: 0xb31d, Hi: 0xb337, Stride: 1}, + {Lo: 0xb339, Hi: 0xb353, Stride: 1}, + {Lo: 0xb355, Hi: 0xb36f, Stride: 1}, + {Lo: 0xb371, Hi: 0xb38b, Stride: 1}, + {Lo: 0xb38d, Hi: 0xb3a7, Stride: 1}, + {Lo: 0xb3a9, Hi: 0xb3c3, Stride: 1}, + {Lo: 0xb3c5, Hi: 0xb3df, Stride: 1}, + {Lo: 0xb3e1, Hi: 0xb3fb, Stride: 1}, + {Lo: 0xb3fd, Hi: 0xb417, Stride: 1}, + {Lo: 0xb419, Hi: 0xb433, Stride: 1}, + {Lo: 0xb435, Hi: 0xb44f, Stride: 1}, + {Lo: 0xb451, Hi: 0xb46b, Stride: 1}, + {Lo: 0xb46d, Hi: 0xb487, Stride: 1}, + {Lo: 0xb489, Hi: 0xb4a3, Stride: 1}, + {Lo: 0xb4a5, Hi: 0xb4bf, Stride: 1}, + {Lo: 0xb4c1, Hi: 0xb4db, Stride: 1}, + {Lo: 0xb4dd, Hi: 0xb4f7, Stride: 1}, + {Lo: 0xb4f9, Hi: 0xb513, Stride: 1}, + {Lo: 0xb515, Hi: 0xb52f, Stride: 1}, + {Lo: 0xb531, Hi: 0xb54b, Stride: 1}, + {Lo: 0xb54d, Hi: 0xb567, Stride: 1}, + {Lo: 0xb569, Hi: 0xb583, Stride: 1}, + {Lo: 0xb585, Hi: 0xb59f, Stride: 1}, + {Lo: 0xb5a1, Hi: 0xb5bb, Stride: 1}, + {Lo: 0xb5bd, Hi: 0xb5d7, Stride: 1}, + {Lo: 0xb5d9, Hi: 0xb5f3, Stride: 1}, + {Lo: 0xb5f5, Hi: 0xb60f, Stride: 1}, + {Lo: 0xb611, Hi: 0xb62b, Stride: 1}, + {Lo: 0xb62d, Hi: 0xb647, Stride: 1}, + {Lo: 0xb649, Hi: 0xb663, Stride: 1}, + {Lo: 0xb665, Hi: 0xb67f, Stride: 1}, + {Lo: 0xb681, Hi: 0xb69b, Stride: 1}, + {Lo: 0xb69d, Hi: 0xb6b7, Stride: 1}, + {Lo: 0xb6b9, Hi: 0xb6d3, Stride: 1}, + {Lo: 0xb6d5, Hi: 0xb6ef, Stride: 1}, + {Lo: 0xb6f1, Hi: 0xb70b, Stride: 1}, + {Lo: 0xb70d, Hi: 0xb727, Stride: 1}, + {Lo: 0xb729, Hi: 0xb743, Stride: 1}, + {Lo: 0xb745, Hi: 0xb75f, Stride: 1}, + {Lo: 0xb761, Hi: 0xb77b, Stride: 1}, + {Lo: 0xb77d, Hi: 0xb797, Stride: 1}, + {Lo: 0xb799, Hi: 0xb7b3, Stride: 1}, + {Lo: 0xb7b5, Hi: 0xb7cf, Stride: 1}, + {Lo: 0xb7d1, Hi: 0xb7eb, Stride: 1}, + {Lo: 0xb7ed, Hi: 0xb807, Stride: 1}, + {Lo: 0xb809, Hi: 0xb823, Stride: 1}, + {Lo: 0xb825, Hi: 0xb83f, Stride: 1}, + {Lo: 0xb841, Hi: 0xb85b, Stride: 1}, + {Lo: 0xb85d, Hi: 0xb877, Stride: 1}, + {Lo: 0xb879, Hi: 0xb893, Stride: 1}, + {Lo: 0xb895, Hi: 0xb8af, Stride: 1}, + {Lo: 0xb8b1, Hi: 0xb8cb, Stride: 1}, + {Lo: 0xb8cd, Hi: 0xb8e7, Stride: 1}, + {Lo: 0xb8e9, Hi: 0xb903, Stride: 1}, + {Lo: 0xb905, Hi: 0xb91f, Stride: 1}, + {Lo: 0xb921, Hi: 0xb93b, Stride: 1}, + {Lo: 0xb93d, Hi: 0xb957, Stride: 1}, + {Lo: 0xb959, Hi: 0xb973, Stride: 1}, + {Lo: 0xb975, Hi: 0xb98f, Stride: 1}, + {Lo: 0xb991, Hi: 0xb9ab, Stride: 1}, + {Lo: 0xb9ad, Hi: 0xb9c7, Stride: 1}, + {Lo: 0xb9c9, Hi: 0xb9e3, Stride: 1}, + {Lo: 0xb9e5, Hi: 0xb9ff, Stride: 1}, + {Lo: 0xba01, Hi: 0xba1b, Stride: 1}, + {Lo: 0xba1d, Hi: 0xba37, Stride: 1}, + {Lo: 0xba39, Hi: 0xba53, Stride: 1}, + {Lo: 0xba55, Hi: 0xba6f, Stride: 1}, + {Lo: 0xba71, Hi: 0xba8b, Stride: 1}, + {Lo: 0xba8d, Hi: 0xbaa7, Stride: 1}, + {Lo: 0xbaa9, Hi: 0xbac3, Stride: 1}, + {Lo: 0xbac5, Hi: 0xbadf, Stride: 1}, + {Lo: 0xbae1, Hi: 0xbafb, Stride: 1}, + {Lo: 0xbafd, Hi: 0xbb17, Stride: 1}, + {Lo: 0xbb19, Hi: 0xbb33, Stride: 1}, + {Lo: 0xbb35, Hi: 0xbb4f, Stride: 1}, + {Lo: 0xbb51, Hi: 0xbb6b, Stride: 1}, + {Lo: 0xbb6d, Hi: 0xbb87, Stride: 1}, + {Lo: 0xbb89, Hi: 0xbba3, Stride: 1}, + {Lo: 0xbba5, Hi: 0xbbbf, Stride: 1}, + {Lo: 0xbbc1, Hi: 0xbbdb, Stride: 1}, + {Lo: 0xbbdd, Hi: 0xbbf7, Stride: 1}, + {Lo: 0xbbf9, Hi: 0xbc13, Stride: 1}, + {Lo: 0xbc15, Hi: 0xbc2f, Stride: 1}, + {Lo: 0xbc31, Hi: 0xbc4b, Stride: 1}, + {Lo: 0xbc4d, Hi: 0xbc67, Stride: 1}, + {Lo: 0xbc69, Hi: 0xbc83, Stride: 1}, + {Lo: 0xbc85, Hi: 0xbc9f, Stride: 1}, + {Lo: 0xbca1, Hi: 0xbcbb, Stride: 1}, + {Lo: 0xbcbd, Hi: 0xbcd7, Stride: 1}, + {Lo: 0xbcd9, Hi: 0xbcf3, Stride: 1}, + {Lo: 0xbcf5, Hi: 0xbd0f, Stride: 1}, + {Lo: 0xbd11, Hi: 0xbd2b, Stride: 1}, + {Lo: 0xbd2d, Hi: 0xbd47, Stride: 1}, + {Lo: 0xbd49, Hi: 0xbd63, Stride: 1}, + {Lo: 0xbd65, Hi: 0xbd7f, Stride: 1}, + {Lo: 0xbd81, Hi: 0xbd9b, Stride: 1}, + {Lo: 0xbd9d, Hi: 0xbdb7, Stride: 1}, + {Lo: 0xbdb9, Hi: 0xbdd3, Stride: 1}, + {Lo: 0xbdd5, Hi: 0xbdef, Stride: 1}, + {Lo: 0xbdf1, Hi: 0xbe0b, Stride: 1}, + {Lo: 0xbe0d, Hi: 0xbe27, Stride: 1}, + {Lo: 0xbe29, Hi: 0xbe43, Stride: 1}, + {Lo: 0xbe45, Hi: 0xbe5f, Stride: 1}, + {Lo: 0xbe61, Hi: 0xbe7b, Stride: 1}, + {Lo: 0xbe7d, Hi: 0xbe97, Stride: 1}, + {Lo: 0xbe99, Hi: 0xbeb3, Stride: 1}, + {Lo: 0xbeb5, Hi: 0xbecf, Stride: 1}, + {Lo: 0xbed1, Hi: 0xbeeb, Stride: 1}, + {Lo: 0xbeed, Hi: 0xbf07, Stride: 1}, + {Lo: 0xbf09, Hi: 0xbf23, Stride: 1}, + {Lo: 0xbf25, Hi: 0xbf3f, Stride: 1}, + {Lo: 0xbf41, Hi: 0xbf5b, Stride: 1}, + {Lo: 0xbf5d, Hi: 0xbf77, Stride: 1}, + {Lo: 0xbf79, Hi: 0xbf93, Stride: 1}, + {Lo: 0xbf95, Hi: 0xbfaf, Stride: 1}, + {Lo: 0xbfb1, Hi: 0xbfcb, Stride: 1}, + {Lo: 0xbfcd, Hi: 0xbfe7, Stride: 1}, + {Lo: 0xbfe9, Hi: 0xc003, Stride: 1}, + {Lo: 0xc005, Hi: 0xc01f, Stride: 1}, + {Lo: 0xc021, Hi: 0xc03b, Stride: 1}, + {Lo: 0xc03d, Hi: 0xc057, Stride: 1}, + {Lo: 0xc059, Hi: 0xc073, Stride: 1}, + {Lo: 0xc075, Hi: 0xc08f, Stride: 1}, + {Lo: 0xc091, Hi: 0xc0ab, Stride: 1}, + {Lo: 0xc0ad, Hi: 0xc0c7, Stride: 1}, + {Lo: 0xc0c9, Hi: 0xc0e3, Stride: 1}, + {Lo: 0xc0e5, Hi: 0xc0ff, Stride: 1}, + {Lo: 0xc101, Hi: 0xc11b, Stride: 1}, + {Lo: 0xc11d, Hi: 0xc137, Stride: 1}, + {Lo: 0xc139, Hi: 0xc153, Stride: 1}, + {Lo: 0xc155, Hi: 0xc16f, Stride: 1}, + {Lo: 0xc171, Hi: 0xc18b, Stride: 1}, + {Lo: 0xc18d, Hi: 0xc1a7, Stride: 1}, + {Lo: 0xc1a9, Hi: 0xc1c3, Stride: 1}, + {Lo: 0xc1c5, Hi: 0xc1df, Stride: 1}, + {Lo: 0xc1e1, Hi: 0xc1fb, Stride: 1}, + {Lo: 0xc1fd, Hi: 0xc217, Stride: 1}, + {Lo: 0xc219, Hi: 0xc233, Stride: 1}, + {Lo: 0xc235, Hi: 0xc24f, Stride: 1}, + {Lo: 0xc251, Hi: 0xc26b, Stride: 1}, + {Lo: 0xc26d, Hi: 0xc287, Stride: 1}, + {Lo: 0xc289, Hi: 0xc2a3, Stride: 1}, + {Lo: 0xc2a5, Hi: 0xc2bf, Stride: 1}, + {Lo: 0xc2c1, Hi: 0xc2db, Stride: 1}, + {Lo: 0xc2dd, Hi: 0xc2f7, Stride: 1}, + {Lo: 0xc2f9, Hi: 0xc313, Stride: 1}, + {Lo: 0xc315, Hi: 0xc32f, Stride: 1}, + {Lo: 0xc331, Hi: 0xc34b, Stride: 1}, + {Lo: 0xc34d, Hi: 0xc367, Stride: 1}, + {Lo: 0xc369, Hi: 0xc383, Stride: 1}, + {Lo: 0xc385, Hi: 0xc39f, Stride: 1}, + {Lo: 0xc3a1, Hi: 0xc3bb, Stride: 1}, + {Lo: 0xc3bd, Hi: 0xc3d7, Stride: 1}, + {Lo: 0xc3d9, Hi: 0xc3f3, Stride: 1}, + {Lo: 0xc3f5, Hi: 0xc40f, Stride: 1}, + {Lo: 0xc411, Hi: 0xc42b, Stride: 1}, + {Lo: 0xc42d, Hi: 0xc447, Stride: 1}, + {Lo: 0xc449, Hi: 0xc463, Stride: 1}, + {Lo: 0xc465, Hi: 0xc47f, Stride: 1}, + {Lo: 0xc481, Hi: 0xc49b, Stride: 1}, + {Lo: 0xc49d, Hi: 0xc4b7, Stride: 1}, + {Lo: 0xc4b9, Hi: 0xc4d3, Stride: 1}, + {Lo: 0xc4d5, Hi: 0xc4ef, Stride: 1}, + {Lo: 0xc4f1, Hi: 0xc50b, Stride: 1}, + {Lo: 0xc50d, Hi: 0xc527, Stride: 1}, + {Lo: 0xc529, Hi: 0xc543, Stride: 1}, + {Lo: 0xc545, Hi: 0xc55f, Stride: 1}, + {Lo: 0xc561, Hi: 0xc57b, Stride: 1}, + {Lo: 0xc57d, Hi: 0xc597, Stride: 1}, + {Lo: 0xc599, Hi: 0xc5b3, Stride: 1}, + {Lo: 0xc5b5, Hi: 0xc5cf, Stride: 1}, + {Lo: 0xc5d1, Hi: 0xc5eb, Stride: 1}, + {Lo: 0xc5ed, Hi: 0xc607, Stride: 1}, + {Lo: 0xc609, Hi: 0xc623, Stride: 1}, + {Lo: 0xc625, Hi: 0xc63f, Stride: 1}, + {Lo: 0xc641, Hi: 0xc65b, Stride: 1}, + {Lo: 0xc65d, Hi: 0xc677, Stride: 1}, + {Lo: 0xc679, Hi: 0xc693, Stride: 1}, + {Lo: 0xc695, Hi: 0xc6af, Stride: 1}, + {Lo: 0xc6b1, Hi: 0xc6cb, Stride: 1}, + {Lo: 0xc6cd, Hi: 0xc6e7, Stride: 1}, + {Lo: 0xc6e9, Hi: 0xc703, Stride: 1}, + {Lo: 0xc705, Hi: 0xc71f, Stride: 1}, + {Lo: 0xc721, Hi: 0xc73b, Stride: 1}, + {Lo: 0xc73d, Hi: 0xc757, Stride: 1}, + {Lo: 0xc759, Hi: 0xc773, Stride: 1}, + {Lo: 0xc775, Hi: 0xc78f, Stride: 1}, + {Lo: 0xc791, Hi: 0xc7ab, Stride: 1}, + {Lo: 0xc7ad, Hi: 0xc7c7, Stride: 1}, + {Lo: 0xc7c9, Hi: 0xc7e3, Stride: 1}, + {Lo: 0xc7e5, Hi: 0xc7ff, Stride: 1}, + {Lo: 0xc801, Hi: 0xc81b, Stride: 1}, + {Lo: 0xc81d, Hi: 0xc837, Stride: 1}, + {Lo: 0xc839, Hi: 0xc853, Stride: 1}, + {Lo: 0xc855, Hi: 0xc86f, Stride: 1}, + {Lo: 0xc871, Hi: 0xc88b, Stride: 1}, + {Lo: 0xc88d, Hi: 0xc8a7, Stride: 1}, + {Lo: 0xc8a9, Hi: 0xc8c3, Stride: 1}, + {Lo: 0xc8c5, Hi: 0xc8df, Stride: 1}, + {Lo: 0xc8e1, Hi: 0xc8fb, Stride: 1}, + {Lo: 0xc8fd, Hi: 0xc917, Stride: 1}, + {Lo: 0xc919, Hi: 0xc933, Stride: 1}, + {Lo: 0xc935, Hi: 0xc94f, Stride: 1}, + {Lo: 0xc951, Hi: 0xc96b, Stride: 1}, + {Lo: 0xc96d, Hi: 0xc987, Stride: 1}, + {Lo: 0xc989, Hi: 0xc9a3, Stride: 1}, + {Lo: 0xc9a5, Hi: 0xc9bf, Stride: 1}, + {Lo: 0xc9c1, Hi: 0xc9db, Stride: 1}, + {Lo: 0xc9dd, Hi: 0xc9f7, Stride: 1}, + {Lo: 0xc9f9, Hi: 0xca13, Stride: 1}, + {Lo: 0xca15, Hi: 0xca2f, Stride: 1}, + {Lo: 0xca31, Hi: 0xca4b, Stride: 1}, + {Lo: 0xca4d, Hi: 0xca67, Stride: 1}, + {Lo: 0xca69, Hi: 0xca83, Stride: 1}, + {Lo: 0xca85, Hi: 0xca9f, Stride: 1}, + {Lo: 0xcaa1, Hi: 0xcabb, Stride: 1}, + {Lo: 0xcabd, Hi: 0xcad7, Stride: 1}, + {Lo: 0xcad9, Hi: 0xcaf3, Stride: 1}, + {Lo: 0xcaf5, Hi: 0xcb0f, Stride: 1}, + {Lo: 0xcb11, Hi: 0xcb2b, Stride: 1}, + {Lo: 0xcb2d, Hi: 0xcb47, Stride: 1}, + {Lo: 0xcb49, Hi: 0xcb63, Stride: 1}, + {Lo: 0xcb65, Hi: 0xcb7f, Stride: 1}, + {Lo: 0xcb81, Hi: 0xcb9b, Stride: 1}, + {Lo: 0xcb9d, Hi: 0xcbb7, Stride: 1}, + {Lo: 0xcbb9, Hi: 0xcbd3, Stride: 1}, + {Lo: 0xcbd5, Hi: 0xcbef, Stride: 1}, + {Lo: 0xcbf1, Hi: 0xcc0b, Stride: 1}, + {Lo: 0xcc0d, Hi: 0xcc27, Stride: 1}, + {Lo: 0xcc29, Hi: 0xcc43, Stride: 1}, + {Lo: 0xcc45, Hi: 0xcc5f, Stride: 1}, + {Lo: 0xcc61, Hi: 0xcc7b, Stride: 1}, + {Lo: 0xcc7d, Hi: 0xcc97, Stride: 1}, + {Lo: 0xcc99, Hi: 0xccb3, Stride: 1}, + {Lo: 0xccb5, Hi: 0xcccf, Stride: 1}, + {Lo: 0xccd1, Hi: 0xcceb, Stride: 1}, + {Lo: 0xcced, Hi: 0xcd07, Stride: 1}, + {Lo: 0xcd09, Hi: 0xcd23, Stride: 1}, + {Lo: 0xcd25, Hi: 0xcd3f, Stride: 1}, + {Lo: 0xcd41, Hi: 0xcd5b, Stride: 1}, + {Lo: 0xcd5d, Hi: 0xcd77, Stride: 1}, + {Lo: 0xcd79, Hi: 0xcd93, Stride: 1}, + {Lo: 0xcd95, Hi: 0xcdaf, Stride: 1}, + {Lo: 0xcdb1, Hi: 0xcdcb, Stride: 1}, + {Lo: 0xcdcd, Hi: 0xcde7, Stride: 1}, + {Lo: 0xcde9, Hi: 0xce03, Stride: 1}, + {Lo: 0xce05, Hi: 0xce1f, Stride: 1}, + {Lo: 0xce21, Hi: 0xce3b, Stride: 1}, + {Lo: 0xce3d, Hi: 0xce57, Stride: 1}, + {Lo: 0xce59, Hi: 0xce73, Stride: 1}, + {Lo: 0xce75, Hi: 0xce8f, Stride: 1}, + {Lo: 0xce91, Hi: 0xceab, Stride: 1}, + {Lo: 0xcead, Hi: 0xcec7, Stride: 1}, + {Lo: 0xcec9, Hi: 0xcee3, Stride: 1}, + {Lo: 0xcee5, Hi: 0xceff, Stride: 1}, + {Lo: 0xcf01, Hi: 0xcf1b, Stride: 1}, + {Lo: 0xcf1d, Hi: 0xcf37, Stride: 1}, + {Lo: 0xcf39, Hi: 0xcf53, Stride: 1}, + {Lo: 0xcf55, Hi: 0xcf6f, Stride: 1}, + {Lo: 0xcf71, Hi: 0xcf8b, Stride: 1}, + {Lo: 0xcf8d, Hi: 0xcfa7, Stride: 1}, + {Lo: 0xcfa9, Hi: 0xcfc3, Stride: 1}, + {Lo: 0xcfc5, Hi: 0xcfdf, Stride: 1}, + {Lo: 0xcfe1, Hi: 0xcffb, Stride: 1}, + {Lo: 0xcffd, Hi: 0xd017, Stride: 1}, + {Lo: 0xd019, Hi: 0xd033, Stride: 1}, + {Lo: 0xd035, Hi: 0xd04f, Stride: 1}, + {Lo: 0xd051, Hi: 0xd06b, Stride: 1}, + {Lo: 0xd06d, Hi: 0xd087, Stride: 1}, + {Lo: 0xd089, Hi: 0xd0a3, Stride: 1}, + {Lo: 0xd0a5, Hi: 0xd0bf, Stride: 1}, + {Lo: 0xd0c1, Hi: 0xd0db, Stride: 1}, + {Lo: 0xd0dd, Hi: 0xd0f7, Stride: 1}, + {Lo: 0xd0f9, Hi: 0xd113, Stride: 1}, + {Lo: 0xd115, Hi: 0xd12f, Stride: 1}, + {Lo: 0xd131, Hi: 0xd14b, Stride: 1}, + {Lo: 0xd14d, Hi: 0xd167, Stride: 1}, + {Lo: 0xd169, Hi: 0xd183, Stride: 1}, + {Lo: 0xd185, Hi: 0xd19f, Stride: 1}, + {Lo: 0xd1a1, Hi: 0xd1bb, Stride: 1}, + {Lo: 0xd1bd, Hi: 0xd1d7, Stride: 1}, + {Lo: 0xd1d9, Hi: 0xd1f3, Stride: 1}, + {Lo: 0xd1f5, Hi: 0xd20f, Stride: 1}, + {Lo: 0xd211, Hi: 0xd22b, Stride: 1}, + {Lo: 0xd22d, Hi: 0xd247, Stride: 1}, + {Lo: 0xd249, Hi: 0xd263, Stride: 1}, + {Lo: 0xd265, Hi: 0xd27f, Stride: 1}, + {Lo: 0xd281, Hi: 0xd29b, Stride: 1}, + {Lo: 0xd29d, Hi: 0xd2b7, Stride: 1}, + {Lo: 0xd2b9, Hi: 0xd2d3, Stride: 1}, + {Lo: 0xd2d5, Hi: 0xd2ef, Stride: 1}, + {Lo: 0xd2f1, Hi: 0xd30b, Stride: 1}, + {Lo: 0xd30d, Hi: 0xd327, Stride: 1}, + {Lo: 0xd329, Hi: 0xd343, Stride: 1}, + {Lo: 0xd345, Hi: 0xd35f, Stride: 1}, + {Lo: 0xd361, Hi: 0xd37b, Stride: 1}, + {Lo: 0xd37d, Hi: 0xd397, Stride: 1}, + {Lo: 0xd399, Hi: 0xd3b3, Stride: 1}, + {Lo: 0xd3b5, Hi: 0xd3cf, Stride: 1}, + {Lo: 0xd3d1, Hi: 0xd3eb, Stride: 1}, + {Lo: 0xd3ed, Hi: 0xd407, Stride: 1}, + {Lo: 0xd409, Hi: 0xd423, Stride: 1}, + {Lo: 0xd425, Hi: 0xd43f, Stride: 1}, + {Lo: 0xd441, Hi: 0xd45b, Stride: 1}, + {Lo: 0xd45d, Hi: 0xd477, Stride: 1}, + {Lo: 0xd479, Hi: 0xd493, Stride: 1}, + {Lo: 0xd495, Hi: 0xd4af, Stride: 1}, + {Lo: 0xd4b1, Hi: 0xd4cb, Stride: 1}, + {Lo: 0xd4cd, Hi: 0xd4e7, Stride: 1}, + {Lo: 0xd4e9, Hi: 0xd503, Stride: 1}, + {Lo: 0xd505, Hi: 0xd51f, Stride: 1}, + {Lo: 0xd521, Hi: 0xd53b, Stride: 1}, + {Lo: 0xd53d, Hi: 0xd557, Stride: 1}, + {Lo: 0xd559, Hi: 0xd573, Stride: 1}, + {Lo: 0xd575, Hi: 0xd58f, Stride: 1}, + {Lo: 0xd591, Hi: 0xd5ab, Stride: 1}, + {Lo: 0xd5ad, Hi: 0xd5c7, Stride: 1}, + {Lo: 0xd5c9, Hi: 0xd5e3, Stride: 1}, + {Lo: 0xd5e5, Hi: 0xd5ff, Stride: 1}, + {Lo: 0xd601, Hi: 0xd61b, Stride: 1}, + {Lo: 0xd61d, Hi: 0xd637, Stride: 1}, + {Lo: 0xd639, Hi: 0xd653, Stride: 1}, + {Lo: 0xd655, Hi: 0xd66f, Stride: 1}, + {Lo: 0xd671, Hi: 0xd68b, Stride: 1}, + {Lo: 0xd68d, Hi: 0xd6a7, Stride: 1}, + {Lo: 0xd6a9, Hi: 0xd6c3, Stride: 1}, + {Lo: 0xd6c5, Hi: 0xd6df, Stride: 1}, + {Lo: 0xd6e1, Hi: 0xd6fb, Stride: 1}, + {Lo: 0xd6fd, Hi: 0xd717, Stride: 1}, + {Lo: 0xd719, Hi: 0xd733, Stride: 1}, + {Lo: 0xd735, Hi: 0xd74f, Stride: 1}, + {Lo: 0xd751, Hi: 0xd76b, Stride: 1}, + {Lo: 0xd76d, Hi: 0xd787, Stride: 1}, + {Lo: 0xd789, Hi: 0xd7a3, Stride: 1}, + }, +} + +// GraphemeBreakProperty: Prepend +var GraphemeBreakPrepend = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0600, Hi: 0x0605, Stride: 1}, + {Lo: 0x06dd, Hi: 0x070f, Stride: 50}, + {Lo: 0x0890, Hi: 0x0891, Stride: 1}, + {Lo: 0x08e2, Hi: 0x0d4e, Stride: 1132}, + }, + R32: []unicode.Range32{ + {Lo: 0x110bd, Hi: 0x110cd, Stride: 16}, + {Lo: 0x111c2, Hi: 0x111c3, Stride: 1}, + {Lo: 0x1193f, Hi: 0x11941, Stride: 2}, + {Lo: 0x11a3a, Hi: 0x11a84, Stride: 74}, + {Lo: 0x11a85, Hi: 0x11a89, Stride: 1}, + {Lo: 0x11d46, Hi: 0x11f02, Stride: 444}, + }, +} + +// GraphemeBreakProperty: Regional_Indicator +var GraphemeBreakRegional_Indicator = &unicode.RangeTable{ + R32: []unicode.Range32{ + {Lo: 0x1f1e6, Hi: 0x1f1ff, Stride: 1}, + }, +} + +// GraphemeBreakProperty: SpacingMark +var GraphemeBreakSpacingMark = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0903, Hi: 0x093b, Stride: 56}, + {Lo: 0x093e, Hi: 0x0940, Stride: 1}, + {Lo: 0x0949, Hi: 0x094c, Stride: 1}, + {Lo: 0x094e, Hi: 0x094f, Stride: 1}, + {Lo: 0x0982, Hi: 0x0983, Stride: 1}, + {Lo: 0x09bf, Hi: 0x09c0, Stride: 1}, + {Lo: 0x09c7, Hi: 0x09c8, Stride: 1}, + {Lo: 0x09cb, Hi: 0x09cc, Stride: 1}, + {Lo: 0x0a03, Hi: 0x0a3e, Stride: 59}, + {Lo: 0x0a3f, Hi: 0x0a40, Stride: 1}, + {Lo: 0x0a83, Hi: 0x0abe, Stride: 59}, + {Lo: 0x0abf, Hi: 0x0ac0, Stride: 1}, + {Lo: 0x0ac9, Hi: 0x0acb, Stride: 2}, + {Lo: 0x0acc, Hi: 0x0b02, Stride: 54}, + {Lo: 0x0b03, Hi: 0x0b40, Stride: 61}, + {Lo: 0x0b47, Hi: 0x0b48, Stride: 1}, + {Lo: 0x0b4b, Hi: 0x0b4c, Stride: 1}, + {Lo: 0x0bbf, Hi: 0x0bc1, Stride: 2}, + {Lo: 0x0bc2, Hi: 0x0bc6, Stride: 4}, + {Lo: 0x0bc7, Hi: 0x0bc8, Stride: 1}, + {Lo: 0x0bca, Hi: 0x0bcc, Stride: 1}, + {Lo: 0x0c01, Hi: 0x0c03, Stride: 1}, + {Lo: 0x0c41, Hi: 0x0c44, Stride: 1}, + {Lo: 0x0c82, Hi: 0x0c83, Stride: 1}, + {Lo: 0x0cbe, Hi: 0x0cc0, Stride: 2}, + {Lo: 0x0cc1, Hi: 0x0cc3, Stride: 2}, + {Lo: 0x0cc4, Hi: 0x0cc7, Stride: 3}, + {Lo: 0x0cc8, Hi: 0x0cca, Stride: 2}, + {Lo: 0x0ccb, Hi: 0x0cf3, Stride: 40}, + {Lo: 0x0d02, Hi: 0x0d03, Stride: 1}, + {Lo: 0x0d3f, Hi: 0x0d40, Stride: 1}, + {Lo: 0x0d46, Hi: 0x0d48, Stride: 1}, + {Lo: 0x0d4a, Hi: 0x0d4c, Stride: 1}, + {Lo: 0x0d82, Hi: 0x0d83, Stride: 1}, + {Lo: 0x0dd0, Hi: 0x0dd1, Stride: 1}, + {Lo: 0x0dd8, Hi: 0x0dde, Stride: 1}, + {Lo: 0x0df2, Hi: 0x0df3, Stride: 1}, + {Lo: 0x0e33, Hi: 0x0eb3, Stride: 128}, + {Lo: 0x0f3e, Hi: 0x0f3f, Stride: 1}, + {Lo: 0x0f7f, Hi: 0x1031, Stride: 178}, + {Lo: 0x103b, Hi: 0x103c, Stride: 1}, + {Lo: 0x1056, Hi: 0x1057, Stride: 1}, + {Lo: 0x1084, Hi: 0x1715, Stride: 1681}, + {Lo: 0x1734, Hi: 0x17b6, Stride: 130}, + {Lo: 0x17be, Hi: 0x17c5, Stride: 1}, + {Lo: 0x17c7, Hi: 0x17c8, Stride: 1}, + {Lo: 0x1923, Hi: 0x1926, Stride: 1}, + {Lo: 0x1929, Hi: 0x192b, Stride: 1}, + {Lo: 0x1930, Hi: 0x1931, Stride: 1}, + {Lo: 0x1933, Hi: 0x1938, Stride: 1}, + {Lo: 0x1a19, Hi: 0x1a1a, Stride: 1}, + {Lo: 0x1a55, Hi: 0x1a57, Stride: 2}, + {Lo: 0x1a6d, Hi: 0x1a72, Stride: 1}, + {Lo: 0x1b04, Hi: 0x1b3b, Stride: 55}, + {Lo: 0x1b3d, Hi: 0x1b41, Stride: 1}, + {Lo: 0x1b43, Hi: 0x1b44, Stride: 1}, + {Lo: 0x1b82, Hi: 0x1ba1, Stride: 31}, + {Lo: 0x1ba6, Hi: 0x1ba7, Stride: 1}, + {Lo: 0x1baa, Hi: 0x1be7, Stride: 61}, + {Lo: 0x1bea, Hi: 0x1bec, Stride: 1}, + {Lo: 0x1bee, Hi: 0x1bf2, Stride: 4}, + {Lo: 0x1bf3, Hi: 0x1c24, Stride: 49}, + {Lo: 0x1c25, Hi: 0x1c2b, Stride: 1}, + {Lo: 0x1c34, Hi: 0x1c35, Stride: 1}, + {Lo: 0x1ce1, Hi: 0x1cf7, Stride: 22}, + {Lo: 0xa823, Hi: 0xa824, Stride: 1}, + {Lo: 0xa827, Hi: 0xa880, Stride: 89}, + {Lo: 0xa881, Hi: 0xa8b4, Stride: 51}, + {Lo: 0xa8b5, Hi: 0xa8c3, Stride: 1}, + {Lo: 0xa952, Hi: 0xa953, Stride: 1}, + {Lo: 0xa983, Hi: 0xa9b4, Stride: 49}, + {Lo: 0xa9b5, Hi: 0xa9ba, Stride: 5}, + {Lo: 0xa9bb, Hi: 0xa9be, Stride: 3}, + {Lo: 0xa9bf, Hi: 0xa9c0, Stride: 1}, + {Lo: 0xaa2f, Hi: 0xaa30, Stride: 1}, + {Lo: 0xaa33, Hi: 0xaa34, Stride: 1}, + {Lo: 0xaa4d, Hi: 0xaaeb, Stride: 158}, + {Lo: 0xaaee, Hi: 0xaaef, Stride: 1}, + {Lo: 0xaaf5, Hi: 0xabe3, Stride: 238}, + {Lo: 0xabe4, Hi: 0xabe6, Stride: 2}, + {Lo: 0xabe7, Hi: 0xabe9, Stride: 2}, + {Lo: 0xabea, Hi: 0xabec, Stride: 2}, + }, + R32: []unicode.Range32{ + {Lo: 0x11000, Hi: 0x11002, Stride: 2}, + {Lo: 0x11082, Hi: 0x110b0, Stride: 46}, + {Lo: 0x110b1, Hi: 0x110b2, Stride: 1}, + {Lo: 0x110b7, Hi: 0x110b8, Stride: 1}, + {Lo: 0x1112c, Hi: 0x11145, Stride: 25}, + {Lo: 0x11146, Hi: 0x11182, Stride: 60}, + {Lo: 0x111b3, Hi: 0x111b5, Stride: 1}, + {Lo: 0x111bf, Hi: 0x111c0, Stride: 1}, + {Lo: 0x111ce, Hi: 0x1122c, Stride: 94}, + {Lo: 0x1122d, Hi: 0x1122e, Stride: 1}, + {Lo: 0x11232, Hi: 0x11233, Stride: 1}, + {Lo: 0x11235, Hi: 0x112e0, Stride: 171}, + {Lo: 0x112e1, Hi: 0x112e2, Stride: 1}, + {Lo: 0x11302, Hi: 0x11303, Stride: 1}, + {Lo: 0x1133f, Hi: 0x11341, Stride: 2}, + {Lo: 0x11342, Hi: 0x11344, Stride: 1}, + {Lo: 0x11347, Hi: 0x11348, Stride: 1}, + {Lo: 0x1134b, Hi: 0x1134d, Stride: 1}, + {Lo: 0x11362, Hi: 0x11363, Stride: 1}, + {Lo: 0x11435, Hi: 0x11437, Stride: 1}, + {Lo: 0x11440, Hi: 0x11441, Stride: 1}, + {Lo: 0x11445, Hi: 0x114b1, Stride: 108}, + {Lo: 0x114b2, Hi: 0x114b9, Stride: 7}, + {Lo: 0x114bb, Hi: 0x114bc, Stride: 1}, + {Lo: 0x114be, Hi: 0x114c1, Stride: 3}, + {Lo: 0x115b0, Hi: 0x115b1, Stride: 1}, + {Lo: 0x115b8, Hi: 0x115bb, Stride: 1}, + {Lo: 0x115be, Hi: 0x11630, Stride: 114}, + {Lo: 0x11631, Hi: 0x11632, Stride: 1}, + {Lo: 0x1163b, Hi: 0x1163c, Stride: 1}, + {Lo: 0x1163e, Hi: 0x116ac, Stride: 110}, + {Lo: 0x116ae, Hi: 0x116af, Stride: 1}, + {Lo: 0x116b6, Hi: 0x11726, Stride: 112}, + {Lo: 0x1182c, Hi: 0x1182e, Stride: 1}, + {Lo: 0x11838, Hi: 0x11931, Stride: 249}, + {Lo: 0x11932, Hi: 0x11935, Stride: 1}, + {Lo: 0x11937, Hi: 0x11938, Stride: 1}, + {Lo: 0x1193d, Hi: 0x11940, Stride: 3}, + {Lo: 0x11942, Hi: 0x119d1, Stride: 143}, + {Lo: 0x119d2, Hi: 0x119d3, Stride: 1}, + {Lo: 0x119dc, Hi: 0x119df, Stride: 1}, + {Lo: 0x119e4, Hi: 0x11a39, Stride: 85}, + {Lo: 0x11a57, Hi: 0x11a58, Stride: 1}, + {Lo: 0x11a97, Hi: 0x11c2f, Stride: 408}, + {Lo: 0x11c3e, Hi: 0x11ca9, Stride: 107}, + {Lo: 0x11cb1, Hi: 0x11cb4, Stride: 3}, + {Lo: 0x11d8a, Hi: 0x11d8e, Stride: 1}, + {Lo: 0x11d93, Hi: 0x11d94, Stride: 1}, + {Lo: 0x11d96, Hi: 0x11ef5, Stride: 351}, + {Lo: 0x11ef6, Hi: 0x11f03, Stride: 13}, + {Lo: 0x11f34, Hi: 0x11f35, Stride: 1}, + {Lo: 0x11f3e, Hi: 0x11f3f, Stride: 1}, + {Lo: 0x11f41, Hi: 0x16f51, Stride: 20496}, + {Lo: 0x16f52, Hi: 0x16f87, Stride: 1}, + {Lo: 0x16ff0, Hi: 0x16ff1, Stride: 1}, + {Lo: 0x1d166, Hi: 0x1d16d, Stride: 7}, + }, +} + +// GraphemeBreakProperty: T +var GraphemeBreakT = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x11a8, Hi: 0x11ff, Stride: 1}, + {Lo: 0xd7cb, Hi: 0xd7fb, Stride: 1}, + }, +} + +// GraphemeBreakProperty: V +var GraphemeBreakV = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x1160, Hi: 0x11a7, Stride: 1}, + {Lo: 0xd7b0, Hi: 0xd7c6, Stride: 1}, + }, +} + +// GraphemeBreakProperty: ZWJ +var GraphemeBreakZWJ = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x200d, Hi: 0x200d, Stride: 1}, + }, +} + +// contains all the runes having a non nil grapheme break property +var graphemeBreakAll = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0000, Hi: 0x001f, Stride: 1}, + {Lo: 0x007f, Hi: 0x009f, Stride: 1}, + {Lo: 0x00ad, Hi: 0x00ad, Stride: 1}, + {Lo: 0x0300, Hi: 0x036f, Stride: 1}, + {Lo: 0x0483, Hi: 0x0489, Stride: 1}, + {Lo: 0x0591, Hi: 0x05bd, Stride: 1}, + {Lo: 0x05bf, Hi: 0x05c1, Stride: 2}, + {Lo: 0x05c2, Hi: 0x05c4, Stride: 2}, + {Lo: 0x05c5, Hi: 0x05c7, Stride: 2}, + {Lo: 0x0600, Hi: 0x0605, Stride: 1}, + {Lo: 0x0610, Hi: 0x061a, Stride: 1}, + {Lo: 0x061c, Hi: 0x061c, Stride: 1}, + {Lo: 0x064b, Hi: 0x065f, Stride: 1}, + {Lo: 0x0670, Hi: 0x06d6, Stride: 102}, + {Lo: 0x06d7, Hi: 0x06dd, Stride: 1}, + {Lo: 0x06df, Hi: 0x06e4, Stride: 1}, + {Lo: 0x06e7, Hi: 0x06e8, Stride: 1}, + {Lo: 0x06ea, Hi: 0x06ed, Stride: 1}, + {Lo: 0x070f, Hi: 0x070f, Stride: 1}, + {Lo: 0x0711, Hi: 0x0730, Stride: 31}, + {Lo: 0x0731, Hi: 0x074a, Stride: 1}, + {Lo: 0x07a6, Hi: 0x07b0, Stride: 1}, + {Lo: 0x07eb, Hi: 0x07f3, Stride: 1}, + {Lo: 0x07fd, Hi: 0x0816, Stride: 25}, + {Lo: 0x0817, Hi: 0x0819, Stride: 1}, + {Lo: 0x081b, Hi: 0x0823, Stride: 1}, + {Lo: 0x0825, Hi: 0x0827, Stride: 1}, + {Lo: 0x0829, Hi: 0x082d, Stride: 1}, + {Lo: 0x0859, Hi: 0x085b, Stride: 1}, + {Lo: 0x0890, Hi: 0x0891, Stride: 1}, + {Lo: 0x0898, Hi: 0x089f, Stride: 1}, + {Lo: 0x08ca, Hi: 0x0903, Stride: 1}, + {Lo: 0x093a, Hi: 0x093c, Stride: 1}, + {Lo: 0x093e, Hi: 0x094f, Stride: 1}, + {Lo: 0x0951, Hi: 0x0957, Stride: 1}, + {Lo: 0x0962, Hi: 0x0963, Stride: 1}, + {Lo: 0x0981, Hi: 0x0983, Stride: 1}, + {Lo: 0x09bc, Hi: 0x09be, Stride: 2}, + {Lo: 0x09bf, Hi: 0x09c4, Stride: 1}, + {Lo: 0x09c7, Hi: 0x09c8, Stride: 1}, + {Lo: 0x09cb, Hi: 0x09cd, Stride: 1}, + {Lo: 0x09d7, Hi: 0x09d7, Stride: 10}, + {Lo: 0x09e2, Hi: 0x09e3, Stride: 1}, + {Lo: 0x09fe, Hi: 0x0a01, Stride: 3}, + {Lo: 0x0a02, Hi: 0x0a03, Stride: 1}, + {Lo: 0x0a3c, Hi: 0x0a3e, Stride: 2}, + {Lo: 0x0a3f, Hi: 0x0a42, Stride: 1}, + {Lo: 0x0a47, Hi: 0x0a48, Stride: 1}, + {Lo: 0x0a4b, Hi: 0x0a4d, Stride: 1}, + {Lo: 0x0a51, Hi: 0x0a70, Stride: 31}, + {Lo: 0x0a71, Hi: 0x0a75, Stride: 4}, + {Lo: 0x0a81, Hi: 0x0a83, Stride: 1}, + {Lo: 0x0abc, Hi: 0x0abe, Stride: 2}, + {Lo: 0x0abf, Hi: 0x0ac5, Stride: 1}, + {Lo: 0x0ac7, Hi: 0x0ac9, Stride: 1}, + {Lo: 0x0acb, Hi: 0x0acd, Stride: 1}, + {Lo: 0x0ae2, Hi: 0x0ae2, Stride: 21}, + {Lo: 0x0ae3, Hi: 0x0afa, Stride: 23}, + {Lo: 0x0afb, Hi: 0x0aff, Stride: 1}, + {Lo: 0x0b01, Hi: 0x0b03, Stride: 1}, + {Lo: 0x0b3c, Hi: 0x0b3c, Stride: 1}, + {Lo: 0x0b3e, Hi: 0x0b44, Stride: 1}, + {Lo: 0x0b47, Hi: 0x0b48, Stride: 1}, + {Lo: 0x0b4b, Hi: 0x0b4d, Stride: 1}, + {Lo: 0x0b55, Hi: 0x0b57, Stride: 1}, + {Lo: 0x0b62, Hi: 0x0b63, Stride: 1}, + {Lo: 0x0b82, Hi: 0x0bbe, Stride: 60}, + {Lo: 0x0bbf, Hi: 0x0bc2, Stride: 1}, + {Lo: 0x0bc6, Hi: 0x0bc8, Stride: 1}, + {Lo: 0x0bca, Hi: 0x0bcd, Stride: 1}, + {Lo: 0x0bd7, Hi: 0x0c00, Stride: 41}, + {Lo: 0x0c01, Hi: 0x0c04, Stride: 1}, + {Lo: 0x0c3c, Hi: 0x0c3c, Stride: 56}, + {Lo: 0x0c3e, Hi: 0x0c44, Stride: 1}, + {Lo: 0x0c46, Hi: 0x0c48, Stride: 1}, + {Lo: 0x0c4a, Hi: 0x0c4d, Stride: 1}, + {Lo: 0x0c55, Hi: 0x0c56, Stride: 1}, + {Lo: 0x0c62, Hi: 0x0c63, Stride: 1}, + {Lo: 0x0c81, Hi: 0x0c83, Stride: 1}, + {Lo: 0x0cbc, Hi: 0x0cbe, Stride: 2}, + {Lo: 0x0cbf, Hi: 0x0cc4, Stride: 1}, + {Lo: 0x0cc6, Hi: 0x0cc8, Stride: 1}, + {Lo: 0x0cca, Hi: 0x0ccd, Stride: 1}, + {Lo: 0x0cd5, Hi: 0x0cd5, Stride: 8}, + {Lo: 0x0cd6, Hi: 0x0ce2, Stride: 12}, + {Lo: 0x0ce3, Hi: 0x0cf3, Stride: 16}, + {Lo: 0x0d00, Hi: 0x0d03, Stride: 1}, + {Lo: 0x0d3b, Hi: 0x0d3c, Stride: 1}, + {Lo: 0x0d3e, Hi: 0x0d44, Stride: 1}, + {Lo: 0x0d46, Hi: 0x0d48, Stride: 1}, + {Lo: 0x0d4a, Hi: 0x0d4e, Stride: 1}, + {Lo: 0x0d57, Hi: 0x0d57, Stride: 1}, + {Lo: 0x0d62, Hi: 0x0d63, Stride: 1}, + {Lo: 0x0d81, Hi: 0x0d83, Stride: 1}, + {Lo: 0x0dca, Hi: 0x0dcf, Stride: 5}, + {Lo: 0x0dd0, Hi: 0x0dd4, Stride: 1}, + {Lo: 0x0dd6, Hi: 0x0dd6, Stride: 1}, + {Lo: 0x0dd8, Hi: 0x0ddf, Stride: 1}, + {Lo: 0x0df2, Hi: 0x0df3, Stride: 1}, + {Lo: 0x0e31, Hi: 0x0e33, Stride: 2}, + {Lo: 0x0e34, Hi: 0x0e3a, Stride: 1}, + {Lo: 0x0e47, Hi: 0x0e4e, Stride: 1}, + {Lo: 0x0eb1, Hi: 0x0eb3, Stride: 2}, + {Lo: 0x0eb4, Hi: 0x0ebc, Stride: 1}, + {Lo: 0x0ec8, Hi: 0x0ece, Stride: 1}, + {Lo: 0x0f18, Hi: 0x0f19, Stride: 1}, + {Lo: 0x0f35, Hi: 0x0f39, Stride: 2}, + {Lo: 0x0f3e, Hi: 0x0f3f, Stride: 1}, + {Lo: 0x0f71, Hi: 0x0f84, Stride: 1}, + {Lo: 0x0f86, Hi: 0x0f87, Stride: 1}, + {Lo: 0x0f8d, Hi: 0x0f97, Stride: 1}, + {Lo: 0x0f99, Hi: 0x0fbc, Stride: 1}, + {Lo: 0x0fc6, Hi: 0x102d, Stride: 103}, + {Lo: 0x102e, Hi: 0x1037, Stride: 1}, + {Lo: 0x1039, Hi: 0x103e, Stride: 1}, + {Lo: 0x1056, Hi: 0x1059, Stride: 1}, + {Lo: 0x105e, Hi: 0x1060, Stride: 1}, + {Lo: 0x1071, Hi: 0x1074, Stride: 1}, + {Lo: 0x1082, Hi: 0x1084, Stride: 2}, + {Lo: 0x1085, Hi: 0x1086, Stride: 1}, + {Lo: 0x108d, Hi: 0x109d, Stride: 16}, + {Lo: 0x1100, Hi: 0x11ff, Stride: 1}, + {Lo: 0x135d, Hi: 0x135f, Stride: 1}, + {Lo: 0x1712, Hi: 0x1715, Stride: 1}, + {Lo: 0x1732, Hi: 0x1734, Stride: 1}, + {Lo: 0x1752, Hi: 0x1753, Stride: 1}, + {Lo: 0x1772, Hi: 0x1773, Stride: 1}, + {Lo: 0x17b4, Hi: 0x17d3, Stride: 1}, + {Lo: 0x17dd, Hi: 0x180b, Stride: 46}, + {Lo: 0x180c, Hi: 0x180f, Stride: 1}, + {Lo: 0x1885, Hi: 0x1885, Stride: 118}, + {Lo: 0x1886, Hi: 0x18a9, Stride: 35}, + {Lo: 0x1920, Hi: 0x192b, Stride: 1}, + {Lo: 0x1930, Hi: 0x193b, Stride: 1}, + {Lo: 0x1a17, Hi: 0x1a1b, Stride: 1}, + {Lo: 0x1a55, Hi: 0x1a5e, Stride: 1}, + {Lo: 0x1a60, Hi: 0x1a62, Stride: 2}, + {Lo: 0x1a65, Hi: 0x1a7c, Stride: 1}, + {Lo: 0x1a7f, Hi: 0x1ab0, Stride: 49}, + {Lo: 0x1ab1, Hi: 0x1ace, Stride: 1}, + {Lo: 0x1b00, Hi: 0x1b04, Stride: 1}, + {Lo: 0x1b34, Hi: 0x1b44, Stride: 1}, + {Lo: 0x1b6b, Hi: 0x1b73, Stride: 1}, + {Lo: 0x1b80, Hi: 0x1b82, Stride: 1}, + {Lo: 0x1ba1, Hi: 0x1bad, Stride: 1}, + {Lo: 0x1be6, Hi: 0x1bf3, Stride: 1}, + {Lo: 0x1c24, Hi: 0x1c37, Stride: 1}, + {Lo: 0x1cd0, Hi: 0x1cd2, Stride: 1}, + {Lo: 0x1cd4, Hi: 0x1ce8, Stride: 1}, + {Lo: 0x1ced, Hi: 0x1cf4, Stride: 7}, + {Lo: 0x1cf7, Hi: 0x1cf9, Stride: 1}, + {Lo: 0x1dc0, Hi: 0x1dff, Stride: 1}, + {Lo: 0x200b, Hi: 0x200f, Stride: 1}, + {Lo: 0x2028, Hi: 0x202e, Stride: 1}, + {Lo: 0x2060, Hi: 0x206f, Stride: 1}, + {Lo: 0x20d0, Hi: 0x20f0, Stride: 1}, + {Lo: 0x2cef, Hi: 0x2cf1, Stride: 1}, + {Lo: 0x2d7f, Hi: 0x2de0, Stride: 97}, + {Lo: 0x2de1, Hi: 0x2dff, Stride: 1}, + {Lo: 0x302a, Hi: 0x302f, Stride: 1}, + {Lo: 0x3099, Hi: 0x309a, Stride: 1}, + {Lo: 0xa66f, Hi: 0xa672, Stride: 1}, + {Lo: 0xa674, Hi: 0xa67d, Stride: 1}, + {Lo: 0xa69e, Hi: 0xa69f, Stride: 1}, + {Lo: 0xa6f0, Hi: 0xa6f1, Stride: 1}, + {Lo: 0xa802, Hi: 0xa806, Stride: 4}, + {Lo: 0xa80b, Hi: 0xa80b, Stride: 1}, + {Lo: 0xa823, Hi: 0xa827, Stride: 1}, + {Lo: 0xa82c, Hi: 0xa880, Stride: 84}, + {Lo: 0xa881, Hi: 0xa8b4, Stride: 51}, + {Lo: 0xa8b5, Hi: 0xa8c5, Stride: 1}, + {Lo: 0xa8e0, Hi: 0xa8f1, Stride: 1}, + {Lo: 0xa8ff, Hi: 0xa926, Stride: 39}, + {Lo: 0xa927, Hi: 0xa92d, Stride: 1}, + {Lo: 0xa947, Hi: 0xa953, Stride: 1}, + {Lo: 0xa960, Hi: 0xa97c, Stride: 1}, + {Lo: 0xa980, Hi: 0xa983, Stride: 1}, + {Lo: 0xa9b3, Hi: 0xa9c0, Stride: 1}, + {Lo: 0xa9e5, Hi: 0xaa29, Stride: 68}, + {Lo: 0xaa2a, Hi: 0xaa36, Stride: 1}, + {Lo: 0xaa43, Hi: 0xaa4c, Stride: 9}, + {Lo: 0xaa4d, Hi: 0xaa4d, Stride: 1}, + {Lo: 0xaa7c, Hi: 0xaab0, Stride: 52}, + {Lo: 0xaab2, Hi: 0xaab4, Stride: 1}, + {Lo: 0xaab7, Hi: 0xaab8, Stride: 1}, + {Lo: 0xaabe, Hi: 0xaabf, Stride: 1}, + {Lo: 0xaac1, Hi: 0xaaeb, Stride: 42}, + {Lo: 0xaaec, Hi: 0xaaef, Stride: 1}, + {Lo: 0xaaf5, Hi: 0xaaf6, Stride: 1}, + {Lo: 0xabe3, Hi: 0xabea, Stride: 1}, + {Lo: 0xabec, Hi: 0xabed, Stride: 1}, + {Lo: 0xac00, Hi: 0xd7a3, Stride: 1}, + {Lo: 0xd7b0, Hi: 0xd7c6, Stride: 1}, + {Lo: 0xd7cb, Hi: 0xd7fb, Stride: 1}, + {Lo: 0xfb1e, Hi: 0xfb1e, Stride: 1}, + {Lo: 0xfe00, Hi: 0xfe0f, Stride: 1}, + {Lo: 0xfe20, Hi: 0xfe2f, Stride: 1}, + {Lo: 0xfeff, Hi: 0xfeff, Stride: 1}, + {Lo: 0xff9e, Hi: 0xff9f, Stride: 1}, + {Lo: 0xfff0, Hi: 0xfffb, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x101fd, Hi: 0x102e0, Stride: 227}, + {Lo: 0x10376, Hi: 0x1037a, Stride: 1}, + {Lo: 0x10a01, Hi: 0x10a03, Stride: 1}, + {Lo: 0x10a05, Hi: 0x10a06, Stride: 1}, + {Lo: 0x10a0c, Hi: 0x10a0f, Stride: 1}, + {Lo: 0x10a38, Hi: 0x10a3a, Stride: 1}, + {Lo: 0x10a3f, Hi: 0x10ae5, Stride: 166}, + {Lo: 0x10ae6, Hi: 0x10d24, Stride: 574}, + {Lo: 0x10d25, Hi: 0x10d27, Stride: 1}, + {Lo: 0x10eab, Hi: 0x10eac, Stride: 1}, + {Lo: 0x10efd, Hi: 0x10eff, Stride: 1}, + {Lo: 0x10f46, Hi: 0x10f50, Stride: 1}, + {Lo: 0x10f82, Hi: 0x10f85, Stride: 1}, + {Lo: 0x11000, Hi: 0x11002, Stride: 1}, + {Lo: 0x11038, Hi: 0x11046, Stride: 1}, + {Lo: 0x11070, Hi: 0x11073, Stride: 3}, + {Lo: 0x11074, Hi: 0x1107f, Stride: 11}, + {Lo: 0x11080, Hi: 0x11082, Stride: 1}, + {Lo: 0x110b0, Hi: 0x110ba, Stride: 1}, + {Lo: 0x110bd, Hi: 0x110c2, Stride: 5}, + {Lo: 0x110cd, Hi: 0x11100, Stride: 51}, + {Lo: 0x11101, Hi: 0x11102, Stride: 1}, + {Lo: 0x11127, Hi: 0x11134, Stride: 1}, + {Lo: 0x11145, Hi: 0x11146, Stride: 1}, + {Lo: 0x11173, Hi: 0x11180, Stride: 13}, + {Lo: 0x11181, Hi: 0x11182, Stride: 1}, + {Lo: 0x111b3, Hi: 0x111c0, Stride: 1}, + {Lo: 0x111c2, Hi: 0x111c3, Stride: 1}, + {Lo: 0x111c9, Hi: 0x111cc, Stride: 1}, + {Lo: 0x111ce, Hi: 0x111cf, Stride: 1}, + {Lo: 0x1122c, Hi: 0x11237, Stride: 1}, + {Lo: 0x1123e, Hi: 0x1123e, Stride: 7}, + {Lo: 0x11241, Hi: 0x112df, Stride: 158}, + {Lo: 0x112e0, Hi: 0x112ea, Stride: 1}, + {Lo: 0x11300, Hi: 0x11303, Stride: 1}, + {Lo: 0x1133b, Hi: 0x1133c, Stride: 1}, + {Lo: 0x1133e, Hi: 0x11344, Stride: 1}, + {Lo: 0x11347, Hi: 0x11348, Stride: 1}, + {Lo: 0x1134b, Hi: 0x1134d, Stride: 1}, + {Lo: 0x11357, Hi: 0x11357, Stride: 1}, + {Lo: 0x11362, Hi: 0x11363, Stride: 1}, + {Lo: 0x11366, Hi: 0x1136c, Stride: 1}, + {Lo: 0x11370, Hi: 0x11374, Stride: 1}, + {Lo: 0x11435, Hi: 0x11446, Stride: 1}, + {Lo: 0x1145e, Hi: 0x114b0, Stride: 82}, + {Lo: 0x114b1, Hi: 0x114c3, Stride: 1}, + {Lo: 0x115af, Hi: 0x115b5, Stride: 1}, + {Lo: 0x115b8, Hi: 0x115c0, Stride: 1}, + {Lo: 0x115dc, Hi: 0x115dd, Stride: 1}, + {Lo: 0x11630, Hi: 0x11640, Stride: 1}, + {Lo: 0x116ab, Hi: 0x116b7, Stride: 1}, + {Lo: 0x1171d, Hi: 0x1171f, Stride: 1}, + {Lo: 0x11722, Hi: 0x1172b, Stride: 1}, + {Lo: 0x1182c, Hi: 0x1183a, Stride: 1}, + {Lo: 0x11930, Hi: 0x11935, Stride: 1}, + {Lo: 0x11937, Hi: 0x11938, Stride: 1}, + {Lo: 0x1193b, Hi: 0x11943, Stride: 1}, + {Lo: 0x119d1, Hi: 0x119d7, Stride: 1}, + {Lo: 0x119da, Hi: 0x119e0, Stride: 1}, + {Lo: 0x119e4, Hi: 0x11a01, Stride: 29}, + {Lo: 0x11a02, Hi: 0x11a0a, Stride: 1}, + {Lo: 0x11a33, Hi: 0x11a3e, Stride: 1}, + {Lo: 0x11a47, Hi: 0x11a51, Stride: 10}, + {Lo: 0x11a52, Hi: 0x11a5b, Stride: 1}, + {Lo: 0x11a84, Hi: 0x11a99, Stride: 1}, + {Lo: 0x11c2f, Hi: 0x11c36, Stride: 1}, + {Lo: 0x11c38, Hi: 0x11c3f, Stride: 1}, + {Lo: 0x11c92, Hi: 0x11ca7, Stride: 1}, + {Lo: 0x11ca9, Hi: 0x11cb6, Stride: 1}, + {Lo: 0x11d31, Hi: 0x11d36, Stride: 1}, + {Lo: 0x11d3a, Hi: 0x11d3c, Stride: 2}, + {Lo: 0x11d3d, Hi: 0x11d3f, Stride: 2}, + {Lo: 0x11d40, Hi: 0x11d47, Stride: 1}, + {Lo: 0x11d8a, Hi: 0x11d8e, Stride: 1}, + {Lo: 0x11d90, Hi: 0x11d91, Stride: 1}, + {Lo: 0x11d93, Hi: 0x11d97, Stride: 1}, + {Lo: 0x11ef3, Hi: 0x11ef6, Stride: 1}, + {Lo: 0x11f00, Hi: 0x11f03, Stride: 1}, + {Lo: 0x11f34, Hi: 0x11f3a, Stride: 1}, + {Lo: 0x11f3e, Hi: 0x11f42, Stride: 1}, + {Lo: 0x13430, Hi: 0x13440, Stride: 1}, + {Lo: 0x13447, Hi: 0x13455, Stride: 1}, + {Lo: 0x16af0, Hi: 0x16af4, Stride: 1}, + {Lo: 0x16b30, Hi: 0x16b36, Stride: 1}, + {Lo: 0x16f4f, Hi: 0x16f51, Stride: 2}, + {Lo: 0x16f52, Hi: 0x16f87, Stride: 1}, + {Lo: 0x16f8f, Hi: 0x16f92, Stride: 1}, + {Lo: 0x16fe4, Hi: 0x16fe4, Stride: 1}, + {Lo: 0x16ff0, Hi: 0x16ff1, Stride: 1}, + {Lo: 0x1bc9d, Hi: 0x1bc9e, Stride: 1}, + {Lo: 0x1bca0, Hi: 0x1bca3, Stride: 1}, + {Lo: 0x1cf00, Hi: 0x1cf2d, Stride: 1}, + {Lo: 0x1cf30, Hi: 0x1cf46, Stride: 1}, + {Lo: 0x1d165, Hi: 0x1d169, Stride: 1}, + {Lo: 0x1d16d, Hi: 0x1d182, Stride: 1}, + {Lo: 0x1d185, Hi: 0x1d18b, Stride: 1}, + {Lo: 0x1d1aa, Hi: 0x1d1ad, Stride: 1}, + {Lo: 0x1d242, Hi: 0x1d244, Stride: 1}, + {Lo: 0x1da00, Hi: 0x1da36, Stride: 1}, + {Lo: 0x1da3b, Hi: 0x1da6c, Stride: 1}, + {Lo: 0x1da75, Hi: 0x1da84, Stride: 15}, + {Lo: 0x1da9b, Hi: 0x1da9f, Stride: 1}, + {Lo: 0x1daa1, Hi: 0x1daaf, Stride: 1}, + {Lo: 0x1e000, Hi: 0x1e006, Stride: 1}, + {Lo: 0x1e008, Hi: 0x1e018, Stride: 1}, + {Lo: 0x1e01b, Hi: 0x1e021, Stride: 1}, + {Lo: 0x1e023, Hi: 0x1e024, Stride: 1}, + {Lo: 0x1e026, Hi: 0x1e02a, Stride: 1}, + {Lo: 0x1e08f, Hi: 0x1e130, Stride: 161}, + {Lo: 0x1e131, Hi: 0x1e136, Stride: 1}, + {Lo: 0x1e2ae, Hi: 0x1e2ec, Stride: 62}, + {Lo: 0x1e2ed, Hi: 0x1e2ef, Stride: 1}, + {Lo: 0x1e4ec, Hi: 0x1e4ef, Stride: 1}, + {Lo: 0x1e8d0, Hi: 0x1e8d6, Stride: 1}, + {Lo: 0x1e944, Hi: 0x1e94a, Stride: 1}, + {Lo: 0x1f1e6, Hi: 0x1f1ff, Stride: 1}, + {Lo: 0x1f3fb, Hi: 0x1f3ff, Stride: 1}, + {Lo: 0xe0000, Hi: 0xe0fff, Stride: 1}, + }, + LatinOffset: 3, +} + +var graphemeBreaks = [...]*unicode.RangeTable{ + GraphemeBreakCR, // CR + GraphemeBreakControl, // Control + GraphemeBreakExtend, // Extend + GraphemeBreakL, // L + GraphemeBreakLF, // LF + GraphemeBreakLV, // LV + GraphemeBreakLVT, // LVT + GraphemeBreakPrepend, // Prepend + GraphemeBreakRegional_Indicator, // Regional_Indicator + GraphemeBreakSpacingMark, // SpacingMark + GraphemeBreakT, // T + GraphemeBreakV, // V + GraphemeBreakZWJ, // ZWJ +} diff --git a/vendor/github.com/go-text/typesetting/unicodedata/indic.go b/vendor/github.com/go-text/typesetting/unicodedata/indic.go new file mode 100644 index 0000000..d029ab7 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/unicodedata/indic.go @@ -0,0 +1,168 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package unicodedata + +import "unicode" + +// Code generated by typesettings-utils/generators/unicodedata/cmd/main.go DO NOT EDIT. + +var IndicVirama = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x094d, Hi: 0x0d4d, Stride: 128}, + {Lo: 0x0dca, Hi: 0x1b44, Stride: 3450}, + {Lo: 0xa806, Hi: 0xa8c4, Stride: 190}, + {Lo: 0xa9c0, Hi: 0xa9c0, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x11046, Hi: 0x110b9, Stride: 115}, + {Lo: 0x111c0, Hi: 0x11235, Stride: 117}, + {Lo: 0x1134d, Hi: 0x11442, Stride: 245}, + {Lo: 0x114c2, Hi: 0x115bf, Stride: 253}, + {Lo: 0x1163f, Hi: 0x116b6, Stride: 119}, + {Lo: 0x11839, Hi: 0x119e0, Stride: 423}, + {Lo: 0x11c3f, Hi: 0x11c3f, Stride: 1}, + }, +} + +var IndicVowel_Dependent = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x093a, Hi: 0x093b, Stride: 1}, + {Lo: 0x093e, Hi: 0x094c, Stride: 1}, + {Lo: 0x094e, Hi: 0x094f, Stride: 1}, + {Lo: 0x0955, Hi: 0x0957, Stride: 1}, + {Lo: 0x0962, Hi: 0x0963, Stride: 1}, + {Lo: 0x09be, Hi: 0x09c4, Stride: 1}, + {Lo: 0x09c7, Hi: 0x09c8, Stride: 1}, + {Lo: 0x09cb, Hi: 0x09cc, Stride: 1}, + {Lo: 0x09d7, Hi: 0x09e2, Stride: 11}, + {Lo: 0x09e3, Hi: 0x0a3e, Stride: 91}, + {Lo: 0x0a3f, Hi: 0x0a42, Stride: 1}, + {Lo: 0x0a47, Hi: 0x0a48, Stride: 1}, + {Lo: 0x0a4b, Hi: 0x0a4c, Stride: 1}, + {Lo: 0x0abe, Hi: 0x0ac5, Stride: 1}, + {Lo: 0x0ac7, Hi: 0x0ac9, Stride: 1}, + {Lo: 0x0acb, Hi: 0x0acc, Stride: 1}, + {Lo: 0x0ae2, Hi: 0x0ae3, Stride: 1}, + {Lo: 0x0b3e, Hi: 0x0b44, Stride: 1}, + {Lo: 0x0b47, Hi: 0x0b48, Stride: 1}, + {Lo: 0x0b4b, Hi: 0x0b4c, Stride: 1}, + {Lo: 0x0b55, Hi: 0x0b57, Stride: 1}, + {Lo: 0x0b62, Hi: 0x0b63, Stride: 1}, + {Lo: 0x0bbe, Hi: 0x0bc2, Stride: 1}, + {Lo: 0x0bc6, Hi: 0x0bc8, Stride: 1}, + {Lo: 0x0bca, Hi: 0x0bcc, Stride: 1}, + {Lo: 0x0bd7, Hi: 0x0c3e, Stride: 103}, + {Lo: 0x0c3f, Hi: 0x0c44, Stride: 1}, + {Lo: 0x0c46, Hi: 0x0c48, Stride: 1}, + {Lo: 0x0c4a, Hi: 0x0c4c, Stride: 1}, + {Lo: 0x0c55, Hi: 0x0c56, Stride: 1}, + {Lo: 0x0c62, Hi: 0x0c63, Stride: 1}, + {Lo: 0x0cbe, Hi: 0x0cc4, Stride: 1}, + {Lo: 0x0cc6, Hi: 0x0cc8, Stride: 1}, + {Lo: 0x0cca, Hi: 0x0ccc, Stride: 1}, + {Lo: 0x0cd5, Hi: 0x0cd6, Stride: 1}, + {Lo: 0x0ce2, Hi: 0x0ce3, Stride: 1}, + {Lo: 0x0d3e, Hi: 0x0d44, Stride: 1}, + {Lo: 0x0d46, Hi: 0x0d48, Stride: 1}, + {Lo: 0x0d4a, Hi: 0x0d4c, Stride: 1}, + {Lo: 0x0d57, Hi: 0x0d62, Stride: 11}, + {Lo: 0x0d63, Hi: 0x0dcf, Stride: 108}, + {Lo: 0x0dd0, Hi: 0x0dd4, Stride: 1}, + {Lo: 0x0dd6, Hi: 0x0dd8, Stride: 2}, + {Lo: 0x0dd9, Hi: 0x0ddf, Stride: 1}, + {Lo: 0x0df2, Hi: 0x0df3, Stride: 1}, + {Lo: 0x0e30, Hi: 0x0e39, Stride: 1}, + {Lo: 0x0e40, Hi: 0x0e45, Stride: 1}, + {Lo: 0x0e47, Hi: 0x0eb0, Stride: 105}, + {Lo: 0x0eb1, Hi: 0x0eb9, Stride: 1}, + {Lo: 0x0ebb, Hi: 0x0ec0, Stride: 5}, + {Lo: 0x0ec1, Hi: 0x0ec4, Stride: 1}, + {Lo: 0x0f71, Hi: 0x0f7d, Stride: 1}, + {Lo: 0x0f80, Hi: 0x0f81, Stride: 1}, + {Lo: 0x102b, Hi: 0x1035, Stride: 1}, + {Lo: 0x1056, Hi: 0x1059, Stride: 1}, + {Lo: 0x1062, Hi: 0x1067, Stride: 5}, + {Lo: 0x1068, Hi: 0x1071, Stride: 9}, + {Lo: 0x1072, Hi: 0x1074, Stride: 1}, + {Lo: 0x1083, Hi: 0x1086, Stride: 1}, + {Lo: 0x109c, Hi: 0x109d, Stride: 1}, + {Lo: 0x1712, Hi: 0x1713, Stride: 1}, + {Lo: 0x1732, Hi: 0x1733, Stride: 1}, + {Lo: 0x1752, Hi: 0x1753, Stride: 1}, + {Lo: 0x1772, Hi: 0x1773, Stride: 1}, + {Lo: 0x17b6, Hi: 0x17c5, Stride: 1}, + {Lo: 0x17c8, Hi: 0x1920, Stride: 344}, + {Lo: 0x1921, Hi: 0x1928, Stride: 1}, + {Lo: 0x193a, Hi: 0x19b0, Stride: 118}, + {Lo: 0x19b1, Hi: 0x19c0, Stride: 1}, + {Lo: 0x1a17, Hi: 0x1a1b, Stride: 1}, + {Lo: 0x1a61, Hi: 0x1a73, Stride: 1}, + {Lo: 0x1b35, Hi: 0x1b43, Stride: 1}, + {Lo: 0x1ba4, Hi: 0x1ba9, Stride: 1}, + {Lo: 0x1be7, Hi: 0x1bef, Stride: 1}, + {Lo: 0x1c26, Hi: 0x1c2c, Stride: 1}, + {Lo: 0xa802, Hi: 0xa823, Stride: 33}, + {Lo: 0xa824, Hi: 0xa827, Stride: 1}, + {Lo: 0xa8b5, Hi: 0xa8c3, Stride: 1}, + {Lo: 0xa8ff, Hi: 0xa947, Stride: 72}, + {Lo: 0xa948, Hi: 0xa94e, Stride: 1}, + {Lo: 0xa9b4, Hi: 0xa9bc, Stride: 1}, + {Lo: 0xa9e5, Hi: 0xaa29, Stride: 68}, + {Lo: 0xaa2a, Hi: 0xaa32, Stride: 1}, + {Lo: 0xaab0, Hi: 0xaabe, Stride: 1}, + {Lo: 0xaaeb, Hi: 0xaaef, Stride: 1}, + {Lo: 0xabe3, Hi: 0xabea, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x10a01, Hi: 0x10a03, Stride: 1}, + {Lo: 0x10a05, Hi: 0x10a06, Stride: 1}, + {Lo: 0x10a0c, Hi: 0x10a0d, Stride: 1}, + {Lo: 0x11038, Hi: 0x11045, Stride: 1}, + {Lo: 0x11073, Hi: 0x11074, Stride: 1}, + {Lo: 0x110b0, Hi: 0x110b8, Stride: 1}, + {Lo: 0x110c2, Hi: 0x11127, Stride: 101}, + {Lo: 0x11128, Hi: 0x11132, Stride: 1}, + {Lo: 0x11145, Hi: 0x11146, Stride: 1}, + {Lo: 0x111b3, Hi: 0x111bf, Stride: 1}, + {Lo: 0x111cb, Hi: 0x111cc, Stride: 1}, + {Lo: 0x111ce, Hi: 0x1122c, Stride: 94}, + {Lo: 0x1122d, Hi: 0x11233, Stride: 1}, + {Lo: 0x11241, Hi: 0x112e0, Stride: 159}, + {Lo: 0x112e1, Hi: 0x112e8, Stride: 1}, + {Lo: 0x1133e, Hi: 0x11344, Stride: 1}, + {Lo: 0x11347, Hi: 0x11348, Stride: 1}, + {Lo: 0x1134b, Hi: 0x1134c, Stride: 1}, + {Lo: 0x11357, Hi: 0x11362, Stride: 11}, + {Lo: 0x11363, Hi: 0x11435, Stride: 210}, + {Lo: 0x11436, Hi: 0x11441, Stride: 1}, + {Lo: 0x114b0, Hi: 0x114be, Stride: 1}, + {Lo: 0x115af, Hi: 0x115b5, Stride: 1}, + {Lo: 0x115b8, Hi: 0x115bb, Stride: 1}, + {Lo: 0x115dc, Hi: 0x115dd, Stride: 1}, + {Lo: 0x11630, Hi: 0x1163c, Stride: 1}, + {Lo: 0x11640, Hi: 0x116ad, Stride: 109}, + {Lo: 0x116ae, Hi: 0x116b5, Stride: 1}, + {Lo: 0x11720, Hi: 0x1172a, Stride: 1}, + {Lo: 0x1182c, Hi: 0x11836, Stride: 1}, + {Lo: 0x11930, Hi: 0x11935, Stride: 1}, + {Lo: 0x11937, Hi: 0x11938, Stride: 1}, + {Lo: 0x119d1, Hi: 0x119d7, Stride: 1}, + {Lo: 0x119da, Hi: 0x119dd, Stride: 1}, + {Lo: 0x119e4, Hi: 0x11a01, Stride: 29}, + {Lo: 0x11a02, Hi: 0x11a0a, Stride: 1}, + {Lo: 0x11a51, Hi: 0x11a5b, Stride: 1}, + {Lo: 0x11c2f, Hi: 0x11c36, Stride: 1}, + {Lo: 0x11c38, Hi: 0x11c3b, Stride: 1}, + {Lo: 0x11cb0, Hi: 0x11cb4, Stride: 1}, + {Lo: 0x11d31, Hi: 0x11d36, Stride: 1}, + {Lo: 0x11d3a, Hi: 0x11d3c, Stride: 2}, + {Lo: 0x11d3d, Hi: 0x11d3f, Stride: 2}, + {Lo: 0x11d43, Hi: 0x11d8a, Stride: 71}, + {Lo: 0x11d8b, Hi: 0x11d8e, Stride: 1}, + {Lo: 0x11d90, Hi: 0x11d91, Stride: 1}, + {Lo: 0x11d93, Hi: 0x11d94, Stride: 1}, + {Lo: 0x11ef3, Hi: 0x11ef6, Stride: 1}, + {Lo: 0x11f34, Hi: 0x11f3a, Stride: 1}, + {Lo: 0x11f3e, Hi: 0x11f40, Stride: 1}, + }, +} diff --git a/vendor/github.com/go-text/typesetting/unicodedata/linebreak.go b/vendor/github.com/go-text/typesetting/unicodedata/linebreak.go new file mode 100644 index 0000000..5d3b5e1 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/unicodedata/linebreak.go @@ -0,0 +1,2495 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package unicodedata + +import "unicode" + +// Code generated by typesettings-utils/generators/unicodedata/cmd/main.go DO NOT EDIT. + +// Mandatory Break +var BreakBK = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x000b, Hi: 0x000c, Stride: 1}, + {Lo: 0x2028, Hi: 0x2029, Stride: 1}, + }, + LatinOffset: 1, +} + +// Carriage Return +var BreakCR = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x000d, Hi: 0x000d, Stride: 1}, + }, + LatinOffset: 1, +} + +// Line Feed +var BreakLF = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x000a, Hi: 0x000a, Stride: 1}, + }, + LatinOffset: 1, +} + +// Next Line +var BreakNL = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0085, Hi: 0x0085, Stride: 1}, + }, + LatinOffset: 1, +} + +// Space +var BreakSP = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0020, Hi: 0x0020, Stride: 1}, + }, + LatinOffset: 1, +} + +// Numeric +var BreakNU = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0030, Hi: 0x0039, Stride: 1}, + {Lo: 0x0600, Hi: 0x0605, Stride: 1}, + {Lo: 0x0660, Hi: 0x0669, Stride: 1}, + {Lo: 0x066b, Hi: 0x066c, Stride: 1}, + {Lo: 0x06dd, Hi: 0x06f0, Stride: 19}, + {Lo: 0x06f1, Hi: 0x06f9, Stride: 1}, + {Lo: 0x07c0, Hi: 0x07c9, Stride: 1}, + {Lo: 0x0890, Hi: 0x0891, Stride: 1}, + {Lo: 0x08e2, Hi: 0x0966, Stride: 132}, + {Lo: 0x0967, Hi: 0x096f, Stride: 1}, + {Lo: 0x09e6, Hi: 0x09ef, Stride: 1}, + {Lo: 0x0a66, Hi: 0x0a6f, Stride: 1}, + {Lo: 0x0ae6, Hi: 0x0aef, Stride: 1}, + {Lo: 0x0b66, Hi: 0x0b6f, Stride: 1}, + {Lo: 0x0be6, Hi: 0x0bef, Stride: 1}, + {Lo: 0x0c66, Hi: 0x0c6f, Stride: 1}, + {Lo: 0x0ce6, Hi: 0x0cef, Stride: 1}, + {Lo: 0x0d66, Hi: 0x0d6f, Stride: 1}, + {Lo: 0x0de6, Hi: 0x0def, Stride: 1}, + {Lo: 0x0e50, Hi: 0x0e59, Stride: 1}, + {Lo: 0x0ed0, Hi: 0x0ed9, Stride: 1}, + {Lo: 0x0f20, Hi: 0x0f29, Stride: 1}, + {Lo: 0x1040, Hi: 0x1049, Stride: 1}, + {Lo: 0x1090, Hi: 0x1099, Stride: 1}, + {Lo: 0x17e0, Hi: 0x17e9, Stride: 1}, + {Lo: 0x1810, Hi: 0x1819, Stride: 1}, + {Lo: 0x1946, Hi: 0x194f, Stride: 1}, + {Lo: 0x19d0, Hi: 0x19d9, Stride: 1}, + {Lo: 0x1a80, Hi: 0x1a89, Stride: 1}, + {Lo: 0x1a90, Hi: 0x1a99, Stride: 1}, + {Lo: 0x1bb0, Hi: 0x1bb9, Stride: 1}, + {Lo: 0x1c40, Hi: 0x1c49, Stride: 1}, + {Lo: 0x1c50, Hi: 0x1c59, Stride: 1}, + {Lo: 0xa620, Hi: 0xa629, Stride: 1}, + {Lo: 0xa8d0, Hi: 0xa8d9, Stride: 1}, + {Lo: 0xa900, Hi: 0xa909, Stride: 1}, + {Lo: 0xa9f0, Hi: 0xa9f9, Stride: 1}, + {Lo: 0xabf0, Hi: 0xabf9, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x104a0, Hi: 0x104a9, Stride: 1}, + {Lo: 0x10d30, Hi: 0x10d39, Stride: 1}, + {Lo: 0x110bd, Hi: 0x110cd, Stride: 16}, + {Lo: 0x110f0, Hi: 0x110f9, Stride: 1}, + {Lo: 0x11136, Hi: 0x1113f, Stride: 1}, + {Lo: 0x111d0, Hi: 0x111d9, Stride: 1}, + {Lo: 0x112f0, Hi: 0x112f9, Stride: 1}, + {Lo: 0x11450, Hi: 0x11459, Stride: 1}, + {Lo: 0x114d0, Hi: 0x114d9, Stride: 1}, + {Lo: 0x11650, Hi: 0x11659, Stride: 1}, + {Lo: 0x116c0, Hi: 0x116c9, Stride: 1}, + {Lo: 0x11730, Hi: 0x11739, Stride: 1}, + {Lo: 0x118e0, Hi: 0x118e9, Stride: 1}, + {Lo: 0x11c50, Hi: 0x11c59, Stride: 1}, + {Lo: 0x11d50, Hi: 0x11d59, Stride: 1}, + {Lo: 0x11da0, Hi: 0x11da9, Stride: 1}, + {Lo: 0x16a60, Hi: 0x16a69, Stride: 1}, + {Lo: 0x16ac0, Hi: 0x16ac9, Stride: 1}, + {Lo: 0x16b50, Hi: 0x16b59, Stride: 1}, + {Lo: 0x1d7ce, Hi: 0x1d7ff, Stride: 1}, + {Lo: 0x1e140, Hi: 0x1e149, Stride: 1}, + {Lo: 0x1e2f0, Hi: 0x1e2f9, Stride: 1}, + {Lo: 0x1e4f0, Hi: 0x1e4f9, Stride: 1}, + {Lo: 0x1e950, Hi: 0x1e959, Stride: 1}, + {Lo: 0x1fbf0, Hi: 0x1fbf9, Stride: 1}, + }, + LatinOffset: 1, +} + +// Alphabetic +var BreakAL = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0023, Hi: 0x0026, Stride: 3}, + {Lo: 0x002a, Hi: 0x003c, Stride: 18}, + {Lo: 0x003d, Hi: 0x003e, Stride: 1}, + {Lo: 0x0040, Hi: 0x005a, Stride: 1}, + {Lo: 0x005e, Hi: 0x007a, Stride: 1}, + {Lo: 0x007e, Hi: 0x00a6, Stride: 40}, + {Lo: 0x00a9, Hi: 0x00ac, Stride: 3}, + {Lo: 0x00ae, Hi: 0x00af, Stride: 1}, + {Lo: 0x00b5, Hi: 0x00c0, Stride: 11}, + {Lo: 0x00c1, Hi: 0x00d6, Stride: 1}, + {Lo: 0x00d8, Hi: 0x00f6, Stride: 1}, + {Lo: 0x00f8, Hi: 0x02c6, Stride: 1}, + {Lo: 0x02ce, Hi: 0x02cf, Stride: 1}, + {Lo: 0x02d1, Hi: 0x02d7, Stride: 1}, + {Lo: 0x02dc, Hi: 0x02e0, Stride: 2}, + {Lo: 0x02e1, Hi: 0x02ff, Stride: 1}, + {Lo: 0x0370, Hi: 0x0377, Stride: 1}, + {Lo: 0x037a, Hi: 0x037d, Stride: 1}, + {Lo: 0x037f, Hi: 0x0384, Stride: 5}, + {Lo: 0x0385, Hi: 0x038a, Stride: 1}, + {Lo: 0x038c, Hi: 0x038e, Stride: 2}, + {Lo: 0x038f, Hi: 0x03a1, Stride: 1}, + {Lo: 0x03a3, Hi: 0x0482, Stride: 1}, + {Lo: 0x048a, Hi: 0x052f, Stride: 1}, + {Lo: 0x0531, Hi: 0x0556, Stride: 1}, + {Lo: 0x0559, Hi: 0x0588, Stride: 1}, + {Lo: 0x058d, Hi: 0x058e, Stride: 1}, + {Lo: 0x05c0, Hi: 0x05c3, Stride: 3}, + {Lo: 0x05f3, Hi: 0x05f4, Stride: 1}, + {Lo: 0x0606, Hi: 0x0608, Stride: 1}, + {Lo: 0x060e, Hi: 0x060f, Stride: 1}, + {Lo: 0x0620, Hi: 0x064a, Stride: 1}, + {Lo: 0x066d, Hi: 0x066f, Stride: 1}, + {Lo: 0x0671, Hi: 0x06d3, Stride: 1}, + {Lo: 0x06d5, Hi: 0x06de, Stride: 9}, + {Lo: 0x06e5, Hi: 0x06e6, Stride: 1}, + {Lo: 0x06e9, Hi: 0x06ee, Stride: 5}, + {Lo: 0x06ef, Hi: 0x06fa, Stride: 11}, + {Lo: 0x06fb, Hi: 0x070d, Stride: 1}, + {Lo: 0x070f, Hi: 0x0710, Stride: 1}, + {Lo: 0x0712, Hi: 0x072f, Stride: 1}, + {Lo: 0x074d, Hi: 0x07a5, Stride: 1}, + {Lo: 0x07b1, Hi: 0x07ca, Stride: 25}, + {Lo: 0x07cb, Hi: 0x07ea, Stride: 1}, + {Lo: 0x07f4, Hi: 0x07f7, Stride: 1}, + {Lo: 0x07fa, Hi: 0x0800, Stride: 6}, + {Lo: 0x0801, Hi: 0x0815, Stride: 1}, + {Lo: 0x081a, Hi: 0x0824, Stride: 10}, + {Lo: 0x0828, Hi: 0x0830, Stride: 8}, + {Lo: 0x0831, Hi: 0x083e, Stride: 1}, + {Lo: 0x0840, Hi: 0x0858, Stride: 1}, + {Lo: 0x085e, Hi: 0x0860, Stride: 2}, + {Lo: 0x0861, Hi: 0x086a, Stride: 1}, + {Lo: 0x0870, Hi: 0x088e, Stride: 1}, + {Lo: 0x08a0, Hi: 0x08c9, Stride: 1}, + {Lo: 0x0904, Hi: 0x0939, Stride: 1}, + {Lo: 0x093d, Hi: 0x0950, Stride: 19}, + {Lo: 0x0958, Hi: 0x0961, Stride: 1}, + {Lo: 0x0970, Hi: 0x0980, Stride: 1}, + {Lo: 0x0985, Hi: 0x098c, Stride: 1}, + {Lo: 0x098f, Hi: 0x0990, Stride: 1}, + {Lo: 0x0993, Hi: 0x09a8, Stride: 1}, + {Lo: 0x09aa, Hi: 0x09b0, Stride: 1}, + {Lo: 0x09b2, Hi: 0x09b6, Stride: 4}, + {Lo: 0x09b7, Hi: 0x09b9, Stride: 1}, + {Lo: 0x09bd, Hi: 0x09ce, Stride: 17}, + {Lo: 0x09dc, Hi: 0x09dd, Stride: 1}, + {Lo: 0x09df, Hi: 0x09e1, Stride: 1}, + {Lo: 0x09f0, Hi: 0x09f1, Stride: 1}, + {Lo: 0x09f4, Hi: 0x09f8, Stride: 1}, + {Lo: 0x09fa, Hi: 0x09fc, Stride: 2}, + {Lo: 0x09fd, Hi: 0x0a05, Stride: 8}, + {Lo: 0x0a06, Hi: 0x0a0a, Stride: 1}, + {Lo: 0x0a0f, Hi: 0x0a10, Stride: 1}, + {Lo: 0x0a13, Hi: 0x0a28, Stride: 1}, + {Lo: 0x0a2a, Hi: 0x0a30, Stride: 1}, + {Lo: 0x0a32, Hi: 0x0a33, Stride: 1}, + {Lo: 0x0a35, Hi: 0x0a36, Stride: 1}, + {Lo: 0x0a38, Hi: 0x0a39, Stride: 1}, + {Lo: 0x0a59, Hi: 0x0a5c, Stride: 1}, + {Lo: 0x0a5e, Hi: 0x0a72, Stride: 20}, + {Lo: 0x0a73, Hi: 0x0a74, Stride: 1}, + {Lo: 0x0a76, Hi: 0x0a85, Stride: 15}, + {Lo: 0x0a86, Hi: 0x0a8d, Stride: 1}, + {Lo: 0x0a8f, Hi: 0x0a91, Stride: 1}, + {Lo: 0x0a93, Hi: 0x0aa8, Stride: 1}, + {Lo: 0x0aaa, Hi: 0x0ab0, Stride: 1}, + {Lo: 0x0ab2, Hi: 0x0ab3, Stride: 1}, + {Lo: 0x0ab5, Hi: 0x0ab9, Stride: 1}, + {Lo: 0x0abd, Hi: 0x0ad0, Stride: 19}, + {Lo: 0x0ae0, Hi: 0x0ae1, Stride: 1}, + {Lo: 0x0af0, Hi: 0x0af9, Stride: 9}, + {Lo: 0x0b05, Hi: 0x0b0c, Stride: 1}, + {Lo: 0x0b0f, Hi: 0x0b10, Stride: 1}, + {Lo: 0x0b13, Hi: 0x0b28, Stride: 1}, + {Lo: 0x0b2a, Hi: 0x0b30, Stride: 1}, + {Lo: 0x0b32, Hi: 0x0b33, Stride: 1}, + {Lo: 0x0b35, Hi: 0x0b39, Stride: 1}, + {Lo: 0x0b3d, Hi: 0x0b5c, Stride: 31}, + {Lo: 0x0b5d, Hi: 0x0b5f, Stride: 2}, + {Lo: 0x0b60, Hi: 0x0b61, Stride: 1}, + {Lo: 0x0b70, Hi: 0x0b77, Stride: 1}, + {Lo: 0x0b83, Hi: 0x0b85, Stride: 2}, + {Lo: 0x0b86, Hi: 0x0b8a, Stride: 1}, + {Lo: 0x0b8e, Hi: 0x0b90, Stride: 1}, + {Lo: 0x0b92, Hi: 0x0b95, Stride: 1}, + {Lo: 0x0b99, Hi: 0x0b9a, Stride: 1}, + {Lo: 0x0b9c, Hi: 0x0b9e, Stride: 2}, + {Lo: 0x0b9f, Hi: 0x0ba3, Stride: 4}, + {Lo: 0x0ba4, Hi: 0x0ba8, Stride: 4}, + {Lo: 0x0ba9, Hi: 0x0baa, Stride: 1}, + {Lo: 0x0bae, Hi: 0x0bb9, Stride: 1}, + {Lo: 0x0bd0, Hi: 0x0bf0, Stride: 32}, + {Lo: 0x0bf1, Hi: 0x0bf8, Stride: 1}, + {Lo: 0x0bfa, Hi: 0x0c05, Stride: 11}, + {Lo: 0x0c06, Hi: 0x0c0c, Stride: 1}, + {Lo: 0x0c0e, Hi: 0x0c10, Stride: 1}, + {Lo: 0x0c12, Hi: 0x0c28, Stride: 1}, + {Lo: 0x0c2a, Hi: 0x0c39, Stride: 1}, + {Lo: 0x0c3d, Hi: 0x0c58, Stride: 27}, + {Lo: 0x0c59, Hi: 0x0c5a, Stride: 1}, + {Lo: 0x0c5d, Hi: 0x0c60, Stride: 3}, + {Lo: 0x0c61, Hi: 0x0c78, Stride: 23}, + {Lo: 0x0c79, Hi: 0x0c80, Stride: 1}, + {Lo: 0x0c85, Hi: 0x0c8c, Stride: 1}, + {Lo: 0x0c8e, Hi: 0x0c90, Stride: 1}, + {Lo: 0x0c92, Hi: 0x0ca8, Stride: 1}, + {Lo: 0x0caa, Hi: 0x0cb3, Stride: 1}, + {Lo: 0x0cb5, Hi: 0x0cb9, Stride: 1}, + {Lo: 0x0cbd, Hi: 0x0cdd, Stride: 32}, + {Lo: 0x0cde, Hi: 0x0ce0, Stride: 2}, + {Lo: 0x0ce1, Hi: 0x0cf1, Stride: 16}, + {Lo: 0x0cf2, Hi: 0x0d04, Stride: 18}, + {Lo: 0x0d05, Hi: 0x0d0c, Stride: 1}, + {Lo: 0x0d0e, Hi: 0x0d10, Stride: 1}, + {Lo: 0x0d12, Hi: 0x0d3a, Stride: 1}, + {Lo: 0x0d3d, Hi: 0x0d4e, Stride: 17}, + {Lo: 0x0d4f, Hi: 0x0d54, Stride: 5}, + {Lo: 0x0d55, Hi: 0x0d56, Stride: 1}, + {Lo: 0x0d58, Hi: 0x0d61, Stride: 1}, + {Lo: 0x0d70, Hi: 0x0d78, Stride: 1}, + {Lo: 0x0d7a, Hi: 0x0d7f, Stride: 1}, + {Lo: 0x0d85, Hi: 0x0d96, Stride: 1}, + {Lo: 0x0d9a, Hi: 0x0db1, Stride: 1}, + {Lo: 0x0db3, Hi: 0x0dbb, Stride: 1}, + {Lo: 0x0dbd, Hi: 0x0dc0, Stride: 3}, + {Lo: 0x0dc1, Hi: 0x0dc6, Stride: 1}, + {Lo: 0x0df4, Hi: 0x0e4f, Stride: 91}, + {Lo: 0x0f00, Hi: 0x0f05, Stride: 5}, + {Lo: 0x0f13, Hi: 0x0f15, Stride: 2}, + {Lo: 0x0f16, Hi: 0x0f17, Stride: 1}, + {Lo: 0x0f1a, Hi: 0x0f1f, Stride: 1}, + {Lo: 0x0f2a, Hi: 0x0f33, Stride: 1}, + {Lo: 0x0f36, Hi: 0x0f38, Stride: 2}, + {Lo: 0x0f40, Hi: 0x0f47, Stride: 1}, + {Lo: 0x0f49, Hi: 0x0f6c, Stride: 1}, + {Lo: 0x0f88, Hi: 0x0f8c, Stride: 1}, + {Lo: 0x0fc0, Hi: 0x0fc5, Stride: 1}, + {Lo: 0x0fc7, Hi: 0x0fcc, Stride: 1}, + {Lo: 0x0fce, Hi: 0x0fcf, Stride: 1}, + {Lo: 0x0fd4, Hi: 0x0fd8, Stride: 1}, + {Lo: 0x104c, Hi: 0x104f, Stride: 1}, + {Lo: 0x10a0, Hi: 0x10c5, Stride: 1}, + {Lo: 0x10c7, Hi: 0x10cd, Stride: 6}, + {Lo: 0x10d0, Hi: 0x10ff, Stride: 1}, + {Lo: 0x1200, Hi: 0x1248, Stride: 1}, + {Lo: 0x124a, Hi: 0x124d, Stride: 1}, + {Lo: 0x1250, Hi: 0x1256, Stride: 1}, + {Lo: 0x1258, Hi: 0x125a, Stride: 2}, + {Lo: 0x125b, Hi: 0x125d, Stride: 1}, + {Lo: 0x1260, Hi: 0x1288, Stride: 1}, + {Lo: 0x128a, Hi: 0x128d, Stride: 1}, + {Lo: 0x1290, Hi: 0x12b0, Stride: 1}, + {Lo: 0x12b2, Hi: 0x12b5, Stride: 1}, + {Lo: 0x12b8, Hi: 0x12be, Stride: 1}, + {Lo: 0x12c0, Hi: 0x12c2, Stride: 2}, + {Lo: 0x12c3, Hi: 0x12c5, Stride: 1}, + {Lo: 0x12c8, Hi: 0x12d6, Stride: 1}, + {Lo: 0x12d8, Hi: 0x1310, Stride: 1}, + {Lo: 0x1312, Hi: 0x1315, Stride: 1}, + {Lo: 0x1318, Hi: 0x135a, Stride: 1}, + {Lo: 0x1360, Hi: 0x1362, Stride: 2}, + {Lo: 0x1363, Hi: 0x137c, Stride: 1}, + {Lo: 0x1380, Hi: 0x1399, Stride: 1}, + {Lo: 0x13a0, Hi: 0x13f5, Stride: 1}, + {Lo: 0x13f8, Hi: 0x13fd, Stride: 1}, + {Lo: 0x1401, Hi: 0x167f, Stride: 1}, + {Lo: 0x1681, Hi: 0x169a, Stride: 1}, + {Lo: 0x16a0, Hi: 0x16ea, Stride: 1}, + {Lo: 0x16ee, Hi: 0x16f8, Stride: 1}, + {Lo: 0x1700, Hi: 0x1711, Stride: 1}, + {Lo: 0x171f, Hi: 0x1731, Stride: 1}, + {Lo: 0x1740, Hi: 0x1751, Stride: 1}, + {Lo: 0x1760, Hi: 0x176c, Stride: 1}, + {Lo: 0x176e, Hi: 0x1770, Stride: 1}, + {Lo: 0x17d9, Hi: 0x17f0, Stride: 23}, + {Lo: 0x17f1, Hi: 0x17f9, Stride: 1}, + {Lo: 0x1800, Hi: 0x1801, Stride: 1}, + {Lo: 0x1807, Hi: 0x180a, Stride: 3}, + {Lo: 0x1820, Hi: 0x1878, Stride: 1}, + {Lo: 0x1880, Hi: 0x1884, Stride: 1}, + {Lo: 0x1887, Hi: 0x18a8, Stride: 1}, + {Lo: 0x18aa, Hi: 0x18b0, Stride: 6}, + {Lo: 0x18b1, Hi: 0x18f5, Stride: 1}, + {Lo: 0x1900, Hi: 0x191e, Stride: 1}, + {Lo: 0x1940, Hi: 0x19e0, Stride: 160}, + {Lo: 0x19e1, Hi: 0x1a16, Stride: 1}, + {Lo: 0x1a1e, Hi: 0x1a1f, Stride: 1}, + {Lo: 0x1b83, Hi: 0x1ba0, Stride: 1}, + {Lo: 0x1bae, Hi: 0x1baf, Stride: 1}, + {Lo: 0x1bba, Hi: 0x1bbf, Stride: 1}, + {Lo: 0x1bfc, Hi: 0x1c23, Stride: 1}, + {Lo: 0x1c4d, Hi: 0x1c4f, Stride: 1}, + {Lo: 0x1c5a, Hi: 0x1c7d, Stride: 1}, + {Lo: 0x1c80, Hi: 0x1c88, Stride: 1}, + {Lo: 0x1c90, Hi: 0x1cba, Stride: 1}, + {Lo: 0x1cbd, Hi: 0x1cc7, Stride: 1}, + {Lo: 0x1cd3, Hi: 0x1ce9, Stride: 22}, + {Lo: 0x1cea, Hi: 0x1cec, Stride: 1}, + {Lo: 0x1cee, Hi: 0x1cf3, Stride: 1}, + {Lo: 0x1cf5, Hi: 0x1cf6, Stride: 1}, + {Lo: 0x1cfa, Hi: 0x1d00, Stride: 6}, + {Lo: 0x1d01, Hi: 0x1dbf, Stride: 1}, + {Lo: 0x1e00, Hi: 0x1f15, Stride: 1}, + {Lo: 0x1f18, Hi: 0x1f1d, Stride: 1}, + {Lo: 0x1f20, Hi: 0x1f45, Stride: 1}, + {Lo: 0x1f48, Hi: 0x1f4d, Stride: 1}, + {Lo: 0x1f50, Hi: 0x1f57, Stride: 1}, + {Lo: 0x1f59, Hi: 0x1f5f, Stride: 2}, + {Lo: 0x1f60, Hi: 0x1f7d, Stride: 1}, + {Lo: 0x1f80, Hi: 0x1fb4, Stride: 1}, + {Lo: 0x1fb6, Hi: 0x1fc4, Stride: 1}, + {Lo: 0x1fc6, Hi: 0x1fd3, Stride: 1}, + {Lo: 0x1fd6, Hi: 0x1fdb, Stride: 1}, + {Lo: 0x1fdd, Hi: 0x1fef, Stride: 1}, + {Lo: 0x1ff2, Hi: 0x1ff4, Stride: 1}, + {Lo: 0x1ff6, Hi: 0x1ffc, Stride: 1}, + {Lo: 0x1ffe, Hi: 0x2017, Stride: 25}, + {Lo: 0x2022, Hi: 0x2023, Stride: 1}, + {Lo: 0x2038, Hi: 0x203e, Stride: 6}, + {Lo: 0x203f, Hi: 0x2043, Stride: 1}, + {Lo: 0x204a, Hi: 0x2055, Stride: 1}, + {Lo: 0x205c, Hi: 0x2061, Stride: 5}, + {Lo: 0x2062, Hi: 0x2064, Stride: 1}, + {Lo: 0x2070, Hi: 0x2071, Stride: 1}, + {Lo: 0x2075, Hi: 0x207c, Stride: 1}, + {Lo: 0x2080, Hi: 0x2085, Stride: 5}, + {Lo: 0x2086, Hi: 0x208c, Stride: 1}, + {Lo: 0x2090, Hi: 0x209c, Stride: 1}, + {Lo: 0x2100, Hi: 0x2102, Stride: 1}, + {Lo: 0x2104, Hi: 0x2106, Stride: 2}, + {Lo: 0x2107, Hi: 0x2108, Stride: 1}, + {Lo: 0x210a, Hi: 0x2112, Stride: 1}, + {Lo: 0x2114, Hi: 0x2115, Stride: 1}, + {Lo: 0x2117, Hi: 0x2120, Stride: 1}, + {Lo: 0x2123, Hi: 0x212a, Stride: 1}, + {Lo: 0x212c, Hi: 0x2153, Stride: 1}, + {Lo: 0x2156, Hi: 0x215a, Stride: 1}, + {Lo: 0x215c, Hi: 0x215d, Stride: 1}, + {Lo: 0x215f, Hi: 0x216c, Stride: 13}, + {Lo: 0x216d, Hi: 0x216f, Stride: 1}, + {Lo: 0x217a, Hi: 0x2188, Stride: 1}, + {Lo: 0x218a, Hi: 0x218b, Stride: 1}, + {Lo: 0x219a, Hi: 0x21d1, Stride: 1}, + {Lo: 0x21d3, Hi: 0x21d5, Stride: 2}, + {Lo: 0x21d6, Hi: 0x21ff, Stride: 1}, + {Lo: 0x2201, Hi: 0x2204, Stride: 3}, + {Lo: 0x2205, Hi: 0x2206, Stride: 1}, + {Lo: 0x2209, Hi: 0x220a, Stride: 1}, + {Lo: 0x220c, Hi: 0x220e, Stride: 1}, + {Lo: 0x2210, Hi: 0x2214, Stride: 4}, + {Lo: 0x2216, Hi: 0x2219, Stride: 1}, + {Lo: 0x221b, Hi: 0x221c, Stride: 1}, + {Lo: 0x2221, Hi: 0x2222, Stride: 1}, + {Lo: 0x2224, Hi: 0x2226, Stride: 2}, + {Lo: 0x222d, Hi: 0x222f, Stride: 2}, + {Lo: 0x2230, Hi: 0x2233, Stride: 1}, + {Lo: 0x2238, Hi: 0x223b, Stride: 1}, + {Lo: 0x223e, Hi: 0x2247, Stride: 1}, + {Lo: 0x2249, Hi: 0x224b, Stride: 1}, + {Lo: 0x224d, Hi: 0x2251, Stride: 1}, + {Lo: 0x2253, Hi: 0x225f, Stride: 1}, + {Lo: 0x2262, Hi: 0x2263, Stride: 1}, + {Lo: 0x2268, Hi: 0x2269, Stride: 1}, + {Lo: 0x226c, Hi: 0x226d, Stride: 1}, + {Lo: 0x2270, Hi: 0x2281, Stride: 1}, + {Lo: 0x2284, Hi: 0x2285, Stride: 1}, + {Lo: 0x2288, Hi: 0x2294, Stride: 1}, + {Lo: 0x2296, Hi: 0x2298, Stride: 1}, + {Lo: 0x229a, Hi: 0x22a4, Stride: 1}, + {Lo: 0x22a6, Hi: 0x22be, Stride: 1}, + {Lo: 0x22c0, Hi: 0x22ee, Stride: 1}, + {Lo: 0x22f0, Hi: 0x2307, Stride: 1}, + {Lo: 0x230c, Hi: 0x2311, Stride: 1}, + {Lo: 0x2313, Hi: 0x2319, Stride: 1}, + {Lo: 0x231c, Hi: 0x2328, Stride: 1}, + {Lo: 0x232b, Hi: 0x23ef, Stride: 1}, + {Lo: 0x23f4, Hi: 0x2426, Stride: 1}, + {Lo: 0x2440, Hi: 0x244a, Stride: 1}, + {Lo: 0x24ff, Hi: 0x254c, Stride: 77}, + {Lo: 0x254d, Hi: 0x254f, Stride: 1}, + {Lo: 0x2575, Hi: 0x257f, Stride: 1}, + {Lo: 0x2590, Hi: 0x2591, Stride: 1}, + {Lo: 0x2596, Hi: 0x259f, Stride: 1}, + {Lo: 0x25a2, Hi: 0x25aa, Stride: 8}, + {Lo: 0x25ab, Hi: 0x25b1, Stride: 1}, + {Lo: 0x25b4, Hi: 0x25b5, Stride: 1}, + {Lo: 0x25b8, Hi: 0x25bb, Stride: 1}, + {Lo: 0x25be, Hi: 0x25bf, Stride: 1}, + {Lo: 0x25c2, Hi: 0x25c5, Stride: 1}, + {Lo: 0x25c9, Hi: 0x25ca, Stride: 1}, + {Lo: 0x25cc, Hi: 0x25cd, Stride: 1}, + {Lo: 0x25d2, Hi: 0x25e1, Stride: 1}, + {Lo: 0x25e6, Hi: 0x25ee, Stride: 1}, + {Lo: 0x25f0, Hi: 0x25ff, Stride: 1}, + {Lo: 0x2604, Hi: 0x2607, Stride: 3}, + {Lo: 0x2608, Hi: 0x260a, Stride: 2}, + {Lo: 0x260b, Hi: 0x260d, Stride: 1}, + {Lo: 0x2610, Hi: 0x2613, Stride: 1}, + {Lo: 0x2619, Hi: 0x2620, Stride: 7}, + {Lo: 0x2621, Hi: 0x2638, Stride: 1}, + {Lo: 0x263c, Hi: 0x263f, Stride: 1}, + {Lo: 0x2641, Hi: 0x2643, Stride: 2}, + {Lo: 0x2644, Hi: 0x265f, Stride: 1}, + {Lo: 0x2662, Hi: 0x2666, Stride: 4}, + {Lo: 0x266b, Hi: 0x266e, Stride: 3}, + {Lo: 0x2670, Hi: 0x267e, Stride: 1}, + {Lo: 0x2680, Hi: 0x269d, Stride: 1}, + {Lo: 0x26a0, Hi: 0x26bc, Stride: 1}, + {Lo: 0x26ce, Hi: 0x26e2, Stride: 20}, + {Lo: 0x26e4, Hi: 0x26e7, Stride: 1}, + {Lo: 0x2705, Hi: 0x2707, Stride: 1}, + {Lo: 0x270e, Hi: 0x2756, Stride: 1}, + {Lo: 0x2758, Hi: 0x275a, Stride: 1}, + {Lo: 0x2761, Hi: 0x2765, Stride: 4}, + {Lo: 0x2766, Hi: 0x2767, Stride: 1}, + {Lo: 0x2794, Hi: 0x27c4, Stride: 1}, + {Lo: 0x27c7, Hi: 0x27e5, Stride: 1}, + {Lo: 0x27f0, Hi: 0x2982, Stride: 1}, + {Lo: 0x2999, Hi: 0x29d7, Stride: 1}, + {Lo: 0x29dc, Hi: 0x29fb, Stride: 1}, + {Lo: 0x29fe, Hi: 0x2b54, Stride: 1}, + {Lo: 0x2b5a, Hi: 0x2b73, Stride: 1}, + {Lo: 0x2b76, Hi: 0x2b95, Stride: 1}, + {Lo: 0x2b97, Hi: 0x2cee, Stride: 1}, + {Lo: 0x2cf2, Hi: 0x2cf3, Stride: 1}, + {Lo: 0x2cfd, Hi: 0x2d00, Stride: 3}, + {Lo: 0x2d01, Hi: 0x2d25, Stride: 1}, + {Lo: 0x2d27, Hi: 0x2d2d, Stride: 6}, + {Lo: 0x2d30, Hi: 0x2d67, Stride: 1}, + {Lo: 0x2d6f, Hi: 0x2d80, Stride: 17}, + {Lo: 0x2d81, Hi: 0x2d96, Stride: 1}, + {Lo: 0x2da0, Hi: 0x2da6, Stride: 1}, + {Lo: 0x2da8, Hi: 0x2dae, Stride: 1}, + {Lo: 0x2db0, Hi: 0x2db6, Stride: 1}, + {Lo: 0x2db8, Hi: 0x2dbe, Stride: 1}, + {Lo: 0x2dc0, Hi: 0x2dc6, Stride: 1}, + {Lo: 0x2dc8, Hi: 0x2dce, Stride: 1}, + {Lo: 0x2dd0, Hi: 0x2dd6, Stride: 1}, + {Lo: 0x2dd8, Hi: 0x2dde, Stride: 1}, + {Lo: 0x2e16, Hi: 0x2e1a, Stride: 4}, + {Lo: 0x2e1b, Hi: 0x2e1e, Stride: 3}, + {Lo: 0x2e1f, Hi: 0x2e2f, Stride: 16}, + {Lo: 0x2e32, Hi: 0x2e35, Stride: 3}, + {Lo: 0x2e36, Hi: 0x2e39, Stride: 1}, + {Lo: 0x2e3f, Hi: 0x2e4b, Stride: 12}, + {Lo: 0x2e4d, Hi: 0x2e50, Stride: 3}, + {Lo: 0x2e51, Hi: 0x2e52, Stride: 1}, + {Lo: 0x4dc0, Hi: 0x4dff, Stride: 1}, + {Lo: 0xa4d0, Hi: 0xa4fd, Stride: 1}, + {Lo: 0xa500, Hi: 0xa60c, Stride: 1}, + {Lo: 0xa610, Hi: 0xa61f, Stride: 1}, + {Lo: 0xa62a, Hi: 0xa62b, Stride: 1}, + {Lo: 0xa640, Hi: 0xa66e, Stride: 1}, + {Lo: 0xa673, Hi: 0xa67e, Stride: 11}, + {Lo: 0xa67f, Hi: 0xa69d, Stride: 1}, + {Lo: 0xa6a0, Hi: 0xa6ef, Stride: 1}, + {Lo: 0xa6f2, Hi: 0xa700, Stride: 14}, + {Lo: 0xa701, Hi: 0xa7ca, Stride: 1}, + {Lo: 0xa7d0, Hi: 0xa7d1, Stride: 1}, + {Lo: 0xa7d3, Hi: 0xa7d5, Stride: 2}, + {Lo: 0xa7d6, Hi: 0xa7d9, Stride: 1}, + {Lo: 0xa7f2, Hi: 0xa801, Stride: 1}, + {Lo: 0xa803, Hi: 0xa805, Stride: 1}, + {Lo: 0xa807, Hi: 0xa80a, Stride: 1}, + {Lo: 0xa80c, Hi: 0xa822, Stride: 1}, + {Lo: 0xa828, Hi: 0xa82b, Stride: 1}, + {Lo: 0xa830, Hi: 0xa837, Stride: 1}, + {Lo: 0xa839, Hi: 0xa840, Stride: 7}, + {Lo: 0xa841, Hi: 0xa873, Stride: 1}, + {Lo: 0xa882, Hi: 0xa8b3, Stride: 1}, + {Lo: 0xa8f2, Hi: 0xa8fb, Stride: 1}, + {Lo: 0xa8fd, Hi: 0xa8fe, Stride: 1}, + {Lo: 0xa90a, Hi: 0xa925, Stride: 1}, + {Lo: 0xa930, Hi: 0xa946, Stride: 1}, + {Lo: 0xa95f, Hi: 0xaae0, Stride: 385}, + {Lo: 0xaae1, Hi: 0xaaea, Stride: 1}, + {Lo: 0xaaf2, Hi: 0xaaf4, Stride: 1}, + {Lo: 0xab01, Hi: 0xab06, Stride: 1}, + {Lo: 0xab09, Hi: 0xab0e, Stride: 1}, + {Lo: 0xab11, Hi: 0xab16, Stride: 1}, + {Lo: 0xab20, Hi: 0xab26, Stride: 1}, + {Lo: 0xab28, Hi: 0xab2e, Stride: 1}, + {Lo: 0xab30, Hi: 0xab6b, Stride: 1}, + {Lo: 0xab70, Hi: 0xabe2, Stride: 1}, + {Lo: 0xfb00, Hi: 0xfb06, Stride: 1}, + {Lo: 0xfb13, Hi: 0xfb17, Stride: 1}, + {Lo: 0xfb29, Hi: 0xfb50, Stride: 39}, + {Lo: 0xfb51, Hi: 0xfbc2, Stride: 1}, + {Lo: 0xfbd3, Hi: 0xfd3d, Stride: 1}, + {Lo: 0xfd40, Hi: 0xfd8f, Stride: 1}, + {Lo: 0xfd92, Hi: 0xfdc7, Stride: 1}, + {Lo: 0xfdcf, Hi: 0xfdf0, Stride: 33}, + {Lo: 0xfdf1, Hi: 0xfdfb, Stride: 1}, + {Lo: 0xfdfd, Hi: 0xfdff, Stride: 1}, + {Lo: 0xfe70, Hi: 0xfe74, Stride: 1}, + {Lo: 0xfe76, Hi: 0xfefc, Stride: 1}, + {Lo: 0xffe8, Hi: 0xffee, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x10000, Hi: 0x1000b, Stride: 1}, + {Lo: 0x1000d, Hi: 0x10026, Stride: 1}, + {Lo: 0x10028, Hi: 0x1003a, Stride: 1}, + {Lo: 0x1003c, Hi: 0x1003d, Stride: 1}, + {Lo: 0x1003f, Hi: 0x1004d, Stride: 1}, + {Lo: 0x10050, Hi: 0x1005d, Stride: 1}, + {Lo: 0x10080, Hi: 0x100fa, Stride: 1}, + {Lo: 0x10107, Hi: 0x10133, Stride: 1}, + {Lo: 0x10137, Hi: 0x1018e, Stride: 1}, + {Lo: 0x10190, Hi: 0x1019c, Stride: 1}, + {Lo: 0x101a0, Hi: 0x101d0, Stride: 48}, + {Lo: 0x101d1, Hi: 0x101fc, Stride: 1}, + {Lo: 0x10280, Hi: 0x1029c, Stride: 1}, + {Lo: 0x102a0, Hi: 0x102d0, Stride: 1}, + {Lo: 0x102e1, Hi: 0x102fb, Stride: 1}, + {Lo: 0x10300, Hi: 0x10323, Stride: 1}, + {Lo: 0x1032d, Hi: 0x1034a, Stride: 1}, + {Lo: 0x10350, Hi: 0x10375, Stride: 1}, + {Lo: 0x10380, Hi: 0x1039d, Stride: 1}, + {Lo: 0x103a0, Hi: 0x103c3, Stride: 1}, + {Lo: 0x103c8, Hi: 0x103cf, Stride: 1}, + {Lo: 0x103d1, Hi: 0x103d5, Stride: 1}, + {Lo: 0x10400, Hi: 0x1049d, Stride: 1}, + {Lo: 0x104b0, Hi: 0x104d3, Stride: 1}, + {Lo: 0x104d8, Hi: 0x104fb, Stride: 1}, + {Lo: 0x10500, Hi: 0x10527, Stride: 1}, + {Lo: 0x10530, Hi: 0x10563, Stride: 1}, + {Lo: 0x1056f, Hi: 0x1057a, Stride: 1}, + {Lo: 0x1057c, Hi: 0x1058a, Stride: 1}, + {Lo: 0x1058c, Hi: 0x10592, Stride: 1}, + {Lo: 0x10594, Hi: 0x10595, Stride: 1}, + {Lo: 0x10597, Hi: 0x105a1, Stride: 1}, + {Lo: 0x105a3, Hi: 0x105b1, Stride: 1}, + {Lo: 0x105b3, Hi: 0x105b9, Stride: 1}, + {Lo: 0x105bb, Hi: 0x105bc, Stride: 1}, + {Lo: 0x10600, Hi: 0x10736, Stride: 1}, + {Lo: 0x10740, Hi: 0x10755, Stride: 1}, + {Lo: 0x10760, Hi: 0x10767, Stride: 1}, + {Lo: 0x10780, Hi: 0x10785, Stride: 1}, + {Lo: 0x10787, Hi: 0x107b0, Stride: 1}, + {Lo: 0x107b2, Hi: 0x107ba, Stride: 1}, + {Lo: 0x10800, Hi: 0x10805, Stride: 1}, + {Lo: 0x10808, Hi: 0x1080a, Stride: 2}, + {Lo: 0x1080b, Hi: 0x10835, Stride: 1}, + {Lo: 0x10837, Hi: 0x10838, Stride: 1}, + {Lo: 0x1083c, Hi: 0x1083f, Stride: 3}, + {Lo: 0x10840, Hi: 0x10855, Stride: 1}, + {Lo: 0x10858, Hi: 0x1089e, Stride: 1}, + {Lo: 0x108a7, Hi: 0x108af, Stride: 1}, + {Lo: 0x108e0, Hi: 0x108f2, Stride: 1}, + {Lo: 0x108f4, Hi: 0x108f5, Stride: 1}, + {Lo: 0x108fb, Hi: 0x1091b, Stride: 1}, + {Lo: 0x10920, Hi: 0x10939, Stride: 1}, + {Lo: 0x1093f, Hi: 0x10980, Stride: 65}, + {Lo: 0x10981, Hi: 0x109b7, Stride: 1}, + {Lo: 0x109bc, Hi: 0x109cf, Stride: 1}, + {Lo: 0x109d2, Hi: 0x10a00, Stride: 1}, + {Lo: 0x10a10, Hi: 0x10a13, Stride: 1}, + {Lo: 0x10a15, Hi: 0x10a17, Stride: 1}, + {Lo: 0x10a19, Hi: 0x10a35, Stride: 1}, + {Lo: 0x10a40, Hi: 0x10a48, Stride: 1}, + {Lo: 0x10a58, Hi: 0x10a60, Stride: 8}, + {Lo: 0x10a61, Hi: 0x10a9f, Stride: 1}, + {Lo: 0x10ac0, Hi: 0x10ae4, Stride: 1}, + {Lo: 0x10aeb, Hi: 0x10aef, Stride: 1}, + {Lo: 0x10b00, Hi: 0x10b35, Stride: 1}, + {Lo: 0x10b40, Hi: 0x10b55, Stride: 1}, + {Lo: 0x10b58, Hi: 0x10b72, Stride: 1}, + {Lo: 0x10b78, Hi: 0x10b91, Stride: 1}, + {Lo: 0x10b99, Hi: 0x10b9c, Stride: 1}, + {Lo: 0x10ba9, Hi: 0x10baf, Stride: 1}, + {Lo: 0x10c00, Hi: 0x10c48, Stride: 1}, + {Lo: 0x10c80, Hi: 0x10cb2, Stride: 1}, + {Lo: 0x10cc0, Hi: 0x10cf2, Stride: 1}, + {Lo: 0x10cfa, Hi: 0x10d23, Stride: 1}, + {Lo: 0x10e60, Hi: 0x10e7e, Stride: 1}, + {Lo: 0x10e80, Hi: 0x10ea9, Stride: 1}, + {Lo: 0x10eb0, Hi: 0x10eb1, Stride: 1}, + {Lo: 0x10f00, Hi: 0x10f27, Stride: 1}, + {Lo: 0x10f30, Hi: 0x10f45, Stride: 1}, + {Lo: 0x10f51, Hi: 0x10f59, Stride: 1}, + {Lo: 0x10f70, Hi: 0x10f81, Stride: 1}, + {Lo: 0x10f86, Hi: 0x10f89, Stride: 1}, + {Lo: 0x10fb0, Hi: 0x10fcb, Stride: 1}, + {Lo: 0x10fe0, Hi: 0x10ff6, Stride: 1}, + {Lo: 0x11083, Hi: 0x110af, Stride: 1}, + {Lo: 0x110bb, Hi: 0x110bc, Stride: 1}, + {Lo: 0x110d0, Hi: 0x110e8, Stride: 1}, + {Lo: 0x11103, Hi: 0x11126, Stride: 1}, + {Lo: 0x11144, Hi: 0x11147, Stride: 3}, + {Lo: 0x11150, Hi: 0x11172, Stride: 1}, + {Lo: 0x11174, Hi: 0x11176, Stride: 2}, + {Lo: 0x11183, Hi: 0x111b2, Stride: 1}, + {Lo: 0x111c1, Hi: 0x111c4, Stride: 1}, + {Lo: 0x111c7, Hi: 0x111cd, Stride: 6}, + {Lo: 0x111da, Hi: 0x111dc, Stride: 2}, + {Lo: 0x111e1, Hi: 0x111f4, Stride: 1}, + {Lo: 0x11200, Hi: 0x11211, Stride: 1}, + {Lo: 0x11213, Hi: 0x1122b, Stride: 1}, + {Lo: 0x1123a, Hi: 0x1123d, Stride: 3}, + {Lo: 0x1123f, Hi: 0x11240, Stride: 1}, + {Lo: 0x11280, Hi: 0x11286, Stride: 1}, + {Lo: 0x11288, Hi: 0x1128a, Stride: 2}, + {Lo: 0x1128b, Hi: 0x1128d, Stride: 1}, + {Lo: 0x1128f, Hi: 0x1129d, Stride: 1}, + {Lo: 0x1129f, Hi: 0x112a8, Stride: 1}, + {Lo: 0x112b0, Hi: 0x112de, Stride: 1}, + {Lo: 0x11400, Hi: 0x11434, Stride: 1}, + {Lo: 0x11447, Hi: 0x1144a, Stride: 1}, + {Lo: 0x1144f, Hi: 0x1145d, Stride: 14}, + {Lo: 0x1145f, Hi: 0x11461, Stride: 1}, + {Lo: 0x11480, Hi: 0x114af, Stride: 1}, + {Lo: 0x114c4, Hi: 0x114c7, Stride: 1}, + {Lo: 0x11580, Hi: 0x115ae, Stride: 1}, + {Lo: 0x115c6, Hi: 0x115c8, Stride: 1}, + {Lo: 0x115d8, Hi: 0x115db, Stride: 1}, + {Lo: 0x11600, Hi: 0x1162f, Stride: 1}, + {Lo: 0x11643, Hi: 0x11644, Stride: 1}, + {Lo: 0x11680, Hi: 0x116aa, Stride: 1}, + {Lo: 0x116b8, Hi: 0x116b9, Stride: 1}, + {Lo: 0x11800, Hi: 0x1182b, Stride: 1}, + {Lo: 0x1183b, Hi: 0x118a0, Stride: 101}, + {Lo: 0x118a1, Hi: 0x118df, Stride: 1}, + {Lo: 0x118ea, Hi: 0x118f2, Stride: 1}, + {Lo: 0x118ff, Hi: 0x119a0, Stride: 161}, + {Lo: 0x119a1, Hi: 0x119a7, Stride: 1}, + {Lo: 0x119aa, Hi: 0x119d0, Stride: 1}, + {Lo: 0x119e1, Hi: 0x119e3, Stride: 2}, + {Lo: 0x11a00, Hi: 0x11a0b, Stride: 11}, + {Lo: 0x11a0c, Hi: 0x11a32, Stride: 1}, + {Lo: 0x11a3a, Hi: 0x11a46, Stride: 6}, + {Lo: 0x11a50, Hi: 0x11a5c, Stride: 12}, + {Lo: 0x11a5d, Hi: 0x11a89, Stride: 1}, + {Lo: 0x11a9d, Hi: 0x11ab0, Stride: 19}, + {Lo: 0x11ab1, Hi: 0x11af8, Stride: 1}, + {Lo: 0x11c00, Hi: 0x11c08, Stride: 1}, + {Lo: 0x11c0a, Hi: 0x11c2e, Stride: 1}, + {Lo: 0x11c40, Hi: 0x11c5a, Stride: 26}, + {Lo: 0x11c5b, Hi: 0x11c6c, Stride: 1}, + {Lo: 0x11c72, Hi: 0x11c8f, Stride: 1}, + {Lo: 0x11d00, Hi: 0x11d06, Stride: 1}, + {Lo: 0x11d08, Hi: 0x11d09, Stride: 1}, + {Lo: 0x11d0b, Hi: 0x11d30, Stride: 1}, + {Lo: 0x11d46, Hi: 0x11d60, Stride: 26}, + {Lo: 0x11d61, Hi: 0x11d65, Stride: 1}, + {Lo: 0x11d67, Hi: 0x11d68, Stride: 1}, + {Lo: 0x11d6a, Hi: 0x11d89, Stride: 1}, + {Lo: 0x11d98, Hi: 0x11fb0, Stride: 536}, + {Lo: 0x11fc0, Hi: 0x11fdc, Stride: 1}, + {Lo: 0x11fe1, Hi: 0x11ff1, Stride: 1}, + {Lo: 0x12000, Hi: 0x12399, Stride: 1}, + {Lo: 0x12400, Hi: 0x1246e, Stride: 1}, + {Lo: 0x12480, Hi: 0x12543, Stride: 1}, + {Lo: 0x12f90, Hi: 0x12ff2, Stride: 1}, + {Lo: 0x13000, Hi: 0x13257, Stride: 1}, + {Lo: 0x1325e, Hi: 0x13281, Stride: 1}, + {Lo: 0x13283, Hi: 0x13285, Stride: 1}, + {Lo: 0x1328a, Hi: 0x13378, Stride: 1}, + {Lo: 0x1337c, Hi: 0x1342e, Stride: 1}, + {Lo: 0x13441, Hi: 0x13446, Stride: 1}, + {Lo: 0x14400, Hi: 0x145cd, Stride: 1}, + {Lo: 0x145d0, Hi: 0x14646, Stride: 1}, + {Lo: 0x16800, Hi: 0x16a38, Stride: 1}, + {Lo: 0x16a40, Hi: 0x16a5e, Stride: 1}, + {Lo: 0x16a70, Hi: 0x16abe, Stride: 1}, + {Lo: 0x16ad0, Hi: 0x16aed, Stride: 1}, + {Lo: 0x16b00, Hi: 0x16b2f, Stride: 1}, + {Lo: 0x16b3a, Hi: 0x16b43, Stride: 1}, + {Lo: 0x16b45, Hi: 0x16b5b, Stride: 22}, + {Lo: 0x16b5c, Hi: 0x16b61, Stride: 1}, + {Lo: 0x16b63, Hi: 0x16b77, Stride: 1}, + {Lo: 0x16b7d, Hi: 0x16b8f, Stride: 1}, + {Lo: 0x16e40, Hi: 0x16e96, Stride: 1}, + {Lo: 0x16e99, Hi: 0x16e9a, Stride: 1}, + {Lo: 0x16f00, Hi: 0x16f4a, Stride: 1}, + {Lo: 0x16f50, Hi: 0x16f93, Stride: 67}, + {Lo: 0x16f94, Hi: 0x16f9f, Stride: 1}, + {Lo: 0x18b00, Hi: 0x18cd5, Stride: 1}, + {Lo: 0x1aff0, Hi: 0x1aff3, Stride: 1}, + {Lo: 0x1aff5, Hi: 0x1affb, Stride: 1}, + {Lo: 0x1affd, Hi: 0x1affe, Stride: 1}, + {Lo: 0x1bc00, Hi: 0x1bc6a, Stride: 1}, + {Lo: 0x1bc70, Hi: 0x1bc7c, Stride: 1}, + {Lo: 0x1bc80, Hi: 0x1bc88, Stride: 1}, + {Lo: 0x1bc90, Hi: 0x1bc99, Stride: 1}, + {Lo: 0x1bc9c, Hi: 0x1cf50, Stride: 4788}, + {Lo: 0x1cf51, Hi: 0x1cfc3, Stride: 1}, + {Lo: 0x1d000, Hi: 0x1d0f5, Stride: 1}, + {Lo: 0x1d100, Hi: 0x1d126, Stride: 1}, + {Lo: 0x1d129, Hi: 0x1d164, Stride: 1}, + {Lo: 0x1d16a, Hi: 0x1d16c, Stride: 1}, + {Lo: 0x1d183, Hi: 0x1d184, Stride: 1}, + {Lo: 0x1d18c, Hi: 0x1d1a9, Stride: 1}, + {Lo: 0x1d1ae, Hi: 0x1d1ea, Stride: 1}, + {Lo: 0x1d200, Hi: 0x1d241, Stride: 1}, + {Lo: 0x1d245, Hi: 0x1d2c0, Stride: 123}, + {Lo: 0x1d2c1, Hi: 0x1d2d3, Stride: 1}, + {Lo: 0x1d2e0, Hi: 0x1d2f3, Stride: 1}, + {Lo: 0x1d300, Hi: 0x1d356, Stride: 1}, + {Lo: 0x1d360, Hi: 0x1d378, Stride: 1}, + {Lo: 0x1d400, Hi: 0x1d454, Stride: 1}, + {Lo: 0x1d456, Hi: 0x1d49c, Stride: 1}, + {Lo: 0x1d49e, Hi: 0x1d49f, Stride: 1}, + {Lo: 0x1d4a2, Hi: 0x1d4a5, Stride: 3}, + {Lo: 0x1d4a6, Hi: 0x1d4a9, Stride: 3}, + {Lo: 0x1d4aa, Hi: 0x1d4ac, Stride: 1}, + {Lo: 0x1d4ae, Hi: 0x1d4b9, Stride: 1}, + {Lo: 0x1d4bb, Hi: 0x1d4bd, Stride: 2}, + {Lo: 0x1d4be, Hi: 0x1d4c3, Stride: 1}, + {Lo: 0x1d4c5, Hi: 0x1d505, Stride: 1}, + {Lo: 0x1d507, Hi: 0x1d50a, Stride: 1}, + {Lo: 0x1d50d, Hi: 0x1d514, Stride: 1}, + {Lo: 0x1d516, Hi: 0x1d51c, Stride: 1}, + {Lo: 0x1d51e, Hi: 0x1d539, Stride: 1}, + {Lo: 0x1d53b, Hi: 0x1d53e, Stride: 1}, + {Lo: 0x1d540, Hi: 0x1d544, Stride: 1}, + {Lo: 0x1d546, Hi: 0x1d54a, Stride: 4}, + {Lo: 0x1d54b, Hi: 0x1d550, Stride: 1}, + {Lo: 0x1d552, Hi: 0x1d6a5, Stride: 1}, + {Lo: 0x1d6a8, Hi: 0x1d7cb, Stride: 1}, + {Lo: 0x1d800, Hi: 0x1d9ff, Stride: 1}, + {Lo: 0x1da37, Hi: 0x1da3a, Stride: 1}, + {Lo: 0x1da6d, Hi: 0x1da74, Stride: 1}, + {Lo: 0x1da76, Hi: 0x1da83, Stride: 1}, + {Lo: 0x1da85, Hi: 0x1da86, Stride: 1}, + {Lo: 0x1da8b, Hi: 0x1df00, Stride: 1141}, + {Lo: 0x1df01, Hi: 0x1df1e, Stride: 1}, + {Lo: 0x1df25, Hi: 0x1df2a, Stride: 1}, + {Lo: 0x1e030, Hi: 0x1e06d, Stride: 1}, + {Lo: 0x1e100, Hi: 0x1e12c, Stride: 1}, + {Lo: 0x1e137, Hi: 0x1e13d, Stride: 1}, + {Lo: 0x1e14e, Hi: 0x1e14f, Stride: 1}, + {Lo: 0x1e290, Hi: 0x1e2ad, Stride: 1}, + {Lo: 0x1e2c0, Hi: 0x1e2eb, Stride: 1}, + {Lo: 0x1e4d0, Hi: 0x1e4eb, Stride: 1}, + {Lo: 0x1e7e0, Hi: 0x1e7e6, Stride: 1}, + {Lo: 0x1e7e8, Hi: 0x1e7eb, Stride: 1}, + {Lo: 0x1e7ed, Hi: 0x1e7ee, Stride: 1}, + {Lo: 0x1e7f0, Hi: 0x1e7fe, Stride: 1}, + {Lo: 0x1e800, Hi: 0x1e8c4, Stride: 1}, + {Lo: 0x1e8c7, Hi: 0x1e8cf, Stride: 1}, + {Lo: 0x1e900, Hi: 0x1e943, Stride: 1}, + {Lo: 0x1e94b, Hi: 0x1ec71, Stride: 806}, + {Lo: 0x1ec72, Hi: 0x1ecab, Stride: 1}, + {Lo: 0x1ecad, Hi: 0x1ecaf, Stride: 1}, + {Lo: 0x1ecb1, Hi: 0x1ecb4, Stride: 1}, + {Lo: 0x1ed01, Hi: 0x1ed3d, Stride: 1}, + {Lo: 0x1ee00, Hi: 0x1ee03, Stride: 1}, + {Lo: 0x1ee05, Hi: 0x1ee1f, Stride: 1}, + {Lo: 0x1ee21, Hi: 0x1ee22, Stride: 1}, + {Lo: 0x1ee24, Hi: 0x1ee27, Stride: 3}, + {Lo: 0x1ee29, Hi: 0x1ee32, Stride: 1}, + {Lo: 0x1ee34, Hi: 0x1ee37, Stride: 1}, + {Lo: 0x1ee39, Hi: 0x1ee3b, Stride: 2}, + {Lo: 0x1ee42, Hi: 0x1ee47, Stride: 5}, + {Lo: 0x1ee49, Hi: 0x1ee4d, Stride: 2}, + {Lo: 0x1ee4e, Hi: 0x1ee4f, Stride: 1}, + {Lo: 0x1ee51, Hi: 0x1ee52, Stride: 1}, + {Lo: 0x1ee54, Hi: 0x1ee57, Stride: 3}, + {Lo: 0x1ee59, Hi: 0x1ee61, Stride: 2}, + {Lo: 0x1ee62, Hi: 0x1ee64, Stride: 2}, + {Lo: 0x1ee67, Hi: 0x1ee6a, Stride: 1}, + {Lo: 0x1ee6c, Hi: 0x1ee72, Stride: 1}, + {Lo: 0x1ee74, Hi: 0x1ee77, Stride: 1}, + {Lo: 0x1ee79, Hi: 0x1ee7c, Stride: 1}, + {Lo: 0x1ee7e, Hi: 0x1ee80, Stride: 2}, + {Lo: 0x1ee81, Hi: 0x1ee89, Stride: 1}, + {Lo: 0x1ee8b, Hi: 0x1ee9b, Stride: 1}, + {Lo: 0x1eea1, Hi: 0x1eea3, Stride: 1}, + {Lo: 0x1eea5, Hi: 0x1eea9, Stride: 1}, + {Lo: 0x1eeab, Hi: 0x1eebb, Stride: 1}, + {Lo: 0x1eef0, Hi: 0x1eef1, Stride: 1}, + {Lo: 0x1f12e, Hi: 0x1f12f, Stride: 1}, + {Lo: 0x1f16a, Hi: 0x1f16c, Stride: 1}, + {Lo: 0x1f39c, Hi: 0x1f39d, Stride: 1}, + {Lo: 0x1f3b5, Hi: 0x1f3b6, Stride: 1}, + {Lo: 0x1f3bc, Hi: 0x1f4a0, Stride: 228}, + {Lo: 0x1f4a2, Hi: 0x1f4a4, Stride: 2}, + {Lo: 0x1f4af, Hi: 0x1f4b1, Stride: 2}, + {Lo: 0x1f4b2, Hi: 0x1f500, Stride: 78}, + {Lo: 0x1f501, Hi: 0x1f506, Stride: 1}, + {Lo: 0x1f517, Hi: 0x1f524, Stride: 1}, + {Lo: 0x1f532, Hi: 0x1f549, Stride: 1}, + {Lo: 0x1f5d4, Hi: 0x1f5db, Stride: 1}, + {Lo: 0x1f5f4, Hi: 0x1f5f9, Stride: 1}, + {Lo: 0x1f650, Hi: 0x1f675, Stride: 1}, + {Lo: 0x1f67c, Hi: 0x1f67f, Stride: 1}, + {Lo: 0x1f700, Hi: 0x1f773, Stride: 1}, + {Lo: 0x1f780, Hi: 0x1f7d4, Stride: 1}, + {Lo: 0x1f800, Hi: 0x1f80b, Stride: 1}, + {Lo: 0x1f810, Hi: 0x1f847, Stride: 1}, + {Lo: 0x1f850, Hi: 0x1f859, Stride: 1}, + {Lo: 0x1f860, Hi: 0x1f887, Stride: 1}, + {Lo: 0x1f890, Hi: 0x1f8ad, Stride: 1}, + {Lo: 0x1f900, Hi: 0x1f90b, Stride: 1}, + {Lo: 0x1fa00, Hi: 0x1fa53, Stride: 1}, + {Lo: 0x1fb00, Hi: 0x1fb92, Stride: 1}, + {Lo: 0x1fb94, Hi: 0x1fbca, Stride: 1}, + }, + LatinOffset: 11, +} + +// Infix Numeric Separator +var BreakIS = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x002c, Hi: 0x002e, Stride: 2}, + {Lo: 0x003a, Hi: 0x003b, Stride: 1}, + {Lo: 0x037e, Hi: 0x0589, Stride: 523}, + {Lo: 0x060c, Hi: 0x060d, Stride: 1}, + {Lo: 0x07f8, Hi: 0x2044, Stride: 6220}, + {Lo: 0xfe10, Hi: 0xfe13, Stride: 3}, + {Lo: 0xfe14, Hi: 0xfe14, Stride: 1}, + }, + LatinOffset: 2, +} + +// Prefix Numeric +var BreakPR = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0024, Hi: 0x002b, Stride: 7}, + {Lo: 0x005c, Hi: 0x00a3, Stride: 71}, + {Lo: 0x00a4, Hi: 0x00a5, Stride: 1}, + {Lo: 0x00b1, Hi: 0x058f, Stride: 1246}, + {Lo: 0x07fe, Hi: 0x07ff, Stride: 1}, + {Lo: 0x09fb, Hi: 0x0af1, Stride: 246}, + {Lo: 0x0bf9, Hi: 0x0e3f, Stride: 582}, + {Lo: 0x17db, Hi: 0x20a0, Stride: 2245}, + {Lo: 0x20a1, Hi: 0x20a6, Stride: 1}, + {Lo: 0x20a8, Hi: 0x20b5, Stride: 1}, + {Lo: 0x20b7, Hi: 0x20ba, Stride: 1}, + {Lo: 0x20bc, Hi: 0x20bd, Stride: 1}, + {Lo: 0x20bf, Hi: 0x20c1, Stride: 2}, + {Lo: 0x20c2, Hi: 0x20cf, Stride: 1}, + {Lo: 0x2116, Hi: 0x2212, Stride: 252}, + {Lo: 0x2213, Hi: 0xfe69, Stride: 56406}, + {Lo: 0xff04, Hi: 0xffe1, Stride: 221}, + {Lo: 0xffe5, Hi: 0xffe6, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x1e2ff, Hi: 0x1e2ff, Stride: 1}, + }, + LatinOffset: 3, +} + +// Postfix Numeric +var BreakPO = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0025, Hi: 0x00a2, Stride: 125}, + {Lo: 0x00b0, Hi: 0x0609, Stride: 1369}, + {Lo: 0x060a, Hi: 0x060b, Stride: 1}, + {Lo: 0x066a, Hi: 0x09f2, Stride: 904}, + {Lo: 0x09f3, Hi: 0x09f9, Stride: 6}, + {Lo: 0x0d79, Hi: 0x2030, Stride: 4791}, + {Lo: 0x2031, Hi: 0x2037, Stride: 1}, + {Lo: 0x2057, Hi: 0x20a7, Stride: 80}, + {Lo: 0x20b6, Hi: 0x20bb, Stride: 5}, + {Lo: 0x20be, Hi: 0x20c0, Stride: 2}, + {Lo: 0x2103, Hi: 0x2109, Stride: 6}, + {Lo: 0xa838, Hi: 0xfdfc, Stride: 21956}, + {Lo: 0xfe6a, Hi: 0xff05, Stride: 155}, + {Lo: 0xffe0, Hi: 0xffe0, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x11fdd, Hi: 0x11fe0, Stride: 1}, + {Lo: 0x1ecac, Hi: 0x1ecb0, Stride: 4}, + }, + LatinOffset: 1, +} + +// Open Punctuation +var BreakOP = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0028, Hi: 0x005b, Stride: 51}, + {Lo: 0x007b, Hi: 0x00a1, Stride: 38}, + {Lo: 0x00bf, Hi: 0x0f3a, Stride: 3707}, + {Lo: 0x0f3c, Hi: 0x169b, Stride: 1887}, + {Lo: 0x201a, Hi: 0x201e, Stride: 4}, + {Lo: 0x2045, Hi: 0x207d, Stride: 56}, + {Lo: 0x208d, Hi: 0x2308, Stride: 635}, + {Lo: 0x230a, Hi: 0x2329, Stride: 31}, + {Lo: 0x2768, Hi: 0x2774, Stride: 2}, + {Lo: 0x27c5, Hi: 0x27e6, Stride: 33}, + {Lo: 0x27e8, Hi: 0x27ee, Stride: 2}, + {Lo: 0x2983, Hi: 0x2997, Stride: 2}, + {Lo: 0x29d8, Hi: 0x29da, Stride: 2}, + {Lo: 0x29fc, Hi: 0x2e18, Stride: 1052}, + {Lo: 0x2e22, Hi: 0x2e28, Stride: 2}, + {Lo: 0x2e42, Hi: 0x2e55, Stride: 19}, + {Lo: 0x2e57, Hi: 0x2e5b, Stride: 2}, + {Lo: 0x3008, Hi: 0x3010, Stride: 2}, + {Lo: 0x3014, Hi: 0x301a, Stride: 2}, + {Lo: 0x301d, Hi: 0xfd3f, Stride: 52514}, + {Lo: 0xfe17, Hi: 0xfe35, Stride: 30}, + {Lo: 0xfe37, Hi: 0xfe43, Stride: 2}, + {Lo: 0xfe47, Hi: 0xfe59, Stride: 18}, + {Lo: 0xfe5b, Hi: 0xfe5d, Stride: 2}, + {Lo: 0xff08, Hi: 0xff3b, Stride: 51}, + {Lo: 0xff5b, Hi: 0xff5f, Stride: 4}, + {Lo: 0xff62, Hi: 0xff62, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x13258, Hi: 0x1325a, Stride: 1}, + {Lo: 0x13286, Hi: 0x13288, Stride: 2}, + {Lo: 0x13379, Hi: 0x1342f, Stride: 182}, + {Lo: 0x13437, Hi: 0x1343c, Stride: 5}, + {Lo: 0x1343e, Hi: 0x145ce, Stride: 4496}, + {Lo: 0x1e95e, Hi: 0x1e95f, Stride: 1}, + }, + LatinOffset: 2, +} + +// Close Punctuation +var BreakCL = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x007d, Hi: 0x0f3b, Stride: 3774}, + {Lo: 0x0f3d, Hi: 0x169c, Stride: 1887}, + {Lo: 0x2046, Hi: 0x207e, Stride: 56}, + {Lo: 0x208e, Hi: 0x2309, Stride: 635}, + {Lo: 0x230b, Hi: 0x232a, Stride: 31}, + {Lo: 0x2769, Hi: 0x2775, Stride: 2}, + {Lo: 0x27c6, Hi: 0x27e7, Stride: 33}, + {Lo: 0x27e9, Hi: 0x27ef, Stride: 2}, + {Lo: 0x2984, Hi: 0x2998, Stride: 2}, + {Lo: 0x29d9, Hi: 0x29db, Stride: 2}, + {Lo: 0x29fd, Hi: 0x2e23, Stride: 1062}, + {Lo: 0x2e25, Hi: 0x2e29, Stride: 2}, + {Lo: 0x2e56, Hi: 0x2e5c, Stride: 2}, + {Lo: 0x3001, Hi: 0x3002, Stride: 1}, + {Lo: 0x3009, Hi: 0x3011, Stride: 2}, + {Lo: 0x3015, Hi: 0x301b, Stride: 2}, + {Lo: 0x301e, Hi: 0x301f, Stride: 1}, + {Lo: 0xfd3e, Hi: 0xfe11, Stride: 211}, + {Lo: 0xfe12, Hi: 0xfe18, Stride: 6}, + {Lo: 0xfe36, Hi: 0xfe44, Stride: 2}, + {Lo: 0xfe48, Hi: 0xfe50, Stride: 8}, + {Lo: 0xfe52, Hi: 0xfe5a, Stride: 8}, + {Lo: 0xfe5c, Hi: 0xfe5e, Stride: 2}, + {Lo: 0xff09, Hi: 0xff0c, Stride: 3}, + {Lo: 0xff0e, Hi: 0xff3d, Stride: 47}, + {Lo: 0xff5d, Hi: 0xff60, Stride: 3}, + {Lo: 0xff61, Hi: 0xff63, Stride: 2}, + {Lo: 0xff64, Hi: 0xff64, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x1325b, Hi: 0x1325d, Stride: 1}, + {Lo: 0x13282, Hi: 0x13287, Stride: 5}, + {Lo: 0x13289, Hi: 0x1337a, Stride: 241}, + {Lo: 0x1337b, Hi: 0x13438, Stride: 189}, + {Lo: 0x1343d, Hi: 0x1343f, Stride: 2}, + {Lo: 0x145cf, Hi: 0x145cf, Stride: 1}, + }, +} + +// Close Parenthesis +var BreakCP = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0029, Hi: 0x005d, Stride: 52}, + }, + LatinOffset: 1, +} + +// Quotation +var BreakQU = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0022, Hi: 0x0027, Stride: 5}, + {Lo: 0x00ab, Hi: 0x00bb, Stride: 16}, + {Lo: 0x2018, Hi: 0x2019, Stride: 1}, + {Lo: 0x201b, Hi: 0x201d, Stride: 1}, + {Lo: 0x201f, Hi: 0x2039, Stride: 26}, + {Lo: 0x203a, Hi: 0x275b, Stride: 1825}, + {Lo: 0x275c, Hi: 0x2760, Stride: 1}, + {Lo: 0x2e00, Hi: 0x2e0d, Stride: 1}, + {Lo: 0x2e1c, Hi: 0x2e1d, Stride: 1}, + {Lo: 0x2e20, Hi: 0x2e21, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x1f676, Hi: 0x1f678, Stride: 1}, + }, + LatinOffset: 2, +} + +// Hyphen +var BreakHY = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x002d, Hi: 0x002d, Stride: 1}, + }, + LatinOffset: 1, +} + +// Surrogate +var BreakSG = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0xd800, Hi: 0xdfff, Stride: 1}, + }, +} + +// Non-breaking ("Glue") +var BreakGL = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x00a0, Hi: 0x034f, Stride: 687}, + {Lo: 0x035c, Hi: 0x0362, Stride: 1}, + {Lo: 0x0f08, Hi: 0x0f0c, Stride: 4}, + {Lo: 0x0f12, Hi: 0x0fd9, Stride: 199}, + {Lo: 0x0fda, Hi: 0x180e, Stride: 2100}, + {Lo: 0x1dcd, Hi: 0x1dfc, Stride: 47}, + {Lo: 0x2007, Hi: 0x2011, Stride: 10}, + {Lo: 0x202f, Hi: 0x202f, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x1107f, Hi: 0x13430, Stride: 9137}, + {Lo: 0x13431, Hi: 0x13436, Stride: 1}, + {Lo: 0x13439, Hi: 0x1343b, Stride: 1}, + {Lo: 0x16fe4, Hi: 0x16fe4, Stride: 1}, + }, +} + +// Nonstarter +var BreakNS = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x17d6, Hi: 0x203c, Stride: 2150}, + {Lo: 0x203d, Hi: 0x2047, Stride: 10}, + {Lo: 0x2048, Hi: 0x2049, Stride: 1}, + {Lo: 0x3005, Hi: 0x301c, Stride: 23}, + {Lo: 0x303b, Hi: 0x303c, Stride: 1}, + {Lo: 0x309b, Hi: 0x309e, Stride: 1}, + {Lo: 0x30a0, Hi: 0x30fb, Stride: 91}, + {Lo: 0x30fd, Hi: 0x30fe, Stride: 1}, + {Lo: 0xa015, Hi: 0xfe54, Stride: 24127}, + {Lo: 0xfe55, Hi: 0xff1a, Stride: 197}, + {Lo: 0xff1b, Hi: 0xff65, Stride: 74}, + {Lo: 0xff9e, Hi: 0xff9f, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x16fe0, Hi: 0x16fe3, Stride: 1}, + {Lo: 0x1f679, Hi: 0x1f67b, Stride: 1}, + }, +} + +// Exclamation/Interrogation +var BreakEX = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0021, Hi: 0x003f, Stride: 30}, + {Lo: 0x05c6, Hi: 0x061b, Stride: 85}, + {Lo: 0x061d, Hi: 0x061f, Stride: 1}, + {Lo: 0x06d4, Hi: 0x07f9, Stride: 293}, + {Lo: 0x0f0d, Hi: 0x0f11, Stride: 1}, + {Lo: 0x0f14, Hi: 0x1802, Stride: 2286}, + {Lo: 0x1803, Hi: 0x1808, Stride: 5}, + {Lo: 0x1809, Hi: 0x1944, Stride: 315}, + {Lo: 0x1945, Hi: 0x2762, Stride: 3613}, + {Lo: 0x2763, Hi: 0x2cf9, Stride: 1430}, + {Lo: 0x2cfe, Hi: 0x2e2e, Stride: 304}, + {Lo: 0x2e53, Hi: 0x2e54, Stride: 1}, + {Lo: 0xa60e, Hi: 0xa876, Stride: 616}, + {Lo: 0xa877, Hi: 0xfe15, Stride: 21918}, + {Lo: 0xfe16, Hi: 0xfe56, Stride: 64}, + {Lo: 0xfe57, Hi: 0xff01, Stride: 170}, + {Lo: 0xff1f, Hi: 0xff1f, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x115c4, Hi: 0x115c5, Stride: 1}, + {Lo: 0x11c71, Hi: 0x11c71, Stride: 1}, + }, + LatinOffset: 1, +} + +// Symbols Allowing Break After +var BreakSY = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x002f, Hi: 0x002f, Stride: 1}, + }, + LatinOffset: 1, +} + +// Hebrew Letter +var BreakHL = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x05d0, Hi: 0x05ea, Stride: 1}, + {Lo: 0x05ef, Hi: 0x05f2, Stride: 1}, + {Lo: 0xfb1d, Hi: 0xfb1f, Stride: 2}, + {Lo: 0xfb20, Hi: 0xfb28, Stride: 1}, + {Lo: 0xfb2a, Hi: 0xfb36, Stride: 1}, + {Lo: 0xfb38, Hi: 0xfb3c, Stride: 1}, + {Lo: 0xfb3e, Hi: 0xfb40, Stride: 2}, + {Lo: 0xfb41, Hi: 0xfb43, Stride: 2}, + {Lo: 0xfb44, Hi: 0xfb46, Stride: 2}, + {Lo: 0xfb47, Hi: 0xfb4f, Stride: 1}, + }, +} + +// Ideographic +var BreakID = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x1b50, Hi: 0x1b59, Stride: 1}, + {Lo: 0x1b5c, Hi: 0x1b61, Stride: 5}, + {Lo: 0x1b62, Hi: 0x1b6a, Stride: 1}, + {Lo: 0x1b74, Hi: 0x1b7c, Stride: 1}, + {Lo: 0x231a, Hi: 0x231b, Stride: 1}, + {Lo: 0x23f0, Hi: 0x23f3, Stride: 1}, + {Lo: 0x2600, Hi: 0x2603, Stride: 1}, + {Lo: 0x2614, Hi: 0x2615, Stride: 1}, + {Lo: 0x2618, Hi: 0x261a, Stride: 2}, + {Lo: 0x261b, Hi: 0x261c, Stride: 1}, + {Lo: 0x261e, Hi: 0x261f, Stride: 1}, + {Lo: 0x2639, Hi: 0x263b, Stride: 1}, + {Lo: 0x2668, Hi: 0x267f, Stride: 23}, + {Lo: 0x26bd, Hi: 0x26c8, Stride: 1}, + {Lo: 0x26cd, Hi: 0x26cf, Stride: 2}, + {Lo: 0x26d0, Hi: 0x26d1, Stride: 1}, + {Lo: 0x26d3, Hi: 0x26d4, Stride: 1}, + {Lo: 0x26d8, Hi: 0x26d9, Stride: 1}, + {Lo: 0x26dc, Hi: 0x26df, Stride: 3}, + {Lo: 0x26e0, Hi: 0x26e1, Stride: 1}, + {Lo: 0x26ea, Hi: 0x26f1, Stride: 7}, + {Lo: 0x26f2, Hi: 0x26f5, Stride: 1}, + {Lo: 0x26f7, Hi: 0x26f8, Stride: 1}, + {Lo: 0x26fa, Hi: 0x26fd, Stride: 3}, + {Lo: 0x26fe, Hi: 0x2704, Stride: 1}, + {Lo: 0x2708, Hi: 0x2709, Stride: 1}, + {Lo: 0x2764, Hi: 0x2e80, Stride: 1820}, + {Lo: 0x2e81, Hi: 0x2e99, Stride: 1}, + {Lo: 0x2e9b, Hi: 0x2ef3, Stride: 1}, + {Lo: 0x2f00, Hi: 0x2fd5, Stride: 1}, + {Lo: 0x2ff0, Hi: 0x2fff, Stride: 1}, + {Lo: 0x3003, Hi: 0x3004, Stride: 1}, + {Lo: 0x3006, Hi: 0x3007, Stride: 1}, + {Lo: 0x3012, Hi: 0x3013, Stride: 1}, + {Lo: 0x3020, Hi: 0x3029, Stride: 1}, + {Lo: 0x3030, Hi: 0x3034, Stride: 1}, + {Lo: 0x3036, Hi: 0x303a, Stride: 1}, + {Lo: 0x303d, Hi: 0x303f, Stride: 1}, + {Lo: 0x3042, Hi: 0x304a, Stride: 2}, + {Lo: 0x304b, Hi: 0x3062, Stride: 1}, + {Lo: 0x3064, Hi: 0x3082, Stride: 1}, + {Lo: 0x3084, Hi: 0x3088, Stride: 2}, + {Lo: 0x3089, Hi: 0x308d, Stride: 1}, + {Lo: 0x308f, Hi: 0x3094, Stride: 1}, + {Lo: 0x309f, Hi: 0x30a2, Stride: 3}, + {Lo: 0x30a4, Hi: 0x30aa, Stride: 2}, + {Lo: 0x30ab, Hi: 0x30c2, Stride: 1}, + {Lo: 0x30c4, Hi: 0x30e2, Stride: 1}, + {Lo: 0x30e4, Hi: 0x30e8, Stride: 2}, + {Lo: 0x30e9, Hi: 0x30ed, Stride: 1}, + {Lo: 0x30ef, Hi: 0x30f4, Stride: 1}, + {Lo: 0x30f7, Hi: 0x30fa, Stride: 1}, + {Lo: 0x30ff, Hi: 0x3105, Stride: 6}, + {Lo: 0x3106, Hi: 0x312f, Stride: 1}, + {Lo: 0x3131, Hi: 0x318e, Stride: 1}, + {Lo: 0x3190, Hi: 0x31e3, Stride: 1}, + {Lo: 0x31ef, Hi: 0x3200, Stride: 17}, + {Lo: 0x3201, Hi: 0x321e, Stride: 1}, + {Lo: 0x3220, Hi: 0x3247, Stride: 1}, + {Lo: 0x3250, Hi: 0x4dbf, Stride: 1}, + {Lo: 0x4e00, Hi: 0xa014, Stride: 1}, + {Lo: 0xa016, Hi: 0xa48c, Stride: 1}, + {Lo: 0xa490, Hi: 0xa4c6, Stride: 1}, + {Lo: 0xa9c1, Hi: 0xa9c6, Stride: 1}, + {Lo: 0xa9ca, Hi: 0xa9cd, Stride: 1}, + {Lo: 0xa9d0, Hi: 0xa9d9, Stride: 1}, + {Lo: 0xa9de, Hi: 0xa9df, Stride: 1}, + {Lo: 0xaa50, Hi: 0xaa59, Stride: 1}, + {Lo: 0xaa5c, Hi: 0xf900, Stride: 20132}, + {Lo: 0xf901, Hi: 0xfaff, Stride: 1}, + {Lo: 0xfe30, Hi: 0xfe34, Stride: 1}, + {Lo: 0xfe45, Hi: 0xfe46, Stride: 1}, + {Lo: 0xfe49, Hi: 0xfe4f, Stride: 1}, + {Lo: 0xfe51, Hi: 0xfe5f, Stride: 7}, + {Lo: 0xfe60, Hi: 0xfe66, Stride: 1}, + {Lo: 0xfe68, Hi: 0xfe6b, Stride: 3}, + {Lo: 0xff02, Hi: 0xff03, Stride: 1}, + {Lo: 0xff06, Hi: 0xff07, Stride: 1}, + {Lo: 0xff0a, Hi: 0xff0b, Stride: 1}, + {Lo: 0xff0d, Hi: 0xff0f, Stride: 2}, + {Lo: 0xff10, Hi: 0xff19, Stride: 1}, + {Lo: 0xff1c, Hi: 0xff1e, Stride: 1}, + {Lo: 0xff20, Hi: 0xff3a, Stride: 1}, + {Lo: 0xff3c, Hi: 0xff3e, Stride: 2}, + {Lo: 0xff3f, Hi: 0xff5a, Stride: 1}, + {Lo: 0xff5c, Hi: 0xff5e, Stride: 2}, + {Lo: 0xff66, Hi: 0xff71, Stride: 11}, + {Lo: 0xff72, Hi: 0xff9d, Stride: 1}, + {Lo: 0xffa0, Hi: 0xffbe, Stride: 1}, + {Lo: 0xffc2, Hi: 0xffc7, Stride: 1}, + {Lo: 0xffca, Hi: 0xffcf, Stride: 1}, + {Lo: 0xffd2, Hi: 0xffd7, Stride: 1}, + {Lo: 0xffda, Hi: 0xffdc, Stride: 1}, + {Lo: 0xffe2, Hi: 0xffe4, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x11049, Hi: 0x1104d, Stride: 1}, + {Lo: 0x11052, Hi: 0x11065, Stride: 1}, + {Lo: 0x11950, Hi: 0x11959, Stride: 1}, + {Lo: 0x11f45, Hi: 0x11f4f, Stride: 1}, + {Lo: 0x17000, Hi: 0x187f7, Stride: 1}, + {Lo: 0x18800, Hi: 0x18aff, Stride: 1}, + {Lo: 0x18d00, Hi: 0x18d08, Stride: 1}, + {Lo: 0x1b000, Hi: 0x1b122, Stride: 1}, + {Lo: 0x1b170, Hi: 0x1b2fb, Stride: 1}, + {Lo: 0x1f000, Hi: 0x1f0ff, Stride: 1}, + {Lo: 0x1f10d, Hi: 0x1f10f, Stride: 1}, + {Lo: 0x1f16d, Hi: 0x1f16f, Stride: 1}, + {Lo: 0x1f1ad, Hi: 0x1f1e5, Stride: 1}, + {Lo: 0x1f200, Hi: 0x1f384, Stride: 1}, + {Lo: 0x1f386, Hi: 0x1f39b, Stride: 1}, + {Lo: 0x1f39e, Hi: 0x1f3b4, Stride: 1}, + {Lo: 0x1f3b7, Hi: 0x1f3bb, Stride: 1}, + {Lo: 0x1f3bd, Hi: 0x1f3c1, Stride: 1}, + {Lo: 0x1f3c5, Hi: 0x1f3c6, Stride: 1}, + {Lo: 0x1f3c8, Hi: 0x1f3c9, Stride: 1}, + {Lo: 0x1f3cd, Hi: 0x1f3fa, Stride: 1}, + {Lo: 0x1f400, Hi: 0x1f441, Stride: 1}, + {Lo: 0x1f444, Hi: 0x1f445, Stride: 1}, + {Lo: 0x1f451, Hi: 0x1f465, Stride: 1}, + {Lo: 0x1f479, Hi: 0x1f47b, Stride: 1}, + {Lo: 0x1f47d, Hi: 0x1f480, Stride: 1}, + {Lo: 0x1f484, Hi: 0x1f488, Stride: 4}, + {Lo: 0x1f489, Hi: 0x1f48e, Stride: 1}, + {Lo: 0x1f490, Hi: 0x1f492, Stride: 2}, + {Lo: 0x1f493, Hi: 0x1f49f, Stride: 1}, + {Lo: 0x1f4a1, Hi: 0x1f4a5, Stride: 2}, + {Lo: 0x1f4a6, Hi: 0x1f4a9, Stride: 1}, + {Lo: 0x1f4ab, Hi: 0x1f4ae, Stride: 1}, + {Lo: 0x1f4b0, Hi: 0x1f4b3, Stride: 3}, + {Lo: 0x1f4b4, Hi: 0x1f4ff, Stride: 1}, + {Lo: 0x1f507, Hi: 0x1f516, Stride: 1}, + {Lo: 0x1f525, Hi: 0x1f531, Stride: 1}, + {Lo: 0x1f54a, Hi: 0x1f573, Stride: 1}, + {Lo: 0x1f576, Hi: 0x1f579, Stride: 1}, + {Lo: 0x1f57b, Hi: 0x1f58f, Stride: 1}, + {Lo: 0x1f591, Hi: 0x1f594, Stride: 1}, + {Lo: 0x1f597, Hi: 0x1f5d3, Stride: 1}, + {Lo: 0x1f5dc, Hi: 0x1f5f3, Stride: 1}, + {Lo: 0x1f5fa, Hi: 0x1f644, Stride: 1}, + {Lo: 0x1f648, Hi: 0x1f64a, Stride: 1}, + {Lo: 0x1f680, Hi: 0x1f6a2, Stride: 1}, + {Lo: 0x1f6a4, Hi: 0x1f6b3, Stride: 1}, + {Lo: 0x1f6b7, Hi: 0x1f6bf, Stride: 1}, + {Lo: 0x1f6c1, Hi: 0x1f6cb, Stride: 1}, + {Lo: 0x1f6cd, Hi: 0x1f6ff, Stride: 1}, + {Lo: 0x1f774, Hi: 0x1f77f, Stride: 1}, + {Lo: 0x1f7d5, Hi: 0x1f7ff, Stride: 1}, + {Lo: 0x1f80c, Hi: 0x1f80f, Stride: 1}, + {Lo: 0x1f848, Hi: 0x1f84f, Stride: 1}, + {Lo: 0x1f85a, Hi: 0x1f85f, Stride: 1}, + {Lo: 0x1f888, Hi: 0x1f88f, Stride: 1}, + {Lo: 0x1f8ae, Hi: 0x1f8ff, Stride: 1}, + {Lo: 0x1f90d, Hi: 0x1f90e, Stride: 1}, + {Lo: 0x1f910, Hi: 0x1f917, Stride: 1}, + {Lo: 0x1f920, Hi: 0x1f925, Stride: 1}, + {Lo: 0x1f927, Hi: 0x1f92f, Stride: 1}, + {Lo: 0x1f93a, Hi: 0x1f93b, Stride: 1}, + {Lo: 0x1f93f, Hi: 0x1f976, Stride: 1}, + {Lo: 0x1f978, Hi: 0x1f9b4, Stride: 1}, + {Lo: 0x1f9b7, Hi: 0x1f9ba, Stride: 3}, + {Lo: 0x1f9bc, Hi: 0x1f9cc, Stride: 1}, + {Lo: 0x1f9d0, Hi: 0x1f9de, Stride: 14}, + {Lo: 0x1f9df, Hi: 0x1f9ff, Stride: 1}, + {Lo: 0x1fa54, Hi: 0x1fac2, Stride: 1}, + {Lo: 0x1fac6, Hi: 0x1faef, Stride: 1}, + {Lo: 0x1faf9, Hi: 0x1faff, Stride: 1}, + {Lo: 0x1fc00, Hi: 0x1fffd, Stride: 1}, + {Lo: 0x20000, Hi: 0x2fffd, Stride: 1}, + {Lo: 0x30000, Hi: 0x3fffd, Stride: 1}, + }, +} + +// Inseparable +var BreakIN = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x2024, Hi: 0x2026, Stride: 1}, + {Lo: 0x22ef, Hi: 0xfe19, Stride: 56106}, + }, + R32: []unicode.Range32{ + {Lo: 0x10af6, Hi: 0x10af6, Stride: 1}, + }, +} + +// Break After +var BreakBA = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0009, Hi: 0x007c, Stride: 115}, + {Lo: 0x00ad, Hi: 0x058a, Stride: 1245}, + {Lo: 0x05be, Hi: 0x0964, Stride: 934}, + {Lo: 0x0965, Hi: 0x0e5a, Stride: 1269}, + {Lo: 0x0e5b, Hi: 0x0f0b, Stride: 176}, + {Lo: 0x0f34, Hi: 0x0f7f, Stride: 75}, + {Lo: 0x0f85, Hi: 0x0fbe, Stride: 57}, + {Lo: 0x0fbf, Hi: 0x0fd2, Stride: 19}, + {Lo: 0x104a, Hi: 0x104b, Stride: 1}, + {Lo: 0x1361, Hi: 0x1400, Stride: 159}, + {Lo: 0x1680, Hi: 0x16eb, Stride: 107}, + {Lo: 0x16ec, Hi: 0x16ed, Stride: 1}, + {Lo: 0x1735, Hi: 0x1736, Stride: 1}, + {Lo: 0x17d4, Hi: 0x17d5, Stride: 1}, + {Lo: 0x17d8, Hi: 0x17da, Stride: 2}, + {Lo: 0x1804, Hi: 0x1805, Stride: 1}, + {Lo: 0x1b5a, Hi: 0x1b5b, Stride: 1}, + {Lo: 0x1b5d, Hi: 0x1b60, Stride: 1}, + {Lo: 0x1b7d, Hi: 0x1b7e, Stride: 1}, + {Lo: 0x1c3b, Hi: 0x1c3f, Stride: 1}, + {Lo: 0x1c7e, Hi: 0x1c7f, Stride: 1}, + {Lo: 0x2000, Hi: 0x2006, Stride: 1}, + {Lo: 0x2008, Hi: 0x200a, Stride: 1}, + {Lo: 0x2010, Hi: 0x2012, Stride: 2}, + {Lo: 0x2013, Hi: 0x2027, Stride: 20}, + {Lo: 0x2056, Hi: 0x2058, Stride: 2}, + {Lo: 0x2059, Hi: 0x205b, Stride: 1}, + {Lo: 0x205d, Hi: 0x205f, Stride: 1}, + {Lo: 0x2cfa, Hi: 0x2cfc, Stride: 1}, + {Lo: 0x2cff, Hi: 0x2d70, Stride: 113}, + {Lo: 0x2e0e, Hi: 0x2e15, Stride: 1}, + {Lo: 0x2e17, Hi: 0x2e19, Stride: 2}, + {Lo: 0x2e2a, Hi: 0x2e2d, Stride: 1}, + {Lo: 0x2e30, Hi: 0x2e31, Stride: 1}, + {Lo: 0x2e33, Hi: 0x2e34, Stride: 1}, + {Lo: 0x2e3c, Hi: 0x2e3e, Stride: 1}, + {Lo: 0x2e40, Hi: 0x2e41, Stride: 1}, + {Lo: 0x2e43, Hi: 0x2e4a, Stride: 1}, + {Lo: 0x2e4c, Hi: 0x2e4e, Stride: 2}, + {Lo: 0x2e4f, Hi: 0x2e5d, Stride: 14}, + {Lo: 0x3000, Hi: 0xa4fe, Stride: 29950}, + {Lo: 0xa4ff, Hi: 0xa60d, Stride: 270}, + {Lo: 0xa60f, Hi: 0xa6f3, Stride: 228}, + {Lo: 0xa6f4, Hi: 0xa6f7, Stride: 1}, + {Lo: 0xa8ce, Hi: 0xa8cf, Stride: 1}, + {Lo: 0xa92e, Hi: 0xa92f, Stride: 1}, + {Lo: 0xa9c7, Hi: 0xa9c9, Stride: 1}, + {Lo: 0xa9cf, Hi: 0xaa40, Stride: 113}, + {Lo: 0xaa41, Hi: 0xaa42, Stride: 1}, + {Lo: 0xaa44, Hi: 0xaa4b, Stride: 1}, + {Lo: 0xaa5d, Hi: 0xaa5f, Stride: 1}, + {Lo: 0xaaf0, Hi: 0xaaf1, Stride: 1}, + {Lo: 0xabeb, Hi: 0xabeb, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x10100, Hi: 0x10102, Stride: 1}, + {Lo: 0x1039f, Hi: 0x103d0, Stride: 49}, + {Lo: 0x10857, Hi: 0x1091f, Stride: 200}, + {Lo: 0x10a50, Hi: 0x10a57, Stride: 1}, + {Lo: 0x10af0, Hi: 0x10af5, Stride: 1}, + {Lo: 0x10b39, Hi: 0x10b3f, Stride: 1}, + {Lo: 0x10ead, Hi: 0x11047, Stride: 410}, + {Lo: 0x11048, Hi: 0x110be, Stride: 118}, + {Lo: 0x110bf, Hi: 0x110c1, Stride: 1}, + {Lo: 0x11140, Hi: 0x11143, Stride: 1}, + {Lo: 0x111c5, Hi: 0x111c6, Stride: 1}, + {Lo: 0x111c8, Hi: 0x111dd, Stride: 21}, + {Lo: 0x111de, Hi: 0x111df, Stride: 1}, + {Lo: 0x11238, Hi: 0x11239, Stride: 1}, + {Lo: 0x1123b, Hi: 0x1123c, Stride: 1}, + {Lo: 0x112a9, Hi: 0x1133d, Stride: 148}, + {Lo: 0x1135d, Hi: 0x1144b, Stride: 238}, + {Lo: 0x1144c, Hi: 0x1144e, Stride: 1}, + {Lo: 0x1145a, Hi: 0x1145b, Stride: 1}, + {Lo: 0x115c2, Hi: 0x115c3, Stride: 1}, + {Lo: 0x115c9, Hi: 0x115d7, Stride: 1}, + {Lo: 0x11641, Hi: 0x11642, Stride: 1}, + {Lo: 0x1173c, Hi: 0x1173e, Stride: 1}, + {Lo: 0x11944, Hi: 0x11946, Stride: 1}, + {Lo: 0x11a41, Hi: 0x11a44, Stride: 1}, + {Lo: 0x11a9a, Hi: 0x11a9c, Stride: 1}, + {Lo: 0x11aa1, Hi: 0x11aa2, Stride: 1}, + {Lo: 0x11c41, Hi: 0x11c45, Stride: 1}, + {Lo: 0x11ef2, Hi: 0x11ef7, Stride: 5}, + {Lo: 0x11ef8, Hi: 0x11f43, Stride: 75}, + {Lo: 0x11f44, Hi: 0x11fff, Stride: 187}, + {Lo: 0x12470, Hi: 0x12474, Stride: 1}, + {Lo: 0x16a6e, Hi: 0x16a6f, Stride: 1}, + {Lo: 0x16af5, Hi: 0x16b37, Stride: 66}, + {Lo: 0x16b38, Hi: 0x16b39, Stride: 1}, + {Lo: 0x16b44, Hi: 0x16e97, Stride: 851}, + {Lo: 0x16e98, Hi: 0x1bc9f, Stride: 19975}, + {Lo: 0x1da87, Hi: 0x1da8a, Stride: 1}, + }, + LatinOffset: 1, +} + +// Break Before +var BreakBB = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x00b4, Hi: 0x02c8, Stride: 532}, + {Lo: 0x02cc, Hi: 0x02df, Stride: 19}, + {Lo: 0x0c77, Hi: 0x0c84, Stride: 13}, + {Lo: 0x0f01, Hi: 0x0f04, Stride: 1}, + {Lo: 0x0f06, Hi: 0x0f07, Stride: 1}, + {Lo: 0x0f09, Hi: 0x0f0a, Stride: 1}, + {Lo: 0x0fd0, Hi: 0x0fd1, Stride: 1}, + {Lo: 0x0fd3, Hi: 0x1806, Stride: 2099}, + {Lo: 0x1ffd, Hi: 0xa874, Stride: 34935}, + {Lo: 0xa875, Hi: 0xa8fc, Stride: 135}, + }, + R32: []unicode.Range32{ + {Lo: 0x11175, Hi: 0x111db, Stride: 102}, + {Lo: 0x115c1, Hi: 0x11660, Stride: 159}, + {Lo: 0x11661, Hi: 0x1166c, Stride: 1}, + {Lo: 0x119e2, Hi: 0x11a3f, Stride: 93}, + {Lo: 0x11a45, Hi: 0x11a9e, Stride: 89}, + {Lo: 0x11a9f, Hi: 0x11aa0, Stride: 1}, + {Lo: 0x11b00, Hi: 0x11b09, Stride: 1}, + {Lo: 0x11c70, Hi: 0x11c70, Stride: 1}, + }, +} + +// Break Opportunity Before and After +var BreakB2 = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x2014, Hi: 0x2e3a, Stride: 3622}, + {Lo: 0x2e3b, Hi: 0x2e3b, Stride: 1}, + }, +} + +// Zero Width Space +var BreakZW = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x200b, Hi: 0x200b, Stride: 1}, + }, +} + +// Combining Mark +var BreakCM = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0000, Hi: 0x0008, Stride: 1}, + {Lo: 0x000e, Hi: 0x001f, Stride: 1}, + {Lo: 0x007f, Hi: 0x0084, Stride: 1}, + {Lo: 0x0086, Hi: 0x009f, Stride: 1}, + {Lo: 0x0300, Hi: 0x034e, Stride: 1}, + {Lo: 0x0350, Hi: 0x035b, Stride: 1}, + {Lo: 0x0363, Hi: 0x036f, Stride: 1}, + {Lo: 0x0483, Hi: 0x0489, Stride: 1}, + {Lo: 0x0591, Hi: 0x05bd, Stride: 1}, + {Lo: 0x05bf, Hi: 0x05c1, Stride: 2}, + {Lo: 0x05c2, Hi: 0x05c4, Stride: 2}, + {Lo: 0x05c5, Hi: 0x05c7, Stride: 2}, + {Lo: 0x0610, Hi: 0x061a, Stride: 1}, + {Lo: 0x061c, Hi: 0x064b, Stride: 47}, + {Lo: 0x064c, Hi: 0x065f, Stride: 1}, + {Lo: 0x0670, Hi: 0x06d6, Stride: 102}, + {Lo: 0x06d7, Hi: 0x06dc, Stride: 1}, + {Lo: 0x06df, Hi: 0x06e4, Stride: 1}, + {Lo: 0x06e7, Hi: 0x06e8, Stride: 1}, + {Lo: 0x06ea, Hi: 0x06ed, Stride: 1}, + {Lo: 0x0711, Hi: 0x0730, Stride: 31}, + {Lo: 0x0731, Hi: 0x074a, Stride: 1}, + {Lo: 0x07a6, Hi: 0x07b0, Stride: 1}, + {Lo: 0x07eb, Hi: 0x07f3, Stride: 1}, + {Lo: 0x07fd, Hi: 0x0816, Stride: 25}, + {Lo: 0x0817, Hi: 0x0819, Stride: 1}, + {Lo: 0x081b, Hi: 0x0823, Stride: 1}, + {Lo: 0x0825, Hi: 0x0827, Stride: 1}, + {Lo: 0x0829, Hi: 0x082d, Stride: 1}, + {Lo: 0x0859, Hi: 0x085b, Stride: 1}, + {Lo: 0x0898, Hi: 0x089f, Stride: 1}, + {Lo: 0x08ca, Hi: 0x08e1, Stride: 1}, + {Lo: 0x08e3, Hi: 0x0903, Stride: 1}, + {Lo: 0x093a, Hi: 0x093c, Stride: 1}, + {Lo: 0x093e, Hi: 0x094f, Stride: 1}, + {Lo: 0x0951, Hi: 0x0957, Stride: 1}, + {Lo: 0x0962, Hi: 0x0963, Stride: 1}, + {Lo: 0x0981, Hi: 0x0983, Stride: 1}, + {Lo: 0x09bc, Hi: 0x09be, Stride: 2}, + {Lo: 0x09bf, Hi: 0x09c4, Stride: 1}, + {Lo: 0x09c7, Hi: 0x09c8, Stride: 1}, + {Lo: 0x09cb, Hi: 0x09cd, Stride: 1}, + {Lo: 0x09d7, Hi: 0x09e2, Stride: 11}, + {Lo: 0x09e3, Hi: 0x09fe, Stride: 27}, + {Lo: 0x0a01, Hi: 0x0a03, Stride: 1}, + {Lo: 0x0a3c, Hi: 0x0a3e, Stride: 2}, + {Lo: 0x0a3f, Hi: 0x0a42, Stride: 1}, + {Lo: 0x0a47, Hi: 0x0a48, Stride: 1}, + {Lo: 0x0a4b, Hi: 0x0a4d, Stride: 1}, + {Lo: 0x0a51, Hi: 0x0a70, Stride: 31}, + {Lo: 0x0a71, Hi: 0x0a75, Stride: 4}, + {Lo: 0x0a81, Hi: 0x0a83, Stride: 1}, + {Lo: 0x0abc, Hi: 0x0abe, Stride: 2}, + {Lo: 0x0abf, Hi: 0x0ac5, Stride: 1}, + {Lo: 0x0ac7, Hi: 0x0ac9, Stride: 1}, + {Lo: 0x0acb, Hi: 0x0acd, Stride: 1}, + {Lo: 0x0ae2, Hi: 0x0ae3, Stride: 1}, + {Lo: 0x0afa, Hi: 0x0aff, Stride: 1}, + {Lo: 0x0b01, Hi: 0x0b03, Stride: 1}, + {Lo: 0x0b3c, Hi: 0x0b3e, Stride: 2}, + {Lo: 0x0b3f, Hi: 0x0b44, Stride: 1}, + {Lo: 0x0b47, Hi: 0x0b48, Stride: 1}, + {Lo: 0x0b4b, Hi: 0x0b4d, Stride: 1}, + {Lo: 0x0b55, Hi: 0x0b57, Stride: 1}, + {Lo: 0x0b62, Hi: 0x0b63, Stride: 1}, + {Lo: 0x0b82, Hi: 0x0bbe, Stride: 60}, + {Lo: 0x0bbf, Hi: 0x0bc2, Stride: 1}, + {Lo: 0x0bc6, Hi: 0x0bc8, Stride: 1}, + {Lo: 0x0bca, Hi: 0x0bcd, Stride: 1}, + {Lo: 0x0bd7, Hi: 0x0c00, Stride: 41}, + {Lo: 0x0c01, Hi: 0x0c04, Stride: 1}, + {Lo: 0x0c3c, Hi: 0x0c3e, Stride: 2}, + {Lo: 0x0c3f, Hi: 0x0c44, Stride: 1}, + {Lo: 0x0c46, Hi: 0x0c48, Stride: 1}, + {Lo: 0x0c4a, Hi: 0x0c4d, Stride: 1}, + {Lo: 0x0c55, Hi: 0x0c56, Stride: 1}, + {Lo: 0x0c62, Hi: 0x0c63, Stride: 1}, + {Lo: 0x0c81, Hi: 0x0c83, Stride: 1}, + {Lo: 0x0cbc, Hi: 0x0cbe, Stride: 2}, + {Lo: 0x0cbf, Hi: 0x0cc4, Stride: 1}, + {Lo: 0x0cc6, Hi: 0x0cc8, Stride: 1}, + {Lo: 0x0cca, Hi: 0x0ccd, Stride: 1}, + {Lo: 0x0cd5, Hi: 0x0cd6, Stride: 1}, + {Lo: 0x0ce2, Hi: 0x0ce3, Stride: 1}, + {Lo: 0x0cf3, Hi: 0x0d00, Stride: 13}, + {Lo: 0x0d01, Hi: 0x0d03, Stride: 1}, + {Lo: 0x0d3b, Hi: 0x0d3c, Stride: 1}, + {Lo: 0x0d3e, Hi: 0x0d44, Stride: 1}, + {Lo: 0x0d46, Hi: 0x0d48, Stride: 1}, + {Lo: 0x0d4a, Hi: 0x0d4d, Stride: 1}, + {Lo: 0x0d57, Hi: 0x0d62, Stride: 11}, + {Lo: 0x0d63, Hi: 0x0d81, Stride: 30}, + {Lo: 0x0d82, Hi: 0x0d83, Stride: 1}, + {Lo: 0x0dca, Hi: 0x0dcf, Stride: 5}, + {Lo: 0x0dd0, Hi: 0x0dd4, Stride: 1}, + {Lo: 0x0dd6, Hi: 0x0dd8, Stride: 2}, + {Lo: 0x0dd9, Hi: 0x0ddf, Stride: 1}, + {Lo: 0x0df2, Hi: 0x0df3, Stride: 1}, + {Lo: 0x0f18, Hi: 0x0f19, Stride: 1}, + {Lo: 0x0f35, Hi: 0x0f39, Stride: 2}, + {Lo: 0x0f3e, Hi: 0x0f3f, Stride: 1}, + {Lo: 0x0f71, Hi: 0x0f7e, Stride: 1}, + {Lo: 0x0f80, Hi: 0x0f84, Stride: 1}, + {Lo: 0x0f86, Hi: 0x0f87, Stride: 1}, + {Lo: 0x0f8d, Hi: 0x0f97, Stride: 1}, + {Lo: 0x0f99, Hi: 0x0fbc, Stride: 1}, + {Lo: 0x0fc6, Hi: 0x135d, Stride: 919}, + {Lo: 0x135e, Hi: 0x135f, Stride: 1}, + {Lo: 0x1712, Hi: 0x1715, Stride: 1}, + {Lo: 0x1732, Hi: 0x1734, Stride: 1}, + {Lo: 0x1752, Hi: 0x1753, Stride: 1}, + {Lo: 0x1772, Hi: 0x1773, Stride: 1}, + {Lo: 0x180b, Hi: 0x180d, Stride: 1}, + {Lo: 0x180f, Hi: 0x1885, Stride: 118}, + {Lo: 0x1886, Hi: 0x18a9, Stride: 35}, + {Lo: 0x1920, Hi: 0x192b, Stride: 1}, + {Lo: 0x1930, Hi: 0x193b, Stride: 1}, + {Lo: 0x1a17, Hi: 0x1a1b, Stride: 1}, + {Lo: 0x1a7f, Hi: 0x1ab0, Stride: 49}, + {Lo: 0x1ab1, Hi: 0x1ace, Stride: 1}, + {Lo: 0x1b00, Hi: 0x1b04, Stride: 1}, + {Lo: 0x1b34, Hi: 0x1b43, Stride: 1}, + {Lo: 0x1b6b, Hi: 0x1b73, Stride: 1}, + {Lo: 0x1b80, Hi: 0x1b82, Stride: 1}, + {Lo: 0x1ba1, Hi: 0x1bad, Stride: 1}, + {Lo: 0x1be6, Hi: 0x1bf1, Stride: 1}, + {Lo: 0x1c24, Hi: 0x1c37, Stride: 1}, + {Lo: 0x1cd0, Hi: 0x1cd2, Stride: 1}, + {Lo: 0x1cd4, Hi: 0x1ce8, Stride: 1}, + {Lo: 0x1ced, Hi: 0x1cf4, Stride: 7}, + {Lo: 0x1cf7, Hi: 0x1cf9, Stride: 1}, + {Lo: 0x1dc0, Hi: 0x1dcc, Stride: 1}, + {Lo: 0x1dce, Hi: 0x1dfb, Stride: 1}, + {Lo: 0x1dfd, Hi: 0x1dff, Stride: 1}, + {Lo: 0x200c, Hi: 0x200e, Stride: 2}, + {Lo: 0x200f, Hi: 0x202a, Stride: 27}, + {Lo: 0x202b, Hi: 0x202e, Stride: 1}, + {Lo: 0x2066, Hi: 0x206f, Stride: 1}, + {Lo: 0x20d0, Hi: 0x20f0, Stride: 1}, + {Lo: 0x2cef, Hi: 0x2cf1, Stride: 1}, + {Lo: 0x2d7f, Hi: 0x2de0, Stride: 97}, + {Lo: 0x2de1, Hi: 0x2dff, Stride: 1}, + {Lo: 0x302a, Hi: 0x302f, Stride: 1}, + {Lo: 0x3035, Hi: 0x3099, Stride: 100}, + {Lo: 0x309a, Hi: 0xa66f, Stride: 30165}, + {Lo: 0xa670, Hi: 0xa672, Stride: 1}, + {Lo: 0xa674, Hi: 0xa67d, Stride: 1}, + {Lo: 0xa69e, Hi: 0xa69f, Stride: 1}, + {Lo: 0xa6f0, Hi: 0xa6f1, Stride: 1}, + {Lo: 0xa802, Hi: 0xa806, Stride: 4}, + {Lo: 0xa80b, Hi: 0xa823, Stride: 24}, + {Lo: 0xa824, Hi: 0xa827, Stride: 1}, + {Lo: 0xa82c, Hi: 0xa880, Stride: 84}, + {Lo: 0xa881, Hi: 0xa8b4, Stride: 51}, + {Lo: 0xa8b5, Hi: 0xa8c5, Stride: 1}, + {Lo: 0xa8e0, Hi: 0xa8f1, Stride: 1}, + {Lo: 0xa8ff, Hi: 0xa926, Stride: 39}, + {Lo: 0xa927, Hi: 0xa92d, Stride: 1}, + {Lo: 0xa947, Hi: 0xa953, Stride: 1}, + {Lo: 0xa980, Hi: 0xa983, Stride: 1}, + {Lo: 0xa9b3, Hi: 0xa9bf, Stride: 1}, + {Lo: 0xaa29, Hi: 0xaa36, Stride: 1}, + {Lo: 0xaa43, Hi: 0xaa4c, Stride: 9}, + {Lo: 0xaa4d, Hi: 0xaaeb, Stride: 158}, + {Lo: 0xaaec, Hi: 0xaaef, Stride: 1}, + {Lo: 0xaaf5, Hi: 0xaaf6, Stride: 1}, + {Lo: 0xabe3, Hi: 0xabea, Stride: 1}, + {Lo: 0xabec, Hi: 0xabed, Stride: 1}, + {Lo: 0xfb1e, Hi: 0xfe00, Stride: 738}, + {Lo: 0xfe01, Hi: 0xfe0f, Stride: 1}, + {Lo: 0xfe20, Hi: 0xfe2f, Stride: 1}, + {Lo: 0xfff9, Hi: 0xfffb, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x101fd, Hi: 0x102e0, Stride: 227}, + {Lo: 0x10376, Hi: 0x1037a, Stride: 1}, + {Lo: 0x10a01, Hi: 0x10a03, Stride: 1}, + {Lo: 0x10a05, Hi: 0x10a06, Stride: 1}, + {Lo: 0x10a0c, Hi: 0x10a0f, Stride: 1}, + {Lo: 0x10a38, Hi: 0x10a3a, Stride: 1}, + {Lo: 0x10a3f, Hi: 0x10ae5, Stride: 166}, + {Lo: 0x10ae6, Hi: 0x10d24, Stride: 574}, + {Lo: 0x10d25, Hi: 0x10d27, Stride: 1}, + {Lo: 0x10eab, Hi: 0x10eac, Stride: 1}, + {Lo: 0x10efd, Hi: 0x10eff, Stride: 1}, + {Lo: 0x10f46, Hi: 0x10f50, Stride: 1}, + {Lo: 0x10f82, Hi: 0x10f85, Stride: 1}, + {Lo: 0x11000, Hi: 0x11002, Stride: 1}, + {Lo: 0x11038, Hi: 0x11045, Stride: 1}, + {Lo: 0x11070, Hi: 0x11073, Stride: 3}, + {Lo: 0x11074, Hi: 0x11080, Stride: 12}, + {Lo: 0x11081, Hi: 0x11082, Stride: 1}, + {Lo: 0x110b0, Hi: 0x110ba, Stride: 1}, + {Lo: 0x110c2, Hi: 0x11100, Stride: 62}, + {Lo: 0x11101, Hi: 0x11102, Stride: 1}, + {Lo: 0x11127, Hi: 0x11134, Stride: 1}, + {Lo: 0x11145, Hi: 0x11146, Stride: 1}, + {Lo: 0x11173, Hi: 0x11180, Stride: 13}, + {Lo: 0x11181, Hi: 0x11182, Stride: 1}, + {Lo: 0x111b3, Hi: 0x111c0, Stride: 1}, + {Lo: 0x111c9, Hi: 0x111cc, Stride: 1}, + {Lo: 0x111ce, Hi: 0x111cf, Stride: 1}, + {Lo: 0x1122c, Hi: 0x11237, Stride: 1}, + {Lo: 0x1123e, Hi: 0x11241, Stride: 3}, + {Lo: 0x112df, Hi: 0x112ea, Stride: 1}, + {Lo: 0x11300, Hi: 0x11303, Stride: 1}, + {Lo: 0x1133b, Hi: 0x1133c, Stride: 1}, + {Lo: 0x1133e, Hi: 0x11344, Stride: 1}, + {Lo: 0x11347, Hi: 0x11348, Stride: 1}, + {Lo: 0x1134b, Hi: 0x1134c, Stride: 1}, + {Lo: 0x11357, Hi: 0x11362, Stride: 11}, + {Lo: 0x11363, Hi: 0x11366, Stride: 3}, + {Lo: 0x11367, Hi: 0x1136c, Stride: 1}, + {Lo: 0x11370, Hi: 0x11374, Stride: 1}, + {Lo: 0x11435, Hi: 0x11446, Stride: 1}, + {Lo: 0x1145e, Hi: 0x114b0, Stride: 82}, + {Lo: 0x114b1, Hi: 0x114c3, Stride: 1}, + {Lo: 0x115af, Hi: 0x115b5, Stride: 1}, + {Lo: 0x115b8, Hi: 0x115c0, Stride: 1}, + {Lo: 0x115dc, Hi: 0x115dd, Stride: 1}, + {Lo: 0x11630, Hi: 0x11640, Stride: 1}, + {Lo: 0x116ab, Hi: 0x116b7, Stride: 1}, + {Lo: 0x1182c, Hi: 0x1183a, Stride: 1}, + {Lo: 0x11930, Hi: 0x11935, Stride: 1}, + {Lo: 0x11937, Hi: 0x11938, Stride: 1}, + {Lo: 0x1193b, Hi: 0x1193d, Stride: 1}, + {Lo: 0x11940, Hi: 0x11942, Stride: 2}, + {Lo: 0x11943, Hi: 0x119d1, Stride: 142}, + {Lo: 0x119d2, Hi: 0x119d7, Stride: 1}, + {Lo: 0x119da, Hi: 0x119e0, Stride: 1}, + {Lo: 0x119e4, Hi: 0x11a01, Stride: 29}, + {Lo: 0x11a02, Hi: 0x11a0a, Stride: 1}, + {Lo: 0x11a33, Hi: 0x11a39, Stride: 1}, + {Lo: 0x11a3b, Hi: 0x11a3e, Stride: 1}, + {Lo: 0x11a47, Hi: 0x11a51, Stride: 10}, + {Lo: 0x11a52, Hi: 0x11a5b, Stride: 1}, + {Lo: 0x11a8a, Hi: 0x11a99, Stride: 1}, + {Lo: 0x11c2f, Hi: 0x11c36, Stride: 1}, + {Lo: 0x11c38, Hi: 0x11c3f, Stride: 1}, + {Lo: 0x11c92, Hi: 0x11ca7, Stride: 1}, + {Lo: 0x11ca9, Hi: 0x11cb6, Stride: 1}, + {Lo: 0x11d31, Hi: 0x11d36, Stride: 1}, + {Lo: 0x11d3a, Hi: 0x11d3c, Stride: 2}, + {Lo: 0x11d3d, Hi: 0x11d3f, Stride: 2}, + {Lo: 0x11d40, Hi: 0x11d45, Stride: 1}, + {Lo: 0x11d47, Hi: 0x11d8a, Stride: 67}, + {Lo: 0x11d8b, Hi: 0x11d8e, Stride: 1}, + {Lo: 0x11d90, Hi: 0x11d91, Stride: 1}, + {Lo: 0x11d93, Hi: 0x11d97, Stride: 1}, + {Lo: 0x11ef3, Hi: 0x11ef6, Stride: 1}, + {Lo: 0x11f00, Hi: 0x11f01, Stride: 1}, + {Lo: 0x11f03, Hi: 0x11f34, Stride: 49}, + {Lo: 0x11f35, Hi: 0x11f3a, Stride: 1}, + {Lo: 0x11f3e, Hi: 0x11f41, Stride: 1}, + {Lo: 0x13440, Hi: 0x13447, Stride: 7}, + {Lo: 0x13448, Hi: 0x13455, Stride: 1}, + {Lo: 0x16af0, Hi: 0x16af4, Stride: 1}, + {Lo: 0x16b30, Hi: 0x16b36, Stride: 1}, + {Lo: 0x16f4f, Hi: 0x16f51, Stride: 2}, + {Lo: 0x16f52, Hi: 0x16f87, Stride: 1}, + {Lo: 0x16f8f, Hi: 0x16f92, Stride: 1}, + {Lo: 0x16ff0, Hi: 0x16ff1, Stride: 1}, + {Lo: 0x1bc9d, Hi: 0x1bc9e, Stride: 1}, + {Lo: 0x1bca0, Hi: 0x1bca3, Stride: 1}, + {Lo: 0x1cf00, Hi: 0x1cf2d, Stride: 1}, + {Lo: 0x1cf30, Hi: 0x1cf46, Stride: 1}, + {Lo: 0x1d165, Hi: 0x1d169, Stride: 1}, + {Lo: 0x1d16d, Hi: 0x1d182, Stride: 1}, + {Lo: 0x1d185, Hi: 0x1d18b, Stride: 1}, + {Lo: 0x1d1aa, Hi: 0x1d1ad, Stride: 1}, + {Lo: 0x1d242, Hi: 0x1d244, Stride: 1}, + {Lo: 0x1da00, Hi: 0x1da36, Stride: 1}, + {Lo: 0x1da3b, Hi: 0x1da6c, Stride: 1}, + {Lo: 0x1da75, Hi: 0x1da84, Stride: 15}, + {Lo: 0x1da9b, Hi: 0x1da9f, Stride: 1}, + {Lo: 0x1daa1, Hi: 0x1daaf, Stride: 1}, + {Lo: 0x1e000, Hi: 0x1e006, Stride: 1}, + {Lo: 0x1e008, Hi: 0x1e018, Stride: 1}, + {Lo: 0x1e01b, Hi: 0x1e021, Stride: 1}, + {Lo: 0x1e023, Hi: 0x1e024, Stride: 1}, + {Lo: 0x1e026, Hi: 0x1e02a, Stride: 1}, + {Lo: 0x1e08f, Hi: 0x1e130, Stride: 161}, + {Lo: 0x1e131, Hi: 0x1e136, Stride: 1}, + {Lo: 0x1e2ae, Hi: 0x1e2ec, Stride: 62}, + {Lo: 0x1e2ed, Hi: 0x1e2ef, Stride: 1}, + {Lo: 0x1e4ec, Hi: 0x1e4ef, Stride: 1}, + {Lo: 0x1e8d0, Hi: 0x1e8d6, Stride: 1}, + {Lo: 0x1e944, Hi: 0x1e94a, Stride: 1}, + {Lo: 0xe0001, Hi: 0xe0020, Stride: 31}, + {Lo: 0xe0021, Hi: 0xe007f, Stride: 1}, + {Lo: 0xe0100, Hi: 0xe01ef, Stride: 1}, + }, + LatinOffset: 4, +} + +// Emoji Base +var BreakEB = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x261d, Hi: 0x26f9, Stride: 220}, + {Lo: 0x270a, Hi: 0x270d, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x1f385, Hi: 0x1f3c2, Stride: 61}, + {Lo: 0x1f3c3, Hi: 0x1f3c4, Stride: 1}, + {Lo: 0x1f3c7, Hi: 0x1f3ca, Stride: 3}, + {Lo: 0x1f3cb, Hi: 0x1f3cc, Stride: 1}, + {Lo: 0x1f442, Hi: 0x1f443, Stride: 1}, + {Lo: 0x1f446, Hi: 0x1f450, Stride: 1}, + {Lo: 0x1f466, Hi: 0x1f478, Stride: 1}, + {Lo: 0x1f47c, Hi: 0x1f481, Stride: 5}, + {Lo: 0x1f482, Hi: 0x1f483, Stride: 1}, + {Lo: 0x1f485, Hi: 0x1f487, Stride: 1}, + {Lo: 0x1f48f, Hi: 0x1f491, Stride: 2}, + {Lo: 0x1f4aa, Hi: 0x1f574, Stride: 202}, + {Lo: 0x1f575, Hi: 0x1f57a, Stride: 5}, + {Lo: 0x1f590, Hi: 0x1f595, Stride: 5}, + {Lo: 0x1f596, Hi: 0x1f645, Stride: 175}, + {Lo: 0x1f646, Hi: 0x1f647, Stride: 1}, + {Lo: 0x1f64b, Hi: 0x1f64f, Stride: 1}, + {Lo: 0x1f6a3, Hi: 0x1f6b4, Stride: 17}, + {Lo: 0x1f6b5, Hi: 0x1f6b6, Stride: 1}, + {Lo: 0x1f6c0, Hi: 0x1f6cc, Stride: 12}, + {Lo: 0x1f90c, Hi: 0x1f90f, Stride: 3}, + {Lo: 0x1f918, Hi: 0x1f91f, Stride: 1}, + {Lo: 0x1f926, Hi: 0x1f930, Stride: 10}, + {Lo: 0x1f931, Hi: 0x1f939, Stride: 1}, + {Lo: 0x1f93c, Hi: 0x1f93e, Stride: 1}, + {Lo: 0x1f977, Hi: 0x1f9b5, Stride: 62}, + {Lo: 0x1f9b6, Hi: 0x1f9b8, Stride: 2}, + {Lo: 0x1f9b9, Hi: 0x1f9bb, Stride: 2}, + {Lo: 0x1f9cd, Hi: 0x1f9cf, Stride: 1}, + {Lo: 0x1f9d1, Hi: 0x1f9dd, Stride: 1}, + {Lo: 0x1fac3, Hi: 0x1fac5, Stride: 1}, + {Lo: 0x1faf0, Hi: 0x1faf8, Stride: 1}, + }, +} + +// Emoji Modifier +var BreakEM = &unicode.RangeTable{ + R32: []unicode.Range32{ + {Lo: 0x1f3fb, Hi: 0x1f3ff, Stride: 1}, + }, +} + +// Word Joiner +var BreakWJ = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x2060, Hi: 0xfeff, Stride: 56991}, + }, +} + +// Zero width joiner +var BreakZWJ = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x200d, Hi: 0x200d, Stride: 1}, + }, +} + +// Hangul LV Syllable +var BreakH2 = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0xac00, Hi: 0xd788, Stride: 28}, + }, +} + +// Hangul LVT Syllable +var BreakH3 = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0xac01, Hi: 0xac1b, Stride: 1}, + {Lo: 0xac1d, Hi: 0xac37, Stride: 1}, + {Lo: 0xac39, Hi: 0xac53, Stride: 1}, + {Lo: 0xac55, Hi: 0xac6f, Stride: 1}, + {Lo: 0xac71, Hi: 0xac8b, Stride: 1}, + {Lo: 0xac8d, Hi: 0xaca7, Stride: 1}, + {Lo: 0xaca9, Hi: 0xacc3, Stride: 1}, + {Lo: 0xacc5, Hi: 0xacdf, Stride: 1}, + {Lo: 0xace1, Hi: 0xacfb, Stride: 1}, + {Lo: 0xacfd, Hi: 0xad17, Stride: 1}, + {Lo: 0xad19, Hi: 0xad33, Stride: 1}, + {Lo: 0xad35, Hi: 0xad4f, Stride: 1}, + {Lo: 0xad51, Hi: 0xad6b, Stride: 1}, + {Lo: 0xad6d, Hi: 0xad87, Stride: 1}, + {Lo: 0xad89, Hi: 0xada3, Stride: 1}, + {Lo: 0xada5, Hi: 0xadbf, Stride: 1}, + {Lo: 0xadc1, Hi: 0xaddb, Stride: 1}, + {Lo: 0xaddd, Hi: 0xadf7, Stride: 1}, + {Lo: 0xadf9, Hi: 0xae13, Stride: 1}, + {Lo: 0xae15, Hi: 0xae2f, Stride: 1}, + {Lo: 0xae31, Hi: 0xae4b, Stride: 1}, + {Lo: 0xae4d, Hi: 0xae67, Stride: 1}, + {Lo: 0xae69, Hi: 0xae83, Stride: 1}, + {Lo: 0xae85, Hi: 0xae9f, Stride: 1}, + {Lo: 0xaea1, Hi: 0xaebb, Stride: 1}, + {Lo: 0xaebd, Hi: 0xaed7, Stride: 1}, + {Lo: 0xaed9, Hi: 0xaef3, Stride: 1}, + {Lo: 0xaef5, Hi: 0xaf0f, Stride: 1}, + {Lo: 0xaf11, Hi: 0xaf2b, Stride: 1}, + {Lo: 0xaf2d, Hi: 0xaf47, Stride: 1}, + {Lo: 0xaf49, Hi: 0xaf63, Stride: 1}, + {Lo: 0xaf65, Hi: 0xaf7f, Stride: 1}, + {Lo: 0xaf81, Hi: 0xaf9b, Stride: 1}, + {Lo: 0xaf9d, Hi: 0xafb7, Stride: 1}, + {Lo: 0xafb9, Hi: 0xafd3, Stride: 1}, + {Lo: 0xafd5, Hi: 0xafef, Stride: 1}, + {Lo: 0xaff1, Hi: 0xb00b, Stride: 1}, + {Lo: 0xb00d, Hi: 0xb027, Stride: 1}, + {Lo: 0xb029, Hi: 0xb043, Stride: 1}, + {Lo: 0xb045, Hi: 0xb05f, Stride: 1}, + {Lo: 0xb061, Hi: 0xb07b, Stride: 1}, + {Lo: 0xb07d, Hi: 0xb097, Stride: 1}, + {Lo: 0xb099, Hi: 0xb0b3, Stride: 1}, + {Lo: 0xb0b5, Hi: 0xb0cf, Stride: 1}, + {Lo: 0xb0d1, Hi: 0xb0eb, Stride: 1}, + {Lo: 0xb0ed, Hi: 0xb107, Stride: 1}, + {Lo: 0xb109, Hi: 0xb123, Stride: 1}, + {Lo: 0xb125, Hi: 0xb13f, Stride: 1}, + {Lo: 0xb141, Hi: 0xb15b, Stride: 1}, + {Lo: 0xb15d, Hi: 0xb177, Stride: 1}, + {Lo: 0xb179, Hi: 0xb193, Stride: 1}, + {Lo: 0xb195, Hi: 0xb1af, Stride: 1}, + {Lo: 0xb1b1, Hi: 0xb1cb, Stride: 1}, + {Lo: 0xb1cd, Hi: 0xb1e7, Stride: 1}, + {Lo: 0xb1e9, Hi: 0xb203, Stride: 1}, + {Lo: 0xb205, Hi: 0xb21f, Stride: 1}, + {Lo: 0xb221, Hi: 0xb23b, Stride: 1}, + {Lo: 0xb23d, Hi: 0xb257, Stride: 1}, + {Lo: 0xb259, Hi: 0xb273, Stride: 1}, + {Lo: 0xb275, Hi: 0xb28f, Stride: 1}, + {Lo: 0xb291, Hi: 0xb2ab, Stride: 1}, + {Lo: 0xb2ad, Hi: 0xb2c7, Stride: 1}, + {Lo: 0xb2c9, Hi: 0xb2e3, Stride: 1}, + {Lo: 0xb2e5, Hi: 0xb2ff, Stride: 1}, + {Lo: 0xb301, Hi: 0xb31b, Stride: 1}, + {Lo: 0xb31d, Hi: 0xb337, Stride: 1}, + {Lo: 0xb339, Hi: 0xb353, Stride: 1}, + {Lo: 0xb355, Hi: 0xb36f, Stride: 1}, + {Lo: 0xb371, Hi: 0xb38b, Stride: 1}, + {Lo: 0xb38d, Hi: 0xb3a7, Stride: 1}, + {Lo: 0xb3a9, Hi: 0xb3c3, Stride: 1}, + {Lo: 0xb3c5, Hi: 0xb3df, Stride: 1}, + {Lo: 0xb3e1, Hi: 0xb3fb, Stride: 1}, + {Lo: 0xb3fd, Hi: 0xb417, Stride: 1}, + {Lo: 0xb419, Hi: 0xb433, Stride: 1}, + {Lo: 0xb435, Hi: 0xb44f, Stride: 1}, + {Lo: 0xb451, Hi: 0xb46b, Stride: 1}, + {Lo: 0xb46d, Hi: 0xb487, Stride: 1}, + {Lo: 0xb489, Hi: 0xb4a3, Stride: 1}, + {Lo: 0xb4a5, Hi: 0xb4bf, Stride: 1}, + {Lo: 0xb4c1, Hi: 0xb4db, Stride: 1}, + {Lo: 0xb4dd, Hi: 0xb4f7, Stride: 1}, + {Lo: 0xb4f9, Hi: 0xb513, Stride: 1}, + {Lo: 0xb515, Hi: 0xb52f, Stride: 1}, + {Lo: 0xb531, Hi: 0xb54b, Stride: 1}, + {Lo: 0xb54d, Hi: 0xb567, Stride: 1}, + {Lo: 0xb569, Hi: 0xb583, Stride: 1}, + {Lo: 0xb585, Hi: 0xb59f, Stride: 1}, + {Lo: 0xb5a1, Hi: 0xb5bb, Stride: 1}, + {Lo: 0xb5bd, Hi: 0xb5d7, Stride: 1}, + {Lo: 0xb5d9, Hi: 0xb5f3, Stride: 1}, + {Lo: 0xb5f5, Hi: 0xb60f, Stride: 1}, + {Lo: 0xb611, Hi: 0xb62b, Stride: 1}, + {Lo: 0xb62d, Hi: 0xb647, Stride: 1}, + {Lo: 0xb649, Hi: 0xb663, Stride: 1}, + {Lo: 0xb665, Hi: 0xb67f, Stride: 1}, + {Lo: 0xb681, Hi: 0xb69b, Stride: 1}, + {Lo: 0xb69d, Hi: 0xb6b7, Stride: 1}, + {Lo: 0xb6b9, Hi: 0xb6d3, Stride: 1}, + {Lo: 0xb6d5, Hi: 0xb6ef, Stride: 1}, + {Lo: 0xb6f1, Hi: 0xb70b, Stride: 1}, + {Lo: 0xb70d, Hi: 0xb727, Stride: 1}, + {Lo: 0xb729, Hi: 0xb743, Stride: 1}, + {Lo: 0xb745, Hi: 0xb75f, Stride: 1}, + {Lo: 0xb761, Hi: 0xb77b, Stride: 1}, + {Lo: 0xb77d, Hi: 0xb797, Stride: 1}, + {Lo: 0xb799, Hi: 0xb7b3, Stride: 1}, + {Lo: 0xb7b5, Hi: 0xb7cf, Stride: 1}, + {Lo: 0xb7d1, Hi: 0xb7eb, Stride: 1}, + {Lo: 0xb7ed, Hi: 0xb807, Stride: 1}, + {Lo: 0xb809, Hi: 0xb823, Stride: 1}, + {Lo: 0xb825, Hi: 0xb83f, Stride: 1}, + {Lo: 0xb841, Hi: 0xb85b, Stride: 1}, + {Lo: 0xb85d, Hi: 0xb877, Stride: 1}, + {Lo: 0xb879, Hi: 0xb893, Stride: 1}, + {Lo: 0xb895, Hi: 0xb8af, Stride: 1}, + {Lo: 0xb8b1, Hi: 0xb8cb, Stride: 1}, + {Lo: 0xb8cd, Hi: 0xb8e7, Stride: 1}, + {Lo: 0xb8e9, Hi: 0xb903, Stride: 1}, + {Lo: 0xb905, Hi: 0xb91f, Stride: 1}, + {Lo: 0xb921, Hi: 0xb93b, Stride: 1}, + {Lo: 0xb93d, Hi: 0xb957, Stride: 1}, + {Lo: 0xb959, Hi: 0xb973, Stride: 1}, + {Lo: 0xb975, Hi: 0xb98f, Stride: 1}, + {Lo: 0xb991, Hi: 0xb9ab, Stride: 1}, + {Lo: 0xb9ad, Hi: 0xb9c7, Stride: 1}, + {Lo: 0xb9c9, Hi: 0xb9e3, Stride: 1}, + {Lo: 0xb9e5, Hi: 0xb9ff, Stride: 1}, + {Lo: 0xba01, Hi: 0xba1b, Stride: 1}, + {Lo: 0xba1d, Hi: 0xba37, Stride: 1}, + {Lo: 0xba39, Hi: 0xba53, Stride: 1}, + {Lo: 0xba55, Hi: 0xba6f, Stride: 1}, + {Lo: 0xba71, Hi: 0xba8b, Stride: 1}, + {Lo: 0xba8d, Hi: 0xbaa7, Stride: 1}, + {Lo: 0xbaa9, Hi: 0xbac3, Stride: 1}, + {Lo: 0xbac5, Hi: 0xbadf, Stride: 1}, + {Lo: 0xbae1, Hi: 0xbafb, Stride: 1}, + {Lo: 0xbafd, Hi: 0xbb17, Stride: 1}, + {Lo: 0xbb19, Hi: 0xbb33, Stride: 1}, + {Lo: 0xbb35, Hi: 0xbb4f, Stride: 1}, + {Lo: 0xbb51, Hi: 0xbb6b, Stride: 1}, + {Lo: 0xbb6d, Hi: 0xbb87, Stride: 1}, + {Lo: 0xbb89, Hi: 0xbba3, Stride: 1}, + {Lo: 0xbba5, Hi: 0xbbbf, Stride: 1}, + {Lo: 0xbbc1, Hi: 0xbbdb, Stride: 1}, + {Lo: 0xbbdd, Hi: 0xbbf7, Stride: 1}, + {Lo: 0xbbf9, Hi: 0xbc13, Stride: 1}, + {Lo: 0xbc15, Hi: 0xbc2f, Stride: 1}, + {Lo: 0xbc31, Hi: 0xbc4b, Stride: 1}, + {Lo: 0xbc4d, Hi: 0xbc67, Stride: 1}, + {Lo: 0xbc69, Hi: 0xbc83, Stride: 1}, + {Lo: 0xbc85, Hi: 0xbc9f, Stride: 1}, + {Lo: 0xbca1, Hi: 0xbcbb, Stride: 1}, + {Lo: 0xbcbd, Hi: 0xbcd7, Stride: 1}, + {Lo: 0xbcd9, Hi: 0xbcf3, Stride: 1}, + {Lo: 0xbcf5, Hi: 0xbd0f, Stride: 1}, + {Lo: 0xbd11, Hi: 0xbd2b, Stride: 1}, + {Lo: 0xbd2d, Hi: 0xbd47, Stride: 1}, + {Lo: 0xbd49, Hi: 0xbd63, Stride: 1}, + {Lo: 0xbd65, Hi: 0xbd7f, Stride: 1}, + {Lo: 0xbd81, Hi: 0xbd9b, Stride: 1}, + {Lo: 0xbd9d, Hi: 0xbdb7, Stride: 1}, + {Lo: 0xbdb9, Hi: 0xbdd3, Stride: 1}, + {Lo: 0xbdd5, Hi: 0xbdef, Stride: 1}, + {Lo: 0xbdf1, Hi: 0xbe0b, Stride: 1}, + {Lo: 0xbe0d, Hi: 0xbe27, Stride: 1}, + {Lo: 0xbe29, Hi: 0xbe43, Stride: 1}, + {Lo: 0xbe45, Hi: 0xbe5f, Stride: 1}, + {Lo: 0xbe61, Hi: 0xbe7b, Stride: 1}, + {Lo: 0xbe7d, Hi: 0xbe97, Stride: 1}, + {Lo: 0xbe99, Hi: 0xbeb3, Stride: 1}, + {Lo: 0xbeb5, Hi: 0xbecf, Stride: 1}, + {Lo: 0xbed1, Hi: 0xbeeb, Stride: 1}, + {Lo: 0xbeed, Hi: 0xbf07, Stride: 1}, + {Lo: 0xbf09, Hi: 0xbf23, Stride: 1}, + {Lo: 0xbf25, Hi: 0xbf3f, Stride: 1}, + {Lo: 0xbf41, Hi: 0xbf5b, Stride: 1}, + {Lo: 0xbf5d, Hi: 0xbf77, Stride: 1}, + {Lo: 0xbf79, Hi: 0xbf93, Stride: 1}, + {Lo: 0xbf95, Hi: 0xbfaf, Stride: 1}, + {Lo: 0xbfb1, Hi: 0xbfcb, Stride: 1}, + {Lo: 0xbfcd, Hi: 0xbfe7, Stride: 1}, + {Lo: 0xbfe9, Hi: 0xc003, Stride: 1}, + {Lo: 0xc005, Hi: 0xc01f, Stride: 1}, + {Lo: 0xc021, Hi: 0xc03b, Stride: 1}, + {Lo: 0xc03d, Hi: 0xc057, Stride: 1}, + {Lo: 0xc059, Hi: 0xc073, Stride: 1}, + {Lo: 0xc075, Hi: 0xc08f, Stride: 1}, + {Lo: 0xc091, Hi: 0xc0ab, Stride: 1}, + {Lo: 0xc0ad, Hi: 0xc0c7, Stride: 1}, + {Lo: 0xc0c9, Hi: 0xc0e3, Stride: 1}, + {Lo: 0xc0e5, Hi: 0xc0ff, Stride: 1}, + {Lo: 0xc101, Hi: 0xc11b, Stride: 1}, + {Lo: 0xc11d, Hi: 0xc137, Stride: 1}, + {Lo: 0xc139, Hi: 0xc153, Stride: 1}, + {Lo: 0xc155, Hi: 0xc16f, Stride: 1}, + {Lo: 0xc171, Hi: 0xc18b, Stride: 1}, + {Lo: 0xc18d, Hi: 0xc1a7, Stride: 1}, + {Lo: 0xc1a9, Hi: 0xc1c3, Stride: 1}, + {Lo: 0xc1c5, Hi: 0xc1df, Stride: 1}, + {Lo: 0xc1e1, Hi: 0xc1fb, Stride: 1}, + {Lo: 0xc1fd, Hi: 0xc217, Stride: 1}, + {Lo: 0xc219, Hi: 0xc233, Stride: 1}, + {Lo: 0xc235, Hi: 0xc24f, Stride: 1}, + {Lo: 0xc251, Hi: 0xc26b, Stride: 1}, + {Lo: 0xc26d, Hi: 0xc287, Stride: 1}, + {Lo: 0xc289, Hi: 0xc2a3, Stride: 1}, + {Lo: 0xc2a5, Hi: 0xc2bf, Stride: 1}, + {Lo: 0xc2c1, Hi: 0xc2db, Stride: 1}, + {Lo: 0xc2dd, Hi: 0xc2f7, Stride: 1}, + {Lo: 0xc2f9, Hi: 0xc313, Stride: 1}, + {Lo: 0xc315, Hi: 0xc32f, Stride: 1}, + {Lo: 0xc331, Hi: 0xc34b, Stride: 1}, + {Lo: 0xc34d, Hi: 0xc367, Stride: 1}, + {Lo: 0xc369, Hi: 0xc383, Stride: 1}, + {Lo: 0xc385, Hi: 0xc39f, Stride: 1}, + {Lo: 0xc3a1, Hi: 0xc3bb, Stride: 1}, + {Lo: 0xc3bd, Hi: 0xc3d7, Stride: 1}, + {Lo: 0xc3d9, Hi: 0xc3f3, Stride: 1}, + {Lo: 0xc3f5, Hi: 0xc40f, Stride: 1}, + {Lo: 0xc411, Hi: 0xc42b, Stride: 1}, + {Lo: 0xc42d, Hi: 0xc447, Stride: 1}, + {Lo: 0xc449, Hi: 0xc463, Stride: 1}, + {Lo: 0xc465, Hi: 0xc47f, Stride: 1}, + {Lo: 0xc481, Hi: 0xc49b, Stride: 1}, + {Lo: 0xc49d, Hi: 0xc4b7, Stride: 1}, + {Lo: 0xc4b9, Hi: 0xc4d3, Stride: 1}, + {Lo: 0xc4d5, Hi: 0xc4ef, Stride: 1}, + {Lo: 0xc4f1, Hi: 0xc50b, Stride: 1}, + {Lo: 0xc50d, Hi: 0xc527, Stride: 1}, + {Lo: 0xc529, Hi: 0xc543, Stride: 1}, + {Lo: 0xc545, Hi: 0xc55f, Stride: 1}, + {Lo: 0xc561, Hi: 0xc57b, Stride: 1}, + {Lo: 0xc57d, Hi: 0xc597, Stride: 1}, + {Lo: 0xc599, Hi: 0xc5b3, Stride: 1}, + {Lo: 0xc5b5, Hi: 0xc5cf, Stride: 1}, + {Lo: 0xc5d1, Hi: 0xc5eb, Stride: 1}, + {Lo: 0xc5ed, Hi: 0xc607, Stride: 1}, + {Lo: 0xc609, Hi: 0xc623, Stride: 1}, + {Lo: 0xc625, Hi: 0xc63f, Stride: 1}, + {Lo: 0xc641, Hi: 0xc65b, Stride: 1}, + {Lo: 0xc65d, Hi: 0xc677, Stride: 1}, + {Lo: 0xc679, Hi: 0xc693, Stride: 1}, + {Lo: 0xc695, Hi: 0xc6af, Stride: 1}, + {Lo: 0xc6b1, Hi: 0xc6cb, Stride: 1}, + {Lo: 0xc6cd, Hi: 0xc6e7, Stride: 1}, + {Lo: 0xc6e9, Hi: 0xc703, Stride: 1}, + {Lo: 0xc705, Hi: 0xc71f, Stride: 1}, + {Lo: 0xc721, Hi: 0xc73b, Stride: 1}, + {Lo: 0xc73d, Hi: 0xc757, Stride: 1}, + {Lo: 0xc759, Hi: 0xc773, Stride: 1}, + {Lo: 0xc775, Hi: 0xc78f, Stride: 1}, + {Lo: 0xc791, Hi: 0xc7ab, Stride: 1}, + {Lo: 0xc7ad, Hi: 0xc7c7, Stride: 1}, + {Lo: 0xc7c9, Hi: 0xc7e3, Stride: 1}, + {Lo: 0xc7e5, Hi: 0xc7ff, Stride: 1}, + {Lo: 0xc801, Hi: 0xc81b, Stride: 1}, + {Lo: 0xc81d, Hi: 0xc837, Stride: 1}, + {Lo: 0xc839, Hi: 0xc853, Stride: 1}, + {Lo: 0xc855, Hi: 0xc86f, Stride: 1}, + {Lo: 0xc871, Hi: 0xc88b, Stride: 1}, + {Lo: 0xc88d, Hi: 0xc8a7, Stride: 1}, + {Lo: 0xc8a9, Hi: 0xc8c3, Stride: 1}, + {Lo: 0xc8c5, Hi: 0xc8df, Stride: 1}, + {Lo: 0xc8e1, Hi: 0xc8fb, Stride: 1}, + {Lo: 0xc8fd, Hi: 0xc917, Stride: 1}, + {Lo: 0xc919, Hi: 0xc933, Stride: 1}, + {Lo: 0xc935, Hi: 0xc94f, Stride: 1}, + {Lo: 0xc951, Hi: 0xc96b, Stride: 1}, + {Lo: 0xc96d, Hi: 0xc987, Stride: 1}, + {Lo: 0xc989, Hi: 0xc9a3, Stride: 1}, + {Lo: 0xc9a5, Hi: 0xc9bf, Stride: 1}, + {Lo: 0xc9c1, Hi: 0xc9db, Stride: 1}, + {Lo: 0xc9dd, Hi: 0xc9f7, Stride: 1}, + {Lo: 0xc9f9, Hi: 0xca13, Stride: 1}, + {Lo: 0xca15, Hi: 0xca2f, Stride: 1}, + {Lo: 0xca31, Hi: 0xca4b, Stride: 1}, + {Lo: 0xca4d, Hi: 0xca67, Stride: 1}, + {Lo: 0xca69, Hi: 0xca83, Stride: 1}, + {Lo: 0xca85, Hi: 0xca9f, Stride: 1}, + {Lo: 0xcaa1, Hi: 0xcabb, Stride: 1}, + {Lo: 0xcabd, Hi: 0xcad7, Stride: 1}, + {Lo: 0xcad9, Hi: 0xcaf3, Stride: 1}, + {Lo: 0xcaf5, Hi: 0xcb0f, Stride: 1}, + {Lo: 0xcb11, Hi: 0xcb2b, Stride: 1}, + {Lo: 0xcb2d, Hi: 0xcb47, Stride: 1}, + {Lo: 0xcb49, Hi: 0xcb63, Stride: 1}, + {Lo: 0xcb65, Hi: 0xcb7f, Stride: 1}, + {Lo: 0xcb81, Hi: 0xcb9b, Stride: 1}, + {Lo: 0xcb9d, Hi: 0xcbb7, Stride: 1}, + {Lo: 0xcbb9, Hi: 0xcbd3, Stride: 1}, + {Lo: 0xcbd5, Hi: 0xcbef, Stride: 1}, + {Lo: 0xcbf1, Hi: 0xcc0b, Stride: 1}, + {Lo: 0xcc0d, Hi: 0xcc27, Stride: 1}, + {Lo: 0xcc29, Hi: 0xcc43, Stride: 1}, + {Lo: 0xcc45, Hi: 0xcc5f, Stride: 1}, + {Lo: 0xcc61, Hi: 0xcc7b, Stride: 1}, + {Lo: 0xcc7d, Hi: 0xcc97, Stride: 1}, + {Lo: 0xcc99, Hi: 0xccb3, Stride: 1}, + {Lo: 0xccb5, Hi: 0xcccf, Stride: 1}, + {Lo: 0xccd1, Hi: 0xcceb, Stride: 1}, + {Lo: 0xcced, Hi: 0xcd07, Stride: 1}, + {Lo: 0xcd09, Hi: 0xcd23, Stride: 1}, + {Lo: 0xcd25, Hi: 0xcd3f, Stride: 1}, + {Lo: 0xcd41, Hi: 0xcd5b, Stride: 1}, + {Lo: 0xcd5d, Hi: 0xcd77, Stride: 1}, + {Lo: 0xcd79, Hi: 0xcd93, Stride: 1}, + {Lo: 0xcd95, Hi: 0xcdaf, Stride: 1}, + {Lo: 0xcdb1, Hi: 0xcdcb, Stride: 1}, + {Lo: 0xcdcd, Hi: 0xcde7, Stride: 1}, + {Lo: 0xcde9, Hi: 0xce03, Stride: 1}, + {Lo: 0xce05, Hi: 0xce1f, Stride: 1}, + {Lo: 0xce21, Hi: 0xce3b, Stride: 1}, + {Lo: 0xce3d, Hi: 0xce57, Stride: 1}, + {Lo: 0xce59, Hi: 0xce73, Stride: 1}, + {Lo: 0xce75, Hi: 0xce8f, Stride: 1}, + {Lo: 0xce91, Hi: 0xceab, Stride: 1}, + {Lo: 0xcead, Hi: 0xcec7, Stride: 1}, + {Lo: 0xcec9, Hi: 0xcee3, Stride: 1}, + {Lo: 0xcee5, Hi: 0xceff, Stride: 1}, + {Lo: 0xcf01, Hi: 0xcf1b, Stride: 1}, + {Lo: 0xcf1d, Hi: 0xcf37, Stride: 1}, + {Lo: 0xcf39, Hi: 0xcf53, Stride: 1}, + {Lo: 0xcf55, Hi: 0xcf6f, Stride: 1}, + {Lo: 0xcf71, Hi: 0xcf8b, Stride: 1}, + {Lo: 0xcf8d, Hi: 0xcfa7, Stride: 1}, + {Lo: 0xcfa9, Hi: 0xcfc3, Stride: 1}, + {Lo: 0xcfc5, Hi: 0xcfdf, Stride: 1}, + {Lo: 0xcfe1, Hi: 0xcffb, Stride: 1}, + {Lo: 0xcffd, Hi: 0xd017, Stride: 1}, + {Lo: 0xd019, Hi: 0xd033, Stride: 1}, + {Lo: 0xd035, Hi: 0xd04f, Stride: 1}, + {Lo: 0xd051, Hi: 0xd06b, Stride: 1}, + {Lo: 0xd06d, Hi: 0xd087, Stride: 1}, + {Lo: 0xd089, Hi: 0xd0a3, Stride: 1}, + {Lo: 0xd0a5, Hi: 0xd0bf, Stride: 1}, + {Lo: 0xd0c1, Hi: 0xd0db, Stride: 1}, + {Lo: 0xd0dd, Hi: 0xd0f7, Stride: 1}, + {Lo: 0xd0f9, Hi: 0xd113, Stride: 1}, + {Lo: 0xd115, Hi: 0xd12f, Stride: 1}, + {Lo: 0xd131, Hi: 0xd14b, Stride: 1}, + {Lo: 0xd14d, Hi: 0xd167, Stride: 1}, + {Lo: 0xd169, Hi: 0xd183, Stride: 1}, + {Lo: 0xd185, Hi: 0xd19f, Stride: 1}, + {Lo: 0xd1a1, Hi: 0xd1bb, Stride: 1}, + {Lo: 0xd1bd, Hi: 0xd1d7, Stride: 1}, + {Lo: 0xd1d9, Hi: 0xd1f3, Stride: 1}, + {Lo: 0xd1f5, Hi: 0xd20f, Stride: 1}, + {Lo: 0xd211, Hi: 0xd22b, Stride: 1}, + {Lo: 0xd22d, Hi: 0xd247, Stride: 1}, + {Lo: 0xd249, Hi: 0xd263, Stride: 1}, + {Lo: 0xd265, Hi: 0xd27f, Stride: 1}, + {Lo: 0xd281, Hi: 0xd29b, Stride: 1}, + {Lo: 0xd29d, Hi: 0xd2b7, Stride: 1}, + {Lo: 0xd2b9, Hi: 0xd2d3, Stride: 1}, + {Lo: 0xd2d5, Hi: 0xd2ef, Stride: 1}, + {Lo: 0xd2f1, Hi: 0xd30b, Stride: 1}, + {Lo: 0xd30d, Hi: 0xd327, Stride: 1}, + {Lo: 0xd329, Hi: 0xd343, Stride: 1}, + {Lo: 0xd345, Hi: 0xd35f, Stride: 1}, + {Lo: 0xd361, Hi: 0xd37b, Stride: 1}, + {Lo: 0xd37d, Hi: 0xd397, Stride: 1}, + {Lo: 0xd399, Hi: 0xd3b3, Stride: 1}, + {Lo: 0xd3b5, Hi: 0xd3cf, Stride: 1}, + {Lo: 0xd3d1, Hi: 0xd3eb, Stride: 1}, + {Lo: 0xd3ed, Hi: 0xd407, Stride: 1}, + {Lo: 0xd409, Hi: 0xd423, Stride: 1}, + {Lo: 0xd425, Hi: 0xd43f, Stride: 1}, + {Lo: 0xd441, Hi: 0xd45b, Stride: 1}, + {Lo: 0xd45d, Hi: 0xd477, Stride: 1}, + {Lo: 0xd479, Hi: 0xd493, Stride: 1}, + {Lo: 0xd495, Hi: 0xd4af, Stride: 1}, + {Lo: 0xd4b1, Hi: 0xd4cb, Stride: 1}, + {Lo: 0xd4cd, Hi: 0xd4e7, Stride: 1}, + {Lo: 0xd4e9, Hi: 0xd503, Stride: 1}, + {Lo: 0xd505, Hi: 0xd51f, Stride: 1}, + {Lo: 0xd521, Hi: 0xd53b, Stride: 1}, + {Lo: 0xd53d, Hi: 0xd557, Stride: 1}, + {Lo: 0xd559, Hi: 0xd573, Stride: 1}, + {Lo: 0xd575, Hi: 0xd58f, Stride: 1}, + {Lo: 0xd591, Hi: 0xd5ab, Stride: 1}, + {Lo: 0xd5ad, Hi: 0xd5c7, Stride: 1}, + {Lo: 0xd5c9, Hi: 0xd5e3, Stride: 1}, + {Lo: 0xd5e5, Hi: 0xd5ff, Stride: 1}, + {Lo: 0xd601, Hi: 0xd61b, Stride: 1}, + {Lo: 0xd61d, Hi: 0xd637, Stride: 1}, + {Lo: 0xd639, Hi: 0xd653, Stride: 1}, + {Lo: 0xd655, Hi: 0xd66f, Stride: 1}, + {Lo: 0xd671, Hi: 0xd68b, Stride: 1}, + {Lo: 0xd68d, Hi: 0xd6a7, Stride: 1}, + {Lo: 0xd6a9, Hi: 0xd6c3, Stride: 1}, + {Lo: 0xd6c5, Hi: 0xd6df, Stride: 1}, + {Lo: 0xd6e1, Hi: 0xd6fb, Stride: 1}, + {Lo: 0xd6fd, Hi: 0xd717, Stride: 1}, + {Lo: 0xd719, Hi: 0xd733, Stride: 1}, + {Lo: 0xd735, Hi: 0xd74f, Stride: 1}, + {Lo: 0xd751, Hi: 0xd76b, Stride: 1}, + {Lo: 0xd76d, Hi: 0xd787, Stride: 1}, + {Lo: 0xd789, Hi: 0xd7a3, Stride: 1}, + }, +} + +// Hangul L Jamo +var BreakJL = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x1100, Hi: 0x115f, Stride: 1}, + {Lo: 0xa960, Hi: 0xa97c, Stride: 1}, + }, +} + +// Hangul V Jamo +var BreakJV = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x1160, Hi: 0x11a7, Stride: 1}, + {Lo: 0xd7b0, Hi: 0xd7c6, Stride: 1}, + }, +} + +// Hangul T Jamo +var BreakJT = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x11a8, Hi: 0x11ff, Stride: 1}, + {Lo: 0xd7cb, Hi: 0xd7fb, Stride: 1}, + }, +} + +// Regional Indicator +var BreakRI = &unicode.RangeTable{ + R32: []unicode.Range32{ + {Lo: 0x1f1e6, Hi: 0x1f1ff, Stride: 1}, + }, +} + +// Contingent Break Opportunity +var BreakCB = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0xfffc, Hi: 0xfffc, Stride: 1}, + }, +} + +// Ambiguous (Alphabetic or Ideographic) +var BreakAI = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x00a7, Hi: 0x00a8, Stride: 1}, + {Lo: 0x00aa, Hi: 0x00b2, Stride: 8}, + {Lo: 0x00b3, Hi: 0x00b6, Stride: 3}, + {Lo: 0x00b7, Hi: 0x00ba, Stride: 1}, + {Lo: 0x00bc, Hi: 0x00be, Stride: 1}, + {Lo: 0x00d7, Hi: 0x00f7, Stride: 32}, + {Lo: 0x02c7, Hi: 0x02c9, Stride: 2}, + {Lo: 0x02ca, Hi: 0x02cb, Stride: 1}, + {Lo: 0x02cd, Hi: 0x02d0, Stride: 3}, + {Lo: 0x02d8, Hi: 0x02db, Stride: 1}, + {Lo: 0x02dd, Hi: 0x2015, Stride: 7480}, + {Lo: 0x2016, Hi: 0x2020, Stride: 10}, + {Lo: 0x2021, Hi: 0x203b, Stride: 26}, + {Lo: 0x2074, Hi: 0x207f, Stride: 11}, + {Lo: 0x2081, Hi: 0x2084, Stride: 1}, + {Lo: 0x2105, Hi: 0x2121, Stride: 14}, + {Lo: 0x2122, Hi: 0x212b, Stride: 9}, + {Lo: 0x2154, Hi: 0x2155, Stride: 1}, + {Lo: 0x215b, Hi: 0x215e, Stride: 3}, + {Lo: 0x2160, Hi: 0x216b, Stride: 1}, + {Lo: 0x2170, Hi: 0x2179, Stride: 1}, + {Lo: 0x2189, Hi: 0x2190, Stride: 7}, + {Lo: 0x2191, Hi: 0x2199, Stride: 1}, + {Lo: 0x21d2, Hi: 0x21d4, Stride: 2}, + {Lo: 0x2200, Hi: 0x2202, Stride: 2}, + {Lo: 0x2203, Hi: 0x2207, Stride: 4}, + {Lo: 0x2208, Hi: 0x220b, Stride: 3}, + {Lo: 0x220f, Hi: 0x2211, Stride: 2}, + {Lo: 0x2215, Hi: 0x221a, Stride: 5}, + {Lo: 0x221d, Hi: 0x2220, Stride: 1}, + {Lo: 0x2223, Hi: 0x2227, Stride: 2}, + {Lo: 0x2228, Hi: 0x222c, Stride: 1}, + {Lo: 0x222e, Hi: 0x2234, Stride: 6}, + {Lo: 0x2235, Hi: 0x2237, Stride: 1}, + {Lo: 0x223c, Hi: 0x223d, Stride: 1}, + {Lo: 0x2248, Hi: 0x224c, Stride: 4}, + {Lo: 0x2252, Hi: 0x2260, Stride: 14}, + {Lo: 0x2261, Hi: 0x2264, Stride: 3}, + {Lo: 0x2265, Hi: 0x2267, Stride: 1}, + {Lo: 0x226a, Hi: 0x226b, Stride: 1}, + {Lo: 0x226e, Hi: 0x226f, Stride: 1}, + {Lo: 0x2282, Hi: 0x2283, Stride: 1}, + {Lo: 0x2286, Hi: 0x2287, Stride: 1}, + {Lo: 0x2295, Hi: 0x2299, Stride: 4}, + {Lo: 0x22a5, Hi: 0x22bf, Stride: 26}, + {Lo: 0x2312, Hi: 0x2460, Stride: 334}, + {Lo: 0x2461, Hi: 0x24fe, Stride: 1}, + {Lo: 0x2500, Hi: 0x254b, Stride: 1}, + {Lo: 0x2550, Hi: 0x2574, Stride: 1}, + {Lo: 0x2580, Hi: 0x258f, Stride: 1}, + {Lo: 0x2592, Hi: 0x2595, Stride: 1}, + {Lo: 0x25a0, Hi: 0x25a1, Stride: 1}, + {Lo: 0x25a3, Hi: 0x25a9, Stride: 1}, + {Lo: 0x25b2, Hi: 0x25b3, Stride: 1}, + {Lo: 0x25b6, Hi: 0x25b7, Stride: 1}, + {Lo: 0x25bc, Hi: 0x25bd, Stride: 1}, + {Lo: 0x25c0, Hi: 0x25c1, Stride: 1}, + {Lo: 0x25c6, Hi: 0x25c8, Stride: 1}, + {Lo: 0x25cb, Hi: 0x25ce, Stride: 3}, + {Lo: 0x25cf, Hi: 0x25d1, Stride: 1}, + {Lo: 0x25e2, Hi: 0x25e5, Stride: 1}, + {Lo: 0x25ef, Hi: 0x2605, Stride: 22}, + {Lo: 0x2606, Hi: 0x2609, Stride: 3}, + {Lo: 0x260e, Hi: 0x260f, Stride: 1}, + {Lo: 0x2616, Hi: 0x2617, Stride: 1}, + {Lo: 0x2640, Hi: 0x2642, Stride: 2}, + {Lo: 0x2660, Hi: 0x2661, Stride: 1}, + {Lo: 0x2663, Hi: 0x2665, Stride: 1}, + {Lo: 0x2667, Hi: 0x2669, Stride: 2}, + {Lo: 0x266a, Hi: 0x266c, Stride: 2}, + {Lo: 0x266d, Hi: 0x266f, Stride: 2}, + {Lo: 0x269e, Hi: 0x269f, Stride: 1}, + {Lo: 0x26c9, Hi: 0x26cc, Stride: 1}, + {Lo: 0x26d2, Hi: 0x26d5, Stride: 3}, + {Lo: 0x26d6, Hi: 0x26d7, Stride: 1}, + {Lo: 0x26da, Hi: 0x26db, Stride: 1}, + {Lo: 0x26dd, Hi: 0x26de, Stride: 1}, + {Lo: 0x26e3, Hi: 0x26e8, Stride: 5}, + {Lo: 0x26e9, Hi: 0x26eb, Stride: 2}, + {Lo: 0x26ec, Hi: 0x26f0, Stride: 1}, + {Lo: 0x26f6, Hi: 0x26fb, Stride: 5}, + {Lo: 0x26fc, Hi: 0x2757, Stride: 91}, + {Lo: 0x2776, Hi: 0x2793, Stride: 1}, + {Lo: 0x2b55, Hi: 0x2b59, Stride: 1}, + {Lo: 0x3248, Hi: 0x324f, Stride: 1}, + {Lo: 0xfffd, Hi: 0xfffd, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x1f100, Hi: 0x1f10c, Stride: 1}, + {Lo: 0x1f110, Hi: 0x1f12d, Stride: 1}, + {Lo: 0x1f130, Hi: 0x1f169, Stride: 1}, + {Lo: 0x1f170, Hi: 0x1f1ac, Stride: 1}, + }, + LatinOffset: 6, +} + +// Conditional Japanese Starter +var BreakCJ = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x3041, Hi: 0x3049, Stride: 2}, + {Lo: 0x3063, Hi: 0x3083, Stride: 32}, + {Lo: 0x3085, Hi: 0x3087, Stride: 2}, + {Lo: 0x308e, Hi: 0x3095, Stride: 7}, + {Lo: 0x3096, Hi: 0x30a1, Stride: 11}, + {Lo: 0x30a3, Hi: 0x30a9, Stride: 2}, + {Lo: 0x30c3, Hi: 0x30e3, Stride: 32}, + {Lo: 0x30e5, Hi: 0x30e7, Stride: 2}, + {Lo: 0x30ee, Hi: 0x30f5, Stride: 7}, + {Lo: 0x30f6, Hi: 0x30fc, Stride: 6}, + {Lo: 0x31f0, Hi: 0x31ff, Stride: 1}, + {Lo: 0xff67, Hi: 0xff70, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x1b132, Hi: 0x1b150, Stride: 30}, + {Lo: 0x1b151, Hi: 0x1b152, Stride: 1}, + {Lo: 0x1b155, Hi: 0x1b164, Stride: 15}, + {Lo: 0x1b165, Hi: 0x1b167, Stride: 1}, + }, +} + +// Complex Context Dependent (South East Asian) +var BreakSA = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0e01, Hi: 0x0e3a, Stride: 1}, + {Lo: 0x0e40, Hi: 0x0e4e, Stride: 1}, + {Lo: 0x0e81, Hi: 0x0e82, Stride: 1}, + {Lo: 0x0e84, Hi: 0x0e86, Stride: 2}, + {Lo: 0x0e87, Hi: 0x0e8a, Stride: 1}, + {Lo: 0x0e8c, Hi: 0x0ea3, Stride: 1}, + {Lo: 0x0ea5, Hi: 0x0ea7, Stride: 2}, + {Lo: 0x0ea8, Hi: 0x0ebd, Stride: 1}, + {Lo: 0x0ec0, Hi: 0x0ec4, Stride: 1}, + {Lo: 0x0ec6, Hi: 0x0ec8, Stride: 2}, + {Lo: 0x0ec9, Hi: 0x0ece, Stride: 1}, + {Lo: 0x0edc, Hi: 0x0edf, Stride: 1}, + {Lo: 0x1000, Hi: 0x103f, Stride: 1}, + {Lo: 0x1050, Hi: 0x108f, Stride: 1}, + {Lo: 0x109a, Hi: 0x109f, Stride: 1}, + {Lo: 0x1780, Hi: 0x17d3, Stride: 1}, + {Lo: 0x17d7, Hi: 0x17dc, Stride: 5}, + {Lo: 0x17dd, Hi: 0x1950, Stride: 371}, + {Lo: 0x1951, Hi: 0x196d, Stride: 1}, + {Lo: 0x1970, Hi: 0x1974, Stride: 1}, + {Lo: 0x1980, Hi: 0x19ab, Stride: 1}, + {Lo: 0x19b0, Hi: 0x19c9, Stride: 1}, + {Lo: 0x19da, Hi: 0x19de, Stride: 4}, + {Lo: 0x19df, Hi: 0x1a20, Stride: 65}, + {Lo: 0x1a21, Hi: 0x1a5e, Stride: 1}, + {Lo: 0x1a60, Hi: 0x1a7c, Stride: 1}, + {Lo: 0x1aa0, Hi: 0x1aad, Stride: 1}, + {Lo: 0xa9e0, Hi: 0xa9ef, Stride: 1}, + {Lo: 0xa9fa, Hi: 0xa9fe, Stride: 1}, + {Lo: 0xaa60, Hi: 0xaac2, Stride: 1}, + {Lo: 0xaadb, Hi: 0xaadf, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x11700, Hi: 0x1171a, Stride: 1}, + {Lo: 0x1171d, Hi: 0x1172b, Stride: 1}, + {Lo: 0x1173a, Hi: 0x1173b, Stride: 1}, + {Lo: 0x1173f, Hi: 0x11746, Stride: 1}, + }, +} + +// Unknown +var BreakXX = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0xe000, Hi: 0xf8ff, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0xf0000, Hi: 0xffffd, Stride: 1}, + {Lo: 0x100000, Hi: 0x10fffd, Stride: 1}, + }, +} + +var lineBreaks = [...]*unicode.RangeTable{ + BreakBK, // BK + BreakCR, // CR + BreakLF, // LF + BreakNL, // NL + BreakSP, // SP + BreakNU, // NU + BreakAL, // AL + BreakIS, // IS + BreakPR, // PR + BreakPO, // PO + BreakOP, // OP + BreakCL, // CL + BreakCP, // CP + BreakQU, // QU + BreakHY, // HY + BreakSG, // SG + BreakGL, // GL + BreakNS, // NS + BreakEX, // EX + BreakSY, // SY + BreakHL, // HL + BreakID, // ID + BreakIN, // IN + BreakBA, // BA + BreakBB, // BB + BreakB2, // B2 + BreakZW, // ZW + BreakCM, // CM + BreakEB, // EB + BreakEM, // EM + BreakWJ, // WJ + BreakZWJ, // ZWJ + BreakH2, // H2 + BreakH3, // H3 + BreakJL, // JL + BreakJV, // JV + BreakJT, // JT + BreakRI, // RI + BreakCB, // CB + BreakAI, // AI + BreakCJ, // CJ + BreakSA, // SA + BreakXX, // XX +} diff --git a/vendor/github.com/go-text/typesetting/unicodedata/mirroring.go b/vendor/github.com/go-text/typesetting/unicodedata/mirroring.go new file mode 100644 index 0000000..db85a87 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/unicodedata/mirroring.go @@ -0,0 +1,436 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package unicodedata + +// Code generated by typesettings-utils/generators/unicodedata/cmd/main.go DO NOT EDIT. + +var mirroring = map[rune]rune{ // 428 entries + 0x0028: 0x0029, + 0x0029: 0x0028, + 0x003c: 0x003e, + 0x003e: 0x003c, + 0x005b: 0x005d, + 0x005d: 0x005b, + 0x007b: 0x007d, + 0x007d: 0x007b, + 0x00ab: 0x00bb, + 0x00bb: 0x00ab, + 0x0f3a: 0x0f3b, + 0x0f3b: 0x0f3a, + 0x0f3c: 0x0f3d, + 0x0f3d: 0x0f3c, + 0x169b: 0x169c, + 0x169c: 0x169b, + 0x2039: 0x203a, + 0x203a: 0x2039, + 0x2045: 0x2046, + 0x2046: 0x2045, + 0x207d: 0x207e, + 0x207e: 0x207d, + 0x208d: 0x208e, + 0x208e: 0x208d, + 0x2208: 0x220b, + 0x2209: 0x220c, + 0x220a: 0x220d, + 0x220b: 0x2208, + 0x220c: 0x2209, + 0x220d: 0x220a, + 0x2215: 0x29f5, + 0x221f: 0x2bfe, + 0x2220: 0x29a3, + 0x2221: 0x299b, + 0x2222: 0x29a0, + 0x2224: 0x2aee, + 0x223c: 0x223d, + 0x223d: 0x223c, + 0x2243: 0x22cd, + 0x2245: 0x224c, + 0x224c: 0x2245, + 0x2252: 0x2253, + 0x2253: 0x2252, + 0x2254: 0x2255, + 0x2255: 0x2254, + 0x2264: 0x2265, + 0x2265: 0x2264, + 0x2266: 0x2267, + 0x2267: 0x2266, + 0x2268: 0x2269, + 0x2269: 0x2268, + 0x226a: 0x226b, + 0x226b: 0x226a, + 0x226e: 0x226f, + 0x226f: 0x226e, + 0x2270: 0x2271, + 0x2271: 0x2270, + 0x2272: 0x2273, + 0x2273: 0x2272, + 0x2274: 0x2275, + 0x2275: 0x2274, + 0x2276: 0x2277, + 0x2277: 0x2276, + 0x2278: 0x2279, + 0x2279: 0x2278, + 0x227a: 0x227b, + 0x227b: 0x227a, + 0x227c: 0x227d, + 0x227d: 0x227c, + 0x227e: 0x227f, + 0x227f: 0x227e, + 0x2280: 0x2281, + 0x2281: 0x2280, + 0x2282: 0x2283, + 0x2283: 0x2282, + 0x2284: 0x2285, + 0x2285: 0x2284, + 0x2286: 0x2287, + 0x2287: 0x2286, + 0x2288: 0x2289, + 0x2289: 0x2288, + 0x228a: 0x228b, + 0x228b: 0x228a, + 0x228f: 0x2290, + 0x2290: 0x228f, + 0x2291: 0x2292, + 0x2292: 0x2291, + 0x2298: 0x29b8, + 0x22a2: 0x22a3, + 0x22a3: 0x22a2, + 0x22a6: 0x2ade, + 0x22a8: 0x2ae4, + 0x22a9: 0x2ae3, + 0x22ab: 0x2ae5, + 0x22b0: 0x22b1, + 0x22b1: 0x22b0, + 0x22b2: 0x22b3, + 0x22b3: 0x22b2, + 0x22b4: 0x22b5, + 0x22b5: 0x22b4, + 0x22b6: 0x22b7, + 0x22b7: 0x22b6, + 0x22b8: 0x27dc, + 0x22c9: 0x22ca, + 0x22ca: 0x22c9, + 0x22cb: 0x22cc, + 0x22cc: 0x22cb, + 0x22cd: 0x2243, + 0x22d0: 0x22d1, + 0x22d1: 0x22d0, + 0x22d6: 0x22d7, + 0x22d7: 0x22d6, + 0x22d8: 0x22d9, + 0x22d9: 0x22d8, + 0x22da: 0x22db, + 0x22db: 0x22da, + 0x22dc: 0x22dd, + 0x22dd: 0x22dc, + 0x22de: 0x22df, + 0x22df: 0x22de, + 0x22e0: 0x22e1, + 0x22e1: 0x22e0, + 0x22e2: 0x22e3, + 0x22e3: 0x22e2, + 0x22e4: 0x22e5, + 0x22e5: 0x22e4, + 0x22e6: 0x22e7, + 0x22e7: 0x22e6, + 0x22e8: 0x22e9, + 0x22e9: 0x22e8, + 0x22ea: 0x22eb, + 0x22eb: 0x22ea, + 0x22ec: 0x22ed, + 0x22ed: 0x22ec, + 0x22f0: 0x22f1, + 0x22f1: 0x22f0, + 0x22f2: 0x22fa, + 0x22f3: 0x22fb, + 0x22f4: 0x22fc, + 0x22f6: 0x22fd, + 0x22f7: 0x22fe, + 0x22fa: 0x22f2, + 0x22fb: 0x22f3, + 0x22fc: 0x22f4, + 0x22fd: 0x22f6, + 0x22fe: 0x22f7, + 0x2308: 0x2309, + 0x2309: 0x2308, + 0x230a: 0x230b, + 0x230b: 0x230a, + 0x2329: 0x232a, + 0x232a: 0x2329, + 0x2768: 0x2769, + 0x2769: 0x2768, + 0x276a: 0x276b, + 0x276b: 0x276a, + 0x276c: 0x276d, + 0x276d: 0x276c, + 0x276e: 0x276f, + 0x276f: 0x276e, + 0x2770: 0x2771, + 0x2771: 0x2770, + 0x2772: 0x2773, + 0x2773: 0x2772, + 0x2774: 0x2775, + 0x2775: 0x2774, + 0x27c3: 0x27c4, + 0x27c4: 0x27c3, + 0x27c5: 0x27c6, + 0x27c6: 0x27c5, + 0x27c8: 0x27c9, + 0x27c9: 0x27c8, + 0x27cb: 0x27cd, + 0x27cd: 0x27cb, + 0x27d5: 0x27d6, + 0x27d6: 0x27d5, + 0x27dc: 0x22b8, + 0x27dd: 0x27de, + 0x27de: 0x27dd, + 0x27e2: 0x27e3, + 0x27e3: 0x27e2, + 0x27e4: 0x27e5, + 0x27e5: 0x27e4, + 0x27e6: 0x27e7, + 0x27e7: 0x27e6, + 0x27e8: 0x27e9, + 0x27e9: 0x27e8, + 0x27ea: 0x27eb, + 0x27eb: 0x27ea, + 0x27ec: 0x27ed, + 0x27ed: 0x27ec, + 0x27ee: 0x27ef, + 0x27ef: 0x27ee, + 0x2983: 0x2984, + 0x2984: 0x2983, + 0x2985: 0x2986, + 0x2986: 0x2985, + 0x2987: 0x2988, + 0x2988: 0x2987, + 0x2989: 0x298a, + 0x298a: 0x2989, + 0x298b: 0x298c, + 0x298c: 0x298b, + 0x298d: 0x2990, + 0x298e: 0x298f, + 0x298f: 0x298e, + 0x2990: 0x298d, + 0x2991: 0x2992, + 0x2992: 0x2991, + 0x2993: 0x2994, + 0x2994: 0x2993, + 0x2995: 0x2996, + 0x2996: 0x2995, + 0x2997: 0x2998, + 0x2998: 0x2997, + 0x299b: 0x2221, + 0x29a0: 0x2222, + 0x29a3: 0x2220, + 0x29a4: 0x29a5, + 0x29a5: 0x29a4, + 0x29a8: 0x29a9, + 0x29a9: 0x29a8, + 0x29aa: 0x29ab, + 0x29ab: 0x29aa, + 0x29ac: 0x29ad, + 0x29ad: 0x29ac, + 0x29ae: 0x29af, + 0x29af: 0x29ae, + 0x29b8: 0x2298, + 0x29c0: 0x29c1, + 0x29c1: 0x29c0, + 0x29c4: 0x29c5, + 0x29c5: 0x29c4, + 0x29cf: 0x29d0, + 0x29d0: 0x29cf, + 0x29d1: 0x29d2, + 0x29d2: 0x29d1, + 0x29d4: 0x29d5, + 0x29d5: 0x29d4, + 0x29d8: 0x29d9, + 0x29d9: 0x29d8, + 0x29da: 0x29db, + 0x29db: 0x29da, + 0x29e8: 0x29e9, + 0x29e9: 0x29e8, + 0x29f5: 0x2215, + 0x29f8: 0x29f9, + 0x29f9: 0x29f8, + 0x29fc: 0x29fd, + 0x29fd: 0x29fc, + 0x2a2b: 0x2a2c, + 0x2a2c: 0x2a2b, + 0x2a2d: 0x2a2e, + 0x2a2e: 0x2a2d, + 0x2a34: 0x2a35, + 0x2a35: 0x2a34, + 0x2a3c: 0x2a3d, + 0x2a3d: 0x2a3c, + 0x2a64: 0x2a65, + 0x2a65: 0x2a64, + 0x2a79: 0x2a7a, + 0x2a7a: 0x2a79, + 0x2a7b: 0x2a7c, + 0x2a7c: 0x2a7b, + 0x2a7d: 0x2a7e, + 0x2a7e: 0x2a7d, + 0x2a7f: 0x2a80, + 0x2a80: 0x2a7f, + 0x2a81: 0x2a82, + 0x2a82: 0x2a81, + 0x2a83: 0x2a84, + 0x2a84: 0x2a83, + 0x2a85: 0x2a86, + 0x2a86: 0x2a85, + 0x2a87: 0x2a88, + 0x2a88: 0x2a87, + 0x2a89: 0x2a8a, + 0x2a8a: 0x2a89, + 0x2a8b: 0x2a8c, + 0x2a8c: 0x2a8b, + 0x2a8d: 0x2a8e, + 0x2a8e: 0x2a8d, + 0x2a8f: 0x2a90, + 0x2a90: 0x2a8f, + 0x2a91: 0x2a92, + 0x2a92: 0x2a91, + 0x2a93: 0x2a94, + 0x2a94: 0x2a93, + 0x2a95: 0x2a96, + 0x2a96: 0x2a95, + 0x2a97: 0x2a98, + 0x2a98: 0x2a97, + 0x2a99: 0x2a9a, + 0x2a9a: 0x2a99, + 0x2a9b: 0x2a9c, + 0x2a9c: 0x2a9b, + 0x2a9d: 0x2a9e, + 0x2a9e: 0x2a9d, + 0x2a9f: 0x2aa0, + 0x2aa0: 0x2a9f, + 0x2aa1: 0x2aa2, + 0x2aa2: 0x2aa1, + 0x2aa6: 0x2aa7, + 0x2aa7: 0x2aa6, + 0x2aa8: 0x2aa9, + 0x2aa9: 0x2aa8, + 0x2aaa: 0x2aab, + 0x2aab: 0x2aaa, + 0x2aac: 0x2aad, + 0x2aad: 0x2aac, + 0x2aaf: 0x2ab0, + 0x2ab0: 0x2aaf, + 0x2ab1: 0x2ab2, + 0x2ab2: 0x2ab1, + 0x2ab3: 0x2ab4, + 0x2ab4: 0x2ab3, + 0x2ab5: 0x2ab6, + 0x2ab6: 0x2ab5, + 0x2ab7: 0x2ab8, + 0x2ab8: 0x2ab7, + 0x2ab9: 0x2aba, + 0x2aba: 0x2ab9, + 0x2abb: 0x2abc, + 0x2abc: 0x2abb, + 0x2abd: 0x2abe, + 0x2abe: 0x2abd, + 0x2abf: 0x2ac0, + 0x2ac0: 0x2abf, + 0x2ac1: 0x2ac2, + 0x2ac2: 0x2ac1, + 0x2ac3: 0x2ac4, + 0x2ac4: 0x2ac3, + 0x2ac5: 0x2ac6, + 0x2ac6: 0x2ac5, + 0x2ac7: 0x2ac8, + 0x2ac8: 0x2ac7, + 0x2ac9: 0x2aca, + 0x2aca: 0x2ac9, + 0x2acb: 0x2acc, + 0x2acc: 0x2acb, + 0x2acd: 0x2ace, + 0x2ace: 0x2acd, + 0x2acf: 0x2ad0, + 0x2ad0: 0x2acf, + 0x2ad1: 0x2ad2, + 0x2ad2: 0x2ad1, + 0x2ad3: 0x2ad4, + 0x2ad4: 0x2ad3, + 0x2ad5: 0x2ad6, + 0x2ad6: 0x2ad5, + 0x2ade: 0x22a6, + 0x2ae3: 0x22a9, + 0x2ae4: 0x22a8, + 0x2ae5: 0x22ab, + 0x2aec: 0x2aed, + 0x2aed: 0x2aec, + 0x2aee: 0x2224, + 0x2af7: 0x2af8, + 0x2af8: 0x2af7, + 0x2af9: 0x2afa, + 0x2afa: 0x2af9, + 0x2bfe: 0x221f, + 0x2e02: 0x2e03, + 0x2e03: 0x2e02, + 0x2e04: 0x2e05, + 0x2e05: 0x2e04, + 0x2e09: 0x2e0a, + 0x2e0a: 0x2e09, + 0x2e0c: 0x2e0d, + 0x2e0d: 0x2e0c, + 0x2e1c: 0x2e1d, + 0x2e1d: 0x2e1c, + 0x2e20: 0x2e21, + 0x2e21: 0x2e20, + 0x2e22: 0x2e23, + 0x2e23: 0x2e22, + 0x2e24: 0x2e25, + 0x2e25: 0x2e24, + 0x2e26: 0x2e27, + 0x2e27: 0x2e26, + 0x2e28: 0x2e29, + 0x2e29: 0x2e28, + 0x2e55: 0x2e56, + 0x2e56: 0x2e55, + 0x2e57: 0x2e58, + 0x2e58: 0x2e57, + 0x2e59: 0x2e5a, + 0x2e5a: 0x2e59, + 0x2e5b: 0x2e5c, + 0x2e5c: 0x2e5b, + 0x3008: 0x3009, + 0x3009: 0x3008, + 0x300a: 0x300b, + 0x300b: 0x300a, + 0x300c: 0x300d, + 0x300d: 0x300c, + 0x300e: 0x300f, + 0x300f: 0x300e, + 0x3010: 0x3011, + 0x3011: 0x3010, + 0x3014: 0x3015, + 0x3015: 0x3014, + 0x3016: 0x3017, + 0x3017: 0x3016, + 0x3018: 0x3019, + 0x3019: 0x3018, + 0x301a: 0x301b, + 0x301b: 0x301a, + 0xfe59: 0xfe5a, + 0xfe5a: 0xfe59, + 0xfe5b: 0xfe5c, + 0xfe5c: 0xfe5b, + 0xfe5d: 0xfe5e, + 0xfe5e: 0xfe5d, + 0xfe64: 0xfe65, + 0xfe65: 0xfe64, + 0xff08: 0xff09, + 0xff09: 0xff08, + 0xff1c: 0xff1e, + 0xff1e: 0xff1c, + 0xff3b: 0xff3d, + 0xff3d: 0xff3b, + 0xff5b: 0xff5d, + 0xff5d: 0xff5b, + 0xff5f: 0xff60, + 0xff60: 0xff5f, + 0xff62: 0xff63, + 0xff63: 0xff62, +} diff --git a/vendor/github.com/go-text/typesetting/unicodedata/sentence_break.go b/vendor/github.com/go-text/typesetting/unicodedata/sentence_break.go new file mode 100644 index 0000000..4113898 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/unicodedata/sentence_break.go @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package unicodedata + +import "unicode" + +// Code generated by typesettings-utils/generators/unicodedata/cmd/main.go DO NOT EDIT. + +// SentenceBreakProperty: STerm +var STerm = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0021, Hi: 0x003f, Stride: 30}, + {Lo: 0x0589, Hi: 0x061d, Stride: 148}, + {Lo: 0x061e, Hi: 0x061f, Stride: 1}, + {Lo: 0x06d4, Hi: 0x0700, Stride: 44}, + {Lo: 0x0701, Hi: 0x0702, Stride: 1}, + {Lo: 0x07f9, Hi: 0x0837, Stride: 62}, + {Lo: 0x0839, Hi: 0x083d, Stride: 4}, + {Lo: 0x083e, Hi: 0x0964, Stride: 294}, + {Lo: 0x0965, Hi: 0x104a, Stride: 1765}, + {Lo: 0x104b, Hi: 0x1362, Stride: 791}, + {Lo: 0x1367, Hi: 0x1368, Stride: 1}, + {Lo: 0x166e, Hi: 0x1735, Stride: 199}, + {Lo: 0x1736, Hi: 0x17d4, Stride: 158}, + {Lo: 0x17d5, Hi: 0x1803, Stride: 46}, + {Lo: 0x1809, Hi: 0x1944, Stride: 315}, + {Lo: 0x1945, Hi: 0x1aa8, Stride: 355}, + {Lo: 0x1aa9, Hi: 0x1aab, Stride: 1}, + {Lo: 0x1b5a, Hi: 0x1b5b, Stride: 1}, + {Lo: 0x1b5e, Hi: 0x1b5f, Stride: 1}, + {Lo: 0x1b7d, Hi: 0x1b7e, Stride: 1}, + {Lo: 0x1c3b, Hi: 0x1c3c, Stride: 1}, + {Lo: 0x1c7e, Hi: 0x1c7f, Stride: 1}, + {Lo: 0x203c, Hi: 0x203d, Stride: 1}, + {Lo: 0x2047, Hi: 0x2049, Stride: 1}, + {Lo: 0x2e2e, Hi: 0x2e3c, Stride: 14}, + {Lo: 0x2e53, Hi: 0x2e54, Stride: 1}, + {Lo: 0x3002, Hi: 0xa4ff, Stride: 29949}, + {Lo: 0xa60e, Hi: 0xa60f, Stride: 1}, + {Lo: 0xa6f3, Hi: 0xa6f7, Stride: 4}, + {Lo: 0xa876, Hi: 0xa877, Stride: 1}, + {Lo: 0xa8ce, Hi: 0xa8cf, Stride: 1}, + {Lo: 0xa92f, Hi: 0xa9c8, Stride: 153}, + {Lo: 0xa9c9, Hi: 0xaa5d, Stride: 148}, + {Lo: 0xaa5e, Hi: 0xaa5f, Stride: 1}, + {Lo: 0xaaf0, Hi: 0xaaf1, Stride: 1}, + {Lo: 0xabeb, Hi: 0xfe56, Stride: 21099}, + {Lo: 0xfe57, Hi: 0xff01, Stride: 170}, + {Lo: 0xff1f, Hi: 0xff61, Stride: 66}, + }, + R32: []unicode.Range32{ + {Lo: 0x10a56, Hi: 0x10a57, Stride: 1}, + {Lo: 0x10f55, Hi: 0x10f59, Stride: 1}, + {Lo: 0x10f86, Hi: 0x10f89, Stride: 1}, + {Lo: 0x11047, Hi: 0x11048, Stride: 1}, + {Lo: 0x110be, Hi: 0x110c1, Stride: 1}, + {Lo: 0x11141, Hi: 0x11143, Stride: 1}, + {Lo: 0x111c5, Hi: 0x111c6, Stride: 1}, + {Lo: 0x111cd, Hi: 0x111de, Stride: 17}, + {Lo: 0x111df, Hi: 0x11238, Stride: 89}, + {Lo: 0x11239, Hi: 0x1123b, Stride: 2}, + {Lo: 0x1123c, Hi: 0x112a9, Stride: 109}, + {Lo: 0x1144b, Hi: 0x1144c, Stride: 1}, + {Lo: 0x115c2, Hi: 0x115c3, Stride: 1}, + {Lo: 0x115c9, Hi: 0x115d7, Stride: 1}, + {Lo: 0x11641, Hi: 0x11642, Stride: 1}, + {Lo: 0x1173c, Hi: 0x1173e, Stride: 1}, + {Lo: 0x11944, Hi: 0x11946, Stride: 2}, + {Lo: 0x11a42, Hi: 0x11a43, Stride: 1}, + {Lo: 0x11a9b, Hi: 0x11a9c, Stride: 1}, + {Lo: 0x11c41, Hi: 0x11c42, Stride: 1}, + {Lo: 0x11ef7, Hi: 0x11ef8, Stride: 1}, + {Lo: 0x11f43, Hi: 0x11f44, Stride: 1}, + {Lo: 0x16a6e, Hi: 0x16a6f, Stride: 1}, + {Lo: 0x16af5, Hi: 0x16b37, Stride: 66}, + {Lo: 0x16b38, Hi: 0x16b44, Stride: 12}, + {Lo: 0x16e98, Hi: 0x1bc9f, Stride: 19975}, + {Lo: 0x1da88, Hi: 0x1da88, Stride: 1}, + }, + LatinOffset: 1, +} diff --git a/vendor/github.com/go-text/typesetting/unicodedata/unicode.go b/vendor/github.com/go-text/typesetting/unicodedata/unicode.go new file mode 100644 index 0000000..20dd70b --- /dev/null +++ b/vendor/github.com/go-text/typesetting/unicodedata/unicode.go @@ -0,0 +1,218 @@ +// Package unicodedata provides additional lookup functions for unicode +// properties, not covered by the standard package unicode. +package unicodedata + +import ( + "unicode" + + "github.com/go-text/typesetting/language" +) + +var categories []*unicode.RangeTable + +func init() { + for cat, table := range unicode.Categories { + if len(cat) == 2 { + categories = append(categories, table) + } + } +} + +// LookupType returns the unicode general categorie of the rune, +// or nil if not found. +func LookupType(r rune) *unicode.RangeTable { + for _, table := range categories { + if unicode.Is(table, r) { + return table + } + } + return nil +} + +// LookupCombiningClass returns the class used for the Canonical Ordering Algorithm in the Unicode Standard, +// defaulting to 0. +// +// From http://www.unicode.org/reports/tr44/#Canonical_Combining_Class: +// "This property could be considered either an enumerated property or a numeric property: +// the principal use of the property is in terms of the numeric values. +// For the property value names associated with different numeric values, +// see DerivedCombiningClass.txt and Canonical Combining Class Values." +func LookupCombiningClass(ch rune) uint8 { + for i, t := range combiningClasses { + if t == nil { + continue + } + if unicode.Is(t, ch) { + return uint8(i) + } + } + return 0 +} + +// LookupLineBreakClass returns the break class for the rune (see the constants BreakXXX) +func LookupLineBreakClass(ch rune) *unicode.RangeTable { + for _, class := range lineBreaks { + if unicode.Is(class, ch) { + return class + } + } + return BreakXX +} + +// LookupGraphemeBreakClass returns the grapheme break property for the rune (see the constants GraphemeBreakXXX), +// or nil +func LookupGraphemeBreakClass(ch rune) *unicode.RangeTable { + // a lot of runes do not have a grapheme break property : + // avoid testing all the graphemeBreaks classes for them + if !unicode.Is(graphemeBreakAll, ch) { + return nil + } + for _, class := range graphemeBreaks { + if unicode.Is(class, ch) { + return class + } + } + return nil +} + +// LookupordBreakClass returns the word break property for the rune (see the constants ordBreakXXX), +// or nil +func LookupWordBreakClass(ch rune) *unicode.RangeTable { + // a lot of runes do not have a word break property : + // avoid testing all the wordBreaks classes for them + if !unicode.Is(wordBreakAll, ch) { + return nil + } + for _, class := range wordBreaks { + if unicode.Is(class, ch) { + return class + } + } + return nil +} + +// LookupMirrorChar finds the mirrored equivalent of a character as defined in +// the file BidiMirroring.txt of the Unicode Character Database available at +// http://www.unicode.org/Public/UNIDATA/BidiMirroring.txt. +// +// If the input character is declared as a mirroring character in the +// Unicode standard and has a mirrored equivalent, it is returned with `true`. +// Otherwise the input character itself returned with `false`. +func LookupMirrorChar(ch rune) (rune, bool) { + m, ok := mirroring[ch] + if !ok { + m = ch + } + return m, ok +} + +// Algorithmic hangul syllables [de]composition, used +// in Compose and Decompose, but also exported for additional shaper +// processing. +const ( + HangulSBase = 0xAC00 + HangulLBase = 0x1100 + HangulVBase = 0x1161 + HangulTBase = 0x11A7 + HangulSCount = 11172 + HangulLCount = 19 + HangulVCount = 21 + HangulTCount = 28 + HangulNCount = HangulVCount * HangulTCount +) + +func decomposeHangul(ab rune) (a, b rune, ok bool) { + si := ab - HangulSBase + + if si < 0 || si >= HangulSCount { + return 0, 0, false + } + + if si%HangulTCount != 0 { // LV,T + return HangulSBase + (si/HangulTCount)*HangulTCount, HangulTBase + (si % HangulTCount), true + } // L,V + return HangulLBase + (si / HangulNCount), HangulVBase + (si%HangulNCount)/HangulTCount, true +} + +func composeHangul(a, b rune) (rune, bool) { + if a >= HangulSBase && a < (HangulSBase+HangulSCount) && b > HangulTBase && b < (HangulTBase+HangulTCount) && (a-HangulSBase)%HangulTCount == 0 { + // LV,T + return a + (b - HangulTBase), true + } else if a >= HangulLBase && a < (HangulLBase+HangulLCount) && b >= HangulVBase && b < (HangulVBase+HangulVCount) { + // L,V + li := a - HangulLBase + vi := b - HangulVBase + return HangulSBase + li*HangulNCount + vi*HangulTCount, true + } + return 0, false +} + +// Decompose decompose an input Unicode code point, +// returning the two decomposed code points, if successful. +// It returns `false` otherwise. +func Decompose(ab rune) (a, b rune, ok bool) { + if a, b, ok = decomposeHangul(ab); ok { + return a, b, true + } + + // Check if it's a single-character decomposition. + if m1, ok := decompose1[ab]; ok { + return m1, 0, true + } + if m2, ok := decompose2[ab]; ok { + return m2[0], m2[1], true + } + return ab, 0, false +} + +// Compose composes a sequence of two input Unicode code +// points by canonical equivalence, returning the composed code, if successful. +// It returns `false` otherwise +func Compose(a, b rune) (rune, bool) { + // Hangul is handled algorithmically. + if ab, ok := composeHangul(a, b); ok { + return ab, true + } + u := compose[[2]rune{a, b}] + return u, u != 0 +} + +// ArabicJoining is a property used to shape Arabic runes. +// See the table ArabicJoinings. +type ArabicJoining byte + +const ( + U ArabicJoining = 'U' // Un-joining, e.g. Full Stop + R ArabicJoining = 'R' // Right-joining, e.g. Arabic Letter Dal + Alaph ArabicJoining = 'a' // Alaph group (included in kind R) + DalathRish ArabicJoining = 'd' // Dalat Rish group (included in kind R) + D ArabicJoining = 'D' // Dual-joining, e.g. Arabic Letter Ain + C ArabicJoining = 'C' // Join-Causing, e.g. Tatweel, ZWJ + L ArabicJoining = 'L' // Left-joining, i.e. fictional + T ArabicJoining = 'T' // Transparent, e.g. Arabic Fatha + G ArabicJoining = 'G' // Ignored, e.g. LRE, RLE, ZWNBSP +) + +// LookupVerticalOrientation returns the prefered orientation +// for the given script. +func LookupVerticalOrientation(s language.Script) ScriptVerticalOrientation { + for _, script := range uprightOrMixedScripts { + if script.script == s { + return script + } + } + + // all other scripts have full R (sideways) + return ScriptVerticalOrientation{exceptions: nil, script: s, isMainSideways: true} +} + +// Orientation returns the prefered orientation +// for the given rune. +// If the rune does not belong to this script, the default orientation of this script +// is returned (regardless of the actual script of the given rune). +func (sv ScriptVerticalOrientation) Orientation(r rune) (isSideways bool) { + if sv.exceptions == nil || !unicode.Is(sv.exceptions, r) { + return sv.isMainSideways + } + return !sv.isMainSideways +} diff --git a/vendor/github.com/go-text/typesetting/unicodedata/vertical_orientation.go b/vendor/github.com/go-text/typesetting/unicodedata/vertical_orientation.go new file mode 100644 index 0000000..6c14420 --- /dev/null +++ b/vendor/github.com/go-text/typesetting/unicodedata/vertical_orientation.go @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package unicodedata + +import ( + "unicode" + + "github.com/go-text/typesetting/language" +) + +// Code generated by typesettings-utils/generators/unicodedata/cmd/main.go DO NOT EDIT. + +// ScriptVerticalOrientation provides the glyph oriention +// to use for vertical text. +type ScriptVerticalOrientation struct { + exceptions *unicode.RangeTable + script language.Script + isMainSideways bool +} + +// uprightOrMixedScripts is the list of scripts +// which may use both mode ("upright" or "sideways") for vertical text orientation +var uprightOrMixedScripts = [...]ScriptVerticalOrientation{ + {nil, language.Anatolian_Hieroglyphs, false}, + {nil, language.Bopomofo, false}, + { + &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x1400, Hi: 0x1400, Stride: 1}, + }, + }, language.Canadian_Aboriginal, false, + }, + {nil, language.Egyptian_Hieroglyphs, false}, + {nil, language.Han, false}, + { + &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0xffa0, Hi: 0xffbe, Stride: 1}, + {Lo: 0xffc2, Hi: 0xffc7, Stride: 1}, + {Lo: 0xffca, Hi: 0xffcf, Stride: 1}, + {Lo: 0xffd2, Hi: 0xffd7, Stride: 1}, + {Lo: 0xffda, Hi: 0xffdc, Stride: 1}, + }, + }, language.Hangul, false, + }, + {nil, language.Hiragana, false}, + { + &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0xff66, Hi: 0xff6f, Stride: 1}, + {Lo: 0xff71, Hi: 0xff9d, Stride: 1}, + }, + }, language.Katakana, false, + }, + {nil, language.Khitan_Small_Script, false}, + { + &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x2160, Hi: 0x2188, Stride: 1}, + {Lo: 0xff21, Hi: 0xff3a, Stride: 1}, + {Lo: 0xff41, Hi: 0xff5a, Stride: 1}, + }, + }, language.Latin, true, + }, + {nil, language.Meroitic_Hieroglyphs, false}, + {nil, language.Nushu, false}, + {nil, language.Siddham, false}, + {nil, language.SignWriting, false}, + {nil, language.Soyombo, false}, + {nil, language.Tangut, false}, + {nil, language.Yi, false}, + {nil, language.Zanabazar_Square, false}, +} diff --git a/vendor/github.com/go-text/typesetting/unicodedata/word_break.go b/vendor/github.com/go-text/typesetting/unicodedata/word_break.go new file mode 100644 index 0000000..d062b3c --- /dev/null +++ b/vendor/github.com/go-text/typesetting/unicodedata/word_break.go @@ -0,0 +1,2650 @@ +// SPDX-License-Identifier: Unlicense OR BSD-3-Clause + +package unicodedata + +import "unicode" + +// Code generated by typesettings-utils/generators/unicodedata/cmd/main.go DO NOT EDIT. + +// WordBreakProperty: ALetter +var WordBreakALetter = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0041, Hi: 0x005a, Stride: 1}, + {Lo: 0x0061, Hi: 0x007a, Stride: 1}, + {Lo: 0x00aa, Hi: 0x00b5, Stride: 11}, + {Lo: 0x00ba, Hi: 0x00c0, Stride: 6}, + {Lo: 0x00c1, Hi: 0x00d6, Stride: 1}, + {Lo: 0x00d8, Hi: 0x00f6, Stride: 1}, + {Lo: 0x00f8, Hi: 0x02d7, Stride: 1}, + {Lo: 0x02de, Hi: 0x02ff, Stride: 1}, + {Lo: 0x0370, Hi: 0x0374, Stride: 1}, + {Lo: 0x0376, Hi: 0x0377, Stride: 1}, + {Lo: 0x037a, Hi: 0x037d, Stride: 1}, + {Lo: 0x037f, Hi: 0x0386, Stride: 7}, + {Lo: 0x0388, Hi: 0x038a, Stride: 1}, + {Lo: 0x038c, Hi: 0x038e, Stride: 2}, + {Lo: 0x038f, Hi: 0x03a1, Stride: 1}, + {Lo: 0x03a3, Hi: 0x03f5, Stride: 1}, + {Lo: 0x03f7, Hi: 0x0481, Stride: 1}, + {Lo: 0x048a, Hi: 0x052f, Stride: 1}, + {Lo: 0x0531, Hi: 0x0556, Stride: 1}, + {Lo: 0x0559, Hi: 0x055c, Stride: 1}, + {Lo: 0x055e, Hi: 0x0560, Stride: 2}, + {Lo: 0x0561, Hi: 0x0588, Stride: 1}, + {Lo: 0x058a, Hi: 0x05f3, Stride: 105}, + {Lo: 0x0620, Hi: 0x064a, Stride: 1}, + {Lo: 0x066e, Hi: 0x066f, Stride: 1}, + {Lo: 0x0671, Hi: 0x06d3, Stride: 1}, + {Lo: 0x06d5, Hi: 0x06e5, Stride: 16}, + {Lo: 0x06e6, Hi: 0x06ee, Stride: 8}, + {Lo: 0x06ef, Hi: 0x06fa, Stride: 11}, + {Lo: 0x06fb, Hi: 0x06fc, Stride: 1}, + {Lo: 0x06ff, Hi: 0x070f, Stride: 16}, + {Lo: 0x0710, Hi: 0x0712, Stride: 2}, + {Lo: 0x0713, Hi: 0x072f, Stride: 1}, + {Lo: 0x074d, Hi: 0x07a5, Stride: 1}, + {Lo: 0x07b1, Hi: 0x07ca, Stride: 25}, + {Lo: 0x07cb, Hi: 0x07ea, Stride: 1}, + {Lo: 0x07f4, Hi: 0x07f5, Stride: 1}, + {Lo: 0x07fa, Hi: 0x0800, Stride: 6}, + {Lo: 0x0801, Hi: 0x0815, Stride: 1}, + {Lo: 0x081a, Hi: 0x0824, Stride: 10}, + {Lo: 0x0828, Hi: 0x0840, Stride: 24}, + {Lo: 0x0841, Hi: 0x0858, Stride: 1}, + {Lo: 0x0860, Hi: 0x086a, Stride: 1}, + {Lo: 0x0870, Hi: 0x0887, Stride: 1}, + {Lo: 0x0889, Hi: 0x088e, Stride: 1}, + {Lo: 0x08a0, Hi: 0x08c9, Stride: 1}, + {Lo: 0x0904, Hi: 0x0939, Stride: 1}, + {Lo: 0x093d, Hi: 0x0950, Stride: 19}, + {Lo: 0x0958, Hi: 0x0961, Stride: 1}, + {Lo: 0x0971, Hi: 0x0980, Stride: 1}, + {Lo: 0x0985, Hi: 0x098c, Stride: 1}, + {Lo: 0x098f, Hi: 0x0990, Stride: 1}, + {Lo: 0x0993, Hi: 0x09a8, Stride: 1}, + {Lo: 0x09aa, Hi: 0x09b0, Stride: 1}, + {Lo: 0x09b2, Hi: 0x09b6, Stride: 4}, + {Lo: 0x09b7, Hi: 0x09b9, Stride: 1}, + {Lo: 0x09bd, Hi: 0x09ce, Stride: 17}, + {Lo: 0x09dc, Hi: 0x09dd, Stride: 1}, + {Lo: 0x09df, Hi: 0x09e1, Stride: 1}, + {Lo: 0x09f0, Hi: 0x09f1, Stride: 1}, + {Lo: 0x09fc, Hi: 0x0a05, Stride: 9}, + {Lo: 0x0a06, Hi: 0x0a0a, Stride: 1}, + {Lo: 0x0a0f, Hi: 0x0a10, Stride: 1}, + {Lo: 0x0a13, Hi: 0x0a28, Stride: 1}, + {Lo: 0x0a2a, Hi: 0x0a30, Stride: 1}, + {Lo: 0x0a32, Hi: 0x0a33, Stride: 1}, + {Lo: 0x0a35, Hi: 0x0a36, Stride: 1}, + {Lo: 0x0a38, Hi: 0x0a39, Stride: 1}, + {Lo: 0x0a59, Hi: 0x0a5c, Stride: 1}, + {Lo: 0x0a5e, Hi: 0x0a72, Stride: 20}, + {Lo: 0x0a73, Hi: 0x0a74, Stride: 1}, + {Lo: 0x0a85, Hi: 0x0a8d, Stride: 1}, + {Lo: 0x0a8f, Hi: 0x0a91, Stride: 1}, + {Lo: 0x0a93, Hi: 0x0aa8, Stride: 1}, + {Lo: 0x0aaa, Hi: 0x0ab0, Stride: 1}, + {Lo: 0x0ab2, Hi: 0x0ab3, Stride: 1}, + {Lo: 0x0ab5, Hi: 0x0ab9, Stride: 1}, + {Lo: 0x0abd, Hi: 0x0ad0, Stride: 19}, + {Lo: 0x0ae0, Hi: 0x0ae1, Stride: 1}, + {Lo: 0x0af9, Hi: 0x0b05, Stride: 12}, + {Lo: 0x0b06, Hi: 0x0b0c, Stride: 1}, + {Lo: 0x0b0f, Hi: 0x0b10, Stride: 1}, + {Lo: 0x0b13, Hi: 0x0b28, Stride: 1}, + {Lo: 0x0b2a, Hi: 0x0b30, Stride: 1}, + {Lo: 0x0b32, Hi: 0x0b33, Stride: 1}, + {Lo: 0x0b35, Hi: 0x0b39, Stride: 1}, + {Lo: 0x0b3d, Hi: 0x0b5c, Stride: 31}, + {Lo: 0x0b5d, Hi: 0x0b5f, Stride: 2}, + {Lo: 0x0b60, Hi: 0x0b61, Stride: 1}, + {Lo: 0x0b71, Hi: 0x0b83, Stride: 18}, + {Lo: 0x0b85, Hi: 0x0b8a, Stride: 1}, + {Lo: 0x0b8e, Hi: 0x0b90, Stride: 1}, + {Lo: 0x0b92, Hi: 0x0b95, Stride: 1}, + {Lo: 0x0b99, Hi: 0x0b9a, Stride: 1}, + {Lo: 0x0b9c, Hi: 0x0b9e, Stride: 2}, + {Lo: 0x0b9f, Hi: 0x0ba3, Stride: 4}, + {Lo: 0x0ba4, Hi: 0x0ba8, Stride: 4}, + {Lo: 0x0ba9, Hi: 0x0baa, Stride: 1}, + {Lo: 0x0bae, Hi: 0x0bb9, Stride: 1}, + {Lo: 0x0bd0, Hi: 0x0c05, Stride: 53}, + {Lo: 0x0c06, Hi: 0x0c0c, Stride: 1}, + {Lo: 0x0c0e, Hi: 0x0c10, Stride: 1}, + {Lo: 0x0c12, Hi: 0x0c28, Stride: 1}, + {Lo: 0x0c2a, Hi: 0x0c39, Stride: 1}, + {Lo: 0x0c3d, Hi: 0x0c58, Stride: 27}, + {Lo: 0x0c59, Hi: 0x0c5a, Stride: 1}, + {Lo: 0x0c5d, Hi: 0x0c60, Stride: 3}, + {Lo: 0x0c61, Hi: 0x0c80, Stride: 31}, + {Lo: 0x0c85, Hi: 0x0c8c, Stride: 1}, + {Lo: 0x0c8e, Hi: 0x0c90, Stride: 1}, + {Lo: 0x0c92, Hi: 0x0ca8, Stride: 1}, + {Lo: 0x0caa, Hi: 0x0cb3, Stride: 1}, + {Lo: 0x0cb5, Hi: 0x0cb9, Stride: 1}, + {Lo: 0x0cbd, Hi: 0x0cdd, Stride: 32}, + {Lo: 0x0cde, Hi: 0x0ce0, Stride: 2}, + {Lo: 0x0ce1, Hi: 0x0cf1, Stride: 16}, + {Lo: 0x0cf2, Hi: 0x0d04, Stride: 18}, + {Lo: 0x0d05, Hi: 0x0d0c, Stride: 1}, + {Lo: 0x0d0e, Hi: 0x0d10, Stride: 1}, + {Lo: 0x0d12, Hi: 0x0d3a, Stride: 1}, + {Lo: 0x0d3d, Hi: 0x0d4e, Stride: 17}, + {Lo: 0x0d54, Hi: 0x0d56, Stride: 1}, + {Lo: 0x0d5f, Hi: 0x0d61, Stride: 1}, + {Lo: 0x0d7a, Hi: 0x0d7f, Stride: 1}, + {Lo: 0x0d85, Hi: 0x0d96, Stride: 1}, + {Lo: 0x0d9a, Hi: 0x0db1, Stride: 1}, + {Lo: 0x0db3, Hi: 0x0dbb, Stride: 1}, + {Lo: 0x0dbd, Hi: 0x0dc0, Stride: 3}, + {Lo: 0x0dc1, Hi: 0x0dc6, Stride: 1}, + {Lo: 0x0f00, Hi: 0x0f40, Stride: 64}, + {Lo: 0x0f41, Hi: 0x0f47, Stride: 1}, + {Lo: 0x0f49, Hi: 0x0f6c, Stride: 1}, + {Lo: 0x0f88, Hi: 0x0f8c, Stride: 1}, + {Lo: 0x10a0, Hi: 0x10c5, Stride: 1}, + {Lo: 0x10c7, Hi: 0x10cd, Stride: 6}, + {Lo: 0x10d0, Hi: 0x10fa, Stride: 1}, + {Lo: 0x10fc, Hi: 0x1248, Stride: 1}, + {Lo: 0x124a, Hi: 0x124d, Stride: 1}, + {Lo: 0x1250, Hi: 0x1256, Stride: 1}, + {Lo: 0x1258, Hi: 0x125a, Stride: 2}, + {Lo: 0x125b, Hi: 0x125d, Stride: 1}, + {Lo: 0x1260, Hi: 0x1288, Stride: 1}, + {Lo: 0x128a, Hi: 0x128d, Stride: 1}, + {Lo: 0x1290, Hi: 0x12b0, Stride: 1}, + {Lo: 0x12b2, Hi: 0x12b5, Stride: 1}, + {Lo: 0x12b8, Hi: 0x12be, Stride: 1}, + {Lo: 0x12c0, Hi: 0x12c2, Stride: 2}, + {Lo: 0x12c3, Hi: 0x12c5, Stride: 1}, + {Lo: 0x12c8, Hi: 0x12d6, Stride: 1}, + {Lo: 0x12d8, Hi: 0x1310, Stride: 1}, + {Lo: 0x1312, Hi: 0x1315, Stride: 1}, + {Lo: 0x1318, Hi: 0x135a, Stride: 1}, + {Lo: 0x1380, Hi: 0x138f, Stride: 1}, + {Lo: 0x13a0, Hi: 0x13f5, Stride: 1}, + {Lo: 0x13f8, Hi: 0x13fd, Stride: 1}, + {Lo: 0x1401, Hi: 0x166c, Stride: 1}, + {Lo: 0x166f, Hi: 0x167f, Stride: 1}, + {Lo: 0x1681, Hi: 0x169a, Stride: 1}, + {Lo: 0x16a0, Hi: 0x16ea, Stride: 1}, + {Lo: 0x16ee, Hi: 0x16f8, Stride: 1}, + {Lo: 0x1700, Hi: 0x1711, Stride: 1}, + {Lo: 0x171f, Hi: 0x1731, Stride: 1}, + {Lo: 0x1740, Hi: 0x1751, Stride: 1}, + {Lo: 0x1760, Hi: 0x176c, Stride: 1}, + {Lo: 0x176e, Hi: 0x1770, Stride: 1}, + {Lo: 0x1820, Hi: 0x1878, Stride: 1}, + {Lo: 0x1880, Hi: 0x1884, Stride: 1}, + {Lo: 0x1887, Hi: 0x18a8, Stride: 1}, + {Lo: 0x18aa, Hi: 0x18b0, Stride: 6}, + {Lo: 0x18b1, Hi: 0x18f5, Stride: 1}, + {Lo: 0x1900, Hi: 0x191e, Stride: 1}, + {Lo: 0x1a00, Hi: 0x1a16, Stride: 1}, + {Lo: 0x1b05, Hi: 0x1b33, Stride: 1}, + {Lo: 0x1b45, Hi: 0x1b4c, Stride: 1}, + {Lo: 0x1b83, Hi: 0x1ba0, Stride: 1}, + {Lo: 0x1bae, Hi: 0x1baf, Stride: 1}, + {Lo: 0x1bba, Hi: 0x1be5, Stride: 1}, + {Lo: 0x1c00, Hi: 0x1c23, Stride: 1}, + {Lo: 0x1c4d, Hi: 0x1c4f, Stride: 1}, + {Lo: 0x1c5a, Hi: 0x1c7d, Stride: 1}, + {Lo: 0x1c80, Hi: 0x1c88, Stride: 1}, + {Lo: 0x1c90, Hi: 0x1cba, Stride: 1}, + {Lo: 0x1cbd, Hi: 0x1cbf, Stride: 1}, + {Lo: 0x1ce9, Hi: 0x1cec, Stride: 1}, + {Lo: 0x1cee, Hi: 0x1cf3, Stride: 1}, + {Lo: 0x1cf5, Hi: 0x1cf6, Stride: 1}, + {Lo: 0x1cfa, Hi: 0x1d00, Stride: 6}, + {Lo: 0x1d01, Hi: 0x1dbf, Stride: 1}, + {Lo: 0x1e00, Hi: 0x1f15, Stride: 1}, + {Lo: 0x1f18, Hi: 0x1f1d, Stride: 1}, + {Lo: 0x1f20, Hi: 0x1f45, Stride: 1}, + {Lo: 0x1f48, Hi: 0x1f4d, Stride: 1}, + {Lo: 0x1f50, Hi: 0x1f57, Stride: 1}, + {Lo: 0x1f59, Hi: 0x1f5f, Stride: 2}, + {Lo: 0x1f60, Hi: 0x1f7d, Stride: 1}, + {Lo: 0x1f80, Hi: 0x1fb4, Stride: 1}, + {Lo: 0x1fb6, Hi: 0x1fbc, Stride: 1}, + {Lo: 0x1fbe, Hi: 0x1fc2, Stride: 4}, + {Lo: 0x1fc3, Hi: 0x1fc4, Stride: 1}, + {Lo: 0x1fc6, Hi: 0x1fcc, Stride: 1}, + {Lo: 0x1fd0, Hi: 0x1fd3, Stride: 1}, + {Lo: 0x1fd6, Hi: 0x1fdb, Stride: 1}, + {Lo: 0x1fe0, Hi: 0x1fec, Stride: 1}, + {Lo: 0x1ff2, Hi: 0x1ff4, Stride: 1}, + {Lo: 0x1ff6, Hi: 0x1ffc, Stride: 1}, + {Lo: 0x2071, Hi: 0x207f, Stride: 14}, + {Lo: 0x2090, Hi: 0x209c, Stride: 1}, + {Lo: 0x2102, Hi: 0x2107, Stride: 5}, + {Lo: 0x210a, Hi: 0x2113, Stride: 1}, + {Lo: 0x2115, Hi: 0x2119, Stride: 4}, + {Lo: 0x211a, Hi: 0x211d, Stride: 1}, + {Lo: 0x2124, Hi: 0x212a, Stride: 2}, + {Lo: 0x212b, Hi: 0x212d, Stride: 1}, + {Lo: 0x212f, Hi: 0x2139, Stride: 1}, + {Lo: 0x213c, Hi: 0x213f, Stride: 1}, + {Lo: 0x2145, Hi: 0x2149, Stride: 1}, + {Lo: 0x214e, Hi: 0x2160, Stride: 18}, + {Lo: 0x2161, Hi: 0x2188, Stride: 1}, + {Lo: 0x24b6, Hi: 0x24e9, Stride: 1}, + {Lo: 0x2c00, Hi: 0x2ce4, Stride: 1}, + {Lo: 0x2ceb, Hi: 0x2cee, Stride: 1}, + {Lo: 0x2cf2, Hi: 0x2cf3, Stride: 1}, + {Lo: 0x2d00, Hi: 0x2d25, Stride: 1}, + {Lo: 0x2d27, Hi: 0x2d2d, Stride: 6}, + {Lo: 0x2d30, Hi: 0x2d67, Stride: 1}, + {Lo: 0x2d6f, Hi: 0x2d80, Stride: 17}, + {Lo: 0x2d81, Hi: 0x2d96, Stride: 1}, + {Lo: 0x2da0, Hi: 0x2da6, Stride: 1}, + {Lo: 0x2da8, Hi: 0x2dae, Stride: 1}, + {Lo: 0x2db0, Hi: 0x2db6, Stride: 1}, + {Lo: 0x2db8, Hi: 0x2dbe, Stride: 1}, + {Lo: 0x2dc0, Hi: 0x2dc6, Stride: 1}, + {Lo: 0x2dc8, Hi: 0x2dce, Stride: 1}, + {Lo: 0x2dd0, Hi: 0x2dd6, Stride: 1}, + {Lo: 0x2dd8, Hi: 0x2dde, Stride: 1}, + {Lo: 0x2e2f, Hi: 0x3005, Stride: 470}, + {Lo: 0x303b, Hi: 0x303c, Stride: 1}, + {Lo: 0x3105, Hi: 0x312f, Stride: 1}, + {Lo: 0x3131, Hi: 0x318e, Stride: 1}, + {Lo: 0x31a0, Hi: 0x31bf, Stride: 1}, + {Lo: 0xa000, Hi: 0xa48c, Stride: 1}, + {Lo: 0xa4d0, Hi: 0xa4fd, Stride: 1}, + {Lo: 0xa500, Hi: 0xa60c, Stride: 1}, + {Lo: 0xa610, Hi: 0xa61f, Stride: 1}, + {Lo: 0xa62a, Hi: 0xa62b, Stride: 1}, + {Lo: 0xa640, Hi: 0xa66e, Stride: 1}, + {Lo: 0xa67f, Hi: 0xa69d, Stride: 1}, + {Lo: 0xa6a0, Hi: 0xa6ef, Stride: 1}, + {Lo: 0xa708, Hi: 0xa7ca, Stride: 1}, + {Lo: 0xa7d0, Hi: 0xa7d1, Stride: 1}, + {Lo: 0xa7d3, Hi: 0xa7d5, Stride: 2}, + {Lo: 0xa7d6, Hi: 0xa7d9, Stride: 1}, + {Lo: 0xa7f2, Hi: 0xa801, Stride: 1}, + {Lo: 0xa803, Hi: 0xa805, Stride: 1}, + {Lo: 0xa807, Hi: 0xa80a, Stride: 1}, + {Lo: 0xa80c, Hi: 0xa822, Stride: 1}, + {Lo: 0xa840, Hi: 0xa873, Stride: 1}, + {Lo: 0xa882, Hi: 0xa8b3, Stride: 1}, + {Lo: 0xa8f2, Hi: 0xa8f7, Stride: 1}, + {Lo: 0xa8fb, Hi: 0xa8fd, Stride: 2}, + {Lo: 0xa8fe, Hi: 0xa90a, Stride: 12}, + {Lo: 0xa90b, Hi: 0xa925, Stride: 1}, + {Lo: 0xa930, Hi: 0xa946, Stride: 1}, + {Lo: 0xa960, Hi: 0xa97c, Stride: 1}, + {Lo: 0xa984, Hi: 0xa9b2, Stride: 1}, + {Lo: 0xa9cf, Hi: 0xaa00, Stride: 49}, + {Lo: 0xaa01, Hi: 0xaa28, Stride: 1}, + {Lo: 0xaa40, Hi: 0xaa42, Stride: 1}, + {Lo: 0xaa44, Hi: 0xaa4b, Stride: 1}, + {Lo: 0xaae0, Hi: 0xaaea, Stride: 1}, + {Lo: 0xaaf2, Hi: 0xaaf4, Stride: 1}, + {Lo: 0xab01, Hi: 0xab06, Stride: 1}, + {Lo: 0xab09, Hi: 0xab0e, Stride: 1}, + {Lo: 0xab11, Hi: 0xab16, Stride: 1}, + {Lo: 0xab20, Hi: 0xab26, Stride: 1}, + {Lo: 0xab28, Hi: 0xab2e, Stride: 1}, + {Lo: 0xab30, Hi: 0xab69, Stride: 1}, + {Lo: 0xab70, Hi: 0xabe2, Stride: 1}, + {Lo: 0xac00, Hi: 0xd7a3, Stride: 1}, + {Lo: 0xd7b0, Hi: 0xd7c6, Stride: 1}, + {Lo: 0xd7cb, Hi: 0xd7fb, Stride: 1}, + {Lo: 0xfb00, Hi: 0xfb06, Stride: 1}, + {Lo: 0xfb13, Hi: 0xfb17, Stride: 1}, + {Lo: 0xfb50, Hi: 0xfbb1, Stride: 1}, + {Lo: 0xfbd3, Hi: 0xfd3d, Stride: 1}, + {Lo: 0xfd50, Hi: 0xfd8f, Stride: 1}, + {Lo: 0xfd92, Hi: 0xfdc7, Stride: 1}, + {Lo: 0xfdf0, Hi: 0xfdfb, Stride: 1}, + {Lo: 0xfe70, Hi: 0xfe74, Stride: 1}, + {Lo: 0xfe76, Hi: 0xfefc, Stride: 1}, + {Lo: 0xff21, Hi: 0xff3a, Stride: 1}, + {Lo: 0xff41, Hi: 0xff5a, Stride: 1}, + {Lo: 0xffa0, Hi: 0xffbe, Stride: 1}, + {Lo: 0xffc2, Hi: 0xffc7, Stride: 1}, + {Lo: 0xffca, Hi: 0xffcf, Stride: 1}, + {Lo: 0xffd2, Hi: 0xffd7, Stride: 1}, + {Lo: 0xffda, Hi: 0xffdc, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x10000, Hi: 0x1000b, Stride: 1}, + {Lo: 0x1000d, Hi: 0x10026, Stride: 1}, + {Lo: 0x10028, Hi: 0x1003a, Stride: 1}, + {Lo: 0x1003c, Hi: 0x1003d, Stride: 1}, + {Lo: 0x1003f, Hi: 0x1004d, Stride: 1}, + {Lo: 0x10050, Hi: 0x1005d, Stride: 1}, + {Lo: 0x10080, Hi: 0x100fa, Stride: 1}, + {Lo: 0x10140, Hi: 0x10174, Stride: 1}, + {Lo: 0x10280, Hi: 0x1029c, Stride: 1}, + {Lo: 0x102a0, Hi: 0x102d0, Stride: 1}, + {Lo: 0x10300, Hi: 0x1031f, Stride: 1}, + {Lo: 0x1032d, Hi: 0x1034a, Stride: 1}, + {Lo: 0x10350, Hi: 0x10375, Stride: 1}, + {Lo: 0x10380, Hi: 0x1039d, Stride: 1}, + {Lo: 0x103a0, Hi: 0x103c3, Stride: 1}, + {Lo: 0x103c8, Hi: 0x103cf, Stride: 1}, + {Lo: 0x103d1, Hi: 0x103d5, Stride: 1}, + {Lo: 0x10400, Hi: 0x1049d, Stride: 1}, + {Lo: 0x104b0, Hi: 0x104d3, Stride: 1}, + {Lo: 0x104d8, Hi: 0x104fb, Stride: 1}, + {Lo: 0x10500, Hi: 0x10527, Stride: 1}, + {Lo: 0x10530, Hi: 0x10563, Stride: 1}, + {Lo: 0x10570, Hi: 0x1057a, Stride: 1}, + {Lo: 0x1057c, Hi: 0x1058a, Stride: 1}, + {Lo: 0x1058c, Hi: 0x10592, Stride: 1}, + {Lo: 0x10594, Hi: 0x10595, Stride: 1}, + {Lo: 0x10597, Hi: 0x105a1, Stride: 1}, + {Lo: 0x105a3, Hi: 0x105b1, Stride: 1}, + {Lo: 0x105b3, Hi: 0x105b9, Stride: 1}, + {Lo: 0x105bb, Hi: 0x105bc, Stride: 1}, + {Lo: 0x10600, Hi: 0x10736, Stride: 1}, + {Lo: 0x10740, Hi: 0x10755, Stride: 1}, + {Lo: 0x10760, Hi: 0x10767, Stride: 1}, + {Lo: 0x10780, Hi: 0x10785, Stride: 1}, + {Lo: 0x10787, Hi: 0x107b0, Stride: 1}, + {Lo: 0x107b2, Hi: 0x107ba, Stride: 1}, + {Lo: 0x10800, Hi: 0x10805, Stride: 1}, + {Lo: 0x10808, Hi: 0x1080a, Stride: 2}, + {Lo: 0x1080b, Hi: 0x10835, Stride: 1}, + {Lo: 0x10837, Hi: 0x10838, Stride: 1}, + {Lo: 0x1083c, Hi: 0x1083f, Stride: 3}, + {Lo: 0x10840, Hi: 0x10855, Stride: 1}, + {Lo: 0x10860, Hi: 0x10876, Stride: 1}, + {Lo: 0x10880, Hi: 0x1089e, Stride: 1}, + {Lo: 0x108e0, Hi: 0x108f2, Stride: 1}, + {Lo: 0x108f4, Hi: 0x108f5, Stride: 1}, + {Lo: 0x10900, Hi: 0x10915, Stride: 1}, + {Lo: 0x10920, Hi: 0x10939, Stride: 1}, + {Lo: 0x10980, Hi: 0x109b7, Stride: 1}, + {Lo: 0x109be, Hi: 0x109bf, Stride: 1}, + {Lo: 0x10a00, Hi: 0x10a10, Stride: 16}, + {Lo: 0x10a11, Hi: 0x10a13, Stride: 1}, + {Lo: 0x10a15, Hi: 0x10a17, Stride: 1}, + {Lo: 0x10a19, Hi: 0x10a35, Stride: 1}, + {Lo: 0x10a60, Hi: 0x10a7c, Stride: 1}, + {Lo: 0x10a80, Hi: 0x10a9c, Stride: 1}, + {Lo: 0x10ac0, Hi: 0x10ac7, Stride: 1}, + {Lo: 0x10ac9, Hi: 0x10ae4, Stride: 1}, + {Lo: 0x10b00, Hi: 0x10b35, Stride: 1}, + {Lo: 0x10b40, Hi: 0x10b55, Stride: 1}, + {Lo: 0x10b60, Hi: 0x10b72, Stride: 1}, + {Lo: 0x10b80, Hi: 0x10b91, Stride: 1}, + {Lo: 0x10c00, Hi: 0x10c48, Stride: 1}, + {Lo: 0x10c80, Hi: 0x10cb2, Stride: 1}, + {Lo: 0x10cc0, Hi: 0x10cf2, Stride: 1}, + {Lo: 0x10d00, Hi: 0x10d23, Stride: 1}, + {Lo: 0x10e80, Hi: 0x10ea9, Stride: 1}, + {Lo: 0x10eb0, Hi: 0x10eb1, Stride: 1}, + {Lo: 0x10f00, Hi: 0x10f1c, Stride: 1}, + {Lo: 0x10f27, Hi: 0x10f30, Stride: 9}, + {Lo: 0x10f31, Hi: 0x10f45, Stride: 1}, + {Lo: 0x10f70, Hi: 0x10f81, Stride: 1}, + {Lo: 0x10fb0, Hi: 0x10fc4, Stride: 1}, + {Lo: 0x10fe0, Hi: 0x10ff6, Stride: 1}, + {Lo: 0x11003, Hi: 0x11037, Stride: 1}, + {Lo: 0x11071, Hi: 0x11072, Stride: 1}, + {Lo: 0x11075, Hi: 0x11083, Stride: 14}, + {Lo: 0x11084, Hi: 0x110af, Stride: 1}, + {Lo: 0x110d0, Hi: 0x110e8, Stride: 1}, + {Lo: 0x11103, Hi: 0x11126, Stride: 1}, + {Lo: 0x11144, Hi: 0x11147, Stride: 3}, + {Lo: 0x11150, Hi: 0x11172, Stride: 1}, + {Lo: 0x11176, Hi: 0x11183, Stride: 13}, + {Lo: 0x11184, Hi: 0x111b2, Stride: 1}, + {Lo: 0x111c1, Hi: 0x111c4, Stride: 1}, + {Lo: 0x111da, Hi: 0x111dc, Stride: 2}, + {Lo: 0x11200, Hi: 0x11211, Stride: 1}, + {Lo: 0x11213, Hi: 0x1122b, Stride: 1}, + {Lo: 0x1123f, Hi: 0x11240, Stride: 1}, + {Lo: 0x11280, Hi: 0x11286, Stride: 1}, + {Lo: 0x11288, Hi: 0x1128a, Stride: 2}, + {Lo: 0x1128b, Hi: 0x1128d, Stride: 1}, + {Lo: 0x1128f, Hi: 0x1129d, Stride: 1}, + {Lo: 0x1129f, Hi: 0x112a8, Stride: 1}, + {Lo: 0x112b0, Hi: 0x112de, Stride: 1}, + {Lo: 0x11305, Hi: 0x1130c, Stride: 1}, + {Lo: 0x1130f, Hi: 0x11310, Stride: 1}, + {Lo: 0x11313, Hi: 0x11328, Stride: 1}, + {Lo: 0x1132a, Hi: 0x11330, Stride: 1}, + {Lo: 0x11332, Hi: 0x11333, Stride: 1}, + {Lo: 0x11335, Hi: 0x11339, Stride: 1}, + {Lo: 0x1133d, Hi: 0x11350, Stride: 19}, + {Lo: 0x1135d, Hi: 0x11361, Stride: 1}, + {Lo: 0x11400, Hi: 0x11434, Stride: 1}, + {Lo: 0x11447, Hi: 0x1144a, Stride: 1}, + {Lo: 0x1145f, Hi: 0x11461, Stride: 1}, + {Lo: 0x11480, Hi: 0x114af, Stride: 1}, + {Lo: 0x114c4, Hi: 0x114c5, Stride: 1}, + {Lo: 0x114c7, Hi: 0x11580, Stride: 185}, + {Lo: 0x11581, Hi: 0x115ae, Stride: 1}, + {Lo: 0x115d8, Hi: 0x115db, Stride: 1}, + {Lo: 0x11600, Hi: 0x1162f, Stride: 1}, + {Lo: 0x11644, Hi: 0x11680, Stride: 60}, + {Lo: 0x11681, Hi: 0x116aa, Stride: 1}, + {Lo: 0x116b8, Hi: 0x11800, Stride: 328}, + {Lo: 0x11801, Hi: 0x1182b, Stride: 1}, + {Lo: 0x118a0, Hi: 0x118df, Stride: 1}, + {Lo: 0x118ff, Hi: 0x11906, Stride: 1}, + {Lo: 0x11909, Hi: 0x1190c, Stride: 3}, + {Lo: 0x1190d, Hi: 0x11913, Stride: 1}, + {Lo: 0x11915, Hi: 0x11916, Stride: 1}, + {Lo: 0x11918, Hi: 0x1192f, Stride: 1}, + {Lo: 0x1193f, Hi: 0x11941, Stride: 2}, + {Lo: 0x119a0, Hi: 0x119a7, Stride: 1}, + {Lo: 0x119aa, Hi: 0x119d0, Stride: 1}, + {Lo: 0x119e1, Hi: 0x119e3, Stride: 2}, + {Lo: 0x11a00, Hi: 0x11a0b, Stride: 11}, + {Lo: 0x11a0c, Hi: 0x11a32, Stride: 1}, + {Lo: 0x11a3a, Hi: 0x11a50, Stride: 22}, + {Lo: 0x11a5c, Hi: 0x11a89, Stride: 1}, + {Lo: 0x11a9d, Hi: 0x11ab0, Stride: 19}, + {Lo: 0x11ab1, Hi: 0x11af8, Stride: 1}, + {Lo: 0x11c00, Hi: 0x11c08, Stride: 1}, + {Lo: 0x11c0a, Hi: 0x11c2e, Stride: 1}, + {Lo: 0x11c40, Hi: 0x11c72, Stride: 50}, + {Lo: 0x11c73, Hi: 0x11c8f, Stride: 1}, + {Lo: 0x11d00, Hi: 0x11d06, Stride: 1}, + {Lo: 0x11d08, Hi: 0x11d09, Stride: 1}, + {Lo: 0x11d0b, Hi: 0x11d30, Stride: 1}, + {Lo: 0x11d46, Hi: 0x11d60, Stride: 26}, + {Lo: 0x11d61, Hi: 0x11d65, Stride: 1}, + {Lo: 0x11d67, Hi: 0x11d68, Stride: 1}, + {Lo: 0x11d6a, Hi: 0x11d89, Stride: 1}, + {Lo: 0x11d98, Hi: 0x11ee0, Stride: 328}, + {Lo: 0x11ee1, Hi: 0x11ef2, Stride: 1}, + {Lo: 0x11f02, Hi: 0x11f04, Stride: 2}, + {Lo: 0x11f05, Hi: 0x11f10, Stride: 1}, + {Lo: 0x11f12, Hi: 0x11f33, Stride: 1}, + {Lo: 0x11fb0, Hi: 0x12000, Stride: 80}, + {Lo: 0x12001, Hi: 0x12399, Stride: 1}, + {Lo: 0x12400, Hi: 0x1246e, Stride: 1}, + {Lo: 0x12480, Hi: 0x12543, Stride: 1}, + {Lo: 0x12f90, Hi: 0x12ff0, Stride: 1}, + {Lo: 0x13000, Hi: 0x1342f, Stride: 1}, + {Lo: 0x13441, Hi: 0x13446, Stride: 1}, + {Lo: 0x14400, Hi: 0x14646, Stride: 1}, + {Lo: 0x16800, Hi: 0x16a38, Stride: 1}, + {Lo: 0x16a40, Hi: 0x16a5e, Stride: 1}, + {Lo: 0x16a70, Hi: 0x16abe, Stride: 1}, + {Lo: 0x16ad0, Hi: 0x16aed, Stride: 1}, + {Lo: 0x16b00, Hi: 0x16b2f, Stride: 1}, + {Lo: 0x16b40, Hi: 0x16b43, Stride: 1}, + {Lo: 0x16b63, Hi: 0x16b77, Stride: 1}, + {Lo: 0x16b7d, Hi: 0x16b8f, Stride: 1}, + {Lo: 0x16e40, Hi: 0x16e7f, Stride: 1}, + {Lo: 0x16f00, Hi: 0x16f4a, Stride: 1}, + {Lo: 0x16f50, Hi: 0x16f93, Stride: 67}, + {Lo: 0x16f94, Hi: 0x16f9f, Stride: 1}, + {Lo: 0x16fe0, Hi: 0x16fe1, Stride: 1}, + {Lo: 0x16fe3, Hi: 0x1bc00, Stride: 19485}, + {Lo: 0x1bc01, Hi: 0x1bc6a, Stride: 1}, + {Lo: 0x1bc70, Hi: 0x1bc7c, Stride: 1}, + {Lo: 0x1bc80, Hi: 0x1bc88, Stride: 1}, + {Lo: 0x1bc90, Hi: 0x1bc99, Stride: 1}, + {Lo: 0x1d400, Hi: 0x1d454, Stride: 1}, + {Lo: 0x1d456, Hi: 0x1d49c, Stride: 1}, + {Lo: 0x1d49e, Hi: 0x1d49f, Stride: 1}, + {Lo: 0x1d4a2, Hi: 0x1d4a5, Stride: 3}, + {Lo: 0x1d4a6, Hi: 0x1d4a9, Stride: 3}, + {Lo: 0x1d4aa, Hi: 0x1d4ac, Stride: 1}, + {Lo: 0x1d4ae, Hi: 0x1d4b9, Stride: 1}, + {Lo: 0x1d4bb, Hi: 0x1d4bd, Stride: 2}, + {Lo: 0x1d4be, Hi: 0x1d4c3, Stride: 1}, + {Lo: 0x1d4c5, Hi: 0x1d505, Stride: 1}, + {Lo: 0x1d507, Hi: 0x1d50a, Stride: 1}, + {Lo: 0x1d50d, Hi: 0x1d514, Stride: 1}, + {Lo: 0x1d516, Hi: 0x1d51c, Stride: 1}, + {Lo: 0x1d51e, Hi: 0x1d539, Stride: 1}, + {Lo: 0x1d53b, Hi: 0x1d53e, Stride: 1}, + {Lo: 0x1d540, Hi: 0x1d544, Stride: 1}, + {Lo: 0x1d546, Hi: 0x1d54a, Stride: 4}, + {Lo: 0x1d54b, Hi: 0x1d550, Stride: 1}, + {Lo: 0x1d552, Hi: 0x1d6a5, Stride: 1}, + {Lo: 0x1d6a8, Hi: 0x1d6c0, Stride: 1}, + {Lo: 0x1d6c2, Hi: 0x1d6da, Stride: 1}, + {Lo: 0x1d6dc, Hi: 0x1d6fa, Stride: 1}, + {Lo: 0x1d6fc, Hi: 0x1d714, Stride: 1}, + {Lo: 0x1d716, Hi: 0x1d734, Stride: 1}, + {Lo: 0x1d736, Hi: 0x1d74e, Stride: 1}, + {Lo: 0x1d750, Hi: 0x1d76e, Stride: 1}, + {Lo: 0x1d770, Hi: 0x1d788, Stride: 1}, + {Lo: 0x1d78a, Hi: 0x1d7a8, Stride: 1}, + {Lo: 0x1d7aa, Hi: 0x1d7c2, Stride: 1}, + {Lo: 0x1d7c4, Hi: 0x1d7cb, Stride: 1}, + {Lo: 0x1df00, Hi: 0x1df1e, Stride: 1}, + {Lo: 0x1df25, Hi: 0x1df2a, Stride: 1}, + {Lo: 0x1e030, Hi: 0x1e06d, Stride: 1}, + {Lo: 0x1e100, Hi: 0x1e12c, Stride: 1}, + {Lo: 0x1e137, Hi: 0x1e13d, Stride: 1}, + {Lo: 0x1e14e, Hi: 0x1e290, Stride: 322}, + {Lo: 0x1e291, Hi: 0x1e2ad, Stride: 1}, + {Lo: 0x1e2c0, Hi: 0x1e2eb, Stride: 1}, + {Lo: 0x1e4d0, Hi: 0x1e4eb, Stride: 1}, + {Lo: 0x1e7e0, Hi: 0x1e7e6, Stride: 1}, + {Lo: 0x1e7e8, Hi: 0x1e7eb, Stride: 1}, + {Lo: 0x1e7ed, Hi: 0x1e7ee, Stride: 1}, + {Lo: 0x1e7f0, Hi: 0x1e7fe, Stride: 1}, + {Lo: 0x1e800, Hi: 0x1e8c4, Stride: 1}, + {Lo: 0x1e900, Hi: 0x1e943, Stride: 1}, + {Lo: 0x1e94b, Hi: 0x1ee00, Stride: 1205}, + {Lo: 0x1ee01, Hi: 0x1ee03, Stride: 1}, + {Lo: 0x1ee05, Hi: 0x1ee1f, Stride: 1}, + {Lo: 0x1ee21, Hi: 0x1ee22, Stride: 1}, + {Lo: 0x1ee24, Hi: 0x1ee27, Stride: 3}, + {Lo: 0x1ee29, Hi: 0x1ee32, Stride: 1}, + {Lo: 0x1ee34, Hi: 0x1ee37, Stride: 1}, + {Lo: 0x1ee39, Hi: 0x1ee3b, Stride: 2}, + {Lo: 0x1ee42, Hi: 0x1ee47, Stride: 5}, + {Lo: 0x1ee49, Hi: 0x1ee4d, Stride: 2}, + {Lo: 0x1ee4e, Hi: 0x1ee4f, Stride: 1}, + {Lo: 0x1ee51, Hi: 0x1ee52, Stride: 1}, + {Lo: 0x1ee54, Hi: 0x1ee57, Stride: 3}, + {Lo: 0x1ee59, Hi: 0x1ee61, Stride: 2}, + {Lo: 0x1ee62, Hi: 0x1ee64, Stride: 2}, + {Lo: 0x1ee67, Hi: 0x1ee6a, Stride: 1}, + {Lo: 0x1ee6c, Hi: 0x1ee72, Stride: 1}, + {Lo: 0x1ee74, Hi: 0x1ee77, Stride: 1}, + {Lo: 0x1ee79, Hi: 0x1ee7c, Stride: 1}, + {Lo: 0x1ee7e, Hi: 0x1ee80, Stride: 2}, + {Lo: 0x1ee81, Hi: 0x1ee89, Stride: 1}, + {Lo: 0x1ee8b, Hi: 0x1ee9b, Stride: 1}, + {Lo: 0x1eea1, Hi: 0x1eea3, Stride: 1}, + {Lo: 0x1eea5, Hi: 0x1eea9, Stride: 1}, + {Lo: 0x1eeab, Hi: 0x1eebb, Stride: 1}, + {Lo: 0x1f130, Hi: 0x1f149, Stride: 1}, + {Lo: 0x1f150, Hi: 0x1f169, Stride: 1}, + {Lo: 0x1f170, Hi: 0x1f189, Stride: 1}, + }, + LatinOffset: 6, +} + +// WordBreakProperty: Double_Quote +var WordBreakDouble_Quote = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0022, Hi: 0x0022, Stride: 1}, + }, + LatinOffset: 1, +} + +// WordBreakProperty: ExtendFormat +var WordBreakExtendFormat = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x00ad, Hi: 0x0300, Stride: 595}, + {Lo: 0x0301, Hi: 0x036f, Stride: 1}, + {Lo: 0x0483, Hi: 0x0489, Stride: 1}, + {Lo: 0x0591, Hi: 0x05bd, Stride: 1}, + {Lo: 0x05bf, Hi: 0x05c1, Stride: 2}, + {Lo: 0x05c2, Hi: 0x05c4, Stride: 2}, + {Lo: 0x05c5, Hi: 0x05c7, Stride: 2}, + {Lo: 0x0610, Hi: 0x061a, Stride: 1}, + {Lo: 0x061c, Hi: 0x064b, Stride: 47}, + {Lo: 0x064c, Hi: 0x065f, Stride: 1}, + {Lo: 0x0670, Hi: 0x06d6, Stride: 102}, + {Lo: 0x06d7, Hi: 0x06dc, Stride: 1}, + {Lo: 0x06df, Hi: 0x06e4, Stride: 1}, + {Lo: 0x06e7, Hi: 0x06e8, Stride: 1}, + {Lo: 0x06ea, Hi: 0x06ed, Stride: 1}, + {Lo: 0x0711, Hi: 0x0730, Stride: 31}, + {Lo: 0x0731, Hi: 0x074a, Stride: 1}, + {Lo: 0x07a6, Hi: 0x07b0, Stride: 1}, + {Lo: 0x07eb, Hi: 0x07f3, Stride: 1}, + {Lo: 0x07fd, Hi: 0x0816, Stride: 25}, + {Lo: 0x0817, Hi: 0x0819, Stride: 1}, + {Lo: 0x081b, Hi: 0x0823, Stride: 1}, + {Lo: 0x0825, Hi: 0x0827, Stride: 1}, + {Lo: 0x0829, Hi: 0x082d, Stride: 1}, + {Lo: 0x0859, Hi: 0x085b, Stride: 1}, + {Lo: 0x0898, Hi: 0x089f, Stride: 1}, + {Lo: 0x08ca, Hi: 0x08e1, Stride: 1}, + {Lo: 0x08e3, Hi: 0x0903, Stride: 1}, + {Lo: 0x093a, Hi: 0x093c, Stride: 1}, + {Lo: 0x093e, Hi: 0x094f, Stride: 1}, + {Lo: 0x0951, Hi: 0x0957, Stride: 1}, + {Lo: 0x0962, Hi: 0x0963, Stride: 1}, + {Lo: 0x0981, Hi: 0x0983, Stride: 1}, + {Lo: 0x09bc, Hi: 0x09be, Stride: 2}, + {Lo: 0x09bf, Hi: 0x09c4, Stride: 1}, + {Lo: 0x09c7, Hi: 0x09c8, Stride: 1}, + {Lo: 0x09cb, Hi: 0x09cd, Stride: 1}, + {Lo: 0x09d7, Hi: 0x09e2, Stride: 11}, + {Lo: 0x09e3, Hi: 0x09fe, Stride: 27}, + {Lo: 0x0a01, Hi: 0x0a03, Stride: 1}, + {Lo: 0x0a3c, Hi: 0x0a3e, Stride: 2}, + {Lo: 0x0a3f, Hi: 0x0a42, Stride: 1}, + {Lo: 0x0a47, Hi: 0x0a48, Stride: 1}, + {Lo: 0x0a4b, Hi: 0x0a4d, Stride: 1}, + {Lo: 0x0a51, Hi: 0x0a70, Stride: 31}, + {Lo: 0x0a71, Hi: 0x0a75, Stride: 4}, + {Lo: 0x0a81, Hi: 0x0a83, Stride: 1}, + {Lo: 0x0abc, Hi: 0x0abe, Stride: 2}, + {Lo: 0x0abf, Hi: 0x0ac5, Stride: 1}, + {Lo: 0x0ac7, Hi: 0x0ac9, Stride: 1}, + {Lo: 0x0acb, Hi: 0x0acd, Stride: 1}, + {Lo: 0x0ae2, Hi: 0x0ae3, Stride: 1}, + {Lo: 0x0afa, Hi: 0x0aff, Stride: 1}, + {Lo: 0x0b01, Hi: 0x0b03, Stride: 1}, + {Lo: 0x0b3c, Hi: 0x0b3e, Stride: 2}, + {Lo: 0x0b3f, Hi: 0x0b44, Stride: 1}, + {Lo: 0x0b47, Hi: 0x0b48, Stride: 1}, + {Lo: 0x0b4b, Hi: 0x0b4d, Stride: 1}, + {Lo: 0x0b55, Hi: 0x0b57, Stride: 1}, + {Lo: 0x0b62, Hi: 0x0b63, Stride: 1}, + {Lo: 0x0b82, Hi: 0x0bbe, Stride: 60}, + {Lo: 0x0bbf, Hi: 0x0bc2, Stride: 1}, + {Lo: 0x0bc6, Hi: 0x0bc8, Stride: 1}, + {Lo: 0x0bca, Hi: 0x0bcd, Stride: 1}, + {Lo: 0x0bd7, Hi: 0x0c00, Stride: 41}, + {Lo: 0x0c01, Hi: 0x0c04, Stride: 1}, + {Lo: 0x0c3c, Hi: 0x0c3e, Stride: 2}, + {Lo: 0x0c3f, Hi: 0x0c44, Stride: 1}, + {Lo: 0x0c46, Hi: 0x0c48, Stride: 1}, + {Lo: 0x0c4a, Hi: 0x0c4d, Stride: 1}, + {Lo: 0x0c55, Hi: 0x0c56, Stride: 1}, + {Lo: 0x0c62, Hi: 0x0c63, Stride: 1}, + {Lo: 0x0c81, Hi: 0x0c83, Stride: 1}, + {Lo: 0x0cbc, Hi: 0x0cbe, Stride: 2}, + {Lo: 0x0cbf, Hi: 0x0cc4, Stride: 1}, + {Lo: 0x0cc6, Hi: 0x0cc8, Stride: 1}, + {Lo: 0x0cca, Hi: 0x0ccd, Stride: 1}, + {Lo: 0x0cd5, Hi: 0x0cd6, Stride: 1}, + {Lo: 0x0ce2, Hi: 0x0ce3, Stride: 1}, + {Lo: 0x0cf3, Hi: 0x0d00, Stride: 13}, + {Lo: 0x0d01, Hi: 0x0d03, Stride: 1}, + {Lo: 0x0d3b, Hi: 0x0d3c, Stride: 1}, + {Lo: 0x0d3e, Hi: 0x0d44, Stride: 1}, + {Lo: 0x0d46, Hi: 0x0d48, Stride: 1}, + {Lo: 0x0d4a, Hi: 0x0d4d, Stride: 1}, + {Lo: 0x0d57, Hi: 0x0d62, Stride: 11}, + {Lo: 0x0d63, Hi: 0x0d81, Stride: 30}, + {Lo: 0x0d82, Hi: 0x0d83, Stride: 1}, + {Lo: 0x0dca, Hi: 0x0dcf, Stride: 5}, + {Lo: 0x0dd0, Hi: 0x0dd4, Stride: 1}, + {Lo: 0x0dd6, Hi: 0x0dd8, Stride: 2}, + {Lo: 0x0dd9, Hi: 0x0ddf, Stride: 1}, + {Lo: 0x0df2, Hi: 0x0df3, Stride: 1}, + {Lo: 0x0e31, Hi: 0x0e34, Stride: 3}, + {Lo: 0x0e35, Hi: 0x0e3a, Stride: 1}, + {Lo: 0x0e47, Hi: 0x0e4e, Stride: 1}, + {Lo: 0x0eb1, Hi: 0x0eb4, Stride: 3}, + {Lo: 0x0eb5, Hi: 0x0ebc, Stride: 1}, + {Lo: 0x0ec8, Hi: 0x0ece, Stride: 1}, + {Lo: 0x0f18, Hi: 0x0f19, Stride: 1}, + {Lo: 0x0f35, Hi: 0x0f39, Stride: 2}, + {Lo: 0x0f3e, Hi: 0x0f3f, Stride: 1}, + {Lo: 0x0f71, Hi: 0x0f84, Stride: 1}, + {Lo: 0x0f86, Hi: 0x0f87, Stride: 1}, + {Lo: 0x0f8d, Hi: 0x0f97, Stride: 1}, + {Lo: 0x0f99, Hi: 0x0fbc, Stride: 1}, + {Lo: 0x0fc6, Hi: 0x102b, Stride: 101}, + {Lo: 0x102c, Hi: 0x103e, Stride: 1}, + {Lo: 0x1056, Hi: 0x1059, Stride: 1}, + {Lo: 0x105e, Hi: 0x1060, Stride: 1}, + {Lo: 0x1062, Hi: 0x1064, Stride: 1}, + {Lo: 0x1067, Hi: 0x106d, Stride: 1}, + {Lo: 0x1071, Hi: 0x1074, Stride: 1}, + {Lo: 0x1082, Hi: 0x108d, Stride: 1}, + {Lo: 0x108f, Hi: 0x109a, Stride: 11}, + {Lo: 0x109b, Hi: 0x109d, Stride: 1}, + {Lo: 0x135d, Hi: 0x135f, Stride: 1}, + {Lo: 0x1712, Hi: 0x1715, Stride: 1}, + {Lo: 0x1732, Hi: 0x1734, Stride: 1}, + {Lo: 0x1752, Hi: 0x1753, Stride: 1}, + {Lo: 0x1772, Hi: 0x1773, Stride: 1}, + {Lo: 0x17b4, Hi: 0x17d3, Stride: 1}, + {Lo: 0x17dd, Hi: 0x180b, Stride: 46}, + {Lo: 0x180c, Hi: 0x180f, Stride: 1}, + {Lo: 0x1885, Hi: 0x1886, Stride: 1}, + {Lo: 0x18a9, Hi: 0x1920, Stride: 119}, + {Lo: 0x1921, Hi: 0x192b, Stride: 1}, + {Lo: 0x1930, Hi: 0x193b, Stride: 1}, + {Lo: 0x1a17, Hi: 0x1a1b, Stride: 1}, + {Lo: 0x1a55, Hi: 0x1a5e, Stride: 1}, + {Lo: 0x1a60, Hi: 0x1a7c, Stride: 1}, + {Lo: 0x1a7f, Hi: 0x1ab0, Stride: 49}, + {Lo: 0x1ab1, Hi: 0x1ace, Stride: 1}, + {Lo: 0x1b00, Hi: 0x1b04, Stride: 1}, + {Lo: 0x1b34, Hi: 0x1b44, Stride: 1}, + {Lo: 0x1b6b, Hi: 0x1b73, Stride: 1}, + {Lo: 0x1b80, Hi: 0x1b82, Stride: 1}, + {Lo: 0x1ba1, Hi: 0x1bad, Stride: 1}, + {Lo: 0x1be6, Hi: 0x1bf3, Stride: 1}, + {Lo: 0x1c24, Hi: 0x1c37, Stride: 1}, + {Lo: 0x1cd0, Hi: 0x1cd2, Stride: 1}, + {Lo: 0x1cd4, Hi: 0x1ce8, Stride: 1}, + {Lo: 0x1ced, Hi: 0x1cf4, Stride: 7}, + {Lo: 0x1cf7, Hi: 0x1cf9, Stride: 1}, + {Lo: 0x1dc0, Hi: 0x1dff, Stride: 1}, + {Lo: 0x200c, Hi: 0x200f, Stride: 1}, + {Lo: 0x202a, Hi: 0x202e, Stride: 1}, + {Lo: 0x2060, Hi: 0x2064, Stride: 1}, + {Lo: 0x2066, Hi: 0x206f, Stride: 1}, + {Lo: 0x20d0, Hi: 0x20f0, Stride: 1}, + {Lo: 0x2cef, Hi: 0x2cf1, Stride: 1}, + {Lo: 0x2d7f, Hi: 0x2de0, Stride: 97}, + {Lo: 0x2de1, Hi: 0x2dff, Stride: 1}, + {Lo: 0x302a, Hi: 0x302f, Stride: 1}, + {Lo: 0x3099, Hi: 0x309a, Stride: 1}, + {Lo: 0xa66f, Hi: 0xa672, Stride: 1}, + {Lo: 0xa674, Hi: 0xa67d, Stride: 1}, + {Lo: 0xa69e, Hi: 0xa69f, Stride: 1}, + {Lo: 0xa6f0, Hi: 0xa6f1, Stride: 1}, + {Lo: 0xa802, Hi: 0xa806, Stride: 4}, + {Lo: 0xa80b, Hi: 0xa823, Stride: 24}, + {Lo: 0xa824, Hi: 0xa827, Stride: 1}, + {Lo: 0xa82c, Hi: 0xa880, Stride: 84}, + {Lo: 0xa881, Hi: 0xa8b4, Stride: 51}, + {Lo: 0xa8b5, Hi: 0xa8c5, Stride: 1}, + {Lo: 0xa8e0, Hi: 0xa8f1, Stride: 1}, + {Lo: 0xa8ff, Hi: 0xa926, Stride: 39}, + {Lo: 0xa927, Hi: 0xa92d, Stride: 1}, + {Lo: 0xa947, Hi: 0xa953, Stride: 1}, + {Lo: 0xa980, Hi: 0xa983, Stride: 1}, + {Lo: 0xa9b3, Hi: 0xa9c0, Stride: 1}, + {Lo: 0xa9e5, Hi: 0xaa29, Stride: 68}, + {Lo: 0xaa2a, Hi: 0xaa36, Stride: 1}, + {Lo: 0xaa43, Hi: 0xaa4c, Stride: 9}, + {Lo: 0xaa4d, Hi: 0xaa7b, Stride: 46}, + {Lo: 0xaa7c, Hi: 0xaa7d, Stride: 1}, + {Lo: 0xaab0, Hi: 0xaab2, Stride: 2}, + {Lo: 0xaab3, Hi: 0xaab4, Stride: 1}, + {Lo: 0xaab7, Hi: 0xaab8, Stride: 1}, + {Lo: 0xaabe, Hi: 0xaabf, Stride: 1}, + {Lo: 0xaac1, Hi: 0xaaeb, Stride: 42}, + {Lo: 0xaaec, Hi: 0xaaef, Stride: 1}, + {Lo: 0xaaf5, Hi: 0xaaf6, Stride: 1}, + {Lo: 0xabe3, Hi: 0xabea, Stride: 1}, + {Lo: 0xabec, Hi: 0xabed, Stride: 1}, + {Lo: 0xfb1e, Hi: 0xfe00, Stride: 738}, + {Lo: 0xfe01, Hi: 0xfe0f, Stride: 1}, + {Lo: 0xfe20, Hi: 0xfe2f, Stride: 1}, + {Lo: 0xfeff, Hi: 0xff9e, Stride: 159}, + {Lo: 0xff9f, Hi: 0xfff9, Stride: 90}, + {Lo: 0xfffa, Hi: 0xfffb, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x101fd, Hi: 0x102e0, Stride: 227}, + {Lo: 0x10376, Hi: 0x1037a, Stride: 1}, + {Lo: 0x10a01, Hi: 0x10a03, Stride: 1}, + {Lo: 0x10a05, Hi: 0x10a06, Stride: 1}, + {Lo: 0x10a0c, Hi: 0x10a0f, Stride: 1}, + {Lo: 0x10a38, Hi: 0x10a3a, Stride: 1}, + {Lo: 0x10a3f, Hi: 0x10ae5, Stride: 166}, + {Lo: 0x10ae6, Hi: 0x10d24, Stride: 574}, + {Lo: 0x10d25, Hi: 0x10d27, Stride: 1}, + {Lo: 0x10eab, Hi: 0x10eac, Stride: 1}, + {Lo: 0x10efd, Hi: 0x10eff, Stride: 1}, + {Lo: 0x10f46, Hi: 0x10f50, Stride: 1}, + {Lo: 0x10f82, Hi: 0x10f85, Stride: 1}, + {Lo: 0x11000, Hi: 0x11002, Stride: 1}, + {Lo: 0x11038, Hi: 0x11046, Stride: 1}, + {Lo: 0x11070, Hi: 0x11073, Stride: 3}, + {Lo: 0x11074, Hi: 0x1107f, Stride: 11}, + {Lo: 0x11080, Hi: 0x11082, Stride: 1}, + {Lo: 0x110b0, Hi: 0x110ba, Stride: 1}, + {Lo: 0x110c2, Hi: 0x11100, Stride: 62}, + {Lo: 0x11101, Hi: 0x11102, Stride: 1}, + {Lo: 0x11127, Hi: 0x11134, Stride: 1}, + {Lo: 0x11145, Hi: 0x11146, Stride: 1}, + {Lo: 0x11173, Hi: 0x11180, Stride: 13}, + {Lo: 0x11181, Hi: 0x11182, Stride: 1}, + {Lo: 0x111b3, Hi: 0x111c0, Stride: 1}, + {Lo: 0x111c9, Hi: 0x111cc, Stride: 1}, + {Lo: 0x111ce, Hi: 0x111cf, Stride: 1}, + {Lo: 0x1122c, Hi: 0x11237, Stride: 1}, + {Lo: 0x1123e, Hi: 0x11241, Stride: 3}, + {Lo: 0x112df, Hi: 0x112ea, Stride: 1}, + {Lo: 0x11300, Hi: 0x11303, Stride: 1}, + {Lo: 0x1133b, Hi: 0x1133c, Stride: 1}, + {Lo: 0x1133e, Hi: 0x11344, Stride: 1}, + {Lo: 0x11347, Hi: 0x11348, Stride: 1}, + {Lo: 0x1134b, Hi: 0x1134d, Stride: 1}, + {Lo: 0x11357, Hi: 0x11362, Stride: 11}, + {Lo: 0x11363, Hi: 0x11366, Stride: 3}, + {Lo: 0x11367, Hi: 0x1136c, Stride: 1}, + {Lo: 0x11370, Hi: 0x11374, Stride: 1}, + {Lo: 0x11435, Hi: 0x11446, Stride: 1}, + {Lo: 0x1145e, Hi: 0x114b0, Stride: 82}, + {Lo: 0x114b1, Hi: 0x114c3, Stride: 1}, + {Lo: 0x115af, Hi: 0x115b5, Stride: 1}, + {Lo: 0x115b8, Hi: 0x115c0, Stride: 1}, + {Lo: 0x115dc, Hi: 0x115dd, Stride: 1}, + {Lo: 0x11630, Hi: 0x11640, Stride: 1}, + {Lo: 0x116ab, Hi: 0x116b7, Stride: 1}, + {Lo: 0x1171d, Hi: 0x1172b, Stride: 1}, + {Lo: 0x1182c, Hi: 0x1183a, Stride: 1}, + {Lo: 0x11930, Hi: 0x11935, Stride: 1}, + {Lo: 0x11937, Hi: 0x11938, Stride: 1}, + {Lo: 0x1193b, Hi: 0x1193e, Stride: 1}, + {Lo: 0x11940, Hi: 0x11942, Stride: 2}, + {Lo: 0x11943, Hi: 0x119d1, Stride: 142}, + {Lo: 0x119d2, Hi: 0x119d7, Stride: 1}, + {Lo: 0x119da, Hi: 0x119e0, Stride: 1}, + {Lo: 0x119e4, Hi: 0x11a01, Stride: 29}, + {Lo: 0x11a02, Hi: 0x11a0a, Stride: 1}, + {Lo: 0x11a33, Hi: 0x11a39, Stride: 1}, + {Lo: 0x11a3b, Hi: 0x11a3e, Stride: 1}, + {Lo: 0x11a47, Hi: 0x11a51, Stride: 10}, + {Lo: 0x11a52, Hi: 0x11a5b, Stride: 1}, + {Lo: 0x11a8a, Hi: 0x11a99, Stride: 1}, + {Lo: 0x11c2f, Hi: 0x11c36, Stride: 1}, + {Lo: 0x11c38, Hi: 0x11c3f, Stride: 1}, + {Lo: 0x11c92, Hi: 0x11ca7, Stride: 1}, + {Lo: 0x11ca9, Hi: 0x11cb6, Stride: 1}, + {Lo: 0x11d31, Hi: 0x11d36, Stride: 1}, + {Lo: 0x11d3a, Hi: 0x11d3c, Stride: 2}, + {Lo: 0x11d3d, Hi: 0x11d3f, Stride: 2}, + {Lo: 0x11d40, Hi: 0x11d45, Stride: 1}, + {Lo: 0x11d47, Hi: 0x11d8a, Stride: 67}, + {Lo: 0x11d8b, Hi: 0x11d8e, Stride: 1}, + {Lo: 0x11d90, Hi: 0x11d91, Stride: 1}, + {Lo: 0x11d93, Hi: 0x11d97, Stride: 1}, + {Lo: 0x11ef3, Hi: 0x11ef6, Stride: 1}, + {Lo: 0x11f00, Hi: 0x11f01, Stride: 1}, + {Lo: 0x11f03, Hi: 0x11f34, Stride: 49}, + {Lo: 0x11f35, Hi: 0x11f3a, Stride: 1}, + {Lo: 0x11f3e, Hi: 0x11f42, Stride: 1}, + {Lo: 0x13430, Hi: 0x13440, Stride: 1}, + {Lo: 0x13447, Hi: 0x13455, Stride: 1}, + {Lo: 0x16af0, Hi: 0x16af4, Stride: 1}, + {Lo: 0x16b30, Hi: 0x16b36, Stride: 1}, + {Lo: 0x16f4f, Hi: 0x16f51, Stride: 2}, + {Lo: 0x16f52, Hi: 0x16f87, Stride: 1}, + {Lo: 0x16f8f, Hi: 0x16f92, Stride: 1}, + {Lo: 0x16fe4, Hi: 0x16ff0, Stride: 12}, + {Lo: 0x16ff1, Hi: 0x1bc9d, Stride: 19628}, + {Lo: 0x1bc9e, Hi: 0x1bca0, Stride: 2}, + {Lo: 0x1bca1, Hi: 0x1bca3, Stride: 1}, + {Lo: 0x1cf00, Hi: 0x1cf2d, Stride: 1}, + {Lo: 0x1cf30, Hi: 0x1cf46, Stride: 1}, + {Lo: 0x1d165, Hi: 0x1d169, Stride: 1}, + {Lo: 0x1d16d, Hi: 0x1d182, Stride: 1}, + {Lo: 0x1d185, Hi: 0x1d18b, Stride: 1}, + {Lo: 0x1d1aa, Hi: 0x1d1ad, Stride: 1}, + {Lo: 0x1d242, Hi: 0x1d244, Stride: 1}, + {Lo: 0x1da00, Hi: 0x1da36, Stride: 1}, + {Lo: 0x1da3b, Hi: 0x1da6c, Stride: 1}, + {Lo: 0x1da75, Hi: 0x1da84, Stride: 15}, + {Lo: 0x1da9b, Hi: 0x1da9f, Stride: 1}, + {Lo: 0x1daa1, Hi: 0x1daaf, Stride: 1}, + {Lo: 0x1e000, Hi: 0x1e006, Stride: 1}, + {Lo: 0x1e008, Hi: 0x1e018, Stride: 1}, + {Lo: 0x1e01b, Hi: 0x1e021, Stride: 1}, + {Lo: 0x1e023, Hi: 0x1e024, Stride: 1}, + {Lo: 0x1e026, Hi: 0x1e02a, Stride: 1}, + {Lo: 0x1e08f, Hi: 0x1e130, Stride: 161}, + {Lo: 0x1e131, Hi: 0x1e136, Stride: 1}, + {Lo: 0x1e2ae, Hi: 0x1e2ec, Stride: 62}, + {Lo: 0x1e2ed, Hi: 0x1e2ef, Stride: 1}, + {Lo: 0x1e4ec, Hi: 0x1e4ef, Stride: 1}, + {Lo: 0x1e8d0, Hi: 0x1e8d6, Stride: 1}, + {Lo: 0x1e944, Hi: 0x1e94a, Stride: 1}, + {Lo: 0x1f3fb, Hi: 0x1f3ff, Stride: 1}, + {Lo: 0xe0001, Hi: 0xe0020, Stride: 31}, + {Lo: 0xe0021, Hi: 0xe007f, Stride: 1}, + {Lo: 0xe0100, Hi: 0xe01ef, Stride: 1}, + }, +} + +// WordBreakProperty: ExtendNumLet +var WordBreakExtendNumLet = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x005f, Hi: 0x202f, Stride: 8144}, + {Lo: 0x203f, Hi: 0x2040, Stride: 1}, + {Lo: 0x2054, Hi: 0xfe33, Stride: 56799}, + {Lo: 0xfe34, Hi: 0xfe4d, Stride: 25}, + {Lo: 0xfe4e, Hi: 0xfe4f, Stride: 1}, + {Lo: 0xff3f, Hi: 0xff3f, Stride: 1}, + }, +} + +// WordBreakProperty: Hebrew_Letter +var WordBreakHebrew_Letter = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x05d0, Hi: 0x05ea, Stride: 1}, + {Lo: 0x05ef, Hi: 0x05f2, Stride: 1}, + {Lo: 0xfb1d, Hi: 0xfb1f, Stride: 2}, + {Lo: 0xfb20, Hi: 0xfb28, Stride: 1}, + {Lo: 0xfb2a, Hi: 0xfb36, Stride: 1}, + {Lo: 0xfb38, Hi: 0xfb3c, Stride: 1}, + {Lo: 0xfb3e, Hi: 0xfb40, Stride: 2}, + {Lo: 0xfb41, Hi: 0xfb43, Stride: 2}, + {Lo: 0xfb44, Hi: 0xfb46, Stride: 2}, + {Lo: 0xfb47, Hi: 0xfb4f, Stride: 1}, + }, +} + +// WordBreakProperty: Katakana +var WordBreakKatakana = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x3031, Hi: 0x3035, Stride: 1}, + {Lo: 0x309b, Hi: 0x309c, Stride: 1}, + {Lo: 0x30a0, Hi: 0x30fa, Stride: 1}, + {Lo: 0x30fc, Hi: 0x30ff, Stride: 1}, + {Lo: 0x31f0, Hi: 0x31ff, Stride: 1}, + {Lo: 0x32d0, Hi: 0x32fe, Stride: 1}, + {Lo: 0x3300, Hi: 0x3357, Stride: 1}, + {Lo: 0xff66, Hi: 0xff9d, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x1aff0, Hi: 0x1aff3, Stride: 1}, + {Lo: 0x1aff5, Hi: 0x1affb, Stride: 1}, + {Lo: 0x1affd, Hi: 0x1affe, Stride: 1}, + {Lo: 0x1b000, Hi: 0x1b120, Stride: 288}, + {Lo: 0x1b121, Hi: 0x1b122, Stride: 1}, + {Lo: 0x1b155, Hi: 0x1b164, Stride: 15}, + {Lo: 0x1b165, Hi: 0x1b167, Stride: 1}, + }, +} + +// WordBreakProperty: MidLetter +var WordBreakMidLetter = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x003a, Hi: 0x00b7, Stride: 125}, + {Lo: 0x0387, Hi: 0x055f, Stride: 472}, + {Lo: 0x05f4, Hi: 0x2027, Stride: 6707}, + {Lo: 0xfe13, Hi: 0xfe55, Stride: 66}, + {Lo: 0xff1a, Hi: 0xff1a, Stride: 1}, + }, + LatinOffset: 1, +} + +// WordBreakProperty: MidNum +var WordBreakMidNum = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x002c, Hi: 0x003b, Stride: 15}, + {Lo: 0x037e, Hi: 0x0589, Stride: 523}, + {Lo: 0x060c, Hi: 0x060d, Stride: 1}, + {Lo: 0x066c, Hi: 0x07f8, Stride: 396}, + {Lo: 0x2044, Hi: 0xfe10, Stride: 56780}, + {Lo: 0xfe14, Hi: 0xfe50, Stride: 60}, + {Lo: 0xfe54, Hi: 0xff0c, Stride: 184}, + {Lo: 0xff1b, Hi: 0xff1b, Stride: 1}, + }, + LatinOffset: 1, +} + +// WordBreakProperty: MidNumLet +var WordBreakMidNumLet = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x002e, Hi: 0x2018, Stride: 8170}, + {Lo: 0x2019, Hi: 0x2024, Stride: 11}, + {Lo: 0xfe52, Hi: 0xff07, Stride: 181}, + {Lo: 0xff0e, Hi: 0xff0e, Stride: 1}, + }, +} + +// WordBreakProperty: NewlineCRLF +var WordBreakNewlineCRLF = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x000a, Hi: 0x000d, Stride: 1}, + {Lo: 0x0085, Hi: 0x2028, Stride: 8099}, + {Lo: 0x2029, Hi: 0x2029, Stride: 1}, + }, + LatinOffset: 1, +} + +// WordBreakProperty: Numeric +var WordBreakNumeric = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0030, Hi: 0x0039, Stride: 1}, + {Lo: 0x0600, Hi: 0x0605, Stride: 1}, + {Lo: 0x0660, Hi: 0x0669, Stride: 1}, + {Lo: 0x066b, Hi: 0x06dd, Stride: 114}, + {Lo: 0x06f0, Hi: 0x06f9, Stride: 1}, + {Lo: 0x07c0, Hi: 0x07c9, Stride: 1}, + {Lo: 0x0890, Hi: 0x0891, Stride: 1}, + {Lo: 0x08e2, Hi: 0x0966, Stride: 132}, + {Lo: 0x0967, Hi: 0x096f, Stride: 1}, + {Lo: 0x09e6, Hi: 0x09ef, Stride: 1}, + {Lo: 0x0a66, Hi: 0x0a6f, Stride: 1}, + {Lo: 0x0ae6, Hi: 0x0aef, Stride: 1}, + {Lo: 0x0b66, Hi: 0x0b6f, Stride: 1}, + {Lo: 0x0be6, Hi: 0x0bef, Stride: 1}, + {Lo: 0x0c66, Hi: 0x0c6f, Stride: 1}, + {Lo: 0x0ce6, Hi: 0x0cef, Stride: 1}, + {Lo: 0x0d66, Hi: 0x0d6f, Stride: 1}, + {Lo: 0x0de6, Hi: 0x0def, Stride: 1}, + {Lo: 0x0e50, Hi: 0x0e59, Stride: 1}, + {Lo: 0x0ed0, Hi: 0x0ed9, Stride: 1}, + {Lo: 0x0f20, Hi: 0x0f29, Stride: 1}, + {Lo: 0x1040, Hi: 0x1049, Stride: 1}, + {Lo: 0x1090, Hi: 0x1099, Stride: 1}, + {Lo: 0x17e0, Hi: 0x17e9, Stride: 1}, + {Lo: 0x1810, Hi: 0x1819, Stride: 1}, + {Lo: 0x1946, Hi: 0x194f, Stride: 1}, + {Lo: 0x19d0, Hi: 0x19d9, Stride: 1}, + {Lo: 0x1a80, Hi: 0x1a89, Stride: 1}, + {Lo: 0x1a90, Hi: 0x1a99, Stride: 1}, + {Lo: 0x1b50, Hi: 0x1b59, Stride: 1}, + {Lo: 0x1bb0, Hi: 0x1bb9, Stride: 1}, + {Lo: 0x1c40, Hi: 0x1c49, Stride: 1}, + {Lo: 0x1c50, Hi: 0x1c59, Stride: 1}, + {Lo: 0xa620, Hi: 0xa629, Stride: 1}, + {Lo: 0xa8d0, Hi: 0xa8d9, Stride: 1}, + {Lo: 0xa900, Hi: 0xa909, Stride: 1}, + {Lo: 0xa9d0, Hi: 0xa9d9, Stride: 1}, + {Lo: 0xa9f0, Hi: 0xa9f9, Stride: 1}, + {Lo: 0xaa50, Hi: 0xaa59, Stride: 1}, + {Lo: 0xabf0, Hi: 0xabf9, Stride: 1}, + {Lo: 0xff10, Hi: 0xff19, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x104a0, Hi: 0x104a9, Stride: 1}, + {Lo: 0x10d30, Hi: 0x10d39, Stride: 1}, + {Lo: 0x11066, Hi: 0x1106f, Stride: 1}, + {Lo: 0x110bd, Hi: 0x110cd, Stride: 16}, + {Lo: 0x110f0, Hi: 0x110f9, Stride: 1}, + {Lo: 0x11136, Hi: 0x1113f, Stride: 1}, + {Lo: 0x111d0, Hi: 0x111d9, Stride: 1}, + {Lo: 0x112f0, Hi: 0x112f9, Stride: 1}, + {Lo: 0x11450, Hi: 0x11459, Stride: 1}, + {Lo: 0x114d0, Hi: 0x114d9, Stride: 1}, + {Lo: 0x11650, Hi: 0x11659, Stride: 1}, + {Lo: 0x116c0, Hi: 0x116c9, Stride: 1}, + {Lo: 0x11730, Hi: 0x11739, Stride: 1}, + {Lo: 0x118e0, Hi: 0x118e9, Stride: 1}, + {Lo: 0x11950, Hi: 0x11959, Stride: 1}, + {Lo: 0x11c50, Hi: 0x11c59, Stride: 1}, + {Lo: 0x11d50, Hi: 0x11d59, Stride: 1}, + {Lo: 0x11da0, Hi: 0x11da9, Stride: 1}, + {Lo: 0x11f50, Hi: 0x11f59, Stride: 1}, + {Lo: 0x16a60, Hi: 0x16a69, Stride: 1}, + {Lo: 0x16ac0, Hi: 0x16ac9, Stride: 1}, + {Lo: 0x16b50, Hi: 0x16b59, Stride: 1}, + {Lo: 0x1d7ce, Hi: 0x1d7ff, Stride: 1}, + {Lo: 0x1e140, Hi: 0x1e149, Stride: 1}, + {Lo: 0x1e2f0, Hi: 0x1e2f9, Stride: 1}, + {Lo: 0x1e4f0, Hi: 0x1e4f9, Stride: 1}, + {Lo: 0x1e950, Hi: 0x1e959, Stride: 1}, + {Lo: 0x1fbf0, Hi: 0x1fbf9, Stride: 1}, + }, + LatinOffset: 1, +} + +// WordBreakProperty: Regional_Indicator +var WordBreakRegional_Indicator = &unicode.RangeTable{ + R32: []unicode.Range32{ + {Lo: 0x1f1e6, Hi: 0x1f1ff, Stride: 1}, + }, +} + +// WordBreakProperty: Single_Quote +var WordBreakSingle_Quote = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0027, Hi: 0x0027, Stride: 1}, + }, + LatinOffset: 1, +} + +// WordBreakProperty: WSegSpace +var WordBreakWSegSpace = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0020, Hi: 0x1680, Stride: 5728}, + {Lo: 0x2000, Hi: 0x2006, Stride: 1}, + {Lo: 0x2008, Hi: 0x200a, Stride: 1}, + {Lo: 0x205f, Hi: 0x3000, Stride: 4001}, + }, +} + +// contains all the runes having a non nil word break property +var wordBreakAll = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x000a, Hi: 0x000d, Stride: 1}, + {Lo: 0x0020, Hi: 0x0022, Stride: 2}, + {Lo: 0x0027, Hi: 0x002c, Stride: 5}, + {Lo: 0x002e, Hi: 0x002e, Stride: 1}, + {Lo: 0x0030, Hi: 0x003b, Stride: 1}, + {Lo: 0x0041, Hi: 0x005a, Stride: 1}, + {Lo: 0x005f, Hi: 0x005f, Stride: 1}, + {Lo: 0x0061, Hi: 0x007a, Stride: 1}, + {Lo: 0x0085, Hi: 0x00aa, Stride: 37}, + {Lo: 0x00ad, Hi: 0x00b5, Stride: 8}, + {Lo: 0x00b7, Hi: 0x00b7, Stride: 1}, + {Lo: 0x00ba, Hi: 0x00c0, Stride: 6}, + {Lo: 0x00c1, Hi: 0x00d6, Stride: 1}, + {Lo: 0x00d8, Hi: 0x00f6, Stride: 1}, + {Lo: 0x00f8, Hi: 0x02d7, Stride: 1}, + {Lo: 0x02de, Hi: 0x0374, Stride: 1}, + {Lo: 0x0376, Hi: 0x0377, Stride: 1}, + {Lo: 0x037a, Hi: 0x037f, Stride: 1}, + {Lo: 0x0386, Hi: 0x038a, Stride: 1}, + {Lo: 0x038c, Hi: 0x038e, Stride: 2}, + {Lo: 0x038f, Hi: 0x03a1, Stride: 1}, + {Lo: 0x03a3, Hi: 0x03f5, Stride: 1}, + {Lo: 0x03f7, Hi: 0x0481, Stride: 1}, + {Lo: 0x0483, Hi: 0x052f, Stride: 1}, + {Lo: 0x0531, Hi: 0x0556, Stride: 1}, + {Lo: 0x0559, Hi: 0x055c, Stride: 1}, + {Lo: 0x055e, Hi: 0x058a, Stride: 1}, + {Lo: 0x0591, Hi: 0x05bd, Stride: 1}, + {Lo: 0x05bf, Hi: 0x05c1, Stride: 2}, + {Lo: 0x05c2, Hi: 0x05c4, Stride: 2}, + {Lo: 0x05c5, Hi: 0x05c7, Stride: 2}, + {Lo: 0x05d0, Hi: 0x05ea, Stride: 1}, + {Lo: 0x05ef, Hi: 0x05f4, Stride: 1}, + {Lo: 0x0600, Hi: 0x0605, Stride: 1}, + {Lo: 0x060c, Hi: 0x060d, Stride: 1}, + {Lo: 0x0610, Hi: 0x061a, Stride: 1}, + {Lo: 0x061c, Hi: 0x061c, Stride: 1}, + {Lo: 0x0620, Hi: 0x0669, Stride: 1}, + {Lo: 0x066b, Hi: 0x066c, Stride: 1}, + {Lo: 0x066e, Hi: 0x06d3, Stride: 1}, + {Lo: 0x06d5, Hi: 0x06dd, Stride: 1}, + {Lo: 0x06df, Hi: 0x06e8, Stride: 1}, + {Lo: 0x06ea, Hi: 0x06fc, Stride: 1}, + {Lo: 0x06ff, Hi: 0x070f, Stride: 16}, + {Lo: 0x0710, Hi: 0x074a, Stride: 1}, + {Lo: 0x074d, Hi: 0x07b1, Stride: 1}, + {Lo: 0x07c0, Hi: 0x07f5, Stride: 1}, + {Lo: 0x07f8, Hi: 0x07fa, Stride: 2}, + {Lo: 0x07fd, Hi: 0x0800, Stride: 3}, + {Lo: 0x0801, Hi: 0x082d, Stride: 1}, + {Lo: 0x0840, Hi: 0x085b, Stride: 1}, + {Lo: 0x0860, Hi: 0x086a, Stride: 1}, + {Lo: 0x0870, Hi: 0x0887, Stride: 1}, + {Lo: 0x0889, Hi: 0x088e, Stride: 1}, + {Lo: 0x0890, Hi: 0x0891, Stride: 1}, + {Lo: 0x0898, Hi: 0x0963, Stride: 1}, + {Lo: 0x0966, Hi: 0x096f, Stride: 1}, + {Lo: 0x0971, Hi: 0x0983, Stride: 1}, + {Lo: 0x0985, Hi: 0x098c, Stride: 1}, + {Lo: 0x098f, Hi: 0x0990, Stride: 1}, + {Lo: 0x0993, Hi: 0x09a8, Stride: 1}, + {Lo: 0x09aa, Hi: 0x09b0, Stride: 1}, + {Lo: 0x09b2, Hi: 0x09b6, Stride: 4}, + {Lo: 0x09b7, Hi: 0x09b9, Stride: 1}, + {Lo: 0x09bc, Hi: 0x09c4, Stride: 1}, + {Lo: 0x09c7, Hi: 0x09c8, Stride: 1}, + {Lo: 0x09cb, Hi: 0x09ce, Stride: 1}, + {Lo: 0x09d7, Hi: 0x09d7, Stride: 1}, + {Lo: 0x09dc, Hi: 0x09dd, Stride: 1}, + {Lo: 0x09df, Hi: 0x09e3, Stride: 1}, + {Lo: 0x09e6, Hi: 0x09f1, Stride: 1}, + {Lo: 0x09fc, Hi: 0x09fe, Stride: 2}, + {Lo: 0x0a01, Hi: 0x0a03, Stride: 1}, + {Lo: 0x0a05, Hi: 0x0a0a, Stride: 1}, + {Lo: 0x0a0f, Hi: 0x0a10, Stride: 1}, + {Lo: 0x0a13, Hi: 0x0a28, Stride: 1}, + {Lo: 0x0a2a, Hi: 0x0a30, Stride: 1}, + {Lo: 0x0a32, Hi: 0x0a33, Stride: 1}, + {Lo: 0x0a35, Hi: 0x0a36, Stride: 1}, + {Lo: 0x0a38, Hi: 0x0a39, Stride: 1}, + {Lo: 0x0a3c, Hi: 0x0a3e, Stride: 2}, + {Lo: 0x0a3f, Hi: 0x0a42, Stride: 1}, + {Lo: 0x0a47, Hi: 0x0a48, Stride: 1}, + {Lo: 0x0a4b, Hi: 0x0a4d, Stride: 1}, + {Lo: 0x0a51, Hi: 0x0a51, Stride: 1}, + {Lo: 0x0a59, Hi: 0x0a5c, Stride: 1}, + {Lo: 0x0a5e, Hi: 0x0a5e, Stride: 1}, + {Lo: 0x0a66, Hi: 0x0a75, Stride: 1}, + {Lo: 0x0a81, Hi: 0x0a83, Stride: 1}, + {Lo: 0x0a85, Hi: 0x0a8d, Stride: 1}, + {Lo: 0x0a8f, Hi: 0x0a91, Stride: 1}, + {Lo: 0x0a93, Hi: 0x0aa8, Stride: 1}, + {Lo: 0x0aaa, Hi: 0x0ab0, Stride: 1}, + {Lo: 0x0ab2, Hi: 0x0ab3, Stride: 1}, + {Lo: 0x0ab5, Hi: 0x0ab9, Stride: 1}, + {Lo: 0x0abc, Hi: 0x0ac5, Stride: 1}, + {Lo: 0x0ac7, Hi: 0x0ac9, Stride: 1}, + {Lo: 0x0acb, Hi: 0x0acd, Stride: 1}, + {Lo: 0x0ad0, Hi: 0x0ad0, Stride: 1}, + {Lo: 0x0ae0, Hi: 0x0ae3, Stride: 1}, + {Lo: 0x0ae6, Hi: 0x0aef, Stride: 1}, + {Lo: 0x0af9, Hi: 0x0aff, Stride: 1}, + {Lo: 0x0b01, Hi: 0x0b03, Stride: 1}, + {Lo: 0x0b05, Hi: 0x0b0c, Stride: 1}, + {Lo: 0x0b0f, Hi: 0x0b10, Stride: 1}, + {Lo: 0x0b13, Hi: 0x0b28, Stride: 1}, + {Lo: 0x0b2a, Hi: 0x0b30, Stride: 1}, + {Lo: 0x0b32, Hi: 0x0b33, Stride: 1}, + {Lo: 0x0b35, Hi: 0x0b39, Stride: 1}, + {Lo: 0x0b3c, Hi: 0x0b44, Stride: 1}, + {Lo: 0x0b47, Hi: 0x0b48, Stride: 1}, + {Lo: 0x0b4b, Hi: 0x0b4d, Stride: 1}, + {Lo: 0x0b55, Hi: 0x0b57, Stride: 1}, + {Lo: 0x0b5c, Hi: 0x0b5d, Stride: 1}, + {Lo: 0x0b5f, Hi: 0x0b63, Stride: 1}, + {Lo: 0x0b66, Hi: 0x0b6f, Stride: 1}, + {Lo: 0x0b71, Hi: 0x0b82, Stride: 17}, + {Lo: 0x0b83, Hi: 0x0b83, Stride: 1}, + {Lo: 0x0b85, Hi: 0x0b8a, Stride: 1}, + {Lo: 0x0b8e, Hi: 0x0b90, Stride: 1}, + {Lo: 0x0b92, Hi: 0x0b95, Stride: 1}, + {Lo: 0x0b99, Hi: 0x0b9a, Stride: 1}, + {Lo: 0x0b9c, Hi: 0x0b9e, Stride: 2}, + {Lo: 0x0b9f, Hi: 0x0ba3, Stride: 4}, + {Lo: 0x0ba4, Hi: 0x0ba8, Stride: 4}, + {Lo: 0x0ba9, Hi: 0x0baa, Stride: 1}, + {Lo: 0x0bae, Hi: 0x0bb9, Stride: 1}, + {Lo: 0x0bbe, Hi: 0x0bc2, Stride: 1}, + {Lo: 0x0bc6, Hi: 0x0bc8, Stride: 1}, + {Lo: 0x0bca, Hi: 0x0bcd, Stride: 1}, + {Lo: 0x0bd0, Hi: 0x0bd7, Stride: 7}, + {Lo: 0x0be6, Hi: 0x0bef, Stride: 1}, + {Lo: 0x0c00, Hi: 0x0c0c, Stride: 1}, + {Lo: 0x0c0e, Hi: 0x0c10, Stride: 1}, + {Lo: 0x0c12, Hi: 0x0c28, Stride: 1}, + {Lo: 0x0c2a, Hi: 0x0c39, Stride: 1}, + {Lo: 0x0c3c, Hi: 0x0c44, Stride: 1}, + {Lo: 0x0c46, Hi: 0x0c48, Stride: 1}, + {Lo: 0x0c4a, Hi: 0x0c4d, Stride: 1}, + {Lo: 0x0c55, Hi: 0x0c56, Stride: 1}, + {Lo: 0x0c58, Hi: 0x0c5a, Stride: 1}, + {Lo: 0x0c5d, Hi: 0x0c60, Stride: 3}, + {Lo: 0x0c61, Hi: 0x0c63, Stride: 1}, + {Lo: 0x0c66, Hi: 0x0c6f, Stride: 1}, + {Lo: 0x0c80, Hi: 0x0c83, Stride: 1}, + {Lo: 0x0c85, Hi: 0x0c8c, Stride: 1}, + {Lo: 0x0c8e, Hi: 0x0c90, Stride: 1}, + {Lo: 0x0c92, Hi: 0x0ca8, Stride: 1}, + {Lo: 0x0caa, Hi: 0x0cb3, Stride: 1}, + {Lo: 0x0cb5, Hi: 0x0cb9, Stride: 1}, + {Lo: 0x0cbc, Hi: 0x0cc4, Stride: 1}, + {Lo: 0x0cc6, Hi: 0x0cc8, Stride: 1}, + {Lo: 0x0cca, Hi: 0x0ccd, Stride: 1}, + {Lo: 0x0cd5, Hi: 0x0cd6, Stride: 1}, + {Lo: 0x0cdd, Hi: 0x0cde, Stride: 1}, + {Lo: 0x0ce0, Hi: 0x0ce3, Stride: 1}, + {Lo: 0x0ce6, Hi: 0x0cef, Stride: 1}, + {Lo: 0x0cf1, Hi: 0x0cf3, Stride: 1}, + {Lo: 0x0d00, Hi: 0x0d0c, Stride: 1}, + {Lo: 0x0d0e, Hi: 0x0d10, Stride: 1}, + {Lo: 0x0d12, Hi: 0x0d44, Stride: 1}, + {Lo: 0x0d46, Hi: 0x0d48, Stride: 1}, + {Lo: 0x0d4a, Hi: 0x0d4e, Stride: 1}, + {Lo: 0x0d54, Hi: 0x0d57, Stride: 1}, + {Lo: 0x0d5f, Hi: 0x0d63, Stride: 1}, + {Lo: 0x0d66, Hi: 0x0d6f, Stride: 1}, + {Lo: 0x0d7a, Hi: 0x0d7f, Stride: 1}, + {Lo: 0x0d81, Hi: 0x0d83, Stride: 1}, + {Lo: 0x0d85, Hi: 0x0d96, Stride: 1}, + {Lo: 0x0d9a, Hi: 0x0db1, Stride: 1}, + {Lo: 0x0db3, Hi: 0x0dbb, Stride: 1}, + {Lo: 0x0dbd, Hi: 0x0dc0, Stride: 3}, + {Lo: 0x0dc1, Hi: 0x0dc6, Stride: 1}, + {Lo: 0x0dca, Hi: 0x0dcf, Stride: 5}, + {Lo: 0x0dd0, Hi: 0x0dd4, Stride: 1}, + {Lo: 0x0dd6, Hi: 0x0dd8, Stride: 2}, + {Lo: 0x0dd9, Hi: 0x0ddf, Stride: 1}, + {Lo: 0x0de6, Hi: 0x0def, Stride: 1}, + {Lo: 0x0df2, Hi: 0x0df3, Stride: 1}, + {Lo: 0x0e31, Hi: 0x0e34, Stride: 3}, + {Lo: 0x0e35, Hi: 0x0e3a, Stride: 1}, + {Lo: 0x0e47, Hi: 0x0e4e, Stride: 1}, + {Lo: 0x0e50, Hi: 0x0e59, Stride: 1}, + {Lo: 0x0eb1, Hi: 0x0eb4, Stride: 3}, + {Lo: 0x0eb5, Hi: 0x0ebc, Stride: 1}, + {Lo: 0x0ec8, Hi: 0x0ece, Stride: 1}, + {Lo: 0x0ed0, Hi: 0x0ed9, Stride: 1}, + {Lo: 0x0f00, Hi: 0x0f00, Stride: 1}, + {Lo: 0x0f18, Hi: 0x0f19, Stride: 1}, + {Lo: 0x0f20, Hi: 0x0f29, Stride: 1}, + {Lo: 0x0f35, Hi: 0x0f39, Stride: 2}, + {Lo: 0x0f3e, Hi: 0x0f47, Stride: 1}, + {Lo: 0x0f49, Hi: 0x0f6c, Stride: 1}, + {Lo: 0x0f71, Hi: 0x0f84, Stride: 1}, + {Lo: 0x0f86, Hi: 0x0f97, Stride: 1}, + {Lo: 0x0f99, Hi: 0x0fbc, Stride: 1}, + {Lo: 0x0fc6, Hi: 0x102b, Stride: 101}, + {Lo: 0x102c, Hi: 0x103e, Stride: 1}, + {Lo: 0x1040, Hi: 0x1049, Stride: 1}, + {Lo: 0x1056, Hi: 0x1059, Stride: 1}, + {Lo: 0x105e, Hi: 0x1060, Stride: 1}, + {Lo: 0x1062, Hi: 0x1064, Stride: 1}, + {Lo: 0x1067, Hi: 0x106d, Stride: 1}, + {Lo: 0x1071, Hi: 0x1074, Stride: 1}, + {Lo: 0x1082, Hi: 0x108d, Stride: 1}, + {Lo: 0x108f, Hi: 0x109d, Stride: 1}, + {Lo: 0x10a0, Hi: 0x10c5, Stride: 1}, + {Lo: 0x10c7, Hi: 0x10cd, Stride: 6}, + {Lo: 0x10d0, Hi: 0x10fa, Stride: 1}, + {Lo: 0x10fc, Hi: 0x1248, Stride: 1}, + {Lo: 0x124a, Hi: 0x124d, Stride: 1}, + {Lo: 0x1250, Hi: 0x1256, Stride: 1}, + {Lo: 0x1258, Hi: 0x125a, Stride: 2}, + {Lo: 0x125b, Hi: 0x125d, Stride: 1}, + {Lo: 0x1260, Hi: 0x1288, Stride: 1}, + {Lo: 0x128a, Hi: 0x128d, Stride: 1}, + {Lo: 0x1290, Hi: 0x12b0, Stride: 1}, + {Lo: 0x12b2, Hi: 0x12b5, Stride: 1}, + {Lo: 0x12b8, Hi: 0x12be, Stride: 1}, + {Lo: 0x12c0, Hi: 0x12c2, Stride: 2}, + {Lo: 0x12c3, Hi: 0x12c5, Stride: 1}, + {Lo: 0x12c8, Hi: 0x12d6, Stride: 1}, + {Lo: 0x12d8, Hi: 0x1310, Stride: 1}, + {Lo: 0x1312, Hi: 0x1315, Stride: 1}, + {Lo: 0x1318, Hi: 0x135a, Stride: 1}, + {Lo: 0x135d, Hi: 0x135f, Stride: 1}, + {Lo: 0x1380, Hi: 0x138f, Stride: 1}, + {Lo: 0x13a0, Hi: 0x13f5, Stride: 1}, + {Lo: 0x13f8, Hi: 0x13fd, Stride: 1}, + {Lo: 0x1401, Hi: 0x166c, Stride: 1}, + {Lo: 0x166f, Hi: 0x169a, Stride: 1}, + {Lo: 0x16a0, Hi: 0x16ea, Stride: 1}, + {Lo: 0x16ee, Hi: 0x16f8, Stride: 1}, + {Lo: 0x1700, Hi: 0x1715, Stride: 1}, + {Lo: 0x171f, Hi: 0x1734, Stride: 1}, + {Lo: 0x1740, Hi: 0x1753, Stride: 1}, + {Lo: 0x1760, Hi: 0x176c, Stride: 1}, + {Lo: 0x176e, Hi: 0x1770, Stride: 1}, + {Lo: 0x1772, Hi: 0x1773, Stride: 1}, + {Lo: 0x17b4, Hi: 0x17d3, Stride: 1}, + {Lo: 0x17dd, Hi: 0x17dd, Stride: 1}, + {Lo: 0x17e0, Hi: 0x17e9, Stride: 1}, + {Lo: 0x180b, Hi: 0x1819, Stride: 1}, + {Lo: 0x1820, Hi: 0x1878, Stride: 1}, + {Lo: 0x1880, Hi: 0x18aa, Stride: 1}, + {Lo: 0x18b0, Hi: 0x18f5, Stride: 1}, + {Lo: 0x1900, Hi: 0x191e, Stride: 1}, + {Lo: 0x1920, Hi: 0x192b, Stride: 1}, + {Lo: 0x1930, Hi: 0x193b, Stride: 1}, + {Lo: 0x1946, Hi: 0x194f, Stride: 1}, + {Lo: 0x19d0, Hi: 0x19d9, Stride: 1}, + {Lo: 0x1a00, Hi: 0x1a1b, Stride: 1}, + {Lo: 0x1a55, Hi: 0x1a5e, Stride: 1}, + {Lo: 0x1a60, Hi: 0x1a7c, Stride: 1}, + {Lo: 0x1a7f, Hi: 0x1a89, Stride: 1}, + {Lo: 0x1a90, Hi: 0x1a99, Stride: 1}, + {Lo: 0x1ab0, Hi: 0x1ace, Stride: 1}, + {Lo: 0x1b00, Hi: 0x1b4c, Stride: 1}, + {Lo: 0x1b50, Hi: 0x1b59, Stride: 1}, + {Lo: 0x1b6b, Hi: 0x1b73, Stride: 1}, + {Lo: 0x1b80, Hi: 0x1bf3, Stride: 1}, + {Lo: 0x1c00, Hi: 0x1c37, Stride: 1}, + {Lo: 0x1c40, Hi: 0x1c49, Stride: 1}, + {Lo: 0x1c4d, Hi: 0x1c7d, Stride: 1}, + {Lo: 0x1c80, Hi: 0x1c88, Stride: 1}, + {Lo: 0x1c90, Hi: 0x1cba, Stride: 1}, + {Lo: 0x1cbd, Hi: 0x1cbf, Stride: 1}, + {Lo: 0x1cd0, Hi: 0x1cd2, Stride: 1}, + {Lo: 0x1cd4, Hi: 0x1cfa, Stride: 1}, + {Lo: 0x1d00, Hi: 0x1f15, Stride: 1}, + {Lo: 0x1f18, Hi: 0x1f1d, Stride: 1}, + {Lo: 0x1f20, Hi: 0x1f45, Stride: 1}, + {Lo: 0x1f48, Hi: 0x1f4d, Stride: 1}, + {Lo: 0x1f50, Hi: 0x1f57, Stride: 1}, + {Lo: 0x1f59, Hi: 0x1f5f, Stride: 2}, + {Lo: 0x1f60, Hi: 0x1f7d, Stride: 1}, + {Lo: 0x1f80, Hi: 0x1fb4, Stride: 1}, + {Lo: 0x1fb6, Hi: 0x1fbc, Stride: 1}, + {Lo: 0x1fbe, Hi: 0x1fc2, Stride: 4}, + {Lo: 0x1fc3, Hi: 0x1fc4, Stride: 1}, + {Lo: 0x1fc6, Hi: 0x1fcc, Stride: 1}, + {Lo: 0x1fd0, Hi: 0x1fd3, Stride: 1}, + {Lo: 0x1fd6, Hi: 0x1fdb, Stride: 1}, + {Lo: 0x1fe0, Hi: 0x1fec, Stride: 1}, + {Lo: 0x1ff2, Hi: 0x1ff4, Stride: 1}, + {Lo: 0x1ff6, Hi: 0x1ffc, Stride: 1}, + {Lo: 0x2000, Hi: 0x2006, Stride: 1}, + {Lo: 0x2008, Hi: 0x200a, Stride: 1}, + {Lo: 0x200c, Hi: 0x200f, Stride: 1}, + {Lo: 0x2018, Hi: 0x2019, Stride: 1}, + {Lo: 0x2024, Hi: 0x2027, Stride: 3}, + {Lo: 0x2028, Hi: 0x202f, Stride: 1}, + {Lo: 0x203f, Hi: 0x2040, Stride: 1}, + {Lo: 0x2044, Hi: 0x2054, Stride: 16}, + {Lo: 0x205f, Hi: 0x2064, Stride: 1}, + {Lo: 0x2066, Hi: 0x206f, Stride: 1}, + {Lo: 0x2071, Hi: 0x207f, Stride: 14}, + {Lo: 0x2090, Hi: 0x209c, Stride: 1}, + {Lo: 0x20d0, Hi: 0x20f0, Stride: 1}, + {Lo: 0x2102, Hi: 0x2107, Stride: 5}, + {Lo: 0x210a, Hi: 0x2113, Stride: 1}, + {Lo: 0x2115, Hi: 0x2119, Stride: 4}, + {Lo: 0x211a, Hi: 0x211d, Stride: 1}, + {Lo: 0x2124, Hi: 0x212a, Stride: 2}, + {Lo: 0x212b, Hi: 0x212d, Stride: 1}, + {Lo: 0x212f, Hi: 0x2139, Stride: 1}, + {Lo: 0x213c, Hi: 0x213f, Stride: 1}, + {Lo: 0x2145, Hi: 0x2149, Stride: 1}, + {Lo: 0x214e, Hi: 0x2160, Stride: 18}, + {Lo: 0x2161, Hi: 0x2188, Stride: 1}, + {Lo: 0x24b6, Hi: 0x24e9, Stride: 1}, + {Lo: 0x2c00, Hi: 0x2ce4, Stride: 1}, + {Lo: 0x2ceb, Hi: 0x2cf3, Stride: 1}, + {Lo: 0x2d00, Hi: 0x2d25, Stride: 1}, + {Lo: 0x2d27, Hi: 0x2d2d, Stride: 6}, + {Lo: 0x2d30, Hi: 0x2d67, Stride: 1}, + {Lo: 0x2d6f, Hi: 0x2d7f, Stride: 16}, + {Lo: 0x2d80, Hi: 0x2d96, Stride: 1}, + {Lo: 0x2da0, Hi: 0x2da6, Stride: 1}, + {Lo: 0x2da8, Hi: 0x2dae, Stride: 1}, + {Lo: 0x2db0, Hi: 0x2db6, Stride: 1}, + {Lo: 0x2db8, Hi: 0x2dbe, Stride: 1}, + {Lo: 0x2dc0, Hi: 0x2dc6, Stride: 1}, + {Lo: 0x2dc8, Hi: 0x2dce, Stride: 1}, + {Lo: 0x2dd0, Hi: 0x2dd6, Stride: 1}, + {Lo: 0x2dd8, Hi: 0x2dde, Stride: 1}, + {Lo: 0x2de0, Hi: 0x2dff, Stride: 1}, + {Lo: 0x2e2f, Hi: 0x3000, Stride: 465}, + {Lo: 0x3005, Hi: 0x3005, Stride: 1}, + {Lo: 0x302a, Hi: 0x302f, Stride: 1}, + {Lo: 0x3031, Hi: 0x3035, Stride: 1}, + {Lo: 0x303b, Hi: 0x303c, Stride: 1}, + {Lo: 0x3099, Hi: 0x309c, Stride: 1}, + {Lo: 0x30a0, Hi: 0x30fa, Stride: 1}, + {Lo: 0x30fc, Hi: 0x30ff, Stride: 1}, + {Lo: 0x3105, Hi: 0x312f, Stride: 1}, + {Lo: 0x3131, Hi: 0x318e, Stride: 1}, + {Lo: 0x31a0, Hi: 0x31bf, Stride: 1}, + {Lo: 0x31f0, Hi: 0x31ff, Stride: 1}, + {Lo: 0x32d0, Hi: 0x32fe, Stride: 1}, + {Lo: 0x3300, Hi: 0x3357, Stride: 1}, + {Lo: 0xa000, Hi: 0xa48c, Stride: 1}, + {Lo: 0xa4d0, Hi: 0xa4fd, Stride: 1}, + {Lo: 0xa500, Hi: 0xa60c, Stride: 1}, + {Lo: 0xa610, Hi: 0xa62b, Stride: 1}, + {Lo: 0xa640, Hi: 0xa672, Stride: 1}, + {Lo: 0xa674, Hi: 0xa67d, Stride: 1}, + {Lo: 0xa67f, Hi: 0xa6f1, Stride: 1}, + {Lo: 0xa708, Hi: 0xa7ca, Stride: 1}, + {Lo: 0xa7d0, Hi: 0xa7d1, Stride: 1}, + {Lo: 0xa7d3, Hi: 0xa7d5, Stride: 2}, + {Lo: 0xa7d6, Hi: 0xa7d9, Stride: 1}, + {Lo: 0xa7f2, Hi: 0xa827, Stride: 1}, + {Lo: 0xa82c, Hi: 0xa82c, Stride: 1}, + {Lo: 0xa840, Hi: 0xa873, Stride: 1}, + {Lo: 0xa880, Hi: 0xa8c5, Stride: 1}, + {Lo: 0xa8d0, Hi: 0xa8d9, Stride: 1}, + {Lo: 0xa8e0, Hi: 0xa8f7, Stride: 1}, + {Lo: 0xa8fb, Hi: 0xa8fd, Stride: 2}, + {Lo: 0xa8fe, Hi: 0xa92d, Stride: 1}, + {Lo: 0xa930, Hi: 0xa953, Stride: 1}, + {Lo: 0xa960, Hi: 0xa97c, Stride: 1}, + {Lo: 0xa980, Hi: 0xa9c0, Stride: 1}, + {Lo: 0xa9cf, Hi: 0xa9d9, Stride: 1}, + {Lo: 0xa9e5, Hi: 0xa9e5, Stride: 1}, + {Lo: 0xa9f0, Hi: 0xa9f9, Stride: 1}, + {Lo: 0xaa00, Hi: 0xaa36, Stride: 1}, + {Lo: 0xaa40, Hi: 0xaa4d, Stride: 1}, + {Lo: 0xaa50, Hi: 0xaa59, Stride: 1}, + {Lo: 0xaa7b, Hi: 0xaa7d, Stride: 1}, + {Lo: 0xaab0, Hi: 0xaab2, Stride: 2}, + {Lo: 0xaab3, Hi: 0xaab4, Stride: 1}, + {Lo: 0xaab7, Hi: 0xaab8, Stride: 1}, + {Lo: 0xaabe, Hi: 0xaabf, Stride: 1}, + {Lo: 0xaac1, Hi: 0xaac1, Stride: 1}, + {Lo: 0xaae0, Hi: 0xaaef, Stride: 1}, + {Lo: 0xaaf2, Hi: 0xaaf6, Stride: 1}, + {Lo: 0xab01, Hi: 0xab06, Stride: 1}, + {Lo: 0xab09, Hi: 0xab0e, Stride: 1}, + {Lo: 0xab11, Hi: 0xab16, Stride: 1}, + {Lo: 0xab20, Hi: 0xab26, Stride: 1}, + {Lo: 0xab28, Hi: 0xab2e, Stride: 1}, + {Lo: 0xab30, Hi: 0xab69, Stride: 1}, + {Lo: 0xab70, Hi: 0xabea, Stride: 1}, + {Lo: 0xabec, Hi: 0xabed, Stride: 1}, + {Lo: 0xabf0, Hi: 0xabf9, Stride: 1}, + {Lo: 0xac00, Hi: 0xd7a3, Stride: 1}, + {Lo: 0xd7b0, Hi: 0xd7c6, Stride: 1}, + {Lo: 0xd7cb, Hi: 0xd7fb, Stride: 1}, + {Lo: 0xfb00, Hi: 0xfb06, Stride: 1}, + {Lo: 0xfb13, Hi: 0xfb17, Stride: 1}, + {Lo: 0xfb1d, Hi: 0xfb28, Stride: 1}, + {Lo: 0xfb2a, Hi: 0xfb36, Stride: 1}, + {Lo: 0xfb38, Hi: 0xfb3c, Stride: 1}, + {Lo: 0xfb3e, Hi: 0xfb40, Stride: 2}, + {Lo: 0xfb41, Hi: 0xfb43, Stride: 2}, + {Lo: 0xfb44, Hi: 0xfb46, Stride: 2}, + {Lo: 0xfb47, Hi: 0xfbb1, Stride: 1}, + {Lo: 0xfbd3, Hi: 0xfd3d, Stride: 1}, + {Lo: 0xfd50, Hi: 0xfd8f, Stride: 1}, + {Lo: 0xfd92, Hi: 0xfdc7, Stride: 1}, + {Lo: 0xfdf0, Hi: 0xfdfb, Stride: 1}, + {Lo: 0xfe00, Hi: 0xfe10, Stride: 1}, + {Lo: 0xfe13, Hi: 0xfe14, Stride: 1}, + {Lo: 0xfe20, Hi: 0xfe2f, Stride: 1}, + {Lo: 0xfe33, Hi: 0xfe34, Stride: 1}, + {Lo: 0xfe4d, Hi: 0xfe50, Stride: 1}, + {Lo: 0xfe52, Hi: 0xfe54, Stride: 2}, + {Lo: 0xfe55, Hi: 0xfe55, Stride: 1}, + {Lo: 0xfe70, Hi: 0xfe74, Stride: 1}, + {Lo: 0xfe76, Hi: 0xfefc, Stride: 1}, + {Lo: 0xfeff, Hi: 0xff07, Stride: 8}, + {Lo: 0xff0c, Hi: 0xff10, Stride: 2}, + {Lo: 0xff11, Hi: 0xff1b, Stride: 1}, + {Lo: 0xff21, Hi: 0xff3a, Stride: 1}, + {Lo: 0xff3f, Hi: 0xff3f, Stride: 1}, + {Lo: 0xff41, Hi: 0xff5a, Stride: 1}, + {Lo: 0xff66, Hi: 0xffbe, Stride: 1}, + {Lo: 0xffc2, Hi: 0xffc7, Stride: 1}, + {Lo: 0xffca, Hi: 0xffcf, Stride: 1}, + {Lo: 0xffd2, Hi: 0xffd7, Stride: 1}, + {Lo: 0xffda, Hi: 0xffdc, Stride: 1}, + {Lo: 0xfff9, Hi: 0xfffb, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x10000, Hi: 0x1000b, Stride: 1}, + {Lo: 0x1000d, Hi: 0x10026, Stride: 1}, + {Lo: 0x10028, Hi: 0x1003a, Stride: 1}, + {Lo: 0x1003c, Hi: 0x1003d, Stride: 1}, + {Lo: 0x1003f, Hi: 0x1004d, Stride: 1}, + {Lo: 0x10050, Hi: 0x1005d, Stride: 1}, + {Lo: 0x10080, Hi: 0x100fa, Stride: 1}, + {Lo: 0x10140, Hi: 0x10174, Stride: 1}, + {Lo: 0x101fd, Hi: 0x101fd, Stride: 1}, + {Lo: 0x10280, Hi: 0x1029c, Stride: 1}, + {Lo: 0x102a0, Hi: 0x102d0, Stride: 1}, + {Lo: 0x102e0, Hi: 0x102e0, Stride: 1}, + {Lo: 0x10300, Hi: 0x1031f, Stride: 1}, + {Lo: 0x1032d, Hi: 0x1034a, Stride: 1}, + {Lo: 0x10350, Hi: 0x1037a, Stride: 1}, + {Lo: 0x10380, Hi: 0x1039d, Stride: 1}, + {Lo: 0x103a0, Hi: 0x103c3, Stride: 1}, + {Lo: 0x103c8, Hi: 0x103cf, Stride: 1}, + {Lo: 0x103d1, Hi: 0x103d5, Stride: 1}, + {Lo: 0x10400, Hi: 0x1049d, Stride: 1}, + {Lo: 0x104a0, Hi: 0x104a9, Stride: 1}, + {Lo: 0x104b0, Hi: 0x104d3, Stride: 1}, + {Lo: 0x104d8, Hi: 0x104fb, Stride: 1}, + {Lo: 0x10500, Hi: 0x10527, Stride: 1}, + {Lo: 0x10530, Hi: 0x10563, Stride: 1}, + {Lo: 0x10570, Hi: 0x1057a, Stride: 1}, + {Lo: 0x1057c, Hi: 0x1058a, Stride: 1}, + {Lo: 0x1058c, Hi: 0x10592, Stride: 1}, + {Lo: 0x10594, Hi: 0x10595, Stride: 1}, + {Lo: 0x10597, Hi: 0x105a1, Stride: 1}, + {Lo: 0x105a3, Hi: 0x105b1, Stride: 1}, + {Lo: 0x105b3, Hi: 0x105b9, Stride: 1}, + {Lo: 0x105bb, Hi: 0x105bc, Stride: 1}, + {Lo: 0x10600, Hi: 0x10736, Stride: 1}, + {Lo: 0x10740, Hi: 0x10755, Stride: 1}, + {Lo: 0x10760, Hi: 0x10767, Stride: 1}, + {Lo: 0x10780, Hi: 0x10785, Stride: 1}, + {Lo: 0x10787, Hi: 0x107b0, Stride: 1}, + {Lo: 0x107b2, Hi: 0x107ba, Stride: 1}, + {Lo: 0x10800, Hi: 0x10805, Stride: 1}, + {Lo: 0x10808, Hi: 0x1080a, Stride: 2}, + {Lo: 0x1080b, Hi: 0x10835, Stride: 1}, + {Lo: 0x10837, Hi: 0x10838, Stride: 1}, + {Lo: 0x1083c, Hi: 0x1083f, Stride: 3}, + {Lo: 0x10840, Hi: 0x10855, Stride: 1}, + {Lo: 0x10860, Hi: 0x10876, Stride: 1}, + {Lo: 0x10880, Hi: 0x1089e, Stride: 1}, + {Lo: 0x108e0, Hi: 0x108f2, Stride: 1}, + {Lo: 0x108f4, Hi: 0x108f5, Stride: 1}, + {Lo: 0x10900, Hi: 0x10915, Stride: 1}, + {Lo: 0x10920, Hi: 0x10939, Stride: 1}, + {Lo: 0x10980, Hi: 0x109b7, Stride: 1}, + {Lo: 0x109be, Hi: 0x109bf, Stride: 1}, + {Lo: 0x10a00, Hi: 0x10a03, Stride: 1}, + {Lo: 0x10a05, Hi: 0x10a06, Stride: 1}, + {Lo: 0x10a0c, Hi: 0x10a13, Stride: 1}, + {Lo: 0x10a15, Hi: 0x10a17, Stride: 1}, + {Lo: 0x10a19, Hi: 0x10a35, Stride: 1}, + {Lo: 0x10a38, Hi: 0x10a3a, Stride: 1}, + {Lo: 0x10a3f, Hi: 0x10a3f, Stride: 1}, + {Lo: 0x10a60, Hi: 0x10a7c, Stride: 1}, + {Lo: 0x10a80, Hi: 0x10a9c, Stride: 1}, + {Lo: 0x10ac0, Hi: 0x10ac7, Stride: 1}, + {Lo: 0x10ac9, Hi: 0x10ae6, Stride: 1}, + {Lo: 0x10b00, Hi: 0x10b35, Stride: 1}, + {Lo: 0x10b40, Hi: 0x10b55, Stride: 1}, + {Lo: 0x10b60, Hi: 0x10b72, Stride: 1}, + {Lo: 0x10b80, Hi: 0x10b91, Stride: 1}, + {Lo: 0x10c00, Hi: 0x10c48, Stride: 1}, + {Lo: 0x10c80, Hi: 0x10cb2, Stride: 1}, + {Lo: 0x10cc0, Hi: 0x10cf2, Stride: 1}, + {Lo: 0x10d00, Hi: 0x10d27, Stride: 1}, + {Lo: 0x10d30, Hi: 0x10d39, Stride: 1}, + {Lo: 0x10e80, Hi: 0x10ea9, Stride: 1}, + {Lo: 0x10eab, Hi: 0x10eac, Stride: 1}, + {Lo: 0x10eb0, Hi: 0x10eb1, Stride: 1}, + {Lo: 0x10efd, Hi: 0x10f1c, Stride: 1}, + {Lo: 0x10f27, Hi: 0x10f30, Stride: 9}, + {Lo: 0x10f31, Hi: 0x10f50, Stride: 1}, + {Lo: 0x10f70, Hi: 0x10f85, Stride: 1}, + {Lo: 0x10fb0, Hi: 0x10fc4, Stride: 1}, + {Lo: 0x10fe0, Hi: 0x10ff6, Stride: 1}, + {Lo: 0x11000, Hi: 0x11046, Stride: 1}, + {Lo: 0x11066, Hi: 0x11075, Stride: 1}, + {Lo: 0x1107f, Hi: 0x110ba, Stride: 1}, + {Lo: 0x110bd, Hi: 0x110c2, Stride: 5}, + {Lo: 0x110cd, Hi: 0x110cd, Stride: 1}, + {Lo: 0x110d0, Hi: 0x110e8, Stride: 1}, + {Lo: 0x110f0, Hi: 0x110f9, Stride: 1}, + {Lo: 0x11100, Hi: 0x11134, Stride: 1}, + {Lo: 0x11136, Hi: 0x1113f, Stride: 1}, + {Lo: 0x11144, Hi: 0x11147, Stride: 1}, + {Lo: 0x11150, Hi: 0x11173, Stride: 1}, + {Lo: 0x11176, Hi: 0x11180, Stride: 10}, + {Lo: 0x11181, Hi: 0x111c4, Stride: 1}, + {Lo: 0x111c9, Hi: 0x111cc, Stride: 1}, + {Lo: 0x111ce, Hi: 0x111da, Stride: 1}, + {Lo: 0x111dc, Hi: 0x111dc, Stride: 2}, + {Lo: 0x11200, Hi: 0x11211, Stride: 1}, + {Lo: 0x11213, Hi: 0x11237, Stride: 1}, + {Lo: 0x1123e, Hi: 0x11241, Stride: 1}, + {Lo: 0x11280, Hi: 0x11286, Stride: 1}, + {Lo: 0x11288, Hi: 0x1128a, Stride: 2}, + {Lo: 0x1128b, Hi: 0x1128d, Stride: 1}, + {Lo: 0x1128f, Hi: 0x1129d, Stride: 1}, + {Lo: 0x1129f, Hi: 0x112a8, Stride: 1}, + {Lo: 0x112b0, Hi: 0x112ea, Stride: 1}, + {Lo: 0x112f0, Hi: 0x112f9, Stride: 1}, + {Lo: 0x11300, Hi: 0x11303, Stride: 1}, + {Lo: 0x11305, Hi: 0x1130c, Stride: 1}, + {Lo: 0x1130f, Hi: 0x11310, Stride: 1}, + {Lo: 0x11313, Hi: 0x11328, Stride: 1}, + {Lo: 0x1132a, Hi: 0x11330, Stride: 1}, + {Lo: 0x11332, Hi: 0x11333, Stride: 1}, + {Lo: 0x11335, Hi: 0x11339, Stride: 1}, + {Lo: 0x1133b, Hi: 0x11344, Stride: 1}, + {Lo: 0x11347, Hi: 0x11348, Stride: 1}, + {Lo: 0x1134b, Hi: 0x1134d, Stride: 1}, + {Lo: 0x11350, Hi: 0x11357, Stride: 7}, + {Lo: 0x1135d, Hi: 0x11363, Stride: 1}, + {Lo: 0x11366, Hi: 0x1136c, Stride: 1}, + {Lo: 0x11370, Hi: 0x11374, Stride: 1}, + {Lo: 0x11400, Hi: 0x1144a, Stride: 1}, + {Lo: 0x11450, Hi: 0x11459, Stride: 1}, + {Lo: 0x1145e, Hi: 0x11461, Stride: 1}, + {Lo: 0x11480, Hi: 0x114c5, Stride: 1}, + {Lo: 0x114c7, Hi: 0x114c7, Stride: 1}, + {Lo: 0x114d0, Hi: 0x114d9, Stride: 1}, + {Lo: 0x11580, Hi: 0x115b5, Stride: 1}, + {Lo: 0x115b8, Hi: 0x115c0, Stride: 1}, + {Lo: 0x115d8, Hi: 0x115dd, Stride: 1}, + {Lo: 0x11600, Hi: 0x11640, Stride: 1}, + {Lo: 0x11644, Hi: 0x11644, Stride: 1}, + {Lo: 0x11650, Hi: 0x11659, Stride: 1}, + {Lo: 0x11680, Hi: 0x116b8, Stride: 1}, + {Lo: 0x116c0, Hi: 0x116c9, Stride: 1}, + {Lo: 0x1171d, Hi: 0x1172b, Stride: 1}, + {Lo: 0x11730, Hi: 0x11739, Stride: 1}, + {Lo: 0x11800, Hi: 0x1183a, Stride: 1}, + {Lo: 0x118a0, Hi: 0x118e9, Stride: 1}, + {Lo: 0x118ff, Hi: 0x11906, Stride: 1}, + {Lo: 0x11909, Hi: 0x1190c, Stride: 3}, + {Lo: 0x1190d, Hi: 0x11913, Stride: 1}, + {Lo: 0x11915, Hi: 0x11916, Stride: 1}, + {Lo: 0x11918, Hi: 0x11935, Stride: 1}, + {Lo: 0x11937, Hi: 0x11938, Stride: 1}, + {Lo: 0x1193b, Hi: 0x11943, Stride: 1}, + {Lo: 0x11950, Hi: 0x11959, Stride: 1}, + {Lo: 0x119a0, Hi: 0x119a7, Stride: 1}, + {Lo: 0x119aa, Hi: 0x119d7, Stride: 1}, + {Lo: 0x119da, Hi: 0x119e1, Stride: 1}, + {Lo: 0x119e3, Hi: 0x119e4, Stride: 1}, + {Lo: 0x11a00, Hi: 0x11a3e, Stride: 1}, + {Lo: 0x11a47, Hi: 0x11a50, Stride: 9}, + {Lo: 0x11a51, Hi: 0x11a99, Stride: 1}, + {Lo: 0x11a9d, Hi: 0x11ab0, Stride: 19}, + {Lo: 0x11ab1, Hi: 0x11af8, Stride: 1}, + {Lo: 0x11c00, Hi: 0x11c08, Stride: 1}, + {Lo: 0x11c0a, Hi: 0x11c36, Stride: 1}, + {Lo: 0x11c38, Hi: 0x11c40, Stride: 1}, + {Lo: 0x11c50, Hi: 0x11c59, Stride: 1}, + {Lo: 0x11c72, Hi: 0x11c8f, Stride: 1}, + {Lo: 0x11c92, Hi: 0x11ca7, Stride: 1}, + {Lo: 0x11ca9, Hi: 0x11cb6, Stride: 1}, + {Lo: 0x11d00, Hi: 0x11d06, Stride: 1}, + {Lo: 0x11d08, Hi: 0x11d09, Stride: 1}, + {Lo: 0x11d0b, Hi: 0x11d36, Stride: 1}, + {Lo: 0x11d3a, Hi: 0x11d3c, Stride: 2}, + {Lo: 0x11d3d, Hi: 0x11d3f, Stride: 2}, + {Lo: 0x11d40, Hi: 0x11d47, Stride: 1}, + {Lo: 0x11d50, Hi: 0x11d59, Stride: 1}, + {Lo: 0x11d60, Hi: 0x11d65, Stride: 1}, + {Lo: 0x11d67, Hi: 0x11d68, Stride: 1}, + {Lo: 0x11d6a, Hi: 0x11d8e, Stride: 1}, + {Lo: 0x11d90, Hi: 0x11d91, Stride: 1}, + {Lo: 0x11d93, Hi: 0x11d98, Stride: 1}, + {Lo: 0x11da0, Hi: 0x11da9, Stride: 1}, + {Lo: 0x11ee0, Hi: 0x11ef6, Stride: 1}, + {Lo: 0x11f00, Hi: 0x11f10, Stride: 1}, + {Lo: 0x11f12, Hi: 0x11f3a, Stride: 1}, + {Lo: 0x11f3e, Hi: 0x11f42, Stride: 1}, + {Lo: 0x11f50, Hi: 0x11f59, Stride: 1}, + {Lo: 0x11fb0, Hi: 0x12000, Stride: 80}, + {Lo: 0x12001, Hi: 0x12399, Stride: 1}, + {Lo: 0x12400, Hi: 0x1246e, Stride: 1}, + {Lo: 0x12480, Hi: 0x12543, Stride: 1}, + {Lo: 0x12f90, Hi: 0x12ff0, Stride: 1}, + {Lo: 0x13000, Hi: 0x13455, Stride: 1}, + {Lo: 0x14400, Hi: 0x14646, Stride: 1}, + {Lo: 0x16800, Hi: 0x16a38, Stride: 1}, + {Lo: 0x16a40, Hi: 0x16a5e, Stride: 1}, + {Lo: 0x16a60, Hi: 0x16a69, Stride: 1}, + {Lo: 0x16a70, Hi: 0x16abe, Stride: 1}, + {Lo: 0x16ac0, Hi: 0x16ac9, Stride: 1}, + {Lo: 0x16ad0, Hi: 0x16aed, Stride: 1}, + {Lo: 0x16af0, Hi: 0x16af4, Stride: 1}, + {Lo: 0x16b00, Hi: 0x16b36, Stride: 1}, + {Lo: 0x16b40, Hi: 0x16b43, Stride: 1}, + {Lo: 0x16b50, Hi: 0x16b59, Stride: 1}, + {Lo: 0x16b63, Hi: 0x16b77, Stride: 1}, + {Lo: 0x16b7d, Hi: 0x16b8f, Stride: 1}, + {Lo: 0x16e40, Hi: 0x16e7f, Stride: 1}, + {Lo: 0x16f00, Hi: 0x16f4a, Stride: 1}, + {Lo: 0x16f4f, Hi: 0x16f87, Stride: 1}, + {Lo: 0x16f8f, Hi: 0x16f9f, Stride: 1}, + {Lo: 0x16fe0, Hi: 0x16fe1, Stride: 1}, + {Lo: 0x16fe3, Hi: 0x16fe4, Stride: 1}, + {Lo: 0x16ff0, Hi: 0x16ff1, Stride: 1}, + {Lo: 0x1aff0, Hi: 0x1aff3, Stride: 1}, + {Lo: 0x1aff5, Hi: 0x1affb, Stride: 1}, + {Lo: 0x1affd, Hi: 0x1affe, Stride: 1}, + {Lo: 0x1b000, Hi: 0x1b120, Stride: 288}, + {Lo: 0x1b121, Hi: 0x1b122, Stride: 1}, + {Lo: 0x1b155, Hi: 0x1b164, Stride: 15}, + {Lo: 0x1b165, Hi: 0x1b167, Stride: 1}, + {Lo: 0x1bc00, Hi: 0x1bc6a, Stride: 1}, + {Lo: 0x1bc70, Hi: 0x1bc7c, Stride: 1}, + {Lo: 0x1bc80, Hi: 0x1bc88, Stride: 1}, + {Lo: 0x1bc90, Hi: 0x1bc99, Stride: 1}, + {Lo: 0x1bc9d, Hi: 0x1bc9e, Stride: 1}, + {Lo: 0x1bca0, Hi: 0x1bca3, Stride: 1}, + {Lo: 0x1cf00, Hi: 0x1cf2d, Stride: 1}, + {Lo: 0x1cf30, Hi: 0x1cf46, Stride: 1}, + {Lo: 0x1d165, Hi: 0x1d169, Stride: 1}, + {Lo: 0x1d16d, Hi: 0x1d182, Stride: 1}, + {Lo: 0x1d185, Hi: 0x1d18b, Stride: 1}, + {Lo: 0x1d1aa, Hi: 0x1d1ad, Stride: 1}, + {Lo: 0x1d242, Hi: 0x1d244, Stride: 1}, + {Lo: 0x1d400, Hi: 0x1d454, Stride: 1}, + {Lo: 0x1d456, Hi: 0x1d49c, Stride: 1}, + {Lo: 0x1d49e, Hi: 0x1d49f, Stride: 1}, + {Lo: 0x1d4a2, Hi: 0x1d4a5, Stride: 3}, + {Lo: 0x1d4a6, Hi: 0x1d4a9, Stride: 3}, + {Lo: 0x1d4aa, Hi: 0x1d4ac, Stride: 1}, + {Lo: 0x1d4ae, Hi: 0x1d4b9, Stride: 1}, + {Lo: 0x1d4bb, Hi: 0x1d4bd, Stride: 2}, + {Lo: 0x1d4be, Hi: 0x1d4c3, Stride: 1}, + {Lo: 0x1d4c5, Hi: 0x1d505, Stride: 1}, + {Lo: 0x1d507, Hi: 0x1d50a, Stride: 1}, + {Lo: 0x1d50d, Hi: 0x1d514, Stride: 1}, + {Lo: 0x1d516, Hi: 0x1d51c, Stride: 1}, + {Lo: 0x1d51e, Hi: 0x1d539, Stride: 1}, + {Lo: 0x1d53b, Hi: 0x1d53e, Stride: 1}, + {Lo: 0x1d540, Hi: 0x1d544, Stride: 1}, + {Lo: 0x1d546, Hi: 0x1d54a, Stride: 4}, + {Lo: 0x1d54b, Hi: 0x1d550, Stride: 1}, + {Lo: 0x1d552, Hi: 0x1d6a5, Stride: 1}, + {Lo: 0x1d6a8, Hi: 0x1d6c0, Stride: 1}, + {Lo: 0x1d6c2, Hi: 0x1d6da, Stride: 1}, + {Lo: 0x1d6dc, Hi: 0x1d6fa, Stride: 1}, + {Lo: 0x1d6fc, Hi: 0x1d714, Stride: 1}, + {Lo: 0x1d716, Hi: 0x1d734, Stride: 1}, + {Lo: 0x1d736, Hi: 0x1d74e, Stride: 1}, + {Lo: 0x1d750, Hi: 0x1d76e, Stride: 1}, + {Lo: 0x1d770, Hi: 0x1d788, Stride: 1}, + {Lo: 0x1d78a, Hi: 0x1d7a8, Stride: 1}, + {Lo: 0x1d7aa, Hi: 0x1d7c2, Stride: 1}, + {Lo: 0x1d7c4, Hi: 0x1d7cb, Stride: 1}, + {Lo: 0x1d7ce, Hi: 0x1d7ff, Stride: 1}, + {Lo: 0x1da00, Hi: 0x1da36, Stride: 1}, + {Lo: 0x1da3b, Hi: 0x1da6c, Stride: 1}, + {Lo: 0x1da75, Hi: 0x1da84, Stride: 15}, + {Lo: 0x1da9b, Hi: 0x1da9f, Stride: 1}, + {Lo: 0x1daa1, Hi: 0x1daaf, Stride: 1}, + {Lo: 0x1df00, Hi: 0x1df1e, Stride: 1}, + {Lo: 0x1df25, Hi: 0x1df2a, Stride: 1}, + {Lo: 0x1e000, Hi: 0x1e006, Stride: 1}, + {Lo: 0x1e008, Hi: 0x1e018, Stride: 1}, + {Lo: 0x1e01b, Hi: 0x1e021, Stride: 1}, + {Lo: 0x1e023, Hi: 0x1e024, Stride: 1}, + {Lo: 0x1e026, Hi: 0x1e02a, Stride: 1}, + {Lo: 0x1e030, Hi: 0x1e06d, Stride: 1}, + {Lo: 0x1e08f, Hi: 0x1e08f, Stride: 1}, + {Lo: 0x1e100, Hi: 0x1e12c, Stride: 1}, + {Lo: 0x1e130, Hi: 0x1e13d, Stride: 1}, + {Lo: 0x1e140, Hi: 0x1e149, Stride: 1}, + {Lo: 0x1e14e, Hi: 0x1e290, Stride: 322}, + {Lo: 0x1e291, Hi: 0x1e2ae, Stride: 1}, + {Lo: 0x1e2c0, Hi: 0x1e2f9, Stride: 1}, + {Lo: 0x1e4d0, Hi: 0x1e4f9, Stride: 1}, + {Lo: 0x1e7e0, Hi: 0x1e7e6, Stride: 1}, + {Lo: 0x1e7e8, Hi: 0x1e7eb, Stride: 1}, + {Lo: 0x1e7ed, Hi: 0x1e7ee, Stride: 1}, + {Lo: 0x1e7f0, Hi: 0x1e7fe, Stride: 1}, + {Lo: 0x1e800, Hi: 0x1e8c4, Stride: 1}, + {Lo: 0x1e8d0, Hi: 0x1e8d6, Stride: 1}, + {Lo: 0x1e900, Hi: 0x1e94b, Stride: 1}, + {Lo: 0x1e950, Hi: 0x1e959, Stride: 1}, + {Lo: 0x1ee00, Hi: 0x1ee03, Stride: 1}, + {Lo: 0x1ee05, Hi: 0x1ee1f, Stride: 1}, + {Lo: 0x1ee21, Hi: 0x1ee22, Stride: 1}, + {Lo: 0x1ee24, Hi: 0x1ee27, Stride: 3}, + {Lo: 0x1ee29, Hi: 0x1ee32, Stride: 1}, + {Lo: 0x1ee34, Hi: 0x1ee37, Stride: 1}, + {Lo: 0x1ee39, Hi: 0x1ee3b, Stride: 2}, + {Lo: 0x1ee42, Hi: 0x1ee47, Stride: 5}, + {Lo: 0x1ee49, Hi: 0x1ee4d, Stride: 2}, + {Lo: 0x1ee4e, Hi: 0x1ee4f, Stride: 1}, + {Lo: 0x1ee51, Hi: 0x1ee52, Stride: 1}, + {Lo: 0x1ee54, Hi: 0x1ee57, Stride: 3}, + {Lo: 0x1ee59, Hi: 0x1ee61, Stride: 2}, + {Lo: 0x1ee62, Hi: 0x1ee64, Stride: 2}, + {Lo: 0x1ee67, Hi: 0x1ee6a, Stride: 1}, + {Lo: 0x1ee6c, Hi: 0x1ee72, Stride: 1}, + {Lo: 0x1ee74, Hi: 0x1ee77, Stride: 1}, + {Lo: 0x1ee79, Hi: 0x1ee7c, Stride: 1}, + {Lo: 0x1ee7e, Hi: 0x1ee80, Stride: 2}, + {Lo: 0x1ee81, Hi: 0x1ee89, Stride: 1}, + {Lo: 0x1ee8b, Hi: 0x1ee9b, Stride: 1}, + {Lo: 0x1eea1, Hi: 0x1eea3, Stride: 1}, + {Lo: 0x1eea5, Hi: 0x1eea9, Stride: 1}, + {Lo: 0x1eeab, Hi: 0x1eebb, Stride: 1}, + {Lo: 0x1f130, Hi: 0x1f149, Stride: 1}, + {Lo: 0x1f150, Hi: 0x1f169, Stride: 1}, + {Lo: 0x1f170, Hi: 0x1f189, Stride: 1}, + {Lo: 0x1f1e6, Hi: 0x1f1ff, Stride: 1}, + {Lo: 0x1f3fb, Hi: 0x1f3ff, Stride: 1}, + {Lo: 0x1fbf0, Hi: 0x1fbf9, Stride: 1}, + {Lo: 0xe0001, Hi: 0xe0020, Stride: 31}, + {Lo: 0xe0021, Hi: 0xe007f, Stride: 1}, + {Lo: 0xe0100, Hi: 0xe01ef, Stride: 1}, + }, + LatinOffset: 14, +} + +var wordBreaks = [...]*unicode.RangeTable{ + WordBreakALetter, // ALetter + WordBreakDouble_Quote, // Double_Quote + WordBreakExtendFormat, // ExtendFormat + WordBreakExtendNumLet, // ExtendNumLet + WordBreakHebrew_Letter, // Hebrew_Letter + WordBreakKatakana, // Katakana + WordBreakMidLetter, // MidLetter + WordBreakMidNum, // MidNum + WordBreakMidNumLet, // MidNumLet + WordBreakNewlineCRLF, // NewlineCRLF + WordBreakNumeric, // Numeric + WordBreakRegional_Indicator, // Regional_Indicator + WordBreakSingle_Quote, // Single_Quote + WordBreakWSegSpace, // WSegSpace +} + +// Word contains all the runes we may found in a word, +// that is either a Number (Nd, Nl, No) or a rune with the Alphabetic property +var Word = &unicode.RangeTable{ + R16: []unicode.Range16{ + {Lo: 0x0030, Hi: 0x0039, Stride: 1}, + {Lo: 0x0041, Hi: 0x005a, Stride: 1}, + {Lo: 0x0061, Hi: 0x007a, Stride: 1}, + {Lo: 0x00aa, Hi: 0x00b2, Stride: 8}, + {Lo: 0x00b3, Hi: 0x00b5, Stride: 2}, + {Lo: 0x00b9, Hi: 0x00ba, Stride: 1}, + {Lo: 0x00bc, Hi: 0x00be, Stride: 1}, + {Lo: 0x00c0, Hi: 0x00d6, Stride: 1}, + {Lo: 0x00d8, Hi: 0x00f6, Stride: 1}, + {Lo: 0x00f8, Hi: 0x02c1, Stride: 1}, + {Lo: 0x02c6, Hi: 0x02d1, Stride: 1}, + {Lo: 0x02e0, Hi: 0x02e4, Stride: 1}, + {Lo: 0x02ec, Hi: 0x02ee, Stride: 2}, + {Lo: 0x0345, Hi: 0x0370, Stride: 43}, + {Lo: 0x0371, Hi: 0x0374, Stride: 1}, + {Lo: 0x0376, Hi: 0x0377, Stride: 1}, + {Lo: 0x037a, Hi: 0x037d, Stride: 1}, + {Lo: 0x037f, Hi: 0x0386, Stride: 7}, + {Lo: 0x0388, Hi: 0x038a, Stride: 1}, + {Lo: 0x038c, Hi: 0x038e, Stride: 2}, + {Lo: 0x038f, Hi: 0x03a1, Stride: 1}, + {Lo: 0x03a3, Hi: 0x03f5, Stride: 1}, + {Lo: 0x03f7, Hi: 0x0481, Stride: 1}, + {Lo: 0x048a, Hi: 0x052f, Stride: 1}, + {Lo: 0x0531, Hi: 0x0556, Stride: 1}, + {Lo: 0x0559, Hi: 0x0560, Stride: 7}, + {Lo: 0x0561, Hi: 0x0588, Stride: 1}, + {Lo: 0x05b0, Hi: 0x05bd, Stride: 1}, + {Lo: 0x05bf, Hi: 0x05c1, Stride: 2}, + {Lo: 0x05c2, Hi: 0x05c4, Stride: 2}, + {Lo: 0x05c5, Hi: 0x05c7, Stride: 2}, + {Lo: 0x05d0, Hi: 0x05ea, Stride: 1}, + {Lo: 0x05ef, Hi: 0x05f2, Stride: 1}, + {Lo: 0x0610, Hi: 0x061a, Stride: 1}, + {Lo: 0x0620, Hi: 0x0657, Stride: 1}, + {Lo: 0x0659, Hi: 0x0669, Stride: 1}, + {Lo: 0x066e, Hi: 0x06d3, Stride: 1}, + {Lo: 0x06d5, Hi: 0x06dc, Stride: 1}, + {Lo: 0x06e1, Hi: 0x06e8, Stride: 1}, + {Lo: 0x06ed, Hi: 0x06fc, Stride: 1}, + {Lo: 0x06ff, Hi: 0x0710, Stride: 17}, + {Lo: 0x0711, Hi: 0x073f, Stride: 1}, + {Lo: 0x074d, Hi: 0x07b1, Stride: 1}, + {Lo: 0x07c0, Hi: 0x07ea, Stride: 1}, + {Lo: 0x07f4, Hi: 0x07f5, Stride: 1}, + {Lo: 0x07fa, Hi: 0x0800, Stride: 6}, + {Lo: 0x0801, Hi: 0x0817, Stride: 1}, + {Lo: 0x081a, Hi: 0x082c, Stride: 1}, + {Lo: 0x0840, Hi: 0x0858, Stride: 1}, + {Lo: 0x0860, Hi: 0x086a, Stride: 1}, + {Lo: 0x0870, Hi: 0x0887, Stride: 1}, + {Lo: 0x0889, Hi: 0x088e, Stride: 1}, + {Lo: 0x08a0, Hi: 0x08c9, Stride: 1}, + {Lo: 0x08d4, Hi: 0x08df, Stride: 1}, + {Lo: 0x08e3, Hi: 0x08e9, Stride: 1}, + {Lo: 0x08f0, Hi: 0x093b, Stride: 1}, + {Lo: 0x093d, Hi: 0x094c, Stride: 1}, + {Lo: 0x094e, Hi: 0x0950, Stride: 1}, + {Lo: 0x0955, Hi: 0x0963, Stride: 1}, + {Lo: 0x0966, Hi: 0x096f, Stride: 1}, + {Lo: 0x0971, Hi: 0x0983, Stride: 1}, + {Lo: 0x0985, Hi: 0x098c, Stride: 1}, + {Lo: 0x098f, Hi: 0x0990, Stride: 1}, + {Lo: 0x0993, Hi: 0x09a8, Stride: 1}, + {Lo: 0x09aa, Hi: 0x09b0, Stride: 1}, + {Lo: 0x09b2, Hi: 0x09b6, Stride: 4}, + {Lo: 0x09b7, Hi: 0x09b9, Stride: 1}, + {Lo: 0x09bd, Hi: 0x09c4, Stride: 1}, + {Lo: 0x09c7, Hi: 0x09c8, Stride: 1}, + {Lo: 0x09cb, Hi: 0x09cc, Stride: 1}, + {Lo: 0x09ce, Hi: 0x09d7, Stride: 9}, + {Lo: 0x09dc, Hi: 0x09dd, Stride: 1}, + {Lo: 0x09df, Hi: 0x09e3, Stride: 1}, + {Lo: 0x09e6, Hi: 0x09f1, Stride: 1}, + {Lo: 0x09f4, Hi: 0x09f9, Stride: 1}, + {Lo: 0x09fc, Hi: 0x0a01, Stride: 5}, + {Lo: 0x0a02, Hi: 0x0a03, Stride: 1}, + {Lo: 0x0a05, Hi: 0x0a0a, Stride: 1}, + {Lo: 0x0a0f, Hi: 0x0a10, Stride: 1}, + {Lo: 0x0a13, Hi: 0x0a28, Stride: 1}, + {Lo: 0x0a2a, Hi: 0x0a30, Stride: 1}, + {Lo: 0x0a32, Hi: 0x0a33, Stride: 1}, + {Lo: 0x0a35, Hi: 0x0a36, Stride: 1}, + {Lo: 0x0a38, Hi: 0x0a39, Stride: 1}, + {Lo: 0x0a3e, Hi: 0x0a42, Stride: 1}, + {Lo: 0x0a47, Hi: 0x0a48, Stride: 1}, + {Lo: 0x0a4b, Hi: 0x0a4c, Stride: 1}, + {Lo: 0x0a51, Hi: 0x0a59, Stride: 8}, + {Lo: 0x0a5a, Hi: 0x0a5c, Stride: 1}, + {Lo: 0x0a5e, Hi: 0x0a66, Stride: 8}, + {Lo: 0x0a67, Hi: 0x0a75, Stride: 1}, + {Lo: 0x0a81, Hi: 0x0a83, Stride: 1}, + {Lo: 0x0a85, Hi: 0x0a8d, Stride: 1}, + {Lo: 0x0a8f, Hi: 0x0a91, Stride: 1}, + {Lo: 0x0a93, Hi: 0x0aa8, Stride: 1}, + {Lo: 0x0aaa, Hi: 0x0ab0, Stride: 1}, + {Lo: 0x0ab2, Hi: 0x0ab3, Stride: 1}, + {Lo: 0x0ab5, Hi: 0x0ab9, Stride: 1}, + {Lo: 0x0abd, Hi: 0x0ac5, Stride: 1}, + {Lo: 0x0ac7, Hi: 0x0ac9, Stride: 1}, + {Lo: 0x0acb, Hi: 0x0acc, Stride: 1}, + {Lo: 0x0ad0, Hi: 0x0ae0, Stride: 16}, + {Lo: 0x0ae1, Hi: 0x0ae3, Stride: 1}, + {Lo: 0x0ae6, Hi: 0x0aef, Stride: 1}, + {Lo: 0x0af9, Hi: 0x0afc, Stride: 1}, + {Lo: 0x0b01, Hi: 0x0b03, Stride: 1}, + {Lo: 0x0b05, Hi: 0x0b0c, Stride: 1}, + {Lo: 0x0b0f, Hi: 0x0b10, Stride: 1}, + {Lo: 0x0b13, Hi: 0x0b28, Stride: 1}, + {Lo: 0x0b2a, Hi: 0x0b30, Stride: 1}, + {Lo: 0x0b32, Hi: 0x0b33, Stride: 1}, + {Lo: 0x0b35, Hi: 0x0b39, Stride: 1}, + {Lo: 0x0b3d, Hi: 0x0b44, Stride: 1}, + {Lo: 0x0b47, Hi: 0x0b48, Stride: 1}, + {Lo: 0x0b4b, Hi: 0x0b4c, Stride: 1}, + {Lo: 0x0b56, Hi: 0x0b57, Stride: 1}, + {Lo: 0x0b5c, Hi: 0x0b5d, Stride: 1}, + {Lo: 0x0b5f, Hi: 0x0b63, Stride: 1}, + {Lo: 0x0b66, Hi: 0x0b6f, Stride: 1}, + {Lo: 0x0b71, Hi: 0x0b77, Stride: 1}, + {Lo: 0x0b82, Hi: 0x0b83, Stride: 1}, + {Lo: 0x0b85, Hi: 0x0b8a, Stride: 1}, + {Lo: 0x0b8e, Hi: 0x0b90, Stride: 1}, + {Lo: 0x0b92, Hi: 0x0b95, Stride: 1}, + {Lo: 0x0b99, Hi: 0x0b9a, Stride: 1}, + {Lo: 0x0b9c, Hi: 0x0b9e, Stride: 2}, + {Lo: 0x0b9f, Hi: 0x0ba3, Stride: 4}, + {Lo: 0x0ba4, Hi: 0x0ba8, Stride: 4}, + {Lo: 0x0ba9, Hi: 0x0baa, Stride: 1}, + {Lo: 0x0bae, Hi: 0x0bb9, Stride: 1}, + {Lo: 0x0bbe, Hi: 0x0bc2, Stride: 1}, + {Lo: 0x0bc6, Hi: 0x0bc8, Stride: 1}, + {Lo: 0x0bca, Hi: 0x0bcc, Stride: 1}, + {Lo: 0x0bd0, Hi: 0x0bd7, Stride: 7}, + {Lo: 0x0be6, Hi: 0x0bf2, Stride: 1}, + {Lo: 0x0c00, Hi: 0x0c0c, Stride: 1}, + {Lo: 0x0c0e, Hi: 0x0c10, Stride: 1}, + {Lo: 0x0c12, Hi: 0x0c28, Stride: 1}, + {Lo: 0x0c2a, Hi: 0x0c39, Stride: 1}, + {Lo: 0x0c3d, Hi: 0x0c44, Stride: 1}, + {Lo: 0x0c46, Hi: 0x0c48, Stride: 1}, + {Lo: 0x0c4a, Hi: 0x0c4c, Stride: 1}, + {Lo: 0x0c55, Hi: 0x0c56, Stride: 1}, + {Lo: 0x0c58, Hi: 0x0c5a, Stride: 1}, + {Lo: 0x0c5d, Hi: 0x0c60, Stride: 3}, + {Lo: 0x0c61, Hi: 0x0c63, Stride: 1}, + {Lo: 0x0c66, Hi: 0x0c6f, Stride: 1}, + {Lo: 0x0c78, Hi: 0x0c7e, Stride: 1}, + {Lo: 0x0c80, Hi: 0x0c83, Stride: 1}, + {Lo: 0x0c85, Hi: 0x0c8c, Stride: 1}, + {Lo: 0x0c8e, Hi: 0x0c90, Stride: 1}, + {Lo: 0x0c92, Hi: 0x0ca8, Stride: 1}, + {Lo: 0x0caa, Hi: 0x0cb3, Stride: 1}, + {Lo: 0x0cb5, Hi: 0x0cb9, Stride: 1}, + {Lo: 0x0cbd, Hi: 0x0cc4, Stride: 1}, + {Lo: 0x0cc6, Hi: 0x0cc8, Stride: 1}, + {Lo: 0x0cca, Hi: 0x0ccc, Stride: 1}, + {Lo: 0x0cd5, Hi: 0x0cd6, Stride: 1}, + {Lo: 0x0cdd, Hi: 0x0cde, Stride: 1}, + {Lo: 0x0ce0, Hi: 0x0ce3, Stride: 1}, + {Lo: 0x0ce6, Hi: 0x0cef, Stride: 1}, + {Lo: 0x0cf1, Hi: 0x0cf3, Stride: 1}, + {Lo: 0x0d00, Hi: 0x0d0c, Stride: 1}, + {Lo: 0x0d0e, Hi: 0x0d10, Stride: 1}, + {Lo: 0x0d12, Hi: 0x0d3a, Stride: 1}, + {Lo: 0x0d3d, Hi: 0x0d44, Stride: 1}, + {Lo: 0x0d46, Hi: 0x0d48, Stride: 1}, + {Lo: 0x0d4a, Hi: 0x0d4c, Stride: 1}, + {Lo: 0x0d4e, Hi: 0x0d54, Stride: 6}, + {Lo: 0x0d55, Hi: 0x0d63, Stride: 1}, + {Lo: 0x0d66, Hi: 0x0d78, Stride: 1}, + {Lo: 0x0d7a, Hi: 0x0d7f, Stride: 1}, + {Lo: 0x0d81, Hi: 0x0d83, Stride: 1}, + {Lo: 0x0d85, Hi: 0x0d96, Stride: 1}, + {Lo: 0x0d9a, Hi: 0x0db1, Stride: 1}, + {Lo: 0x0db3, Hi: 0x0dbb, Stride: 1}, + {Lo: 0x0dbd, Hi: 0x0dc0, Stride: 3}, + {Lo: 0x0dc1, Hi: 0x0dc6, Stride: 1}, + {Lo: 0x0dcf, Hi: 0x0dd4, Stride: 1}, + {Lo: 0x0dd6, Hi: 0x0dd8, Stride: 2}, + {Lo: 0x0dd9, Hi: 0x0ddf, Stride: 1}, + {Lo: 0x0de6, Hi: 0x0def, Stride: 1}, + {Lo: 0x0df2, Hi: 0x0df3, Stride: 1}, + {Lo: 0x0e01, Hi: 0x0e3a, Stride: 1}, + {Lo: 0x0e40, Hi: 0x0e46, Stride: 1}, + {Lo: 0x0e4d, Hi: 0x0e50, Stride: 3}, + {Lo: 0x0e51, Hi: 0x0e59, Stride: 1}, + {Lo: 0x0e81, Hi: 0x0e82, Stride: 1}, + {Lo: 0x0e84, Hi: 0x0e86, Stride: 2}, + {Lo: 0x0e87, Hi: 0x0e8a, Stride: 1}, + {Lo: 0x0e8c, Hi: 0x0ea3, Stride: 1}, + {Lo: 0x0ea5, Hi: 0x0ea7, Stride: 2}, + {Lo: 0x0ea8, Hi: 0x0eb9, Stride: 1}, + {Lo: 0x0ebb, Hi: 0x0ebd, Stride: 1}, + {Lo: 0x0ec0, Hi: 0x0ec4, Stride: 1}, + {Lo: 0x0ec6, Hi: 0x0ecd, Stride: 7}, + {Lo: 0x0ed0, Hi: 0x0ed9, Stride: 1}, + {Lo: 0x0edc, Hi: 0x0edf, Stride: 1}, + {Lo: 0x0f00, Hi: 0x0f20, Stride: 32}, + {Lo: 0x0f21, Hi: 0x0f33, Stride: 1}, + {Lo: 0x0f40, Hi: 0x0f47, Stride: 1}, + {Lo: 0x0f49, Hi: 0x0f6c, Stride: 1}, + {Lo: 0x0f71, Hi: 0x0f83, Stride: 1}, + {Lo: 0x0f88, Hi: 0x0f97, Stride: 1}, + {Lo: 0x0f99, Hi: 0x0fbc, Stride: 1}, + {Lo: 0x1000, Hi: 0x1036, Stride: 1}, + {Lo: 0x1038, Hi: 0x103b, Stride: 3}, + {Lo: 0x103c, Hi: 0x1049, Stride: 1}, + {Lo: 0x1050, Hi: 0x109d, Stride: 1}, + {Lo: 0x10a0, Hi: 0x10c5, Stride: 1}, + {Lo: 0x10c7, Hi: 0x10cd, Stride: 6}, + {Lo: 0x10d0, Hi: 0x10fa, Stride: 1}, + {Lo: 0x10fc, Hi: 0x1248, Stride: 1}, + {Lo: 0x124a, Hi: 0x124d, Stride: 1}, + {Lo: 0x1250, Hi: 0x1256, Stride: 1}, + {Lo: 0x1258, Hi: 0x125a, Stride: 2}, + {Lo: 0x125b, Hi: 0x125d, Stride: 1}, + {Lo: 0x1260, Hi: 0x1288, Stride: 1}, + {Lo: 0x128a, Hi: 0x128d, Stride: 1}, + {Lo: 0x1290, Hi: 0x12b0, Stride: 1}, + {Lo: 0x12b2, Hi: 0x12b5, Stride: 1}, + {Lo: 0x12b8, Hi: 0x12be, Stride: 1}, + {Lo: 0x12c0, Hi: 0x12c2, Stride: 2}, + {Lo: 0x12c3, Hi: 0x12c5, Stride: 1}, + {Lo: 0x12c8, Hi: 0x12d6, Stride: 1}, + {Lo: 0x12d8, Hi: 0x1310, Stride: 1}, + {Lo: 0x1312, Hi: 0x1315, Stride: 1}, + {Lo: 0x1318, Hi: 0x135a, Stride: 1}, + {Lo: 0x1369, Hi: 0x137c, Stride: 1}, + {Lo: 0x1380, Hi: 0x138f, Stride: 1}, + {Lo: 0x13a0, Hi: 0x13f5, Stride: 1}, + {Lo: 0x13f8, Hi: 0x13fd, Stride: 1}, + {Lo: 0x1401, Hi: 0x166c, Stride: 1}, + {Lo: 0x166f, Hi: 0x167f, Stride: 1}, + {Lo: 0x1681, Hi: 0x169a, Stride: 1}, + {Lo: 0x16a0, Hi: 0x16ea, Stride: 1}, + {Lo: 0x16ee, Hi: 0x16f8, Stride: 1}, + {Lo: 0x1700, Hi: 0x1713, Stride: 1}, + {Lo: 0x171f, Hi: 0x1733, Stride: 1}, + {Lo: 0x1740, Hi: 0x1753, Stride: 1}, + {Lo: 0x1760, Hi: 0x176c, Stride: 1}, + {Lo: 0x176e, Hi: 0x1770, Stride: 1}, + {Lo: 0x1772, Hi: 0x1773, Stride: 1}, + {Lo: 0x1780, Hi: 0x17b3, Stride: 1}, + {Lo: 0x17b6, Hi: 0x17c8, Stride: 1}, + {Lo: 0x17d7, Hi: 0x17dc, Stride: 5}, + {Lo: 0x17e0, Hi: 0x17e9, Stride: 1}, + {Lo: 0x17f0, Hi: 0x17f9, Stride: 1}, + {Lo: 0x1810, Hi: 0x1819, Stride: 1}, + {Lo: 0x1820, Hi: 0x1878, Stride: 1}, + {Lo: 0x1880, Hi: 0x18aa, Stride: 1}, + {Lo: 0x18b0, Hi: 0x18f5, Stride: 1}, + {Lo: 0x1900, Hi: 0x191e, Stride: 1}, + {Lo: 0x1920, Hi: 0x192b, Stride: 1}, + {Lo: 0x1930, Hi: 0x1938, Stride: 1}, + {Lo: 0x1946, Hi: 0x196d, Stride: 1}, + {Lo: 0x1970, Hi: 0x1974, Stride: 1}, + {Lo: 0x1980, Hi: 0x19ab, Stride: 1}, + {Lo: 0x19b0, Hi: 0x19c9, Stride: 1}, + {Lo: 0x19d0, Hi: 0x19da, Stride: 1}, + {Lo: 0x1a00, Hi: 0x1a1b, Stride: 1}, + {Lo: 0x1a20, Hi: 0x1a5e, Stride: 1}, + {Lo: 0x1a61, Hi: 0x1a74, Stride: 1}, + {Lo: 0x1a80, Hi: 0x1a89, Stride: 1}, + {Lo: 0x1a90, Hi: 0x1a99, Stride: 1}, + {Lo: 0x1aa7, Hi: 0x1abf, Stride: 24}, + {Lo: 0x1ac0, Hi: 0x1acc, Stride: 12}, + {Lo: 0x1acd, Hi: 0x1ace, Stride: 1}, + {Lo: 0x1b00, Hi: 0x1b33, Stride: 1}, + {Lo: 0x1b35, Hi: 0x1b43, Stride: 1}, + {Lo: 0x1b45, Hi: 0x1b4c, Stride: 1}, + {Lo: 0x1b50, Hi: 0x1b59, Stride: 1}, + {Lo: 0x1b80, Hi: 0x1ba9, Stride: 1}, + {Lo: 0x1bac, Hi: 0x1be5, Stride: 1}, + {Lo: 0x1be7, Hi: 0x1bf1, Stride: 1}, + {Lo: 0x1c00, Hi: 0x1c36, Stride: 1}, + {Lo: 0x1c40, Hi: 0x1c49, Stride: 1}, + {Lo: 0x1c4d, Hi: 0x1c7d, Stride: 1}, + {Lo: 0x1c80, Hi: 0x1c88, Stride: 1}, + {Lo: 0x1c90, Hi: 0x1cba, Stride: 1}, + {Lo: 0x1cbd, Hi: 0x1cbf, Stride: 1}, + {Lo: 0x1ce9, Hi: 0x1cec, Stride: 1}, + {Lo: 0x1cee, Hi: 0x1cf3, Stride: 1}, + {Lo: 0x1cf5, Hi: 0x1cf6, Stride: 1}, + {Lo: 0x1cfa, Hi: 0x1d00, Stride: 6}, + {Lo: 0x1d01, Hi: 0x1dbf, Stride: 1}, + {Lo: 0x1de7, Hi: 0x1df4, Stride: 1}, + {Lo: 0x1e00, Hi: 0x1f15, Stride: 1}, + {Lo: 0x1f18, Hi: 0x1f1d, Stride: 1}, + {Lo: 0x1f20, Hi: 0x1f45, Stride: 1}, + {Lo: 0x1f48, Hi: 0x1f4d, Stride: 1}, + {Lo: 0x1f50, Hi: 0x1f57, Stride: 1}, + {Lo: 0x1f59, Hi: 0x1f5f, Stride: 2}, + {Lo: 0x1f60, Hi: 0x1f7d, Stride: 1}, + {Lo: 0x1f80, Hi: 0x1fb4, Stride: 1}, + {Lo: 0x1fb6, Hi: 0x1fbc, Stride: 1}, + {Lo: 0x1fbe, Hi: 0x1fc2, Stride: 4}, + {Lo: 0x1fc3, Hi: 0x1fc4, Stride: 1}, + {Lo: 0x1fc6, Hi: 0x1fcc, Stride: 1}, + {Lo: 0x1fd0, Hi: 0x1fd3, Stride: 1}, + {Lo: 0x1fd6, Hi: 0x1fdb, Stride: 1}, + {Lo: 0x1fe0, Hi: 0x1fec, Stride: 1}, + {Lo: 0x1ff2, Hi: 0x1ff4, Stride: 1}, + {Lo: 0x1ff6, Hi: 0x1ffc, Stride: 1}, + {Lo: 0x2070, Hi: 0x2071, Stride: 1}, + {Lo: 0x2074, Hi: 0x2079, Stride: 1}, + {Lo: 0x207f, Hi: 0x2089, Stride: 1}, + {Lo: 0x2090, Hi: 0x209c, Stride: 1}, + {Lo: 0x2102, Hi: 0x2107, Stride: 5}, + {Lo: 0x210a, Hi: 0x2113, Stride: 1}, + {Lo: 0x2115, Hi: 0x2119, Stride: 4}, + {Lo: 0x211a, Hi: 0x211d, Stride: 1}, + {Lo: 0x2124, Hi: 0x212a, Stride: 2}, + {Lo: 0x212b, Hi: 0x212d, Stride: 1}, + {Lo: 0x212f, Hi: 0x2139, Stride: 1}, + {Lo: 0x213c, Hi: 0x213f, Stride: 1}, + {Lo: 0x2145, Hi: 0x2149, Stride: 1}, + {Lo: 0x214e, Hi: 0x2150, Stride: 2}, + {Lo: 0x2151, Hi: 0x2189, Stride: 1}, + {Lo: 0x2460, Hi: 0x249b, Stride: 1}, + {Lo: 0x24b6, Hi: 0x24ff, Stride: 1}, + {Lo: 0x2776, Hi: 0x2793, Stride: 1}, + {Lo: 0x2c00, Hi: 0x2ce4, Stride: 1}, + {Lo: 0x2ceb, Hi: 0x2cee, Stride: 1}, + {Lo: 0x2cf2, Hi: 0x2cf3, Stride: 1}, + {Lo: 0x2cfd, Hi: 0x2d00, Stride: 3}, + {Lo: 0x2d01, Hi: 0x2d25, Stride: 1}, + {Lo: 0x2d27, Hi: 0x2d2d, Stride: 6}, + {Lo: 0x2d30, Hi: 0x2d67, Stride: 1}, + {Lo: 0x2d6f, Hi: 0x2d80, Stride: 17}, + {Lo: 0x2d81, Hi: 0x2d96, Stride: 1}, + {Lo: 0x2da0, Hi: 0x2da6, Stride: 1}, + {Lo: 0x2da8, Hi: 0x2dae, Stride: 1}, + {Lo: 0x2db0, Hi: 0x2db6, Stride: 1}, + {Lo: 0x2db8, Hi: 0x2dbe, Stride: 1}, + {Lo: 0x2dc0, Hi: 0x2dc6, Stride: 1}, + {Lo: 0x2dc8, Hi: 0x2dce, Stride: 1}, + {Lo: 0x2dd0, Hi: 0x2dd6, Stride: 1}, + {Lo: 0x2dd8, Hi: 0x2dde, Stride: 1}, + {Lo: 0x2de0, Hi: 0x2dff, Stride: 1}, + {Lo: 0x2e2f, Hi: 0x3005, Stride: 470}, + {Lo: 0x3006, Hi: 0x3007, Stride: 1}, + {Lo: 0x3021, Hi: 0x3029, Stride: 1}, + {Lo: 0x3031, Hi: 0x3035, Stride: 1}, + {Lo: 0x3038, Hi: 0x303c, Stride: 1}, + {Lo: 0x3041, Hi: 0x3096, Stride: 1}, + {Lo: 0x309d, Hi: 0x309f, Stride: 1}, + {Lo: 0x30a1, Hi: 0x30fa, Stride: 1}, + {Lo: 0x30fc, Hi: 0x30ff, Stride: 1}, + {Lo: 0x3105, Hi: 0x312f, Stride: 1}, + {Lo: 0x3131, Hi: 0x318e, Stride: 1}, + {Lo: 0x3192, Hi: 0x3195, Stride: 1}, + {Lo: 0x31a0, Hi: 0x31bf, Stride: 1}, + {Lo: 0x31f0, Hi: 0x31ff, Stride: 1}, + {Lo: 0x3220, Hi: 0x3229, Stride: 1}, + {Lo: 0x3248, Hi: 0x324f, Stride: 1}, + {Lo: 0x3251, Hi: 0x325f, Stride: 1}, + {Lo: 0x3280, Hi: 0x3289, Stride: 1}, + {Lo: 0x32b1, Hi: 0x32bf, Stride: 1}, + {Lo: 0x3400, Hi: 0x4dbf, Stride: 1}, + {Lo: 0x4e00, Hi: 0xa48c, Stride: 1}, + {Lo: 0xa4d0, Hi: 0xa4fd, Stride: 1}, + {Lo: 0xa500, Hi: 0xa60c, Stride: 1}, + {Lo: 0xa610, Hi: 0xa62b, Stride: 1}, + {Lo: 0xa640, Hi: 0xa66e, Stride: 1}, + {Lo: 0xa674, Hi: 0xa67b, Stride: 1}, + {Lo: 0xa67f, Hi: 0xa6ef, Stride: 1}, + {Lo: 0xa717, Hi: 0xa71f, Stride: 1}, + {Lo: 0xa722, Hi: 0xa788, Stride: 1}, + {Lo: 0xa78b, Hi: 0xa7ca, Stride: 1}, + {Lo: 0xa7d0, Hi: 0xa7d1, Stride: 1}, + {Lo: 0xa7d3, Hi: 0xa7d5, Stride: 2}, + {Lo: 0xa7d6, Hi: 0xa7d9, Stride: 1}, + {Lo: 0xa7f2, Hi: 0xa805, Stride: 1}, + {Lo: 0xa807, Hi: 0xa827, Stride: 1}, + {Lo: 0xa830, Hi: 0xa835, Stride: 1}, + {Lo: 0xa840, Hi: 0xa873, Stride: 1}, + {Lo: 0xa880, Hi: 0xa8c3, Stride: 1}, + {Lo: 0xa8c5, Hi: 0xa8d0, Stride: 11}, + {Lo: 0xa8d1, Hi: 0xa8d9, Stride: 1}, + {Lo: 0xa8f2, Hi: 0xa8f7, Stride: 1}, + {Lo: 0xa8fb, Hi: 0xa8fd, Stride: 2}, + {Lo: 0xa8fe, Hi: 0xa92a, Stride: 1}, + {Lo: 0xa930, Hi: 0xa952, Stride: 1}, + {Lo: 0xa960, Hi: 0xa97c, Stride: 1}, + {Lo: 0xa980, Hi: 0xa9b2, Stride: 1}, + {Lo: 0xa9b4, Hi: 0xa9bf, Stride: 1}, + {Lo: 0xa9cf, Hi: 0xa9d9, Stride: 1}, + {Lo: 0xa9e0, Hi: 0xa9fe, Stride: 1}, + {Lo: 0xaa00, Hi: 0xaa36, Stride: 1}, + {Lo: 0xaa40, Hi: 0xaa4d, Stride: 1}, + {Lo: 0xaa50, Hi: 0xaa59, Stride: 1}, + {Lo: 0xaa60, Hi: 0xaa76, Stride: 1}, + {Lo: 0xaa7a, Hi: 0xaabe, Stride: 1}, + {Lo: 0xaac0, Hi: 0xaac2, Stride: 2}, + {Lo: 0xaadb, Hi: 0xaadd, Stride: 1}, + {Lo: 0xaae0, Hi: 0xaaef, Stride: 1}, + {Lo: 0xaaf2, Hi: 0xaaf5, Stride: 1}, + {Lo: 0xab01, Hi: 0xab06, Stride: 1}, + {Lo: 0xab09, Hi: 0xab0e, Stride: 1}, + {Lo: 0xab11, Hi: 0xab16, Stride: 1}, + {Lo: 0xab20, Hi: 0xab26, Stride: 1}, + {Lo: 0xab28, Hi: 0xab2e, Stride: 1}, + {Lo: 0xab30, Hi: 0xab5a, Stride: 1}, + {Lo: 0xab5c, Hi: 0xab69, Stride: 1}, + {Lo: 0xab70, Hi: 0xabea, Stride: 1}, + {Lo: 0xabf0, Hi: 0xabf9, Stride: 1}, + {Lo: 0xac00, Hi: 0xd7a3, Stride: 1}, + {Lo: 0xd7b0, Hi: 0xd7c6, Stride: 1}, + {Lo: 0xd7cb, Hi: 0xd7fb, Stride: 1}, + {Lo: 0xf900, Hi: 0xfa6d, Stride: 1}, + {Lo: 0xfa70, Hi: 0xfad9, Stride: 1}, + {Lo: 0xfb00, Hi: 0xfb06, Stride: 1}, + {Lo: 0xfb13, Hi: 0xfb17, Stride: 1}, + {Lo: 0xfb1d, Hi: 0xfb28, Stride: 1}, + {Lo: 0xfb2a, Hi: 0xfb36, Stride: 1}, + {Lo: 0xfb38, Hi: 0xfb3c, Stride: 1}, + {Lo: 0xfb3e, Hi: 0xfb40, Stride: 2}, + {Lo: 0xfb41, Hi: 0xfb43, Stride: 2}, + {Lo: 0xfb44, Hi: 0xfb46, Stride: 2}, + {Lo: 0xfb47, Hi: 0xfbb1, Stride: 1}, + {Lo: 0xfbd3, Hi: 0xfd3d, Stride: 1}, + {Lo: 0xfd50, Hi: 0xfd8f, Stride: 1}, + {Lo: 0xfd92, Hi: 0xfdc7, Stride: 1}, + {Lo: 0xfdf0, Hi: 0xfdfb, Stride: 1}, + {Lo: 0xfe70, Hi: 0xfe74, Stride: 1}, + {Lo: 0xfe76, Hi: 0xfefc, Stride: 1}, + {Lo: 0xff10, Hi: 0xff19, Stride: 1}, + {Lo: 0xff21, Hi: 0xff3a, Stride: 1}, + {Lo: 0xff41, Hi: 0xff5a, Stride: 1}, + {Lo: 0xff66, Hi: 0xffbe, Stride: 1}, + {Lo: 0xffc2, Hi: 0xffc7, Stride: 1}, + {Lo: 0xffca, Hi: 0xffcf, Stride: 1}, + {Lo: 0xffd2, Hi: 0xffd7, Stride: 1}, + {Lo: 0xffda, Hi: 0xffdc, Stride: 1}, + }, + R32: []unicode.Range32{ + {Lo: 0x10000, Hi: 0x1000b, Stride: 1}, + {Lo: 0x1000d, Hi: 0x10026, Stride: 1}, + {Lo: 0x10028, Hi: 0x1003a, Stride: 1}, + {Lo: 0x1003c, Hi: 0x1003d, Stride: 1}, + {Lo: 0x1003f, Hi: 0x1004d, Stride: 1}, + {Lo: 0x10050, Hi: 0x1005d, Stride: 1}, + {Lo: 0x10080, Hi: 0x100fa, Stride: 1}, + {Lo: 0x10107, Hi: 0x10133, Stride: 1}, + {Lo: 0x10140, Hi: 0x10178, Stride: 1}, + {Lo: 0x1018a, Hi: 0x1018b, Stride: 1}, + {Lo: 0x10280, Hi: 0x1029c, Stride: 1}, + {Lo: 0x102a0, Hi: 0x102d0, Stride: 1}, + {Lo: 0x102e1, Hi: 0x102fb, Stride: 1}, + {Lo: 0x10300, Hi: 0x10323, Stride: 1}, + {Lo: 0x1032d, Hi: 0x1034a, Stride: 1}, + {Lo: 0x10350, Hi: 0x1037a, Stride: 1}, + {Lo: 0x10380, Hi: 0x1039d, Stride: 1}, + {Lo: 0x103a0, Hi: 0x103c3, Stride: 1}, + {Lo: 0x103c8, Hi: 0x103cf, Stride: 1}, + {Lo: 0x103d1, Hi: 0x103d5, Stride: 1}, + {Lo: 0x10400, Hi: 0x1049d, Stride: 1}, + {Lo: 0x104a0, Hi: 0x104a9, Stride: 1}, + {Lo: 0x104b0, Hi: 0x104d3, Stride: 1}, + {Lo: 0x104d8, Hi: 0x104fb, Stride: 1}, + {Lo: 0x10500, Hi: 0x10527, Stride: 1}, + {Lo: 0x10530, Hi: 0x10563, Stride: 1}, + {Lo: 0x10570, Hi: 0x1057a, Stride: 1}, + {Lo: 0x1057c, Hi: 0x1058a, Stride: 1}, + {Lo: 0x1058c, Hi: 0x10592, Stride: 1}, + {Lo: 0x10594, Hi: 0x10595, Stride: 1}, + {Lo: 0x10597, Hi: 0x105a1, Stride: 1}, + {Lo: 0x105a3, Hi: 0x105b1, Stride: 1}, + {Lo: 0x105b3, Hi: 0x105b9, Stride: 1}, + {Lo: 0x105bb, Hi: 0x105bc, Stride: 1}, + {Lo: 0x10600, Hi: 0x10736, Stride: 1}, + {Lo: 0x10740, Hi: 0x10755, Stride: 1}, + {Lo: 0x10760, Hi: 0x10767, Stride: 1}, + {Lo: 0x10780, Hi: 0x10785, Stride: 1}, + {Lo: 0x10787, Hi: 0x107b0, Stride: 1}, + {Lo: 0x107b2, Hi: 0x107ba, Stride: 1}, + {Lo: 0x10800, Hi: 0x10805, Stride: 1}, + {Lo: 0x10808, Hi: 0x1080a, Stride: 2}, + {Lo: 0x1080b, Hi: 0x10835, Stride: 1}, + {Lo: 0x10837, Hi: 0x10838, Stride: 1}, + {Lo: 0x1083c, Hi: 0x1083f, Stride: 3}, + {Lo: 0x10840, Hi: 0x10855, Stride: 1}, + {Lo: 0x10858, Hi: 0x10876, Stride: 1}, + {Lo: 0x10879, Hi: 0x1089e, Stride: 1}, + {Lo: 0x108a7, Hi: 0x108af, Stride: 1}, + {Lo: 0x108e0, Hi: 0x108f2, Stride: 1}, + {Lo: 0x108f4, Hi: 0x108f5, Stride: 1}, + {Lo: 0x108fb, Hi: 0x1091b, Stride: 1}, + {Lo: 0x10920, Hi: 0x10939, Stride: 1}, + {Lo: 0x10980, Hi: 0x109b7, Stride: 1}, + {Lo: 0x109bc, Hi: 0x109cf, Stride: 1}, + {Lo: 0x109d2, Hi: 0x10a03, Stride: 1}, + {Lo: 0x10a05, Hi: 0x10a06, Stride: 1}, + {Lo: 0x10a0c, Hi: 0x10a13, Stride: 1}, + {Lo: 0x10a15, Hi: 0x10a17, Stride: 1}, + {Lo: 0x10a19, Hi: 0x10a35, Stride: 1}, + {Lo: 0x10a40, Hi: 0x10a48, Stride: 1}, + {Lo: 0x10a60, Hi: 0x10a7e, Stride: 1}, + {Lo: 0x10a80, Hi: 0x10a9f, Stride: 1}, + {Lo: 0x10ac0, Hi: 0x10ac7, Stride: 1}, + {Lo: 0x10ac9, Hi: 0x10ae4, Stride: 1}, + {Lo: 0x10aeb, Hi: 0x10aef, Stride: 1}, + {Lo: 0x10b00, Hi: 0x10b35, Stride: 1}, + {Lo: 0x10b40, Hi: 0x10b55, Stride: 1}, + {Lo: 0x10b58, Hi: 0x10b72, Stride: 1}, + {Lo: 0x10b78, Hi: 0x10b91, Stride: 1}, + {Lo: 0x10ba9, Hi: 0x10baf, Stride: 1}, + {Lo: 0x10c00, Hi: 0x10c48, Stride: 1}, + {Lo: 0x10c80, Hi: 0x10cb2, Stride: 1}, + {Lo: 0x10cc0, Hi: 0x10cf2, Stride: 1}, + {Lo: 0x10cfa, Hi: 0x10d27, Stride: 1}, + {Lo: 0x10d30, Hi: 0x10d39, Stride: 1}, + {Lo: 0x10e60, Hi: 0x10e7e, Stride: 1}, + {Lo: 0x10e80, Hi: 0x10ea9, Stride: 1}, + {Lo: 0x10eab, Hi: 0x10eac, Stride: 1}, + {Lo: 0x10eb0, Hi: 0x10eb1, Stride: 1}, + {Lo: 0x10f00, Hi: 0x10f27, Stride: 1}, + {Lo: 0x10f30, Hi: 0x10f45, Stride: 1}, + {Lo: 0x10f51, Hi: 0x10f54, Stride: 1}, + {Lo: 0x10f70, Hi: 0x10f81, Stride: 1}, + {Lo: 0x10fb0, Hi: 0x10fcb, Stride: 1}, + {Lo: 0x10fe0, Hi: 0x10ff6, Stride: 1}, + {Lo: 0x11000, Hi: 0x11045, Stride: 1}, + {Lo: 0x11052, Hi: 0x1106f, Stride: 1}, + {Lo: 0x11071, Hi: 0x11075, Stride: 1}, + {Lo: 0x11080, Hi: 0x110b8, Stride: 1}, + {Lo: 0x110c2, Hi: 0x110d0, Stride: 14}, + {Lo: 0x110d1, Hi: 0x110e8, Stride: 1}, + {Lo: 0x110f0, Hi: 0x110f9, Stride: 1}, + {Lo: 0x11100, Hi: 0x11132, Stride: 1}, + {Lo: 0x11136, Hi: 0x1113f, Stride: 1}, + {Lo: 0x11144, Hi: 0x11147, Stride: 1}, + {Lo: 0x11150, Hi: 0x11172, Stride: 1}, + {Lo: 0x11176, Hi: 0x11180, Stride: 10}, + {Lo: 0x11181, Hi: 0x111bf, Stride: 1}, + {Lo: 0x111c1, Hi: 0x111c4, Stride: 1}, + {Lo: 0x111ce, Hi: 0x111da, Stride: 1}, + {Lo: 0x111dc, Hi: 0x111e1, Stride: 5}, + {Lo: 0x111e2, Hi: 0x111f4, Stride: 1}, + {Lo: 0x11200, Hi: 0x11211, Stride: 1}, + {Lo: 0x11213, Hi: 0x11234, Stride: 1}, + {Lo: 0x11237, Hi: 0x1123e, Stride: 7}, + {Lo: 0x1123f, Hi: 0x11241, Stride: 1}, + {Lo: 0x11280, Hi: 0x11286, Stride: 1}, + {Lo: 0x11288, Hi: 0x1128a, Stride: 2}, + {Lo: 0x1128b, Hi: 0x1128d, Stride: 1}, + {Lo: 0x1128f, Hi: 0x1129d, Stride: 1}, + {Lo: 0x1129f, Hi: 0x112a8, Stride: 1}, + {Lo: 0x112b0, Hi: 0x112e8, Stride: 1}, + {Lo: 0x112f0, Hi: 0x112f9, Stride: 1}, + {Lo: 0x11300, Hi: 0x11303, Stride: 1}, + {Lo: 0x11305, Hi: 0x1130c, Stride: 1}, + {Lo: 0x1130f, Hi: 0x11310, Stride: 1}, + {Lo: 0x11313, Hi: 0x11328, Stride: 1}, + {Lo: 0x1132a, Hi: 0x11330, Stride: 1}, + {Lo: 0x11332, Hi: 0x11333, Stride: 1}, + {Lo: 0x11335, Hi: 0x11339, Stride: 1}, + {Lo: 0x1133d, Hi: 0x11344, Stride: 1}, + {Lo: 0x11347, Hi: 0x11348, Stride: 1}, + {Lo: 0x1134b, Hi: 0x1134c, Stride: 1}, + {Lo: 0x11350, Hi: 0x11357, Stride: 7}, + {Lo: 0x1135d, Hi: 0x11363, Stride: 1}, + {Lo: 0x11400, Hi: 0x11441, Stride: 1}, + {Lo: 0x11443, Hi: 0x11445, Stride: 1}, + {Lo: 0x11447, Hi: 0x1144a, Stride: 1}, + {Lo: 0x11450, Hi: 0x11459, Stride: 1}, + {Lo: 0x1145f, Hi: 0x11461, Stride: 1}, + {Lo: 0x11480, Hi: 0x114c1, Stride: 1}, + {Lo: 0x114c4, Hi: 0x114c5, Stride: 1}, + {Lo: 0x114c7, Hi: 0x114d0, Stride: 9}, + {Lo: 0x114d1, Hi: 0x114d9, Stride: 1}, + {Lo: 0x11580, Hi: 0x115b5, Stride: 1}, + {Lo: 0x115b8, Hi: 0x115be, Stride: 1}, + {Lo: 0x115d8, Hi: 0x115dd, Stride: 1}, + {Lo: 0x11600, Hi: 0x1163e, Stride: 1}, + {Lo: 0x11640, Hi: 0x11644, Stride: 4}, + {Lo: 0x11650, Hi: 0x11659, Stride: 1}, + {Lo: 0x11680, Hi: 0x116b5, Stride: 1}, + {Lo: 0x116b8, Hi: 0x116c0, Stride: 8}, + {Lo: 0x116c1, Hi: 0x116c9, Stride: 1}, + {Lo: 0x11700, Hi: 0x1171a, Stride: 1}, + {Lo: 0x1171d, Hi: 0x1172a, Stride: 1}, + {Lo: 0x11730, Hi: 0x1173b, Stride: 1}, + {Lo: 0x11740, Hi: 0x11746, Stride: 1}, + {Lo: 0x11800, Hi: 0x11838, Stride: 1}, + {Lo: 0x118a0, Hi: 0x118f2, Stride: 1}, + {Lo: 0x118ff, Hi: 0x11906, Stride: 1}, + {Lo: 0x11909, Hi: 0x1190c, Stride: 3}, + {Lo: 0x1190d, Hi: 0x11913, Stride: 1}, + {Lo: 0x11915, Hi: 0x11916, Stride: 1}, + {Lo: 0x11918, Hi: 0x11935, Stride: 1}, + {Lo: 0x11937, Hi: 0x11938, Stride: 1}, + {Lo: 0x1193b, Hi: 0x1193c, Stride: 1}, + {Lo: 0x1193f, Hi: 0x11942, Stride: 1}, + {Lo: 0x11950, Hi: 0x11959, Stride: 1}, + {Lo: 0x119a0, Hi: 0x119a7, Stride: 1}, + {Lo: 0x119aa, Hi: 0x119d7, Stride: 1}, + {Lo: 0x119da, Hi: 0x119df, Stride: 1}, + {Lo: 0x119e1, Hi: 0x119e3, Stride: 2}, + {Lo: 0x119e4, Hi: 0x11a00, Stride: 28}, + {Lo: 0x11a01, Hi: 0x11a32, Stride: 1}, + {Lo: 0x11a35, Hi: 0x11a3e, Stride: 1}, + {Lo: 0x11a50, Hi: 0x11a97, Stride: 1}, + {Lo: 0x11a9d, Hi: 0x11ab0, Stride: 19}, + {Lo: 0x11ab1, Hi: 0x11af8, Stride: 1}, + {Lo: 0x11c00, Hi: 0x11c08, Stride: 1}, + {Lo: 0x11c0a, Hi: 0x11c36, Stride: 1}, + {Lo: 0x11c38, Hi: 0x11c3e, Stride: 1}, + {Lo: 0x11c40, Hi: 0x11c50, Stride: 16}, + {Lo: 0x11c51, Hi: 0x11c6c, Stride: 1}, + {Lo: 0x11c72, Hi: 0x11c8f, Stride: 1}, + {Lo: 0x11c92, Hi: 0x11ca7, Stride: 1}, + {Lo: 0x11ca9, Hi: 0x11cb6, Stride: 1}, + {Lo: 0x11d00, Hi: 0x11d06, Stride: 1}, + {Lo: 0x11d08, Hi: 0x11d09, Stride: 1}, + {Lo: 0x11d0b, Hi: 0x11d36, Stride: 1}, + {Lo: 0x11d3a, Hi: 0x11d3c, Stride: 2}, + {Lo: 0x11d3d, Hi: 0x11d3f, Stride: 2}, + {Lo: 0x11d40, Hi: 0x11d41, Stride: 1}, + {Lo: 0x11d43, Hi: 0x11d46, Stride: 3}, + {Lo: 0x11d47, Hi: 0x11d50, Stride: 9}, + {Lo: 0x11d51, Hi: 0x11d59, Stride: 1}, + {Lo: 0x11d60, Hi: 0x11d65, Stride: 1}, + {Lo: 0x11d67, Hi: 0x11d68, Stride: 1}, + {Lo: 0x11d6a, Hi: 0x11d8e, Stride: 1}, + {Lo: 0x11d90, Hi: 0x11d91, Stride: 1}, + {Lo: 0x11d93, Hi: 0x11d96, Stride: 1}, + {Lo: 0x11d98, Hi: 0x11da0, Stride: 8}, + {Lo: 0x11da1, Hi: 0x11da9, Stride: 1}, + {Lo: 0x11ee0, Hi: 0x11ef6, Stride: 1}, + {Lo: 0x11f00, Hi: 0x11f10, Stride: 1}, + {Lo: 0x11f12, Hi: 0x11f3a, Stride: 1}, + {Lo: 0x11f3e, Hi: 0x11f40, Stride: 1}, + {Lo: 0x11f50, Hi: 0x11f59, Stride: 1}, + {Lo: 0x11fb0, Hi: 0x11fc0, Stride: 16}, + {Lo: 0x11fc1, Hi: 0x11fd4, Stride: 1}, + {Lo: 0x12000, Hi: 0x12399, Stride: 1}, + {Lo: 0x12400, Hi: 0x1246e, Stride: 1}, + {Lo: 0x12480, Hi: 0x12543, Stride: 1}, + {Lo: 0x12f90, Hi: 0x12ff0, Stride: 1}, + {Lo: 0x13000, Hi: 0x1342f, Stride: 1}, + {Lo: 0x13441, Hi: 0x13446, Stride: 1}, + {Lo: 0x14400, Hi: 0x14646, Stride: 1}, + {Lo: 0x16800, Hi: 0x16a38, Stride: 1}, + {Lo: 0x16a40, Hi: 0x16a5e, Stride: 1}, + {Lo: 0x16a60, Hi: 0x16a69, Stride: 1}, + {Lo: 0x16a70, Hi: 0x16abe, Stride: 1}, + {Lo: 0x16ac0, Hi: 0x16ac9, Stride: 1}, + {Lo: 0x16ad0, Hi: 0x16aed, Stride: 1}, + {Lo: 0x16b00, Hi: 0x16b2f, Stride: 1}, + {Lo: 0x16b40, Hi: 0x16b43, Stride: 1}, + {Lo: 0x16b50, Hi: 0x16b59, Stride: 1}, + {Lo: 0x16b5b, Hi: 0x16b61, Stride: 1}, + {Lo: 0x16b63, Hi: 0x16b77, Stride: 1}, + {Lo: 0x16b7d, Hi: 0x16b8f, Stride: 1}, + {Lo: 0x16e40, Hi: 0x16e96, Stride: 1}, + {Lo: 0x16f00, Hi: 0x16f4a, Stride: 1}, + {Lo: 0x16f4f, Hi: 0x16f87, Stride: 1}, + {Lo: 0x16f8f, Hi: 0x16f9f, Stride: 1}, + {Lo: 0x16fe0, Hi: 0x16fe1, Stride: 1}, + {Lo: 0x16fe3, Hi: 0x16ff0, Stride: 13}, + {Lo: 0x16ff1, Hi: 0x17000, Stride: 15}, + {Lo: 0x17001, Hi: 0x187f7, Stride: 1}, + {Lo: 0x18800, Hi: 0x18cd5, Stride: 1}, + {Lo: 0x18d00, Hi: 0x18d08, Stride: 1}, + {Lo: 0x1aff0, Hi: 0x1aff3, Stride: 1}, + {Lo: 0x1aff5, Hi: 0x1affb, Stride: 1}, + {Lo: 0x1affd, Hi: 0x1affe, Stride: 1}, + {Lo: 0x1b000, Hi: 0x1b122, Stride: 1}, + {Lo: 0x1b132, Hi: 0x1b150, Stride: 30}, + {Lo: 0x1b151, Hi: 0x1b152, Stride: 1}, + {Lo: 0x1b155, Hi: 0x1b164, Stride: 15}, + {Lo: 0x1b165, Hi: 0x1b167, Stride: 1}, + {Lo: 0x1b170, Hi: 0x1b2fb, Stride: 1}, + {Lo: 0x1bc00, Hi: 0x1bc6a, Stride: 1}, + {Lo: 0x1bc70, Hi: 0x1bc7c, Stride: 1}, + {Lo: 0x1bc80, Hi: 0x1bc88, Stride: 1}, + {Lo: 0x1bc90, Hi: 0x1bc99, Stride: 1}, + {Lo: 0x1bc9e, Hi: 0x1d2c0, Stride: 5666}, + {Lo: 0x1d2c1, Hi: 0x1d2d3, Stride: 1}, + {Lo: 0x1d2e0, Hi: 0x1d2f3, Stride: 1}, + {Lo: 0x1d360, Hi: 0x1d378, Stride: 1}, + {Lo: 0x1d400, Hi: 0x1d454, Stride: 1}, + {Lo: 0x1d456, Hi: 0x1d49c, Stride: 1}, + {Lo: 0x1d49e, Hi: 0x1d49f, Stride: 1}, + {Lo: 0x1d4a2, Hi: 0x1d4a5, Stride: 3}, + {Lo: 0x1d4a6, Hi: 0x1d4a9, Stride: 3}, + {Lo: 0x1d4aa, Hi: 0x1d4ac, Stride: 1}, + {Lo: 0x1d4ae, Hi: 0x1d4b9, Stride: 1}, + {Lo: 0x1d4bb, Hi: 0x1d4bd, Stride: 2}, + {Lo: 0x1d4be, Hi: 0x1d4c3, Stride: 1}, + {Lo: 0x1d4c5, Hi: 0x1d505, Stride: 1}, + {Lo: 0x1d507, Hi: 0x1d50a, Stride: 1}, + {Lo: 0x1d50d, Hi: 0x1d514, Stride: 1}, + {Lo: 0x1d516, Hi: 0x1d51c, Stride: 1}, + {Lo: 0x1d51e, Hi: 0x1d539, Stride: 1}, + {Lo: 0x1d53b, Hi: 0x1d53e, Stride: 1}, + {Lo: 0x1d540, Hi: 0x1d544, Stride: 1}, + {Lo: 0x1d546, Hi: 0x1d54a, Stride: 4}, + {Lo: 0x1d54b, Hi: 0x1d550, Stride: 1}, + {Lo: 0x1d552, Hi: 0x1d6a5, Stride: 1}, + {Lo: 0x1d6a8, Hi: 0x1d6c0, Stride: 1}, + {Lo: 0x1d6c2, Hi: 0x1d6da, Stride: 1}, + {Lo: 0x1d6dc, Hi: 0x1d6fa, Stride: 1}, + {Lo: 0x1d6fc, Hi: 0x1d714, Stride: 1}, + {Lo: 0x1d716, Hi: 0x1d734, Stride: 1}, + {Lo: 0x1d736, Hi: 0x1d74e, Stride: 1}, + {Lo: 0x1d750, Hi: 0x1d76e, Stride: 1}, + {Lo: 0x1d770, Hi: 0x1d788, Stride: 1}, + {Lo: 0x1d78a, Hi: 0x1d7a8, Stride: 1}, + {Lo: 0x1d7aa, Hi: 0x1d7c2, Stride: 1}, + {Lo: 0x1d7c4, Hi: 0x1d7cb, Stride: 1}, + {Lo: 0x1d7ce, Hi: 0x1d7ff, Stride: 1}, + {Lo: 0x1df00, Hi: 0x1df1e, Stride: 1}, + {Lo: 0x1df25, Hi: 0x1df2a, Stride: 1}, + {Lo: 0x1e000, Hi: 0x1e006, Stride: 1}, + {Lo: 0x1e008, Hi: 0x1e018, Stride: 1}, + {Lo: 0x1e01b, Hi: 0x1e021, Stride: 1}, + {Lo: 0x1e023, Hi: 0x1e024, Stride: 1}, + {Lo: 0x1e026, Hi: 0x1e02a, Stride: 1}, + {Lo: 0x1e030, Hi: 0x1e06d, Stride: 1}, + {Lo: 0x1e08f, Hi: 0x1e100, Stride: 113}, + {Lo: 0x1e101, Hi: 0x1e12c, Stride: 1}, + {Lo: 0x1e137, Hi: 0x1e13d, Stride: 1}, + {Lo: 0x1e140, Hi: 0x1e149, Stride: 1}, + {Lo: 0x1e14e, Hi: 0x1e290, Stride: 322}, + {Lo: 0x1e291, Hi: 0x1e2ad, Stride: 1}, + {Lo: 0x1e2c0, Hi: 0x1e2eb, Stride: 1}, + {Lo: 0x1e2f0, Hi: 0x1e2f9, Stride: 1}, + {Lo: 0x1e4d0, Hi: 0x1e4eb, Stride: 1}, + {Lo: 0x1e4f0, Hi: 0x1e4f9, Stride: 1}, + {Lo: 0x1e7e0, Hi: 0x1e7e6, Stride: 1}, + {Lo: 0x1e7e8, Hi: 0x1e7eb, Stride: 1}, + {Lo: 0x1e7ed, Hi: 0x1e7ee, Stride: 1}, + {Lo: 0x1e7f0, Hi: 0x1e7fe, Stride: 1}, + {Lo: 0x1e800, Hi: 0x1e8c4, Stride: 1}, + {Lo: 0x1e8c7, Hi: 0x1e8cf, Stride: 1}, + {Lo: 0x1e900, Hi: 0x1e943, Stride: 1}, + {Lo: 0x1e947, Hi: 0x1e94b, Stride: 4}, + {Lo: 0x1e950, Hi: 0x1e959, Stride: 1}, + {Lo: 0x1ec71, Hi: 0x1ecab, Stride: 1}, + {Lo: 0x1ecad, Hi: 0x1ecaf, Stride: 1}, + {Lo: 0x1ecb1, Hi: 0x1ecb4, Stride: 1}, + {Lo: 0x1ed01, Hi: 0x1ed2d, Stride: 1}, + {Lo: 0x1ed2f, Hi: 0x1ed3d, Stride: 1}, + {Lo: 0x1ee00, Hi: 0x1ee03, Stride: 1}, + {Lo: 0x1ee05, Hi: 0x1ee1f, Stride: 1}, + {Lo: 0x1ee21, Hi: 0x1ee22, Stride: 1}, + {Lo: 0x1ee24, Hi: 0x1ee27, Stride: 3}, + {Lo: 0x1ee29, Hi: 0x1ee32, Stride: 1}, + {Lo: 0x1ee34, Hi: 0x1ee37, Stride: 1}, + {Lo: 0x1ee39, Hi: 0x1ee3b, Stride: 2}, + {Lo: 0x1ee42, Hi: 0x1ee47, Stride: 5}, + {Lo: 0x1ee49, Hi: 0x1ee4d, Stride: 2}, + {Lo: 0x1ee4e, Hi: 0x1ee4f, Stride: 1}, + {Lo: 0x1ee51, Hi: 0x1ee52, Stride: 1}, + {Lo: 0x1ee54, Hi: 0x1ee57, Stride: 3}, + {Lo: 0x1ee59, Hi: 0x1ee61, Stride: 2}, + {Lo: 0x1ee62, Hi: 0x1ee64, Stride: 2}, + {Lo: 0x1ee67, Hi: 0x1ee6a, Stride: 1}, + {Lo: 0x1ee6c, Hi: 0x1ee72, Stride: 1}, + {Lo: 0x1ee74, Hi: 0x1ee77, Stride: 1}, + {Lo: 0x1ee79, Hi: 0x1ee7c, Stride: 1}, + {Lo: 0x1ee7e, Hi: 0x1ee80, Stride: 2}, + {Lo: 0x1ee81, Hi: 0x1ee89, Stride: 1}, + {Lo: 0x1ee8b, Hi: 0x1ee9b, Stride: 1}, + {Lo: 0x1eea1, Hi: 0x1eea3, Stride: 1}, + {Lo: 0x1eea5, Hi: 0x1eea9, Stride: 1}, + {Lo: 0x1eeab, Hi: 0x1eebb, Stride: 1}, + {Lo: 0x1f100, Hi: 0x1f10c, Stride: 1}, + {Lo: 0x1f130, Hi: 0x1f149, Stride: 1}, + {Lo: 0x1f150, Hi: 0x1f169, Stride: 1}, + {Lo: 0x1f170, Hi: 0x1f189, Stride: 1}, + {Lo: 0x1fbf0, Hi: 0x1fbf9, Stride: 1}, + {Lo: 0x20000, Hi: 0x2a6df, Stride: 1}, + {Lo: 0x2a700, Hi: 0x2b739, Stride: 1}, + {Lo: 0x2b740, Hi: 0x2b81d, Stride: 1}, + {Lo: 0x2b820, Hi: 0x2cea1, Stride: 1}, + {Lo: 0x2ceb0, Hi: 0x2ebe0, Stride: 1}, + {Lo: 0x2ebf0, Hi: 0x2ee5d, Stride: 1}, + {Lo: 0x2f800, Hi: 0x2fa1d, Stride: 1}, + {Lo: 0x30000, Hi: 0x3134a, Stride: 1}, + {Lo: 0x31350, Hi: 0x323af, Stride: 1}, + }, + LatinOffset: 9, +} diff --git a/vendor/github.com/godbus/dbus/.travis.yml b/vendor/github.com/godbus/dbus/.travis.yml new file mode 100644 index 0000000..2e1bbb7 --- /dev/null +++ b/vendor/github.com/godbus/dbus/.travis.yml @@ -0,0 +1,40 @@ +dist: precise +language: go +go_import_path: github.com/godbus/dbus +sudo: true + +go: + - 1.6.3 + - 1.7.3 + - tip + +env: + global: + matrix: + - TARGET=amd64 + - TARGET=arm64 + - TARGET=arm + - TARGET=386 + - TARGET=ppc64le + +matrix: + fast_finish: true + allow_failures: + - go: tip + exclude: + - go: tip + env: TARGET=arm + - go: tip + env: TARGET=arm64 + - go: tip + env: TARGET=386 + - go: tip + env: TARGET=ppc64le + +addons: + apt: + packages: + - dbus + - dbus-x11 + +before_install: diff --git a/vendor/github.com/godbus/dbus/CONTRIBUTING.md b/vendor/github.com/godbus/dbus/CONTRIBUTING.md new file mode 100644 index 0000000..c88f9b2 --- /dev/null +++ b/vendor/github.com/godbus/dbus/CONTRIBUTING.md @@ -0,0 +1,50 @@ +# How to Contribute + +## Getting Started + +- Fork the repository on GitHub +- Read the [README](README.markdown) for build and test instructions +- Play with the project, submit bugs, submit patches! + +## Contribution Flow + +This is a rough outline of what a contributor's workflow looks like: + +- Create a topic branch from where you want to base your work (usually master). +- Make commits of logical units. +- Make sure your commit messages are in the proper format (see below). +- Push your changes to a topic branch in your fork of the repository. +- Make sure the tests pass, and add any new tests as appropriate. +- Submit a pull request to the original repository. + +Thanks for your contributions! + +### Format of the Commit Message + +We follow a rough convention for commit messages that is designed to answer two +questions: what changed and why. The subject line should feature the what and +the body of the commit should describe the why. + +``` +scripts: add the test-cluster command + +this uses tmux to setup a test cluster that you can easily kill and +start for debugging. + +Fixes #38 +``` + +The format can be described more formally as follows: + +``` +: + + + +